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