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