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