]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/placex_triggers.sql
tests for composing decomposed suffixes
[nominatim.git] / lib-sql / functions / placex_triggers.sql
1 -- Trigger functions for the placex table.
2
3 -- Retrieve the data needed by the indexer for updating the place.
4 --
5 -- Return parameters:
6 --  name            list of names
7 --  address         list of address tags, either from the object or a surrounding
8 --                  building
9 --  country_feature If the place is a country feature, this contains the
10 --                  country code, otherwise it is null.
11 CREATE OR REPLACE FUNCTION placex_prepare_update(p placex,
12                                                  OUT name HSTORE,
13                                                  OUT address HSTORE,
14                                                  OUT country_feature VARCHAR)
15   AS $$
16 BEGIN
17   -- For POI nodes, check if the address should be derived from a surrounding
18   -- building.
19   IF p.rank_search < 30 OR p.osm_type != 'N' OR p.address is not null THEN
20     address := p.address;
21   ELSE
22     -- The additional && condition works around the misguided query
23     -- planner of postgis 3.0.
24     SELECT placex.address || hstore('_inherited', '') INTO address
25       FROM placex
26      WHERE ST_Covers(geometry, p.centroid)
27            and geometry && p.centroid
28            and placex.address is not null
29            and (placex.address ? 'housenumber' or placex.address ? 'street' or placex.address ? 'place')
30            and rank_search = 30 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
31      LIMIT 1;
32   END IF;
33
34   address := address - '_unlisted_place'::TEXT;
35   name := p.name;
36
37   country_feature := CASE WHEN p.admin_level = 2
38                                and p.class = 'boundary' and p.type = 'administrative'
39                                and p.osm_type = 'R'
40                           THEN p.country_code
41                           ELSE null
42                      END;
43 END;
44 $$
45 LANGUAGE plpgsql STABLE;
46
47
48 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
49                                                   poi_osm_id BIGINT)
50   RETURNS BIGINT
51   AS $$
52 DECLARE
53   location RECORD;
54   parent RECORD;
55 BEGIN
56   FOR location IN
57     SELECT members FROM planet_osm_rels
58     WHERE parts @> ARRAY[poi_osm_id]
59           and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
60           and tags @> ARRAY['associatedStreet']
61   LOOP
62     FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
63       IF location.members[i+1] = 'street' THEN
64         FOR parent IN
65           SELECT place_id from placex
66            WHERE osm_type = 'W' and osm_id = substring(location.members[i],2)::bigint
67                  and name is not null
68                  and rank_search between 26 and 27
69         LOOP
70           RETURN parent.place_id;
71         END LOOP;
72       END IF;
73     END LOOP;
74   END LOOP;
75
76   RETURN NULL;
77 END;
78 $$
79 LANGUAGE plpgsql STABLE;
80
81
82 -- Find the parent road of a POI.
83 --
84 -- \returns Place ID of parent object or NULL if none
85 --
86 -- Copy data from linked items (POIs on ways, addr:street links, relations).
87 --
88 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
89                                                poi_osm_id BIGINT,
90                                                poi_partition SMALLINT,
91                                                bbox GEOMETRY,
92                                                addr_street INTEGER[],
93                                                addr_place INTEGER[],
94                                                is_place_addr BOOLEAN)
95   RETURNS BIGINT
96   AS $$
97 DECLARE
98   parent_place_id BIGINT DEFAULT NULL;
99   location RECORD;
100 BEGIN
101   {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
102
103   -- Is this object part of an associatedStreet relation?
104   parent_place_id := find_associated_street(poi_osm_type, poi_osm_id);
105
106   IF parent_place_id is null THEN
107     parent_place_id := find_parent_for_address(addr_street, addr_place,
108                                                poi_partition, bbox);
109   END IF;
110
111   IF parent_place_id is null and poi_osm_type = 'N' THEN
112     -- Is this node part of an interpolation?
113     FOR location IN
114       SELECT q.parent_place_id
115         FROM location_property_osmline q, planet_osm_ways x
116        WHERE q.linegeo && bbox and x.id = q.osm_id
117              and poi_osm_id = any(x.nodes)
118        LIMIT 1
119     LOOP
120       {% if debug %}RAISE WARNING 'Get parent from interpolation: %', location.parent_place_id;{% endif %}
121       RETURN location.parent_place_id;
122     END LOOP;
123
124     FOR location IN
125       SELECT p.place_id, p.osm_id, p.rank_search, p.address,
126              coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
127         FROM placex p, planet_osm_ways w
128        WHERE p.osm_type = 'W' and p.rank_search >= 26
129              and p.geometry && bbox
130              and w.id = p.osm_id and poi_osm_id = any(w.nodes)
131     LOOP
132       {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
133
134       -- Way IS a road then we are on it - that must be our road
135       IF location.rank_search < 28 THEN
136         {% if debug %}RAISE WARNING 'node in way that is a street %',location;{% endif %}
137         RETURN location.place_id;
138       END IF;
139
140       parent_place_id := find_associated_street('W', location.osm_id);
141     END LOOP;
142   END IF;
143
144   IF parent_place_id is NULL THEN
145     IF is_place_addr THEN
146       -- The address is attached to a place we don't know.
147       -- Instead simply use the containing area with the largest rank.
148       FOR location IN
149         SELECT place_id FROM placex
150          WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
151                AND rank_address between 5 and 25
152          ORDER BY rank_address desc
153       LOOP
154         RETURN location.place_id;
155       END LOOP;
156     ELSEIF ST_Area(bbox) < 0.005 THEN
157       -- for smaller features get the nearest road
158       SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
159       {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
160     ELSE
161       -- for larger features simply find the area with the largest rank that
162       -- contains the bbox, only use addressable features
163       FOR location IN
164         SELECT place_id FROM placex
165          WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
166                AND rank_address between 5 and 25
167         ORDER BY rank_address desc
168       LOOP
169         RETURN location.place_id;
170       END LOOP;
171     END IF;
172   END IF;
173
174   RETURN parent_place_id;
175 END;
176 $$
177 LANGUAGE plpgsql STABLE;
178
179 -- Try to find a linked place for the given object.
180 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
181   RETURNS placex
182   AS $$
183 DECLARE
184   relation_members TEXT[];
185   rel_member RECORD;
186   linked_placex placex%ROWTYPE;
187   bnd_name TEXT;
188 BEGIN
189   IF bnd.rank_search >= 26 or bnd.rank_address = 0
190      or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
191      or bnd.type IN ('postcode', 'postal_code')
192   THEN
193     RETURN NULL;
194   END IF;
195
196   IF bnd.osm_type = 'R' THEN
197     -- see if we have any special relation members
198     SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
199     {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
200
201     -- Search for relation members with role 'lable'.
202     IF relation_members IS NOT NULL THEN
203       FOR rel_member IN
204         SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
205       LOOP
206         {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
207
208         FOR linked_placex IN
209           SELECT * from placex
210           WHERE osm_type = 'N' and osm_id = rel_member.member
211             and class = 'place'
212         LOOP
213           {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
214           RETURN linked_placex;
215         END LOOP;
216
217       END LOOP;
218     END IF;
219   END IF;
220
221   IF bnd.name ? 'name' THEN
222     bnd_name := lower(bnd.name->'name');
223     IF bnd_name = '' THEN
224       bnd_name := NULL;
225     END IF;
226   END IF;
227
228   -- If extratags has a place tag, look for linked nodes by their place type.
229   -- Area and node still have to have the same name.
230   IF bnd.extratags ? 'place' and bnd_name is not null THEN
231     FOR linked_placex IN
232       SELECT * FROM placex
233       WHERE (position(lower(name->'name') in bnd_name) > 0
234              OR position(bnd_name in lower(name->'name')) > 0)
235         AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
236         AND placex.osm_type = 'N'
237         AND placex.linked_place_id is null
238         AND placex.rank_search < 26 -- needed to select the right index
239         AND placex.type != 'postcode'
240         AND ST_Covers(bnd.geometry, placex.geometry)
241     LOOP
242       {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
243       RETURN linked_placex;
244     END LOOP;
245   END IF;
246
247   IF bnd.extratags ? 'wikidata' THEN
248     FOR linked_placex IN
249       SELECT * FROM placex
250       WHERE placex.class = 'place' AND placex.osm_type = 'N'
251         AND placex.extratags ? 'wikidata' -- needed to select right index
252         AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
253         AND placex.linked_place_id is null
254         AND placex.rank_search < 26
255         AND _st_covers(bnd.geometry, placex.geometry)
256       ORDER BY lower(name->'name') = bnd_name desc
257     LOOP
258       {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
259       RETURN linked_placex;
260     END LOOP;
261   END IF;
262
263   -- Name searches can be done for ways as well as relations
264   IF bnd_name is not null THEN
265     {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
266     FOR linked_placex IN
267       SELECT placex.* from placex
268       WHERE lower(name->'name') = bnd_name
269         AND ((bnd.rank_address > 0
270               and bnd.rank_address = (compute_place_rank(placex.country_code,
271                                                          'N', placex.class,
272                                                          placex.type, 15::SMALLINT,
273                                                          false, placex.postcode)).address_rank)
274              OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
275         AND placex.osm_type = 'N'
276         AND placex.class = 'place'
277         AND placex.linked_place_id is null
278         AND placex.rank_search < 26 -- needed to select the right index
279         AND placex.type != 'postcode'
280         AND ST_Covers(bnd.geometry, placex.geometry)
281     LOOP
282       {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
283       RETURN linked_placex;
284     END LOOP;
285   END IF;
286
287   RETURN NULL;
288 END;
289 $$
290 LANGUAGE plpgsql STABLE;
291
292
293 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
294                                                    in_partition SMALLINT,
295                                                    parent_place_id BIGINT,
296                                                    is_place_addr BOOLEAN,
297                                                    country TEXT,
298                                                    token_info JSONB,
299                                                    geometry GEOMETRY,
300                                                    OUT name_vector INTEGER[],
301                                                    OUT nameaddress_vector INTEGER[])
302   AS $$
303 DECLARE
304   parent_name_vector INTEGER[];
305   parent_address_vector INTEGER[];
306   addr_place_ids INTEGER[];
307   hnr_vector INTEGER[];
308
309   addr_item RECORD;
310   addr_place RECORD;
311   parent_address_place_ids BIGINT[];
312 BEGIN
313   nameaddress_vector := '{}'::INTEGER[];
314
315   SELECT s.name_vector, s.nameaddress_vector
316     INTO parent_name_vector, parent_address_vector
317     FROM search_name s
318     WHERE s.place_id = parent_place_id;
319
320   FOR addr_item IN
321     SELECT (get_addr_tag_rank(key, country)).*, match_tokens, search_tokens
322       FROM token_get_address_tokens(token_info)
323       WHERE not search_tokens <@ parent_address_vector
324   LOOP
325     addr_place := get_address_place(in_partition, geometry,
326                                     addr_item.from_rank, addr_item.to_rank,
327                                     addr_item.extent, addr_item.match_tokens);
328
329     IF addr_place is null THEN
330       -- No place found in OSM that matches. Make it at least searchable.
331       nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
332     ELSE
333       IF parent_address_place_ids is null THEN
334         SELECT array_agg(parent_place_id) INTO parent_address_place_ids
335           FROM place_addressline
336           WHERE place_id = parent_place_id;
337       END IF;
338
339       -- If the parent already lists the place in place_address line, then we
340       -- are done. Otherwise, add its own place_address line.
341       IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
342         nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
343
344         INSERT INTO place_addressline (place_id, address_place_id, fromarea,
345                                        isaddress, distance, cached_rank_address)
346           VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
347                     true, addr_place.distance, addr_place.rank_address);
348       END IF;
349     END IF;
350   END LOOP;
351
352   name_vector := token_get_name_search_tokens(token_info);
353
354   -- Check if the parent covers all address terms.
355   -- If not, create a search name entry with the house number as the name.
356   -- This is unusual for the search_name table but prevents that the place
357   -- is returned when we only search for the street/place.
358
359   hnr_vector := token_get_housenumber_search_tokens(token_info);
360
361   IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
362     name_vector := array_merge(name_vector, hnr_vector);
363   END IF;
364
365   IF is_place_addr THEN
366     addr_place_ids := token_addr_place_search_tokens(token_info);
367     IF not addr_place_ids <@ parent_name_vector THEN
368       -- make sure addr:place terms are always searchable
369       nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
370       -- If there is a housenumber, also add the place name as a name,
371       -- so we can search it by the usual housenumber+place algorithms.
372       IF hnr_vector is not null THEN
373         name_vector := array_merge(name_vector, addr_place_ids);
374       END IF;
375     END IF;
376   END IF;
377
378   -- Cheating here by not recomputing all terms but simply using the ones
379   -- from the parent object.
380   nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
381   nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
382
383 END;
384 $$
385 LANGUAGE plpgsql;
386
387
388 -- Insert address of a place into the place_addressline table.
389 --
390 -- \param obj_place_id  Place_id of the place to compute the address for.
391 -- \param partition     Partition number where the place is in.
392 -- \param maxrank       Rank of the place. All address features must have
393 --                      a search rank lower than the given rank.
394 -- \param address       Address terms for the place.
395 -- \param geometry      Geometry to which the address objects should be close.
396 --
397 -- \retval parent_place_id  Place_id of the address object that is the direct
398 --                          ancestor.
399 -- \retval postcode         Postcode computed from the address. This is the
400 --                          addr:postcode of one of the address objects. If
401 --                          more than one of has a postcode, the highest ranking
402 --                          one is used. May be NULL.
403 -- \retval nameaddress_vector  Search terms for the address. This is the sum
404 --                             of name terms of all address objects.
405 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
406                                                partition SMALLINT,
407                                                maxrank SMALLINT,
408                                                token_info JSONB,
409                                                geometry GEOMETRY,
410                                                country TEXT,
411                                                OUT parent_place_id BIGINT,
412                                                OUT postcode TEXT,
413                                                OUT nameaddress_vector INT[])
414   AS $$
415 DECLARE
416   address_havelevel BOOLEAN[];
417
418   location_isaddress BOOLEAN;
419   current_boundary GEOMETRY := NULL;
420   current_node_area GEOMETRY := NULL;
421
422   parent_place_rank INT := 0;
423   addr_place_ids BIGINT[] := '{}'::int[];
424   new_address_vector INT[];
425
426   location RECORD;
427 BEGIN
428   parent_place_id := 0;
429   nameaddress_vector := '{}'::int[];
430
431   address_havelevel := array_fill(false, ARRAY[maxrank]);
432
433   FOR location IN
434     SELECT (get_address_place(partition, geometry, from_rank, to_rank,
435                               extent, match_tokens)).*, search_tokens
436       FROM (SELECT (get_addr_tag_rank(key, country)).*, match_tokens, search_tokens
437               FROM token_get_address_tokens(token_info)) x
438       ORDER BY rank_address, distance, isguess desc
439   LOOP
440     IF location.place_id is null THEN
441       {% if not db.reverse_only %}
442       nameaddress_vector := array_merge(nameaddress_vector, location.search_tokens);
443       {% endif %}
444     ELSE
445       {% if not db.reverse_only %}
446       nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
447       {% endif %}
448
449       location_isaddress := not address_havelevel[location.rank_address];
450       IF not address_havelevel[location.rank_address] THEN
451         address_havelevel[location.rank_address] := true;
452         IF parent_place_rank < location.rank_address THEN
453           parent_place_id := location.place_id;
454           parent_place_rank := location.rank_address;
455         END IF;
456       END IF;
457
458       INSERT INTO place_addressline (place_id, address_place_id, fromarea,
459                                      isaddress, distance, cached_rank_address)
460         VALUES (obj_place_id, location.place_id, not location.isguess,
461                 true, location.distance, location.rank_address);
462
463       addr_place_ids := addr_place_ids || location.place_id;
464     END IF;
465   END LOOP;
466
467   FOR location IN
468     SELECT * FROM getNearFeatures(partition, geometry, maxrank)
469     WHERE not addr_place_ids @> ARRAY[place_id]
470     ORDER BY rank_address, isguess asc,
471              distance *
472                CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
473                     WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
474                     WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
475                     ELSE 1 END ASC
476   LOOP
477     -- Ignore all place nodes that do not fit in a lower level boundary.
478     CONTINUE WHEN location.isguess
479                   and current_boundary is not NULL
480                   and not ST_Contains(current_boundary, location.centroid);
481
482     -- If this is the first item in the rank, then assume it is the address.
483     location_isaddress := not address_havelevel[location.rank_address];
484
485     -- Further sanity checks to ensure that the address forms a sane hierarchy.
486     IF location_isaddress THEN
487       IF location.isguess and current_node_area is not NULL THEN
488         location_isaddress := ST_Contains(current_node_area, location.centroid);
489       END IF;
490       IF not location.isguess and current_boundary is not NULL
491          and location.rank_address != 11 AND location.rank_address != 5 THEN
492         location_isaddress := ST_Contains(current_boundary, location.centroid);
493       END IF;
494     END IF;
495
496     IF location_isaddress THEN
497       address_havelevel[location.rank_address] := true;
498       parent_place_id := location.place_id;
499
500       -- Set postcode if we have one.
501       -- (Returned will be the highest ranking one.)
502       IF location.postcode is not NULL THEN
503         postcode = location.postcode;
504       END IF;
505
506       -- Recompute the areas we need for hierarchy sanity checks.
507       IF location.rank_address != 11 AND location.rank_address != 5 THEN
508         IF location.isguess THEN
509           current_node_area := place_node_fuzzy_area(location.centroid,
510                                                      location.rank_search);
511         ELSE
512           current_node_area := NULL;
513           SELECT p.geometry FROM placex p
514               WHERE p.place_id = location.place_id INTO current_boundary;
515         END IF;
516       END IF;
517     END IF;
518
519     -- Add it to the list of search terms
520     {% if not db.reverse_only %}
521       nameaddress_vector := array_merge(nameaddress_vector,
522                                         location.keywords::integer[]);
523     {% endif %}
524
525     INSERT INTO place_addressline (place_id, address_place_id, fromarea,
526                                      isaddress, distance, cached_rank_address)
527         VALUES (obj_place_id, location.place_id, not location.isguess,
528                 location_isaddress, location.distance, location.rank_address);
529   END LOOP;
530 END;
531 $$
532 LANGUAGE plpgsql;
533
534
535 CREATE OR REPLACE FUNCTION placex_insert()
536   RETURNS TRIGGER
537   AS $$
538 DECLARE
539   postcode TEXT;
540   result BOOLEAN;
541   is_area BOOLEAN;
542   country_code VARCHAR(2);
543   diameter FLOAT;
544   classtable TEXT;
545 BEGIN
546   {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
547
548   NEW.place_id := nextval('seq_place');
549   NEW.indexed_status := 1; --STATUS_NEW
550
551   NEW.centroid := ST_PointOnSurface(NEW.geometry);
552   NEW.country_code := lower(get_country_code(NEW.centroid));
553
554   NEW.partition := get_partition(NEW.country_code);
555   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
556
557   IF NEW.osm_type = 'X' THEN
558     -- E'X'ternal records should already be in the right format so do nothing
559   ELSE
560     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
561
562     IF NEW.class in ('place','boundary')
563        AND NEW.type in ('postcode','postal_code')
564     THEN
565       IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
566           -- most likely just a part of a multipolygon postcode boundary, throw it away
567           RETURN NULL;
568       END IF;
569
570       NEW.name := hstore('ref', NEW.address->'postcode');
571
572     ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
573            AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
574     THEN
575         RETURN NULL;
576     ELSEIF NEW.class = 'boundary' AND NOT is_area
577     THEN
578         RETURN NULL;
579     ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
580            AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
581     THEN
582         RETURN NULL;
583     END IF;
584
585     SELECT * INTO NEW.rank_search, NEW.rank_address
586       FROM compute_place_rank(NEW.country_code,
587                               CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
588                               NEW.class, NEW.type, NEW.admin_level,
589                               (NEW.extratags->'capital') = 'yes',
590                               NEW.address->'postcode');
591
592     -- a country code make no sense below rank 4 (country)
593     IF NEW.rank_search < 4 THEN
594       NEW.country_code := NULL;
595     END IF;
596
597   END IF;
598
599   {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
600
601 {% if not disable_diff_updates %}
602   -- The following is not needed until doing diff updates, and slows the main index process down
603
604   IF NEW.osm_type = 'N' and NEW.rank_search > 28 THEN
605       -- might be part of an interpolation
606       result := osmline_reinsert(NEW.osm_id, NEW.geometry);
607   ELSEIF NEW.rank_address > 0 THEN
608     IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
609       -- Performance: We just can't handle re-indexing for country level changes
610       IF st_area(NEW.geometry) < 1 THEN
611         -- mark items within the geometry for re-indexing
612   --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
613
614         UPDATE placex SET indexed_status = 2
615          WHERE ST_Intersects(NEW.geometry, placex.geometry)
616                and indexed_status = 0
617                and ((rank_address = 0 and rank_search > NEW.rank_address)
618                     or rank_address > NEW.rank_address
619                     or (class = 'place' and osm_type = 'N')
620                    )
621                and (rank_search < 28
622                     or name is not null
623                     or (NEW.rank_address >= 16 and address ? 'place'));
624       END IF;
625     ELSE
626       -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
627       diameter := update_place_diameter(NEW.rank_search);
628       IF diameter > 0 THEN
629   --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
630         IF NEW.rank_search >= 26 THEN
631           -- roads may cause reparenting for >27 rank places
632           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
633           -- reparenting also for OSM Interpolation Lines (and for Tiger?)
634           update location_property_osmline set indexed_status = 2 where indexed_status = 0 and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
635         ELSEIF NEW.rank_search >= 16 THEN
636           -- up to rank 16, street-less addresses may need reparenting
637           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null or address ? 'place');
638         ELSE
639           -- for all other places the search terms may change as well
640           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null);
641         END IF;
642       END IF;
643     END IF;
644   END IF;
645
646
647    -- add to tables for special search
648    -- Note: won't work on initial import because the classtype tables
649    -- do not yet exist. It won't hurt either.
650   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
651   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
652   IF result THEN
653     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
654     USING NEW.place_id, ST_Centroid(NEW.geometry);
655   END IF;
656
657 {% endif %} -- not disable_diff_updates
658
659   RETURN NEW;
660
661 END;
662 $$
663 LANGUAGE plpgsql;
664
665 CREATE OR REPLACE FUNCTION placex_update()
666   RETURNS TRIGGER
667   AS $$
668 DECLARE
669   i INTEGER;
670   location RECORD;
671   relation_members TEXT[];
672
673   geom GEOMETRY;
674   parent_address_level SMALLINT;
675   place_address_level SMALLINT;
676
677   addr_street INTEGER[];
678   addr_place INTEGER[];
679
680   max_rank SMALLINT;
681
682   name_vector INTEGER[];
683   nameaddress_vector INTEGER[];
684   addr_nameaddress_vector INTEGER[];
685
686   linked_node_id BIGINT;
687   linked_importance FLOAT;
688   linked_wikipedia TEXT;
689
690   is_place_address BOOLEAN;
691   result BOOLEAN;
692 BEGIN
693   -- deferred delete
694   IF OLD.indexed_status = 100 THEN
695     {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
696     delete from placex where place_id = OLD.place_id;
697     RETURN NULL;
698   END IF;
699
700   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
701     RETURN NEW;
702   END IF;
703
704   {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
705
706   NEW.indexed_date = now();
707
708   {% if 'search_name' in db.tables %}
709     DELETE from search_name WHERE place_id = NEW.place_id;
710   {% endif %}
711   result := deleteSearchName(NEW.partition, NEW.place_id);
712   DELETE FROM place_addressline WHERE place_id = NEW.place_id;
713   result := deleteRoad(NEW.partition, NEW.place_id);
714   result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
715   UPDATE placex set linked_place_id = null, indexed_status = 2
716          where linked_place_id = NEW.place_id;
717   -- update not necessary for osmline, cause linked_place_id does not exist
718
719   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
720
721   IF NEW.linked_place_id is not null THEN
722     NEW.token_info := null;
723     {% if debug %}RAISE WARNING 'place already linked to %', NEW.linked_place_id;{% endif %}
724     RETURN NEW;
725   END IF;
726
727   -- Postcodes are just here to compute the centroids. They are not searchable
728   -- unless they are a boundary=postal_code.
729   -- There was an error in the style so that boundary=postal_code used to be
730   -- imported as place=postcode. That's why relations are allowed to pass here.
731   -- This can go away in a couple of versions.
732   IF NEW.class = 'place'  and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
733     NEW.token_info := null;
734     RETURN NEW;
735   END IF;
736
737   -- Compute a preliminary centroid.
738   NEW.centroid := ST_PointOnSurface(NEW.geometry);
739
740     -- recalculate country and partition
741   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
742     -- for countries, believe the mapped country code,
743     -- so that we remain in the right partition if the boundaries
744     -- suddenly expand.
745     NEW.country_code := lower(NEW.address->'country');
746     NEW.partition := get_partition(lower(NEW.country_code));
747     IF NEW.partition = 0 THEN
748       NEW.country_code := lower(get_country_code(NEW.centroid));
749       NEW.partition := get_partition(NEW.country_code);
750     END IF;
751   ELSE
752     IF NEW.rank_search >= 4 THEN
753       NEW.country_code := lower(get_country_code(NEW.centroid));
754     ELSE
755       NEW.country_code := NULL;
756     END IF;
757     NEW.partition := get_partition(NEW.country_code);
758   END IF;
759   {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
760
761
762   -- recompute the ranks, they might change when linking changes
763   SELECT * INTO NEW.rank_search, NEW.rank_address
764     FROM compute_place_rank(NEW.country_code,
765                             CASE WHEN ST_GeometryType(NEW.geometry)
766                                         IN ('ST_Polygon','ST_MultiPolygon')
767                             THEN 'A' ELSE NEW.osm_type END,
768                             NEW.class, NEW.type, NEW.admin_level,
769                             (NEW.extratags->'capital') = 'yes',
770                             NEW.address->'postcode');
771   -- We must always increase the address level relative to the admin boundary.
772   IF NEW.class = 'boundary' and NEW.type = 'administrative'
773      and NEW.osm_type = 'R' and NEW.rank_address > 0
774   THEN
775     -- First, check that admin boundaries do not overtake each other rank-wise.
776     parent_address_level := 3;
777     FOR location IN
778       SELECT rank_address,
779              (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
780                         and extratags->'wikidata' = NEW.extratags->'wikidata'
781                    THEN ST_Equals(geometry, NEW.geometry)
782                    ELSE false END) as is_same
783       FROM placex
784       WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
785             and admin_level < NEW.admin_level and admin_level > 3
786             and rank_address > 0
787             and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
788       ORDER BY admin_level desc LIMIT 1
789     LOOP
790       IF location.is_same THEN
791         -- Looks like the same boundary is replicated on multiple admin_levels.
792         -- Usual tagging in Poland. Remove our boundary from addresses.
793         NEW.rank_address := 0;
794       ELSE
795         parent_address_level := location.rank_address;
796         IF location.rank_address >= NEW.rank_address THEN
797           IF location.rank_address >= 24 THEN
798             NEW.rank_address := 25;
799           ELSE
800             NEW.rank_address := location.rank_address + 2;
801           END IF;
802         END IF;
803       END IF;
804     END LOOP;
805
806     IF NEW.rank_address > 9 THEN
807         -- Second check that the boundary is not completely contained in a
808         -- place area with a higher address rank
809         FOR location IN
810           SELECT rank_address FROM placex
811           WHERE class = 'place' and rank_address < 24
812                 and rank_address > NEW.rank_address
813                 and geometry && NEW.geometry
814                 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
815                 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
816           ORDER BY rank_address desc LIMIT 1
817         LOOP
818           NEW.rank_address := location.rank_address + 2;
819         END LOOP;
820     END IF;
821   ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
822      and NEW.rank_address between 16 and 23
823   THEN
824     -- If a place node is contained in a admin boundary with the same address level
825     -- and has not been linked, then make the node a subpart by increasing the
826     -- address rank (city level and above).
827     FOR location IN
828         SELECT rank_address FROM placex
829         WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
830               and rank_address = NEW.rank_address
831               and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
832         LIMIT 1
833     LOOP
834       NEW.rank_address = NEW.rank_address + 2;
835     END LOOP;
836   ELSE
837     parent_address_level := 3;
838   END IF;
839
840   NEW.housenumber := token_normalized_housenumber(NEW.token_info);
841   addr_street := token_addr_street_match_tokens(NEW.token_info);
842   addr_place := token_addr_place_match_tokens(NEW.token_info);
843
844   NEW.postcode := null;
845
846   -- waterway ways are linked when they are part of a relation and have the same class/type
847   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
848       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
849       LOOP
850           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
851               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
852                 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
853                 FOR linked_node_id IN SELECT place_id FROM placex
854                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
855                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
856                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
857                 LOOP
858                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
859                   {% if 'search_name' in db.tables %}
860                     DELETE FROM search_name WHERE place_id = linked_node_id;
861                   {% endif %}
862                 END LOOP;
863               END IF;
864           END LOOP;
865       END LOOP;
866       {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
867   END IF;
868
869   NEW.importance := null;
870   SELECT wikipedia, importance
871     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
872     INTO NEW.wikipedia,NEW.importance;
873
874 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
875
876   -- ---------------------------------------------------------------------------
877   -- For low level elements we inherit from our parent road
878   IF NEW.rank_search > 27 THEN
879
880     {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
881     NEW.parent_place_id := null;
882     is_place_address := coalesce(not NEW.address ? 'street' and NEW.address ? 'place', FALSE);
883
884     -- We have to find our parent road.
885     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
886                                                NEW.partition,
887                                                ST_Envelope(NEW.geometry),
888                                                addr_street, addr_place,
889                                                is_place_address);
890
891     -- If we found the road take a shortcut here.
892     -- Otherwise fall back to the full address getting method below.
893     IF NEW.parent_place_id is not null THEN
894
895       -- Get the details of the parent road
896       SELECT p.country_code, p.postcode, p.name FROM placex p
897        WHERE p.place_id = NEW.parent_place_id INTO location;
898
899       IF is_place_address THEN
900         -- Check if the addr:place tag is part of the parent name
901         SELECT count(*) INTO i
902           FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
903         IF i = 0 THEN
904           NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
905         END IF;
906       END IF;
907
908       NEW.country_code := location.country_code;
909       {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
910
911       -- determine postcode
912       NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
913                                location.postcode,
914                                get_nearest_postcode(NEW.country_code, NEW.centroid));
915
916       IF NEW.name is not NULL THEN
917           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
918       END IF;
919
920       {% if not db.reverse_only %}
921       IF NEW.name is not NULL OR NEW.address is not NULL THEN
922         SELECT * INTO name_vector, nameaddress_vector
923           FROM create_poi_search_terms(NEW.place_id,
924                                        NEW.partition, NEW.parent_place_id,
925                                        is_place_address, NEW.country_code,
926                                        NEW.token_info, NEW.centroid);
927
928         IF array_length(name_vector, 1) is not NULL THEN
929           INSERT INTO search_name (place_id, search_rank, address_rank,
930                                    importance, country_code, name_vector,
931                                    nameaddress_vector, centroid)
932                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
933                          NEW.importance, NEW.country_code, name_vector,
934                          nameaddress_vector, NEW.centroid);
935           {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
936         END IF;
937       END IF;
938       {% endif %}
939
940       NEW.token_info := token_strip_info(NEW.token_info);
941       -- If the address was inherited from a surrounding building,
942       -- do not add it permanently to the table.
943       IF NEW.address ? '_inherited' THEN
944         IF NEW.address ? '_unlisted_place' THEN
945           NEW.address := hstore('_unlisted_place', NEW.address->'_unlisted_place');
946         ELSE
947           NEW.address := null;
948         END IF;
949       END IF;
950
951       RETURN NEW;
952     END IF;
953
954   END IF;
955
956   -- ---------------------------------------------------------------------------
957   -- Full indexing
958   {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
959   SELECT * INTO location FROM find_linked_place(NEW);
960   IF location.place_id is not null THEN
961     {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
962
963     -- Use the linked point as the centre point of the geometry,
964     -- but only if it is within the area of the boundary.
965     geom := coalesce(location.centroid, ST_Centroid(location.geometry));
966     IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
967         NEW.centroid := geom;
968     END IF;
969
970     {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.rank_address;{% endif %}
971     IF location.rank_address > parent_address_level
972        and location.rank_address < 26
973     THEN
974       NEW.rank_address := location.rank_address;
975     END IF;
976
977     -- merge in the label name
978     IF NOT location.name IS NULL THEN
979       NEW.name := location.name || NEW.name;
980     END IF;
981
982     -- merge in extra tags
983     NEW.extratags := hstore('linked_' || location.class, location.type)
984                      || coalesce(location.extratags, ''::hstore)
985                      || coalesce(NEW.extratags, ''::hstore);
986
987     -- mark the linked place (excludes from search results)
988     UPDATE placex set linked_place_id = NEW.place_id
989       WHERE place_id = location.place_id;
990     -- ensure that those places are not found anymore
991     {% if 'search_name' in db.tables %}
992       DELETE FROM search_name WHERE place_id = location.place_id;
993     {% endif %}
994     PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
995
996     SELECT wikipedia, importance
997       FROM compute_importance(location.extratags, NEW.country_code,
998                               'N', location.osm_id)
999       INTO linked_wikipedia,linked_importance;
1000
1001     -- Use the maximum importance if one could be computed from the linked object.
1002     IF linked_importance is not null AND
1003        (NEW.importance is null or NEW.importance < linked_importance)
1004     THEN
1005       NEW.importance = linked_importance;
1006     END IF;
1007   ELSE
1008     -- No linked place? As a last resort check if the boundary is tagged with
1009     -- a place type and adapt the rank address.
1010     IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
1011       SELECT address_rank INTO place_address_level
1012         FROM compute_place_rank(NEW.country_code, 'A', 'place',
1013                                 NEW.extratags->'place', 0::SMALLINT, False, null);
1014       IF place_address_level > parent_address_level and
1015          place_address_level < 26 THEN
1016         NEW.rank_address := place_address_level;
1017       END IF;
1018     END IF;
1019   END IF;
1020
1021   IF NEW.admin_level = 2
1022      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1023      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1024   THEN
1025     -- Update the list of country names. Adding an additional sanity
1026     -- check here: make sure the country does overlap with the area where
1027     -- we expect it to be as per static country grid.
1028     FOR location IN
1029       SELECT country_code FROM country_osm_grid
1030        WHERE ST_Covers(geometry, NEW.centroid) and country_code = NEW.country_code
1031        LIMIT 1
1032     LOOP
1033       {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1034       UPDATE country_name SET name = name || NEW.name WHERE country_code = NEW.country_code;
1035     END LOOP;
1036   END IF;
1037
1038   -- For linear features we need the full geometry for determining the address
1039   -- because they may go through several administrative entities. Otherwise use
1040   -- the centroid for performance reasons.
1041   IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1042     geom := NEW.geometry;
1043   ELSE
1044     geom := NEW.centroid;
1045   END IF;
1046
1047   IF NEW.rank_address = 0 THEN
1048     max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1049     -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1050     -- so use the geometry here too. Just make sure the areas don't become too
1051     -- large.
1052     IF NEW.class = 'natural' or max_rank > 10 THEN
1053       geom := NEW.geometry;
1054     END IF;
1055   ELSEIF NEW.rank_address > 25 THEN
1056     max_rank := 25;
1057   ELSE
1058     max_rank := NEW.rank_address;
1059   END IF;
1060
1061   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1062                                     NEW.token_info, geom, NEW.country_code)
1063     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1064
1065   {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1066
1067   NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
1068                            NEW.postcode);
1069
1070   -- if we have a name add this to the name search table
1071   IF NEW.name IS NOT NULL THEN
1072     -- Initialise the name vector using our name
1073     NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1074     name_vector := token_get_name_search_tokens(NEW.token_info);
1075
1076     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1077       result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1078                              name_vector, NEW.rank_search, NEW.rank_address,
1079                              NEW.postcode, NEW.geometry, NEW.centroid);
1080       {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1081     END IF;
1082
1083     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1084       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1085       {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1086     END IF;
1087
1088     IF NEW.rank_address between 16 and 27 THEN
1089       result := insertSearchName(NEW.partition, NEW.place_id,
1090                                  token_get_name_match_tokens(NEW.token_info),
1091                                  NEW.rank_search, NEW.rank_address, NEW.geometry);
1092     END IF;
1093     {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1094
1095     {% if not db.reverse_only %}
1096         INSERT INTO search_name (place_id, search_rank, address_rank,
1097                                  importance, country_code, name_vector,
1098                                  nameaddress_vector, centroid)
1099                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1100                        NEW.importance, NEW.country_code, name_vector,
1101                        nameaddress_vector, NEW.centroid);
1102     {% endif %}
1103   END IF;
1104
1105   IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1106     NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1107   END IF;
1108
1109   {% if debug %}RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;{% endif %}
1110
1111   NEW.token_info := token_strip_info(NEW.token_info);
1112   RETURN NEW;
1113 END;
1114 $$
1115 LANGUAGE plpgsql;
1116
1117
1118 CREATE OR REPLACE FUNCTION placex_delete()
1119   RETURNS TRIGGER
1120   AS $$
1121 DECLARE
1122   b BOOLEAN;
1123   classtable TEXT;
1124 BEGIN
1125   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1126
1127   IF OLD.linked_place_id is null THEN
1128     update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1129     {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1130     update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1131     {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1132   ELSE
1133     update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1134   END IF;
1135
1136   IF OLD.rank_address < 30 THEN
1137
1138     -- mark everything linked to this place for re-indexing
1139     {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1140     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1141       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1142
1143     {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1144     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1145
1146     {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1147     b := deleteRoad(OLD.partition, OLD.place_id);
1148
1149     {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1150     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1151     {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1152     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1153     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1154
1155   END IF;
1156
1157   {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1158
1159   IF OLD.rank_address < 26 THEN
1160     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1161   END IF;
1162
1163   {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1164
1165   IF OLD.name is not null THEN
1166     {% if 'search_name' in db.tables %}
1167       DELETE from search_name WHERE place_id = OLD.place_id;
1168     {% endif %}
1169     b := deleteSearchName(OLD.partition, OLD.place_id);
1170   END IF;
1171
1172   {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1173
1174   DELETE FROM place_addressline where place_id = OLD.place_id;
1175
1176   {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1177
1178   -- remove from tables for special search
1179   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1180   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1181   IF b THEN
1182     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1183   END IF;
1184
1185   {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1186
1187   RETURN OLD;
1188
1189 END;
1190 $$
1191 LANGUAGE plpgsql;