]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/placex_triggers.sql
Indexing: invert boolean logic to factor-out empty `ELSE` clause
[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 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 BOOLEAN;
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    -- Note: won't work on initial import because the classtype tables
789    -- do not yet exist. It won't hurt either.
790   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
791   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
792   IF result THEN
793     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
794     USING NEW.place_id, NEW.centroid;
795   END IF;
796
797 {% endif %} -- not disable_diff_updates
798
799   RETURN NEW;
800
801 END;
802 $$
803 LANGUAGE plpgsql;
804
805 CREATE OR REPLACE FUNCTION placex_update()
806   RETURNS TRIGGER
807   AS $$
808 DECLARE
809   i INTEGER;
810   location RECORD;
811 {% if db.middle_db_format == '1' %}
812   relation_members TEXT[];
813 {% else %}
814   relation_member JSONB;
815 {% endif %}
816
817   geom GEOMETRY;
818   parent_address_level SMALLINT;
819   place_address_level SMALLINT;
820
821   max_rank SMALLINT;
822
823   name_vector INTEGER[];
824   nameaddress_vector INTEGER[];
825   addr_nameaddress_vector INTEGER[];
826
827   linked_place BIGINT;
828
829   linked_node_id BIGINT;
830   linked_importance FLOAT;
831   linked_wikipedia TEXT;
832
833   is_place_address BOOLEAN;
834   result BOOLEAN;
835 BEGIN
836   -- deferred delete
837   IF OLD.indexed_status = 100 THEN
838     {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
839     delete from placex where place_id = OLD.place_id;
840     RETURN NULL;
841   END IF;
842
843   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
844     RETURN NEW;
845   END IF;
846
847   {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
848
849   NEW.indexed_date = now();
850
851   IF OLD.indexed_status > 1 THEN
852     {% if 'search_name' in db.tables %}
853       DELETE from search_name WHERE place_id = NEW.place_id;
854     {% endif %}
855     result := deleteSearchName(NEW.partition, NEW.place_id);
856     DELETE FROM place_addressline WHERE place_id = NEW.place_id;
857     result := deleteRoad(NEW.partition, NEW.place_id);
858     result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
859   END IF;
860
861   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
862   IF NEW.extratags = ''::hstore THEN
863     NEW.extratags := NULL;
864   END IF;
865
866   -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
867   -- the previous link status.
868   linked_place := NEW.linked_place_id;
869   NEW.linked_place_id := OLD.linked_place_id;
870
871   -- Remove linkage, if we have computed a different new linkee.
872   IF OLD.indexed_status > 1 THEN
873     UPDATE placex
874       SET linked_place_id = null,
875           indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
876       WHERE linked_place_id = NEW.place_id
877             and (linked_place is null or place_id != linked_place);
878   END IF;
879
880   -- Compute a preliminary centroid.
881   NEW.centroid := get_center_point(NEW.geometry);
882
883   -- Record the entrance node locations
884   IF NEW.osm_type = 'W' and (NEW.rank_search > 27 or NEW.class IN ('landuse', 'leisure')) THEN
885     PERFORM place_update_entrances(NEW.place_id, NEW.osm_id);
886   END IF;
887
888     -- recalculate country and partition
889   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
890     -- for countries, believe the mapped country code,
891     -- so that we remain in the right partition if the boundaries
892     -- suddenly expand.
893     NEW.country_code := lower(NEW.address->'country');
894     NEW.partition := get_partition(lower(NEW.country_code));
895     IF NEW.partition = 0 THEN
896       NEW.country_code := lower(get_country_code(NEW.centroid));
897       NEW.partition := get_partition(NEW.country_code);
898     END IF;
899   ELSE
900     IF NEW.rank_search >= 4 THEN
901       NEW.country_code := lower(get_country_code(NEW.centroid));
902     ELSE
903       NEW.country_code := NULL;
904     END IF;
905     NEW.partition := get_partition(NEW.country_code);
906   END IF;
907   {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
908
909
910   -- recompute the ranks, they might change when linking changes
911   SELECT * INTO NEW.rank_search, NEW.rank_address
912     FROM compute_place_rank(NEW.country_code,
913                             CASE WHEN ST_GeometryType(NEW.geometry)
914                                         IN ('ST_Polygon','ST_MultiPolygon')
915                             THEN 'A' ELSE NEW.osm_type END,
916                             NEW.class, NEW.type, NEW.admin_level,
917                             (NEW.extratags->'capital') = 'yes',
918                             NEW.address->'postcode');
919
920   -- Short-cut out for linked places. Note that this must happen after the
921   -- address rank has been recomputed. The linking might nullify a shift in
922   -- address rank.
923   IF NEW.linked_place_id is not null THEN
924     NEW.token_info := null;
925     {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
926     RETURN NEW;
927   END IF;
928
929   -- We must always increase the address level relative to the admin boundary.
930   IF NEW.class = 'boundary' and NEW.type = 'administrative'
931      and NEW.osm_type = 'R' and NEW.rank_address > 0
932   THEN
933     -- First, check that admin boundaries do not overtake each other rank-wise.
934     parent_address_level := 3;
935     FOR location IN
936       SELECT rank_address,
937              (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
938                         and extratags->'wikidata' = NEW.extratags->'wikidata'
939                    THEN ST_Equals(geometry, NEW.geometry)
940                    ELSE false END) as is_same
941       FROM placex
942       WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
943             and admin_level < NEW.admin_level and admin_level > 3
944             and rank_address between 1 and 25 -- for index selection
945             and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- for index selection
946             and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
947       ORDER BY admin_level desc LIMIT 1
948     LOOP
949       IF location.is_same THEN
950         -- Looks like the same boundary is replicated on multiple admin_levels.
951         -- Usual tagging in Poland. Remove our boundary from addresses.
952         NEW.rank_address := 0;
953       ELSE
954         parent_address_level := location.rank_address;
955         IF location.rank_address >= NEW.rank_address THEN
956           IF location.rank_address >= 24 THEN
957             NEW.rank_address := 25;
958           ELSE
959             NEW.rank_address := location.rank_address + 2;
960           END IF;
961         END IF;
962       END IF;
963     END LOOP;
964
965     IF NEW.rank_address > 9 THEN
966         -- Second check that the boundary is not completely contained in a
967         -- place area with a equal or higher address rank.
968         FOR location IN
969           SELECT rank_address
970           FROM placex,
971                LATERAL compute_place_rank(country_code, 'A', class, type,
972                                           admin_level, False, null) prank
973           WHERE class = 'place' and rank_address between 1 and 23
974                 and prank.address_rank >= NEW.rank_address
975                 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
976                 and ST_Contains(geometry, NEW.geometry)
977                 and not ST_Equals(geometry, NEW.geometry)
978           ORDER BY prank.address_rank desc LIMIT 1
979         LOOP
980           NEW.rank_address := location.rank_address + 2;
981         END LOOP;
982     END IF;
983   ELSEIF NEW.class = 'place'
984          and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
985          and NEW.rank_address between 16 and 23
986   THEN
987     -- For place areas make sure they are not completely contained in an area
988     -- with a equal or higher address rank.
989     FOR location IN
990           SELECT rank_address
991           FROM placex,
992                LATERAL compute_place_rank(country_code, 'A', class, type,
993                                           admin_level, False, null) prank
994           WHERE prank.address_rank < 24
995                 and rank_address between 1 and 25 -- select right index
996                 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
997                 and prank.address_rank >= NEW.rank_address
998                 and ST_Contains(geometry, NEW.geometry)
999                 and not ST_Equals(geometry, NEW.geometry)
1000           ORDER BY prank.address_rank desc LIMIT 1
1001         LOOP
1002           NEW.rank_address := location.rank_address + 2;
1003         END LOOP;
1004   ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
1005          and NEW.rank_address between 16 and 23
1006   THEN
1007     -- If a place node is contained in an admin or place boundary with the same
1008     -- address level and has not been linked, then make the node a subpart
1009     -- by increasing the address rank (city level and above).
1010     FOR location IN
1011         SELECT rank_address
1012         FROM placex,
1013              LATERAL compute_place_rank(country_code, 'A', class, type,
1014                                         admin_level, False, null) prank
1015         WHERE osm_type = 'R'
1016               and rank_address between 1 and 25 -- select right index
1017               and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
1018               and ((class = 'place' and prank.address_rank = NEW.rank_address)
1019                    or (class = 'boundary' and rank_address = NEW.rank_address))
1020               and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
1021         LIMIT 1
1022     LOOP
1023       NEW.rank_address = NEW.rank_address + 2;
1024     END LOOP;
1025   ELSE
1026     parent_address_level := 3;
1027   END IF;
1028
1029   NEW.housenumber := token_normalized_housenumber(NEW.token_info);
1030
1031   NEW.postcode := null;
1032
1033   -- waterway ways are linked when they are part of a relation and have the same class/type
1034   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
1035 {% if db.middle_db_format == '1' %}
1036       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
1037       LOOP
1038           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
1039               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
1040                 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
1041                 FOR linked_node_id IN SELECT place_id FROM placex
1042                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
1043                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
1044                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
1045                 LOOP
1046                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1047                   {% if 'search_name' in db.tables %}
1048                     IF OLD.indexed_status > 1 THEN
1049                       DELETE FROM search_name WHERE place_id = linked_node_id;
1050                     END IF;
1051                   {% endif %}
1052                 END LOOP;
1053               END IF;
1054           END LOOP;
1055       END LOOP;
1056 {% else %}
1057     FOR relation_member IN
1058       SELECT value FROM planet_osm_rels r, LATERAL jsonb_array_elements(r.members)
1059       WHERE r.id = NEW.osm_id
1060     LOOP
1061       IF relation_member->>'role' IN ('', 'main_stream', 'side_stream')
1062          and relation_member->>'type' = 'W'
1063       THEN
1064         {% if debug %}RAISE WARNING 'waterway parent %, child %', NEW.osm_id, relation_member;{% endif %}
1065         FOR linked_node_id IN
1066           SELECT place_id FROM placex
1067           WHERE osm_type = 'W' and osm_id = (relation_member->>'ref')::bigint
1068                 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
1069                 and (relation_member->>'role' != 'side_stream' or NEW.name->'name' = name->'name')
1070         LOOP
1071           UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1072           {% if 'search_name' in db.tables %}
1073             DELETE FROM search_name WHERE place_id = linked_node_id;
1074           {% endif %}
1075         END LOOP;
1076       END IF;
1077     END LOOP;
1078 {% endif %}
1079       {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
1080   END IF;
1081
1082   NEW.importance := null;
1083   SELECT wikipedia, importance
1084     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.rank_search, NEW.centroid)
1085     INTO NEW.wikipedia,NEW.importance;
1086
1087 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
1088
1089   -- ---------------------------------------------------------------------------
1090   -- For low level elements we inherit from our parent road
1091   IF NEW.rank_search > 27 THEN
1092
1093     {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1094     NEW.parent_place_id := null;
1095     is_place_address := not token_is_street_address(NEW.token_info);
1096
1097     -- We have to find our parent road.
1098     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
1099                                                NEW.partition,
1100                                                ST_Envelope(NEW.geometry),
1101                                                NEW.token_info,
1102                                                is_place_address);
1103
1104     -- If we found the road take a shortcut here.
1105     -- Otherwise fall back to the full address getting method below.
1106     IF NEW.parent_place_id is not null THEN
1107
1108       -- Get the details of the parent road
1109       SELECT p.country_code, p.postcode, p.name FROM placex p
1110        WHERE p.place_id = NEW.parent_place_id INTO location;
1111
1112       IF is_place_address and NEW.address ? 'place' THEN
1113         -- Check if the addr:place tag is part of the parent name
1114         SELECT count(*) INTO i
1115           FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
1116         IF i = 0 THEN
1117           NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1118         END IF;
1119       END IF;
1120
1121       NEW.country_code := location.country_code;
1122       {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1123
1124       -- determine postcode
1125       NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1126                                location.postcode,
1127                                get_nearest_postcode(NEW.country_code, NEW.centroid));
1128
1129       IF NEW.name is not NULL THEN
1130           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1131       END IF;
1132
1133       {% if not db.reverse_only %}
1134       IF NEW.name is not NULL OR NEW.address is not NULL THEN
1135         SELECT * INTO name_vector, nameaddress_vector
1136           FROM create_poi_search_terms(NEW.place_id,
1137                                        NEW.partition, NEW.parent_place_id,
1138                                        is_place_address, NEW.country_code,
1139                                        NEW.token_info, NEW.centroid);
1140
1141         IF array_length(name_vector, 1) is not NULL THEN
1142           INSERT INTO search_name (place_id, search_rank, address_rank,
1143                                    importance, country_code, name_vector,
1144                                    nameaddress_vector, centroid)
1145                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1146                          NEW.importance, NEW.country_code, name_vector,
1147                          nameaddress_vector, NEW.centroid);
1148           {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1149         END IF;
1150       END IF;
1151       {% endif %}
1152
1153       NEW.token_info := token_strip_info(NEW.token_info);
1154
1155       RETURN NEW;
1156     END IF;
1157
1158   END IF;
1159
1160   -- ---------------------------------------------------------------------------
1161   -- Full indexing
1162   {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1163   IF linked_place is not null THEN
1164     -- Recompute the ranks here as the ones from the linked place might
1165     -- have been shifted to accommodate surrounding boundaries.
1166     SELECT place_id, osm_id, class, type, extratags, rank_search,
1167            centroid, geometry,
1168            (compute_place_rank(country_code, osm_type, class, type, admin_level,
1169                               (extratags->'capital') = 'yes', null)).*
1170       INTO location
1171       FROM placex WHERE place_id = linked_place;
1172
1173     {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1174
1175     -- Use the linked point as the centre point of the geometry,
1176     -- but only if it is within the area of the boundary.
1177     geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1178     IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1179         NEW.centroid := geom;
1180     END IF;
1181
1182     {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1183     IF location.address_rank > parent_address_level
1184        and location.address_rank < 26
1185     THEN
1186       NEW.rank_address := location.address_rank;
1187     END IF;
1188
1189     -- merge in extra tags
1190     NEW.extratags := hstore('linked_' || location.class, location.type)
1191                      || coalesce(location.extratags, ''::hstore)
1192                      || coalesce(NEW.extratags, ''::hstore);
1193
1194     -- mark the linked place (excludes from search results)
1195     -- Force reindexing to remove any traces from the search indexes and
1196     -- reset the address rank if necessary.
1197     UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1198       WHERE place_id = location.place_id;
1199
1200     SELECT wikipedia, importance
1201       FROM compute_importance(location.extratags, NEW.country_code,
1202                               location.rank_search, NEW.centroid)
1203       INTO linked_wikipedia,linked_importance;
1204
1205     -- Use the maximum importance if one could be computed from the linked object.
1206     IF linked_importance is not null AND
1207        (NEW.importance is null or NEW.importance < linked_importance)
1208     THEN
1209       NEW.importance := linked_importance;
1210     END IF;
1211   ELSE
1212     -- No linked place? As a last resort check if the boundary is tagged with
1213     -- a place type and adapt the rank address.
1214     IF NEW.rank_address between 4 and 25 and NEW.extratags ? 'place' THEN
1215       SELECT address_rank INTO place_address_level
1216         FROM compute_place_rank(NEW.country_code, 'A', 'place',
1217                                 NEW.extratags->'place', 0::SMALLINT, False, null);
1218       IF place_address_level > parent_address_level and
1219          place_address_level < 26 THEN
1220         NEW.rank_address := place_address_level;
1221       END IF;
1222     END IF;
1223   END IF;
1224
1225   {% if not disable_diff_updates %}
1226   IF OLD.rank_address != NEW.rank_address THEN
1227     -- After a rank shift all addresses containing us must be updated.
1228     UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1229       WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1230             and p.indexed_status = 0 and p.rank_address between 4 and 25;
1231   END IF;
1232   {% endif %}
1233
1234   IF NEW.admin_level = 2
1235      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1236      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1237   THEN
1238     -- Update the list of country names.
1239     -- Only take the name from the largest area for the given country code
1240     -- in the hope that this is the authoritative one.
1241     -- Also replace any old names so that all mapping mistakes can
1242     -- be fixed through regular OSM updates.
1243     FOR location IN
1244       SELECT osm_id FROM placex
1245        WHERE rank_search = 4 and osm_type = 'R'
1246              and country_code = NEW.country_code
1247        ORDER BY ST_Area(geometry) desc
1248        LIMIT 1
1249     LOOP
1250       IF location.osm_id = NEW.osm_id THEN
1251         {% if debug %}RAISE WARNING 'Updating names for country ''%'' with: %', NEW.country_code, NEW.name;{% endif %}
1252         UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1253       END IF;
1254     END LOOP;
1255   END IF;
1256
1257   -- For linear features we need the full geometry for determining the address
1258   -- because they may go through several administrative entities. Otherwise use
1259   -- the centroid for performance reasons.
1260   IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1261     geom := NEW.geometry;
1262   ELSE
1263     geom := NEW.centroid;
1264   END IF;
1265
1266   IF NEW.rank_address = 0 THEN
1267     max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1268     -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1269     -- so use the geometry here too. Just make sure the areas don't become too
1270     -- large.
1271     IF NEW.class = 'natural' or max_rank > 10 THEN
1272       geom := NEW.geometry;
1273     END IF;
1274   ELSEIF NEW.rank_address > 25 THEN
1275     max_rank := 25;
1276   ELSE
1277     max_rank := NEW.rank_address;
1278   END IF;
1279
1280   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1281                                     NEW.token_info, geom, NEW.centroid,
1282                                     NEW.country_code)
1283     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1284
1285   {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1286
1287   NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1288
1289   -- if we have a name add this to the name search table
1290   name_vector := token_get_name_search_tokens(NEW.token_info);
1291   IF array_length(name_vector, 1) is not NULL THEN
1292     -- Initialise the name vector using our name
1293     NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1294
1295     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1296       result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1297                              name_vector, NEW.rank_search, NEW.rank_address,
1298                              NEW.postcode, NEW.geometry, NEW.centroid);
1299       {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1300     END IF;
1301
1302     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1303       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1304       {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1305     END IF;
1306
1307     IF NEW.rank_address between 16 and 27 THEN
1308       result := insertSearchName(NEW.partition, NEW.place_id,
1309                                  token_get_name_match_tokens(NEW.token_info),
1310                                  NEW.rank_search, NEW.rank_address, NEW.geometry);
1311     END IF;
1312     {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1313
1314     {% if not db.reverse_only %}
1315         INSERT INTO search_name (place_id, search_rank, address_rank,
1316                                  importance, country_code, name_vector,
1317                                  nameaddress_vector, centroid)
1318                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1319                        NEW.importance, NEW.country_code, name_vector,
1320                        nameaddress_vector, NEW.centroid);
1321     {% endif %}
1322   END IF;
1323
1324   IF NEW.postcode is null AND NEW.rank_search > 8
1325      AND (NEW.rank_address > 0
1326           OR ST_GeometryType(NEW.geometry) not in ('ST_LineString','ST_MultiLineString')
1327           OR ST_Length(NEW.geometry) < 0.02)
1328   THEN
1329     NEW.postcode := get_nearest_postcode(NEW.country_code,
1330                                          CASE WHEN NEW.rank_address > 25
1331                                               THEN NEW.centroid ELSE NEW.geometry END);
1332   END IF;
1333
1334   {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1335
1336   NEW.token_info := token_strip_info(NEW.token_info);
1337   RETURN NEW;
1338 END;
1339 $$
1340 LANGUAGE plpgsql;
1341
1342
1343 CREATE OR REPLACE FUNCTION placex_delete()
1344   RETURNS TRIGGER
1345   AS $$
1346 DECLARE
1347   b BOOLEAN;
1348   classtable TEXT;
1349 BEGIN
1350   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1351
1352   IF OLD.linked_place_id is null THEN
1353     UPDATE placex
1354       SET linked_place_id = NULL,
1355           indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
1356       WHERE linked_place_id = OLD.place_id;
1357   ELSE
1358     update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1359   END IF;
1360
1361   IF OLD.rank_address < 30 THEN
1362
1363     -- mark everything linked to this place for re-indexing
1364     {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1365     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1366       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1367
1368     {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1369     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1370
1371     {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1372     b := deleteRoad(OLD.partition, OLD.place_id);
1373
1374     {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1375     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1376     {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1377     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1378     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1379
1380     UPDATE location_postcodes SET indexed_status = 2 WHERE parent_place_id = OLD.place_id;
1381   END IF;
1382
1383   {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1384
1385   IF OLD.rank_address < 26 THEN
1386     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1387   END IF;
1388
1389   {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1390
1391   IF OLD.name is not null THEN
1392     {% if 'search_name' in db.tables %}
1393       DELETE from search_name WHERE place_id = OLD.place_id;
1394     {% endif %}
1395     b := deleteSearchName(OLD.partition, OLD.place_id);
1396   END IF;
1397
1398   {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1399
1400   DELETE FROM place_addressline where place_id = OLD.place_id;
1401
1402   {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1403
1404   -- remove from tables for special search
1405   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1406   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1407   IF b THEN
1408     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1409   END IF;
1410
1411   {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1412   RETURN OLD;
1413
1414 END;
1415 $$
1416 LANGUAGE plpgsql;