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