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