1 -- SPDX-License-Identifier: GPL-2.0-only
3 -- This file is part of Nominatim. (https://nominatim.org)
5 -- Copyright (C) 2026 by the Nominatim developer community.
6 -- For a full list of authors see the git log.
8 -- Trigger functions for the placex table.
10 -- Information returned by update preparation.
11 DROP TYPE IF EXISTS prepare_update_info CASCADE;
12 CREATE TYPE prepare_update_info AS (
15 rank_address SMALLINT,
19 linked_place_id BIGINT,
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
30 result prepare_update_info;
32 default_language VARCHAR(10);
34 IF not p.address ? '_inherited' THEN
35 result.address := p.address;
38 -- For POI nodes, check if the address should be derived from a surrounding
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
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')
53 -- See if we can inherit additional address tags from an interpolation.
54 -- These will become permanent.
56 SELECT address FROM place_interpolation
57 WHERE ARRAY[p.osm_id] && place_interpolation.nodes AND address is not NULL
59 result.address := location.address || result.address;
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 '\_%';
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);
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);
80 IF location.place_id is not NULL THEN
81 result.linked_place_id := location.place_id;
83 IF location.name is not NULL THEN
84 {% if debug %}RAISE WARNING 'Names original: %, location: %', result.name, location.name;{% endif %}
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');
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))
98 FROM each(location.name);
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 %}
104 IF extra_names is not null THEN
105 result.name := result.name || extra_names;
109 {% if debug %}RAISE WARNING 'Final names: %', result.name;{% endif %}
116 LANGUAGE plpgsql STABLE PARALLEL SAFE;
119 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
131 -- Use UNION of two queries (one for Ways, one for Relations) to allow
132 -- PostgreSQL to use partial indexes on placex.osm_type.
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'
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'
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'
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'
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;
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;
182 LANGUAGE plpgsql STABLE PARALLEL SAFE;
185 -- Find the parent road of a POI.
187 -- \returns Place ID of parent object or NULL if none
189 -- Copy data from linked items (POIs on ways, addr:street links, relations).
191 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
193 poi_partition SMALLINT,
196 is_place_addr BOOLEAN)
200 parent_place_id BIGINT DEFAULT NULL;
203 {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
205 -- Is this object part of an associatedStreet relation?
206 parent_place_id := find_associated_street(poi_osm_type, poi_osm_id, bbox);
208 IF parent_place_id is null THEN
209 parent_place_id := find_parent_for_address(token_info, poi_partition, bbox);
212 IF parent_place_id is null and poi_osm_type = 'N' THEN
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)
221 {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
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;
229 parent_place_id := find_associated_street('W', location.osm_id, bbox);
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.
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
244 RETURN location.place_id;
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 %}
251 -- for larger features simply find the area with the largest rank that
252 -- contains the bbox, only use addressable features
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
260 RETURN location.place_id;
265 RETURN parent_place_id;
268 LANGUAGE plpgsql STABLE PARALLEL SAFE;
270 -- Try to find a linked place for the given object.
271 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
275 {% if db.middle_db_format == '1' %}
276 relation_members TEXT[];
278 relation_members JSONB;
281 linked_placex placex%ROWTYPE;
283 bnd_place_type ltree;
285 IF bnd.rank_search >= 26 or bnd.rank_address = 0
286 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
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 %}
296 -- Search for relation members with role 'lable'.
297 IF relation_members IS NOT NULL THEN
299 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
301 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
305 WHERE osm_type = 'N' and osm_id = rel_member.member
306 and categories <@ 'osm.place'
308 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
309 RETURN linked_placex;
316 IF bnd.name ? 'name' THEN
317 bnd_name := lower(bnd.name->'name');
318 IF bnd_name = '' THEN
323 IF bnd.extratags ? 'wikidata' THEN
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
334 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
335 RETURN linked_placex;
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
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)
357 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
358 RETURN linked_placex;
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 %}
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,
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)
383 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
384 RETURN linked_placex;
391 LANGUAGE plpgsql STABLE PARALLEL SAFE;
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,
401 OUT name_vector INTEGER[],
402 OUT nameaddress_vector INTEGER[])
405 parent_name_vector INTEGER[];
406 parent_address_vector INTEGER[];
407 addr_place_ids INTEGER[];
408 hnr_vector INTEGER[];
412 parent_address_place_ids BIGINT[];
414 nameaddress_vector := '{}'::INTEGER[];
416 SELECT s.name_vector, s.nameaddress_vector
417 INTO parent_name_vector, parent_address_vector
419 WHERE s.place_id = parent_place_id;
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
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);
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);
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;
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);
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);
455 name_vector := COALESCE(token_get_name_search_tokens(token_info), '{}'::INTEGER[]);
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.
462 hnr_vector := token_get_housenumber_search_tokens(token_info);
464 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
465 name_vector := array_merge(name_vector, hnr_vector);
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);
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
478 name_vector := array_merge(name_vector, hnr_vector);
480 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
487 -- Insert address of a place into the place_addressline table.
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.
496 -- \retval parent_place_id Place_id of the address object that is the direct
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,
511 OUT parent_place_id BIGINT,
513 OUT nameaddress_vector INT[])
516 address_havelevel BOOLEAN[];
517 place_min_distance FLOAT[];
519 location_isaddress BOOLEAN;
520 current_boundary GEOMETRY := NULL;
521 current_node_area GEOMETRY := NULL;
523 parent_place_rank INT := 0;
524 addr_place_ids BIGINT[] := '{}'::int[];
525 new_address_vector INT[];
529 parent_place_id := 0;
530 nameaddress_vector := '{}'::int[];
532 address_havelevel := array_fill(false, ARRAY[maxrank]);
533 place_min_distance := array_fill(1.0, ARRAY[maxrank]);
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
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,
551 {% if not db.reverse_only %}
552 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
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;
564 IF location.isguess and location.distance < place_min_distance[location.rank_address] THEN
565 place_min_distance[location.rank_address] := location.distance;
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);
573 addr_place_ids := addr_place_ids || location.place_id;
578 SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
579 WHERE not addr_place_ids @> ARRAY[place_id]
580 ORDER BY rank_address, isguess asc,
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
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);
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];
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];
600 IF location.distance < place_min_distance[location.rank_address] THEN
601 place_min_distance[location.rank_address] := location.distance;
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);
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);
616 IF location_isaddress THEN
617 address_havelevel[location.rank_address] := true;
618 parent_place_id := location.place_id;
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;
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);
632 current_node_area := NULL;
633 SELECT p.geometry FROM placex p
634 WHERE p.place_id = location.place_id INTO current_boundary;
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[]);
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);
657 CREATE OR REPLACE FUNCTION placex_insert()
663 country_code VARCHAR(2);
666 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
668 NEW.place_id := nextval('seq_place');
669 NEW.indexed_status := 1; --STATUS_NEW
671 NEW.centroid := get_center_point(NEW.geometry);
673 NEW.country_code := lower(get_country_code(NEW.centroid));
675 NEW.partition := get_partition(NEW.country_code);
676 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
678 IF NEW.osm_type = 'X' THEN
679 -- E'X'ternal records should already be in the right format so do nothing
681 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
683 IF NOT is_rankable_place(NEW.osm_type, NEW.categories, NEW.admin_level,
684 NEW.name, NEW.extratags, is_area)
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;
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);
708 IF NEW.importance IS NULL THEN
709 NEW.importance := 0.40001 - (NEW.rank_search::float / 75);
712 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
720 CREATE OR REPLACE FUNCTION placex_update()
726 {% if db.middle_db_format == '1' %}
727 relation_members TEXT[];
729 relation_member JSONB;
733 parent_address_level SMALLINT;
734 place_address_level SMALLINT;
738 name_vector INTEGER[];
739 nameaddress_vector INTEGER[];
740 addr_nameaddress_vector INTEGER[];
744 linked_node_id BIGINT;
745 linked_importance FLOAT;
746 linked_wikipedia TEXT;
748 is_place_address BOOLEAN;
750 bnd_place_type ltree;
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;
759 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
763 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
765 NEW.indexed_date = now();
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[(
773 || CASE WHEN NEW.class !~ '^[A-Za-z0-9_-]+$'
775 ELSE replace(NEW.class, '-', '_')
778 || CASE WHEN NEW.type = '' OR NEW.type !~ '^[A-Za-z0-9_-]+$'
780 ELSE replace(NEW.type, '-', '_')
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;
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);
795 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
796 IF NEW.extratags = ''::hstore THEN
797 NEW.extratags := NULL;
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
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);
813 -- Compute a preliminary centroid.
814 NEW.centroid := get_center_point(NEW.geometry);
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);
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
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);
834 IF NEW.rank_search >= 4 THEN
835 NEW.country_code := lower(get_country_code(NEW.centroid));
837 NEW.country_code := NULL;
839 NEW.partition := get_partition(NEW.country_code);
841 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
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
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 %}
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
866 -- First, check that admin boundaries do not overtake each other rank-wise.
867 parent_address_level := 3;
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
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
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;
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;
892 NEW.rank_address := location.rank_address + 2;
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.
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
913 NEW.rank_address := location.rank_address + 2;
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
920 -- For place areas make sure they are not completely contained in an area
921 -- with a equal or higher address rank.
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
935 NEW.rank_address := location.rank_address + 2;
937 ELSEIF NEW.categories <@ 'osm.place' and NEW.osm_type = 'N'
938 and NEW.rank_address between 16 and 23
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).
946 LATERAL compute_place_rank(country_code, 'A', categories,
947 admin_level, False, null) prank
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)
956 NEW.rank_address = NEW.rank_address + 2;
959 parent_address_level := 3;
962 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
963 NEW.postcode := null;
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[]
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')
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;
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
995 IF relation_member->>'role' IN ('', 'main_stream', 'side_stream')
996 and relation_member->>'type' = 'W'
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')
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;
1013 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
1016 SELECT wikipedia, importance INTO NEW.wikipedia, NEW.importance
1017 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.rank_search, NEW.centroid);
1019 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
1021 -- ---------------------------------------------------------------------------
1022 -- For low level elements we inherit from our parent road
1023 IF NEW.rank_search > 27 THEN
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);
1029 -- We have to find our parent road.
1030 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
1032 ST_Envelope(NEW.geometry),
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
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;
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';
1049 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1053 NEW.country_code := location.country_code;
1054 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1056 -- determine postcode
1057 NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1059 get_nearest_postcode(NEW.country_code, NEW.centroid));
1061 IF NEW.name is not NULL THEN
1062 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
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);
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 %}
1085 NEW.token_info := token_strip_info(NEW.token_info);
1092 -- ---------------------------------------------------------------------------
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)).*
1103 FROM placex WHERE place_id = linked_place;
1105 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
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;
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
1118 NEW.rank_address := location.address_rank;
1121 -- merge in extra tags
1122 NEW.extratags := hstore('linked_' || location.class, location.type)
1123 || coalesce(location.extratags, ''::hstore)
1124 || coalesce(NEW.extratags, ''::hstore);
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;
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;
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)
1141 NEW.importance := linked_importance;
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;
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;
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'
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.
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
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;
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;
1198 geom := NEW.centroid;
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
1206 IF NEW.categories <@ 'osm.natural' or max_rank > 10 THEN
1207 geom := NEW.geometry;
1209 ELSEIF NEW.rank_address > 25 THEN
1212 max_rank := NEW.rank_address;
1215 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1216 NEW.token_info, geom, NEW.centroid,
1218 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1220 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1222 NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
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);
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 %}
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 %}
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);
1247 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
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);
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)
1264 NEW.postcode := get_nearest_postcode(NEW.country_code,
1265 CASE WHEN NEW.rank_address > 25
1266 THEN NEW.centroid ELSE NEW.geometry END);
1269 {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1271 NEW.token_info := token_strip_info(NEW.token_info);
1278 CREATE OR REPLACE FUNCTION placex_delete()
1284 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1286 IF OLD.linked_place_id is null THEN
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;
1292 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1295 IF OLD.rank_address < 30 THEN
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;
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;
1305 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1306 b := deleteRoad(OLD.partition, OLD.place_id);
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;
1314 UPDATE location_postcodes SET indexed_status = 2 WHERE parent_place_id = OLD.place_id;
1317 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1319 IF OLD.rank_address < 26 THEN
1320 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1323 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
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;
1329 b := deleteSearchName(OLD.partition, OLD.place_id);
1332 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1334 DELETE FROM place_addressline where place_id = OLD.place_id;
1336 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1338 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}