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