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