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