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