]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/placex_triggers.sql
for postcodes use rank_search as base rank for finding addresses
[nominatim.git] / lib-sql / functions / placex_triggers.sql
1 -- SPDX-License-Identifier: GPL-2.0-only
2 --
3 -- This file is part of Nominatim. (https://nominatim.org)
4 --
5 -- Copyright (C) 2024 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;
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;
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;
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      or bnd.type IN ('postcode', 'postal_code')
308   THEN
309     RETURN NULL;
310   END IF;
311
312   IF bnd.osm_type = 'R' THEN
313     -- see if we have any special relation members
314     SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
315     {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
316
317     -- Search for relation members with role 'lable'.
318     IF relation_members IS NOT NULL THEN
319       FOR rel_member IN
320         SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
321       LOOP
322         {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
323
324         FOR linked_placex IN
325           SELECT * from placex
326           WHERE osm_type = 'N' and osm_id = rel_member.member
327             and class = 'place'
328         LOOP
329           {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
330           RETURN linked_placex;
331         END LOOP;
332
333       END LOOP;
334     END IF;
335   END IF;
336
337   IF bnd.name ? 'name' THEN
338     bnd_name := lower(bnd.name->'name');
339     IF bnd_name = '' THEN
340       bnd_name := NULL;
341     END IF;
342   END IF;
343
344   -- If extratags has a place tag, look for linked nodes by their place type.
345   -- Area and node still have to have the same name.
346   IF bnd.extratags ? 'place' and bnd.extratags->'place' != 'postcode'
347      and bnd_name is not null
348   THEN
349     FOR linked_placex IN
350       SELECT * FROM placex
351       WHERE (position(lower(name->'name') in bnd_name) > 0
352              OR position(bnd_name in lower(name->'name')) > 0)
353         AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
354         AND placex.osm_type = 'N'
355         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
356         AND placex.rank_search < 26 -- needed to select the right index
357         AND ST_Covers(bnd.geometry, placex.geometry)
358     LOOP
359       {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
360       RETURN linked_placex;
361     END LOOP;
362   END IF;
363
364   IF bnd.extratags ? 'wikidata' THEN
365     FOR linked_placex IN
366       SELECT * FROM placex
367       WHERE placex.class = 'place' AND placex.osm_type = 'N'
368         AND placex.extratags ? 'wikidata' -- needed to select right index
369         AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
370         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
371         AND placex.rank_search < 26
372         AND _st_covers(bnd.geometry, placex.geometry)
373       ORDER BY lower(name->'name') = bnd_name desc
374     LOOP
375       {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
376       RETURN linked_placex;
377     END LOOP;
378   END IF;
379
380   -- Name searches can be done for ways as well as relations
381   IF bnd_name is not null THEN
382     {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
383     FOR linked_placex IN
384       SELECT placex.* from placex
385       WHERE lower(name->'name') = bnd_name
386         AND ((bnd.rank_address > 0
387               and bnd.rank_address = (compute_place_rank(placex.country_code,
388                                                          'N', placex.class,
389                                                          placex.type, 15::SMALLINT,
390                                                          false, placex.postcode)).address_rank)
391              OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
392         AND placex.osm_type = 'N'
393         AND placex.class = 'place'
394         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
395         AND placex.rank_search < 26 -- needed to select the right index
396         AND placex.type != 'postcode'
397         AND ST_Covers(bnd.geometry, placex.geometry)
398     LOOP
399       {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
400       RETURN linked_placex;
401     END LOOP;
402   END IF;
403
404   RETURN NULL;
405 END;
406 $$
407 LANGUAGE plpgsql STABLE;
408
409
410 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
411                                                    in_partition SMALLINT,
412                                                    parent_place_id BIGINT,
413                                                    is_place_addr BOOLEAN,
414                                                    country TEXT,
415                                                    token_info JSONB,
416                                                    geometry GEOMETRY,
417                                                    OUT name_vector INTEGER[],
418                                                    OUT nameaddress_vector INTEGER[])
419   AS $$
420 DECLARE
421   parent_name_vector INTEGER[];
422   parent_address_vector INTEGER[];
423   addr_place_ids INTEGER[];
424   hnr_vector INTEGER[];
425
426   addr_item RECORD;
427   addr_place RECORD;
428   parent_address_place_ids BIGINT[];
429 BEGIN
430   nameaddress_vector := '{}'::INTEGER[];
431
432   SELECT s.name_vector, s.nameaddress_vector
433     INTO parent_name_vector, parent_address_vector
434     FROM search_name s
435     WHERE s.place_id = parent_place_id;
436
437   FOR addr_item IN
438     SELECT ranks.*, key,
439            token_get_address_search_tokens(token_info, key) as search_tokens
440       FROM token_get_address_keys(token_info) as key,
441            LATERAL get_addr_tag_rank(key, country) as ranks
442       WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
443   LOOP
444     addr_place := get_address_place(in_partition, geometry,
445                                     addr_item.from_rank, addr_item.to_rank,
446                                     addr_item.extent, token_info, addr_item.key);
447
448     IF addr_place is null THEN
449       -- No place found in OSM that matches. Make it at least searchable.
450       nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
451     ELSE
452       IF parent_address_place_ids is null THEN
453         SELECT array_agg(parent_place_id) INTO parent_address_place_ids
454           FROM place_addressline
455           WHERE place_id = parent_place_id;
456       END IF;
457
458       -- If the parent already lists the place in place_address line, then we
459       -- are done. Otherwise, add its own place_address line.
460       IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
461         nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
462
463         INSERT INTO place_addressline (place_id, address_place_id, fromarea,
464                                        isaddress, distance, cached_rank_address)
465           VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
466                     true, addr_place.distance, addr_place.rank_address);
467       END IF;
468     END IF;
469   END LOOP;
470
471   name_vector := token_get_name_search_tokens(token_info);
472
473   -- Check if the parent covers all address terms.
474   -- If not, create a search name entry with the house number as the name.
475   -- This is unusual for the search_name table but prevents that the place
476   -- is returned when we only search for the street/place.
477
478   hnr_vector := token_get_housenumber_search_tokens(token_info);
479
480   IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
481     name_vector := array_merge(name_vector, hnr_vector);
482   END IF;
483
484   IF is_place_addr THEN
485     addr_place_ids := token_addr_place_search_tokens(token_info);
486     IF not addr_place_ids <@ parent_name_vector THEN
487       -- make sure addr:place terms are always searchable
488       nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
489       -- If there is a housenumber, also add the place name as a name,
490       -- so we can search it by the usual housenumber+place algorithms.
491       IF hnr_vector is not null THEN
492         name_vector := array_merge(name_vector, addr_place_ids);
493       END IF;
494     END IF;
495   END IF;
496
497   -- Cheating here by not recomputing all terms but simply using the ones
498   -- from the parent object.
499   nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
500   nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
501
502 END;
503 $$
504 LANGUAGE plpgsql;
505
506
507 -- Insert address of a place into the place_addressline table.
508 --
509 -- \param obj_place_id  Place_id of the place to compute the address for.
510 -- \param partition     Partition number where the place is in.
511 -- \param maxrank       Rank of the place. All address features must have
512 --                      a search rank lower than the given rank.
513 -- \param address       Address terms for the place.
514 -- \param geometry      Geometry to which the address objects should be close.
515 --
516 -- \retval parent_place_id  Place_id of the address object that is the direct
517 --                          ancestor.
518 -- \retval postcode         Postcode computed from the address. This is the
519 --                          addr:postcode of one of the address objects. If
520 --                          more than one of has a postcode, the highest ranking
521 --                          one is used. May be NULL.
522 -- \retval nameaddress_vector  Search terms for the address. This is the sum
523 --                             of name terms of all address objects.
524 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
525                                                partition SMALLINT,
526                                                maxrank SMALLINT,
527                                                token_info JSONB,
528                                                geometry GEOMETRY,
529                                                centroid GEOMETRY,
530                                                country TEXT,
531                                                OUT parent_place_id BIGINT,
532                                                OUT postcode TEXT,
533                                                OUT nameaddress_vector INT[])
534   AS $$
535 DECLARE
536   address_havelevel BOOLEAN[];
537
538   location_isaddress BOOLEAN;
539   current_boundary GEOMETRY := NULL;
540   current_node_area GEOMETRY := NULL;
541
542   parent_place_rank INT := 0;
543   addr_place_ids BIGINT[] := '{}'::int[];
544   new_address_vector INT[];
545
546   location RECORD;
547 BEGIN
548   parent_place_id := 0;
549   nameaddress_vector := '{}'::int[];
550
551   address_havelevel := array_fill(false, ARRAY[maxrank]);
552
553   FOR location IN
554     SELECT apl.*, key
555       FROM (SELECT extra.*, key
556               FROM token_get_address_keys(token_info) as key,
557                    LATERAL get_addr_tag_rank(key, country) as extra) x,
558            LATERAL get_address_place(partition, geometry, from_rank, to_rank,
559                               extent, token_info, key) as apl
560       ORDER BY rank_address, distance, isguess desc
561   LOOP
562     IF location.place_id is null THEN
563       {% if not db.reverse_only %}
564       nameaddress_vector := array_merge(nameaddress_vector,
565                                         token_get_address_search_tokens(token_info,
566                                                                         location.key));
567       {% endif %}
568     ELSE
569       {% if not db.reverse_only %}
570       nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
571       {% endif %}
572
573       location_isaddress := not address_havelevel[location.rank_address];
574       IF not address_havelevel[location.rank_address] THEN
575         address_havelevel[location.rank_address] := true;
576         IF parent_place_rank < location.rank_address THEN
577           parent_place_id := location.place_id;
578           parent_place_rank := location.rank_address;
579         END IF;
580       END IF;
581
582       INSERT INTO place_addressline (place_id, address_place_id, fromarea,
583                                      isaddress, distance, cached_rank_address)
584         VALUES (obj_place_id, location.place_id, not location.isguess,
585                 true, location.distance, location.rank_address);
586
587       addr_place_ids := addr_place_ids || location.place_id;
588     END IF;
589   END LOOP;
590
591   FOR location IN
592     SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
593     WHERE not addr_place_ids @> ARRAY[place_id]
594     ORDER BY rank_address, isguess asc,
595              distance *
596                CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
597                     WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
598                     WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
599                     ELSE 1 END ASC
600   LOOP
601     -- Ignore all place nodes that do not fit in a lower level boundary.
602     CONTINUE WHEN location.isguess
603                   and current_boundary is not NULL
604                   and not ST_Contains(current_boundary, location.centroid);
605
606     -- If this is the first item in the rank, then assume it is the address.
607     location_isaddress := not address_havelevel[location.rank_address];
608
609     -- Further sanity checks to ensure that the address forms a sane hierarchy.
610     IF location_isaddress THEN
611       IF location.isguess and current_node_area is not NULL THEN
612         location_isaddress := ST_Contains(current_node_area, location.centroid);
613       END IF;
614       IF not location.isguess and current_boundary is not NULL
615          and location.rank_address != 11 AND location.rank_address != 5 THEN
616         location_isaddress := ST_Contains(current_boundary, location.centroid);
617       END IF;
618     END IF;
619
620     IF location_isaddress THEN
621       address_havelevel[location.rank_address] := true;
622       parent_place_id := location.place_id;
623
624       -- Set postcode if we have one.
625       -- (Returned will be the highest ranking one.)
626       IF location.postcode is not NULL THEN
627         postcode = location.postcode;
628       END IF;
629
630       -- Recompute the areas we need for hierarchy sanity checks.
631       IF location.rank_address != 11 AND location.rank_address != 5 THEN
632         IF location.isguess THEN
633           current_node_area := place_node_fuzzy_area(location.centroid,
634                                                      location.rank_search);
635         ELSE
636           current_node_area := NULL;
637           SELECT p.geometry FROM placex p
638               WHERE p.place_id = location.place_id INTO current_boundary;
639         END IF;
640       END IF;
641     END IF;
642
643     -- Add it to the list of search terms
644     {% if not db.reverse_only %}
645       nameaddress_vector := array_merge(nameaddress_vector,
646                                         location.keywords::integer[]);
647     {% endif %}
648
649     INSERT INTO place_addressline (place_id, address_place_id, fromarea,
650                                      isaddress, distance, cached_rank_address)
651         VALUES (obj_place_id, location.place_id, not location.isguess,
652                 location_isaddress, location.distance, location.rank_address);
653   END LOOP;
654 END;
655 $$
656 LANGUAGE plpgsql;
657
658
659 CREATE OR REPLACE FUNCTION placex_insert()
660   RETURNS TRIGGER
661   AS $$
662 DECLARE
663   postcode TEXT;
664   result BOOLEAN;
665   is_area BOOLEAN;
666   country_code VARCHAR(2);
667   diameter FLOAT;
668   classtable TEXT;
669 BEGIN
670   {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
671
672   NEW.place_id := nextval('seq_place');
673   NEW.indexed_status := 1; --STATUS_NEW
674
675   NEW.centroid := ST_PointOnSurface(NEW.geometry);
676   NEW.country_code := lower(get_country_code(NEW.centroid));
677
678   NEW.partition := get_partition(NEW.country_code);
679   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
680
681   IF NEW.osm_type = 'X' THEN
682     -- E'X'ternal records should already be in the right format so do nothing
683   ELSE
684     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
685
686     IF NEW.class in ('place','boundary')
687        AND NEW.type in ('postcode','postal_code')
688     THEN
689       IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
690           -- most likely just a part of a multipolygon postcode boundary, throw it away
691           RETURN NULL;
692       END IF;
693
694       NEW.name := hstore('ref', NEW.address->'postcode');
695
696     ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
697            AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
698     THEN
699         RETURN NULL;
700     ELSEIF NEW.class = 'boundary' AND NOT is_area
701     THEN
702         RETURN NULL;
703     ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
704            AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
705     THEN
706         RETURN NULL;
707     END IF;
708
709     SELECT * INTO NEW.rank_search, NEW.rank_address
710       FROM compute_place_rank(NEW.country_code,
711                               CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
712                               NEW.class, NEW.type, NEW.admin_level,
713                               (NEW.extratags->'capital') = 'yes',
714                               NEW.address->'postcode');
715
716     -- a country code make no sense below rank 4 (country)
717     IF NEW.rank_search < 4 THEN
718       NEW.country_code := NULL;
719     END IF;
720
721     -- Simplify polygons with a very large memory footprint when they
722     -- do not take part in address computation.
723     IF NEW.rank_address = 0 THEN
724       NEW.geometry := simplify_large_polygons(NEW.geometry);
725     END IF;
726
727   END IF;
728
729   {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
730
731 {% if not disable_diff_updates %}
732   -- The following is not needed until doing diff updates, and slows the main index process down
733
734   IF NEW.rank_address > 0 THEN
735     IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
736       -- Performance: We just can't handle re-indexing for country level changes
737       IF st_area(NEW.geometry) < 1 THEN
738         -- mark items within the geometry for re-indexing
739   --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
740
741         UPDATE placex SET indexed_status = 2
742          WHERE ST_Intersects(NEW.geometry, placex.geometry)
743                and indexed_status = 0
744                and ((rank_address = 0 and rank_search > NEW.rank_address)
745                     or rank_address > NEW.rank_address
746                     or (class = 'place' and osm_type = 'N')
747                    )
748                and (rank_search < 28
749                     or name is not null
750                     or (NEW.rank_address >= 16 and address ? 'place'));
751       END IF;
752     ELSE
753       -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
754       diameter := update_place_diameter(NEW.rank_search);
755       IF diameter > 0 THEN
756   --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
757         IF NEW.rank_search >= 26 THEN
758           -- roads may cause reparenting for >27 rank places
759           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
760           -- reparenting also for OSM Interpolation Lines (and for Tiger?)
761           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);
762         ELSEIF NEW.rank_search >= 16 THEN
763           -- up to rank 16, street-less addresses may need reparenting
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) and (rank_search < 28 or name is not null or address ? 'place');
765         ELSE
766           -- for all other places the search terms may change as well
767           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);
768         END IF;
769       END IF;
770     END IF;
771   END IF;
772
773
774    -- add to tables for special search
775    -- Note: won't work on initial import because the classtype tables
776    -- do not yet exist. It won't hurt either.
777   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
778   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
779   IF result THEN
780     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
781     USING NEW.place_id, ST_Centroid(NEW.geometry);
782   END IF;
783
784 {% endif %} -- not disable_diff_updates
785
786   RETURN NEW;
787
788 END;
789 $$
790 LANGUAGE plpgsql;
791
792 CREATE OR REPLACE FUNCTION placex_update()
793   RETURNS TRIGGER
794   AS $$
795 DECLARE
796   i INTEGER;
797   location RECORD;
798 {% if db.middle_db_format == '1' %}
799   relation_members TEXT[];
800 {% else %}
801   relation_member JSONB;
802 {% endif %}
803
804   geom GEOMETRY;
805   parent_address_level SMALLINT;
806   place_address_level SMALLINT;
807
808   max_rank SMALLINT;
809
810   name_vector INTEGER[];
811   nameaddress_vector INTEGER[];
812   addr_nameaddress_vector INTEGER[];
813
814   linked_place BIGINT;
815
816   linked_node_id BIGINT;
817   linked_importance FLOAT;
818   linked_wikipedia TEXT;
819
820   is_place_address BOOLEAN;
821   result BOOLEAN;
822 BEGIN
823   -- deferred delete
824   IF OLD.indexed_status = 100 THEN
825     {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
826     delete from placex where place_id = OLD.place_id;
827     RETURN NULL;
828   END IF;
829
830   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
831     RETURN NEW;
832   END IF;
833
834   {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
835
836   NEW.indexed_date = now();
837
838   {% if 'search_name' in db.tables %}
839     DELETE from search_name WHERE place_id = NEW.place_id;
840   {% endif %}
841   result := deleteSearchName(NEW.partition, NEW.place_id);
842   DELETE FROM place_addressline WHERE place_id = NEW.place_id;
843   result := deleteRoad(NEW.partition, NEW.place_id);
844   result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
845
846   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
847   IF NEW.extratags = ''::hstore THEN
848     NEW.extratags := NULL;
849   END IF;
850
851   -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
852   -- the previous link status.
853   linked_place := NEW.linked_place_id;
854   NEW.linked_place_id := OLD.linked_place_id;
855
856   -- Remove linkage, if we have computed a different new linkee.
857   UPDATE placex SET linked_place_id = null, indexed_status = 2
858     WHERE linked_place_id = NEW.place_id
859           and (linked_place is null or linked_place_id != linked_place);
860   -- update not necessary for osmline, cause linked_place_id does not exist
861
862   -- Postcodes are just here to compute the centroids. They are not searchable
863   -- unless they are a boundary=postal_code.
864   -- There was an error in the style so that boundary=postal_code used to be
865   -- imported as place=postcode. That's why relations are allowed to pass here.
866   -- This can go away in a couple of versions.
867   IF NEW.class = 'place'  and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
868     NEW.token_info := null;
869     RETURN NEW;
870   END IF;
871
872   -- Compute a preliminary centroid.
873   NEW.centroid := ST_PointOnSurface(NEW.geometry);
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 geometry && NEW.geometry
964                 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
965                 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
966           ORDER BY prank.address_rank desc LIMIT 1
967         LOOP
968           NEW.rank_address := location.rank_address + 2;
969         END LOOP;
970     END IF;
971   ELSEIF NEW.class = 'place'
972          and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
973          and NEW.rank_address between 16 and 23
974   THEN
975     -- For place areas make sure they are not completely contained in an area
976     -- with a equal or higher address rank.
977     FOR location IN
978           SELECT rank_address
979           FROM placex,
980                LATERAL compute_place_rank(country_code, 'A', class, type,
981                                           admin_level, False, null) prank
982           WHERE prank.address_rank < 24
983                 and rank_address between 1 and 25 -- select right index
984                 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
985                 and prank.address_rank >= NEW.rank_address
986                 and geometry && NEW.geometry
987                 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
988                 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
989           ORDER BY prank.address_rank desc LIMIT 1
990         LOOP
991           NEW.rank_address := location.rank_address + 2;
992         END LOOP;
993   ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
994          and NEW.rank_address between 16 and 23
995   THEN
996     -- If a place node is contained in an admin or place boundary with the same
997     -- address level and has not been linked, then make the node a subpart
998     -- by increasing the address rank (city level and above).
999     FOR location IN
1000         SELECT rank_address
1001         FROM placex,
1002              LATERAL compute_place_rank(country_code, 'A', class, type,
1003                                         admin_level, False, null) prank
1004         WHERE osm_type = 'R'
1005               and rank_address between 1 and 25 -- select right index
1006               and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
1007               and ((class = 'place' and prank.address_rank = NEW.rank_address)
1008                    or (class = 'boundary' and rank_address = NEW.rank_address))
1009               and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
1010         LIMIT 1
1011     LOOP
1012       NEW.rank_address = NEW.rank_address + 2;
1013     END LOOP;
1014   ELSE
1015     parent_address_level := 3;
1016   END IF;
1017
1018   NEW.housenumber := token_normalized_housenumber(NEW.token_info);
1019
1020   NEW.postcode := null;
1021
1022   -- waterway ways are linked when they are part of a relation and have the same class/type
1023   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
1024 {% if db.middle_db_format == '1' %}
1025       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
1026       LOOP
1027           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
1028               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
1029                 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
1030                 FOR linked_node_id IN SELECT place_id FROM placex
1031                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
1032                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
1033                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
1034                 LOOP
1035                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1036                   {% if 'search_name' in db.tables %}
1037                     DELETE FROM search_name WHERE place_id = linked_node_id;
1038                   {% endif %}
1039                 END LOOP;
1040               END IF;
1041           END LOOP;
1042       END LOOP;
1043 {% else %}
1044     FOR relation_member IN
1045       SELECT value FROM planet_osm_rels r, LATERAL jsonb_array_elements(r.members)
1046       WHERE r.id = NEW.osm_id
1047     LOOP
1048       IF relation_member->>'role' IN ('', 'main_stream', 'side_stream')
1049          and relation_member->>'type' = 'W'
1050       THEN
1051         {% if debug %}RAISE WARNING 'waterway parent %, child %', NEW.osm_id, relation_member;{% endif %}
1052         FOR linked_node_id IN
1053           SELECT place_id FROM placex
1054           WHERE osm_type = 'W' and osm_id = (relation_member->>'ref')::bigint
1055                 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
1056                 and (relation_member->>'role' != 'side_stream' or NEW.name->'name' = name->'name')
1057         LOOP
1058           UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1059           {% if 'search_name' in db.tables %}
1060             DELETE FROM search_name WHERE place_id = linked_node_id;
1061           {% endif %}
1062         END LOOP;
1063       END IF;
1064     END LOOP;
1065 {% endif %}
1066       {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
1067   END IF;
1068
1069   NEW.importance := null;
1070   SELECT wikipedia, importance
1071     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.rank_search, NEW.centroid)
1072     INTO NEW.wikipedia,NEW.importance;
1073
1074 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
1075
1076   -- ---------------------------------------------------------------------------
1077   -- For low level elements we inherit from our parent road
1078   IF NEW.rank_search > 27 THEN
1079
1080     {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1081     NEW.parent_place_id := null;
1082     is_place_address := not token_is_street_address(NEW.token_info);
1083
1084     -- We have to find our parent road.
1085     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
1086                                                NEW.partition,
1087                                                ST_Envelope(NEW.geometry),
1088                                                NEW.token_info,
1089                                                is_place_address);
1090
1091     -- If we found the road take a shortcut here.
1092     -- Otherwise fall back to the full address getting method below.
1093     IF NEW.parent_place_id is not null THEN
1094
1095       -- Get the details of the parent road
1096       SELECT p.country_code, p.postcode, p.name FROM placex p
1097        WHERE p.place_id = NEW.parent_place_id INTO location;
1098
1099       IF is_place_address and NEW.address ? 'place' THEN
1100         -- Check if the addr:place tag is part of the parent name
1101         SELECT count(*) INTO i
1102           FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
1103         IF i = 0 THEN
1104           NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1105         END IF;
1106       END IF;
1107
1108       NEW.country_code := location.country_code;
1109       {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1110
1111       -- determine postcode
1112       NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1113                                location.postcode,
1114                                get_nearest_postcode(NEW.country_code, NEW.centroid));
1115
1116       IF NEW.name is not NULL THEN
1117           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1118       END IF;
1119
1120       {% if not db.reverse_only %}
1121       IF NEW.name is not NULL OR NEW.address is not NULL THEN
1122         SELECT * INTO name_vector, nameaddress_vector
1123           FROM create_poi_search_terms(NEW.place_id,
1124                                        NEW.partition, NEW.parent_place_id,
1125                                        is_place_address, NEW.country_code,
1126                                        NEW.token_info, NEW.centroid);
1127
1128         IF array_length(name_vector, 1) is not NULL THEN
1129           INSERT INTO search_name (place_id, search_rank, address_rank,
1130                                    importance, country_code, name_vector,
1131                                    nameaddress_vector, centroid)
1132                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1133                          NEW.importance, NEW.country_code, name_vector,
1134                          nameaddress_vector, NEW.centroid);
1135           {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1136         END IF;
1137       END IF;
1138       {% endif %}
1139
1140       NEW.token_info := token_strip_info(NEW.token_info);
1141
1142       RETURN NEW;
1143     END IF;
1144
1145   END IF;
1146
1147   -- ---------------------------------------------------------------------------
1148   -- Full indexing
1149   {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1150   IF linked_place is not null THEN
1151     -- Recompute the ranks here as the ones from the linked place might
1152     -- have been shifted to accommodate surrounding boundaries.
1153     SELECT place_id, osm_id, class, type, extratags, rank_search,
1154            centroid, geometry,
1155            (compute_place_rank(country_code, osm_type, class, type, admin_level,
1156                               (extratags->'capital') = 'yes', null)).*
1157       INTO location
1158       FROM placex WHERE place_id = linked_place;
1159
1160     {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1161
1162     -- Use the linked point as the centre point of the geometry,
1163     -- but only if it is within the area of the boundary.
1164     geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1165     IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1166         NEW.centroid := geom;
1167     END IF;
1168
1169     {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1170     IF location.address_rank > parent_address_level
1171        and location.address_rank < 26
1172     THEN
1173       NEW.rank_address := location.address_rank;
1174     END IF;
1175
1176     -- merge in extra tags
1177     NEW.extratags := hstore('linked_' || location.class, location.type)
1178                      || coalesce(location.extratags, ''::hstore)
1179                      || coalesce(NEW.extratags, ''::hstore);
1180
1181     -- mark the linked place (excludes from search results)
1182     -- Force reindexing to remove any traces from the search indexes and
1183     -- reset the address rank if necessary.
1184     UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1185       WHERE place_id = location.place_id;
1186     -- ensure that those places are not found anymore
1187     {% if 'search_name' in db.tables %}
1188       DELETE FROM search_name WHERE place_id = location.place_id;
1189     {% endif %}
1190     PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
1191
1192     SELECT wikipedia, importance
1193       FROM compute_importance(location.extratags, NEW.country_code,
1194                               location.rank_search, NEW.centroid)
1195       INTO linked_wikipedia,linked_importance;
1196
1197     -- Use the maximum importance if one could be computed from the linked object.
1198     IF linked_importance is not null AND
1199        (NEW.importance is null or NEW.importance < linked_importance)
1200     THEN
1201       NEW.importance = linked_importance;
1202     END IF;
1203   ELSE
1204     -- No linked place? As a last resort check if the boundary is tagged with
1205     -- a place type and adapt the rank address.
1206     IF NEW.rank_address between 4 and 25 and NEW.extratags ? 'place' THEN
1207       SELECT address_rank INTO place_address_level
1208         FROM compute_place_rank(NEW.country_code, 'A', 'place',
1209                                 NEW.extratags->'place', 0::SMALLINT, False, null);
1210       IF place_address_level > parent_address_level and
1211          place_address_level < 26 THEN
1212         NEW.rank_address := place_address_level;
1213       END IF;
1214     END IF;
1215   END IF;
1216
1217   {% if not disable_diff_updates %}
1218   IF OLD.rank_address != NEW.rank_address THEN
1219     -- After a rank shift all addresses containing us must be updated.
1220     UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1221       WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1222             and p.indexed_status = 0 and p.rank_address between 4 and 25;
1223   END IF;
1224   {% endif %}
1225
1226   IF NEW.admin_level = 2
1227      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1228      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1229   THEN
1230     -- Update the list of country names.
1231     -- Only take the name from the largest area for the given country code
1232     -- in the hope that this is the authoritative one.
1233     -- Also replace any old names so that all mapping mistakes can
1234     -- be fixed through regular OSM updates.
1235     FOR location IN
1236       SELECT osm_id FROM placex
1237        WHERE rank_search = 4 and osm_type = 'R'
1238              and country_code = NEW.country_code
1239        ORDER BY ST_Area(geometry) desc
1240        LIMIT 1
1241     LOOP
1242       IF location.osm_id = NEW.osm_id THEN
1243         {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1244         UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1245       END IF;
1246     END LOOP;
1247   END IF;
1248
1249   -- For linear features we need the full geometry for determining the address
1250   -- because they may go through several administrative entities. Otherwise use
1251   -- the centroid for performance reasons.
1252   IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1253     geom := NEW.geometry;
1254   ELSE
1255     geom := NEW.centroid;
1256   END IF;
1257
1258   IF NEW.rank_address = 0 THEN
1259     max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1260     -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1261     -- so use the geometry here too. Just make sure the areas don't become too
1262     -- large.
1263     IF NEW.class = 'natural' or max_rank > 10 THEN
1264       geom := NEW.geometry;
1265     END IF;
1266   ELSEIF NEW.rank_address > 25 THEN
1267     max_rank := 25;
1268   ELSEIF NEW.class in ('place','boundary') and NEW.type in ('postcode','postal_code') THEN
1269     max_rank := NEW.rank_search;
1270   ELSE
1271     max_rank := NEW.rank_address;
1272   END IF;
1273
1274   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1275                                     NEW.token_info, geom, NEW.centroid,
1276                                     NEW.country_code)
1277     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1278
1279   {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1280
1281   NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1282
1283   -- if we have a name add this to the name search table
1284   IF NEW.name 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     name_vector := token_get_name_search_tokens(NEW.token_info);
1288
1289     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1290       result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1291                              name_vector, NEW.rank_search, NEW.rank_address,
1292                              NEW.postcode, NEW.geometry, NEW.centroid);
1293       {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1294     END IF;
1295
1296     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1297       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1298       {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1299     END IF;
1300
1301     IF NEW.rank_address between 16 and 27 THEN
1302       result := insertSearchName(NEW.partition, NEW.place_id,
1303                                  token_get_name_match_tokens(NEW.token_info),
1304                                  NEW.rank_search, NEW.rank_address, NEW.geometry);
1305     END IF;
1306     {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1307
1308     {% if not db.reverse_only %}
1309         INSERT INTO search_name (place_id, search_rank, address_rank,
1310                                  importance, country_code, name_vector,
1311                                  nameaddress_vector, centroid)
1312                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1313                        NEW.importance, NEW.country_code, name_vector,
1314                        nameaddress_vector, NEW.centroid);
1315     {% endif %}
1316   END IF;
1317
1318   IF NEW.postcode is null AND NEW.rank_search > 8
1319      AND (NEW.rank_address > 0
1320           OR ST_GeometryType(NEW.geometry) not in ('ST_LineString','ST_MultiLineString')
1321           OR ST_Length(NEW.geometry) < 0.02)
1322   THEN
1323     NEW.postcode := get_nearest_postcode(NEW.country_code,
1324                                          CASE WHEN NEW.rank_address > 25
1325                                               THEN NEW.centroid ELSE NEW.geometry END);
1326   END IF;
1327
1328   {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1329
1330   NEW.token_info := token_strip_info(NEW.token_info);
1331   RETURN NEW;
1332 END;
1333 $$
1334 LANGUAGE plpgsql;
1335
1336
1337 CREATE OR REPLACE FUNCTION placex_delete()
1338   RETURNS TRIGGER
1339   AS $$
1340 DECLARE
1341   b BOOLEAN;
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 set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1348     {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1349     update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1350     {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
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   END IF;
1375
1376   {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1377
1378   IF OLD.rank_address < 26 THEN
1379     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1380   END IF;
1381
1382   {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1383
1384   IF OLD.name is not null THEN
1385     {% if 'search_name' in db.tables %}
1386       DELETE from search_name WHERE place_id = OLD.place_id;
1387     {% endif %}
1388     b := deleteSearchName(OLD.partition, OLD.place_id);
1389   END IF;
1390
1391   {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1392
1393   DELETE FROM place_addressline where place_id = OLD.place_id;
1394
1395   {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1396
1397   -- remove from tables for special search
1398   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1399   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1400   IF b THEN
1401     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1402   END IF;
1403
1404   {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1405
1406   RETURN OLD;
1407
1408 END;
1409 $$
1410 LANGUAGE plpgsql;