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