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