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;
284 IF bnd.rank_search >= 26 or bnd.rank_address = 0
285 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
290 IF bnd.osm_type = 'R' THEN
291 -- see if we have any special relation members
292 SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
293 {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
295 -- Search for relation members with role 'lable'.
296 IF relation_members IS NOT NULL THEN
298 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
300 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
304 WHERE osm_type = 'N' and osm_id = rel_member.member
307 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
308 RETURN linked_placex;
315 IF bnd.name ? 'name' THEN
316 bnd_name := lower(bnd.name->'name');
317 IF bnd_name = '' THEN
322 IF bnd.extratags ? 'wikidata' THEN
325 WHERE placex.class = 'place' AND placex.osm_type = 'N'
326 AND placex.extratags ? 'wikidata' -- needed to select right index
327 AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
328 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
329 AND placex.rank_search < 26
330 AND _st_covers(bnd.geometry, placex.geometry)
331 ORDER BY lower(name->'name') = bnd_name desc
333 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
334 RETURN linked_placex;
338 -- If extratags has a place tag, look for linked nodes by their place type.
339 -- Area and node still have to have the same name.
340 IF bnd.extratags ? 'place' and bnd_name is not null
344 WHERE (position(lower(name->'name') in bnd_name) > 0
345 OR position(bnd_name in lower(name->'name')) > 0)
346 AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
347 AND placex.osm_type = 'N'
348 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
349 AND placex.rank_search < 26 -- needed to select the right index
350 AND (NOT placex.extratags ? 'wikidata' OR NOT bnd.extratags ? 'wikidata'
351 OR placex.extratags->'wikidata' = bnd.extratags->'wikidata')
352 AND ST_Covers(bnd.geometry, placex.geometry)
354 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
355 RETURN linked_placex;
359 -- Name searches can be done for ways as well as relations
360 IF bnd_name is not null THEN
361 {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
363 SELECT placex.* from placex
364 WHERE lower(name->'name') = bnd_name
365 AND ((bnd.rank_address > 0
366 and bnd.rank_address = (compute_place_rank(placex.country_code,
368 placex.type, 15::SMALLINT,
369 false, placex.postcode)).address_rank)
370 OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
371 AND placex.osm_type = 'N'
372 AND placex.class = 'place'
373 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
374 AND placex.rank_search < 26 -- needed to select the right index
375 AND (placex.extratags->'wikidata' is null OR bnd.extratags->'wikidata' is null
376 OR placex.extratags->'wikidata' = bnd.extratags->'wikidata')
377 AND ST_Covers(bnd.geometry, placex.geometry)
379 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
380 RETURN linked_placex;
387 LANGUAGE plpgsql STABLE PARALLEL SAFE;
390 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
391 in_partition SMALLINT,
392 parent_place_id BIGINT,
393 is_place_addr BOOLEAN,
397 OUT name_vector INTEGER[],
398 OUT nameaddress_vector INTEGER[])
401 parent_name_vector INTEGER[];
402 parent_address_vector INTEGER[];
403 addr_place_ids INTEGER[];
404 hnr_vector INTEGER[];
408 parent_address_place_ids BIGINT[];
410 nameaddress_vector := '{}'::INTEGER[];
412 SELECT s.name_vector, s.nameaddress_vector
413 INTO parent_name_vector, parent_address_vector
415 WHERE s.place_id = parent_place_id;
419 token_get_address_search_tokens(token_info, key) as search_tokens
420 FROM token_get_address_keys(token_info) as key,
421 LATERAL get_addr_tag_rank(key, country) as ranks
422 WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
424 addr_place := get_address_place(in_partition, geometry,
425 addr_item.from_rank, addr_item.to_rank,
426 addr_item.extent, token_info, addr_item.key);
428 IF addr_place is null THEN
429 -- No place found in OSM that matches. Make it at least searchable.
430 nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
432 IF parent_address_place_ids is null THEN
433 SELECT array_agg(parent_place_id) INTO parent_address_place_ids
434 FROM place_addressline
435 WHERE place_id = parent_place_id;
438 -- If the parent already lists the place in place_address line, then we
439 -- are done. Otherwise, add its own place_address line.
440 IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
441 nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
443 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
444 isaddress, distance, cached_rank_address)
445 VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
446 true, addr_place.distance, addr_place.rank_address);
451 name_vector := COALESCE(token_get_name_search_tokens(token_info), '{}'::INTEGER[]);
453 -- Check if the parent covers all address terms.
454 -- If not, create a search name entry with the house number as the name.
455 -- This is unusual for the search_name table but prevents that the place
456 -- is returned when we only search for the street/place.
458 hnr_vector := token_get_housenumber_search_tokens(token_info);
460 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
461 name_vector := array_merge(name_vector, hnr_vector);
464 -- Cheating here by not recomputing all terms but simply using the ones
465 -- from the parent object.
466 nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
467 nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
469 -- make sure addr:place terms are always searchable
470 IF is_place_addr THEN
471 addr_place_ids := token_addr_place_search_tokens(token_info);
472 IF hnr_vector is not null AND not addr_place_ids <@ parent_name_vector
474 name_vector := array_merge(name_vector, hnr_vector);
476 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
483 -- Insert address of a place into the place_addressline table.
485 -- \param obj_place_id Place_id of the place to compute the address for.
486 -- \param partition Partition number where the place is in.
487 -- \param maxrank Rank of the place. All address features must have
488 -- a search rank lower than the given rank.
489 -- \param address Address terms for the place.
490 -- \param geometry Geometry to which the address objects should be close.
492 -- \retval parent_place_id Place_id of the address object that is the direct
494 -- \retval postcode Postcode computed from the address. This is the
495 -- addr:postcode of one of the address objects. If
496 -- more than one of has a postcode, the highest ranking
497 -- one is used. May be NULL.
498 -- \retval nameaddress_vector Search terms for the address. This is the sum
499 -- of name terms of all address objects.
500 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
507 OUT parent_place_id BIGINT,
509 OUT nameaddress_vector INT[])
512 address_havelevel BOOLEAN[];
513 place_min_distance FLOAT[];
515 location_isaddress BOOLEAN;
516 current_boundary GEOMETRY := NULL;
517 current_node_area GEOMETRY := NULL;
519 parent_place_rank INT := 0;
520 addr_place_ids BIGINT[] := '{}'::int[];
521 new_address_vector INT[];
525 parent_place_id := 0;
526 nameaddress_vector := '{}'::int[];
528 address_havelevel := array_fill(false, ARRAY[maxrank]);
529 place_min_distance := array_fill(1.0, ARRAY[maxrank]);
533 FROM (SELECT extra.*, key
534 FROM token_get_address_keys(token_info) as key,
535 LATERAL get_addr_tag_rank(key, country) as extra) x,
536 LATERAL get_address_place(partition, geometry, from_rank, to_rank,
537 extent, token_info, key) as apl
538 ORDER BY rank_address, distance, isguess desc
540 IF location.place_id is null THEN
541 {% if not db.reverse_only %}
542 nameaddress_vector := array_merge(nameaddress_vector,
543 token_get_address_search_tokens(token_info,
547 {% if not db.reverse_only %}
548 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
551 location_isaddress := not address_havelevel[location.rank_address];
552 IF not address_havelevel[location.rank_address] THEN
553 address_havelevel[location.rank_address] := true;
554 IF parent_place_rank < location.rank_address THEN
555 parent_place_id := location.place_id;
556 parent_place_rank := location.rank_address;
560 IF location.isguess and location.distance < place_min_distance[location.rank_address] THEN
561 place_min_distance[location.rank_address] := location.distance;
564 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
565 isaddress, distance, cached_rank_address)
566 VALUES (obj_place_id, location.place_id, not location.isguess,
567 true, location.distance, location.rank_address);
569 addr_place_ids := addr_place_ids || location.place_id;
574 SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
575 WHERE not addr_place_ids @> ARRAY[place_id]
576 ORDER BY rank_address, isguess asc,
578 CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
579 WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
580 WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
583 -- Ignore all place nodes that do not fit in a lower level boundary.
584 CONTINUE WHEN location.isguess
585 and current_boundary is not NULL
586 and not ST_Contains(current_boundary, location.centroid);
588 -- If this is the first item in the rank, then assume it is the address.
589 location_isaddress := not address_havelevel[location.rank_address];
591 -- Ignore guessed places when they are too far away compared to similar closer ones.
592 IF location.isguess THEN
593 CONTINUE WHEN not location_isaddress
594 AND location.distance > 2 * place_min_distance[location.rank_address];
596 IF location.distance < place_min_distance[location.rank_address] THEN
597 place_min_distance[location.rank_address] := location.distance;
601 -- Further sanity checks to ensure that the address forms a sane hierarchy.
602 IF location_isaddress THEN
603 IF location.isguess and current_node_area is not NULL THEN
604 location_isaddress := ST_Contains(current_node_area, location.centroid);
606 IF not location.isguess and current_boundary is not NULL
607 and location.rank_address != 11 AND location.rank_address != 5 THEN
608 location_isaddress := ST_Contains(current_boundary, location.centroid);
612 IF location_isaddress THEN
613 address_havelevel[location.rank_address] := true;
614 parent_place_id := location.place_id;
616 -- Set postcode if we have one.
617 -- (Returned will be the highest ranking one.)
618 IF location.postcode is not NULL THEN
619 postcode = location.postcode;
622 -- Recompute the areas we need for hierarchy sanity checks.
623 IF location.rank_address != 11 AND location.rank_address != 5 THEN
624 IF location.isguess THEN
625 current_node_area := place_node_fuzzy_area(location.centroid,
626 location.rank_search);
628 current_node_area := NULL;
629 SELECT p.geometry FROM placex p
630 WHERE p.place_id = location.place_id INTO current_boundary;
635 -- Add it to the list of search terms
636 {% if not db.reverse_only %}
637 IF location.rank_address != 11 AND location.rank_address != 5 THEN
638 nameaddress_vector := array_merge(nameaddress_vector,
639 location.keywords::integer[]);
643 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
644 isaddress, distance, cached_rank_address)
645 VALUES (obj_place_id, location.place_id, not location.isguess,
646 location_isaddress, location.distance, location.rank_address);
653 CREATE OR REPLACE FUNCTION placex_insert()
660 country_code VARCHAR(2);
664 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
666 NEW.place_id := nextval('seq_place');
667 NEW.indexed_status := 1; --STATUS_NEW
669 NEW.centroid := get_center_point(NEW.geometry);
670 NEW.country_code := lower(get_country_code(NEW.centroid));
672 NEW.partition := get_partition(NEW.country_code);
673 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
675 IF NEW.osm_type = 'X' THEN
676 -- E'X'ternal records should already be in the right format so do nothing
678 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
680 IF NOT is_rankable_place(NEW.osm_type, NEW.class, NEW.admin_level,
681 NEW.name, NEW.extratags, is_area)
686 SELECT * INTO NEW.rank_search, NEW.rank_address
687 FROM compute_place_rank(NEW.country_code,
688 CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
689 NEW.class, NEW.type, NEW.admin_level,
690 (NEW.extratags->'capital') = 'yes',
691 NEW.address->'postcode');
693 -- a country code make no sense below rank 4 (country)
694 IF NEW.rank_search < 4 THEN
695 NEW.country_code := NULL;
698 -- Simplify polygons with a very large memory footprint when they
699 -- do not take part in address computation.
700 IF NEW.rank_address = 0 THEN
701 NEW.geometry := simplify_large_polygons(NEW.geometry);
706 IF NEW.importance IS NULL THEN
707 NEW.importance := 0.40001 - (NEW.rank_search::float / 75);
710 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
712 {% if not disable_diff_updates %}
713 -- The following is not needed until doing diff updates, and slows the main index process down
715 -- add to tables for special search
716 classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
717 SELECT count(*) INTO result
719 WHERE classtable NOT SIMILAR TO '%\W%'
720 AND tablename = classtable and schemaname = current_schema();
722 EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)'
723 USING NEW.place_id, NEW.centroid;
726 {% endif %} -- not disable_diff_updates
734 CREATE OR REPLACE FUNCTION placex_update()
740 {% if db.middle_db_format == '1' %}
741 relation_members TEXT[];
743 relation_member JSONB;
747 parent_address_level SMALLINT;
748 place_address_level SMALLINT;
752 name_vector INTEGER[];
753 nameaddress_vector INTEGER[];
754 addr_nameaddress_vector INTEGER[];
758 linked_node_id BIGINT;
759 linked_importance FLOAT;
760 linked_wikipedia TEXT;
762 is_place_address BOOLEAN;
766 IF OLD.indexed_status = 100 THEN
767 {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
768 delete from placex where place_id = OLD.place_id;
772 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
776 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
778 NEW.indexed_date = now();
780 IF OLD.indexed_status > 1 THEN
781 {% if 'search_name' in db.tables %}
782 DELETE from search_name WHERE place_id = NEW.place_id;
784 result := deleteSearchName(NEW.partition, NEW.place_id);
785 DELETE FROM place_addressline WHERE place_id = NEW.place_id;
786 result := deleteRoad(NEW.partition, NEW.place_id);
787 result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
790 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
791 IF NEW.extratags = ''::hstore THEN
792 NEW.extratags := NULL;
795 -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
796 -- the previous link status.
797 linked_place := NEW.linked_place_id;
798 NEW.linked_place_id := OLD.linked_place_id;
800 -- Remove linkage, if we have computed a different new linkee.
801 IF OLD.indexed_status > 1 THEN
803 SET linked_place_id = null,
804 indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
805 WHERE linked_place_id = NEW.place_id
806 and (linked_place is null or place_id != linked_place);
809 -- Compute a preliminary centroid.
810 NEW.centroid := get_center_point(NEW.geometry);
812 -- Record the entrance node locations
813 IF NEW.osm_type = 'W' and (NEW.rank_search > 27 or NEW.class IN ('landuse', 'leisure')) THEN
814 PERFORM place_update_entrances(NEW.place_id, NEW.osm_id);
817 -- recalculate country and partition
818 IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
819 -- for countries, believe the mapped country code,
820 -- so that we remain in the right partition if the boundaries
822 NEW.country_code := lower(NEW.address->'country');
823 NEW.partition := get_partition(lower(NEW.country_code));
824 IF NEW.partition = 0 THEN
825 NEW.country_code := lower(get_country_code(NEW.centroid));
826 NEW.partition := get_partition(NEW.country_code);
829 IF NEW.rank_search >= 4 THEN
830 NEW.country_code := lower(get_country_code(NEW.centroid));
832 NEW.country_code := NULL;
834 NEW.partition := get_partition(NEW.country_code);
836 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
839 -- recompute the ranks, they might change when linking changes
840 SELECT * INTO NEW.rank_search, NEW.rank_address
841 FROM compute_place_rank(NEW.country_code,
842 CASE WHEN ST_GeometryType(NEW.geometry)
843 IN ('ST_Polygon','ST_MultiPolygon')
844 THEN 'A' ELSE NEW.osm_type END,
845 NEW.class, NEW.type, NEW.admin_level,
846 (NEW.extratags->'capital') = 'yes',
847 NEW.address->'postcode');
849 -- Short-cut out for linked places. Note that this must happen after the
850 -- address rank has been recomputed. The linking might nullify a shift in
852 IF NEW.linked_place_id is not null THEN
853 NEW.token_info := null;
854 {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
858 -- We must always increase the address level relative to the admin boundary.
859 IF NEW.class = 'boundary' and NEW.type = 'administrative'
860 and NEW.osm_type = 'R' and NEW.rank_address > 0
862 -- First, check that admin boundaries do not overtake each other rank-wise.
863 parent_address_level := 3;
866 (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
867 and extratags->'wikidata' = NEW.extratags->'wikidata'
868 THEN ST_Equals(geometry, NEW.geometry)
869 ELSE false END) as is_same
871 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
872 and admin_level < NEW.admin_level and admin_level > 3
873 and rank_address between 1 and 25 -- for index selection
874 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- for index selection
875 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
876 ORDER BY admin_level desc LIMIT 1
878 IF location.is_same THEN
879 -- Looks like the same boundary is replicated on multiple admin_levels.
880 -- Usual tagging in Poland. Remove our boundary from addresses.
881 NEW.rank_address := 0;
883 parent_address_level := location.rank_address;
884 IF location.rank_address >= NEW.rank_address THEN
885 IF location.rank_address >= 24 THEN
886 NEW.rank_address := 25;
888 NEW.rank_address := location.rank_address + 2;
894 IF NEW.rank_address > 9 THEN
895 -- Second check that the boundary is not completely contained in a
896 -- place area with a equal or higher address rank.
900 LATERAL compute_place_rank(country_code, 'A', class, type,
901 admin_level, False, null) prank
902 WHERE class = 'place' and rank_address between 1 and 23
903 and prank.address_rank >= NEW.rank_address
904 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
905 and ST_Contains(geometry, NEW.geometry)
906 and not ST_Equals(geometry, NEW.geometry)
907 ORDER BY prank.address_rank desc LIMIT 1
909 NEW.rank_address := location.rank_address + 2;
912 ELSEIF NEW.class = 'place'
913 and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
914 and NEW.rank_address between 16 and 23
916 -- For place areas make sure they are not completely contained in an area
917 -- with a equal or higher address rank.
921 LATERAL compute_place_rank(country_code, 'A', class, type,
922 admin_level, False, null) prank
923 WHERE prank.address_rank < 24
924 and rank_address between 1 and 25 -- select right index
925 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
926 and prank.address_rank >= NEW.rank_address
927 and ST_Contains(geometry, NEW.geometry)
928 and not ST_Equals(geometry, NEW.geometry)
929 ORDER BY prank.address_rank desc LIMIT 1
931 NEW.rank_address := location.rank_address + 2;
933 ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
934 and NEW.rank_address between 16 and 23
936 -- If a place node is contained in an admin or place boundary with the same
937 -- address level and has not been linked, then make the node a subpart
938 -- by increasing the address rank (city level and above).
942 LATERAL compute_place_rank(country_code, 'A', class, type,
943 admin_level, False, null) prank
945 and rank_address between 1 and 25 -- select right index
946 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
947 and ((class = 'place' and prank.address_rank = NEW.rank_address)
948 or (class = 'boundary' and rank_address = NEW.rank_address))
949 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
952 NEW.rank_address = NEW.rank_address + 2;
955 parent_address_level := 3;
958 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
960 NEW.postcode := null;
962 -- waterway ways are linked when they are part of a relation and have the same class/type
963 IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
964 {% if db.middle_db_format == '1' %}
965 FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
967 FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
968 IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
969 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
970 FOR linked_node_id IN SELECT place_id FROM placex
971 WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
972 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
973 and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
975 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
976 {% if 'search_name' in db.tables %}
977 IF OLD.indexed_status > 1 THEN
978 DELETE FROM search_name WHERE place_id = linked_node_id;
986 FOR relation_member IN
987 SELECT value FROM planet_osm_rels r, LATERAL jsonb_array_elements(r.members)
988 WHERE r.id = NEW.osm_id
990 IF relation_member->>'role' IN ('', 'main_stream', 'side_stream')
991 and relation_member->>'type' = 'W'
993 {% if debug %}RAISE WARNING 'waterway parent %, child %', NEW.osm_id, relation_member;{% endif %}
994 FOR linked_node_id IN
995 SELECT place_id FROM placex
996 WHERE osm_type = 'W' and osm_id = (relation_member->>'ref')::bigint
997 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
998 and (relation_member->>'role' != 'side_stream' or NEW.name->'name' = name->'name')
1000 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1001 {% if 'search_name' in db.tables %}
1002 DELETE FROM search_name WHERE place_id = linked_node_id;
1008 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
1011 SELECT wikipedia, importance INTO NEW.wikipedia, NEW.importance
1012 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.rank_search, NEW.centroid);
1014 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
1016 -- ---------------------------------------------------------------------------
1017 -- For low level elements we inherit from our parent road
1018 IF NEW.rank_search > 27 THEN
1020 {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1021 NEW.parent_place_id := null;
1022 is_place_address := not token_is_street_address(NEW.token_info);
1024 -- We have to find our parent road.
1025 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
1027 ST_Envelope(NEW.geometry),
1031 -- If we found the road take a shortcut here.
1032 -- Otherwise fall back to the full address getting method below.
1033 IF NEW.parent_place_id is not null THEN
1035 -- Get the details of the parent road
1036 SELECT p.country_code, p.postcode, p.name FROM placex p
1037 WHERE p.place_id = NEW.parent_place_id INTO location;
1039 IF is_place_address and NEW.address ? 'place' THEN
1040 -- Check if the addr:place tag is part of the parent name
1041 SELECT count(*) INTO i
1042 FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
1044 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1048 NEW.country_code := location.country_code;
1049 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1051 -- determine postcode
1052 NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1054 get_nearest_postcode(NEW.country_code, NEW.centroid));
1056 IF NEW.name is not NULL THEN
1057 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1060 {% if not db.reverse_only %}
1061 IF NEW.name is not NULL OR NEW.address is not NULL THEN
1062 SELECT * INTO name_vector, nameaddress_vector
1063 FROM create_poi_search_terms(NEW.place_id,
1064 NEW.partition, NEW.parent_place_id,
1065 is_place_address, NEW.country_code,
1066 NEW.token_info, NEW.centroid);
1068 IF array_length(name_vector, 1) is not NULL THEN
1069 INSERT INTO search_name (place_id, address_rank,
1070 importance, country_code, name_vector,
1071 nameaddress_vector, centroid)
1072 VALUES (NEW.place_id, NEW.rank_address,
1073 NEW.importance, NEW.country_code, name_vector,
1074 nameaddress_vector, NEW.centroid);
1075 {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1080 NEW.token_info := token_strip_info(NEW.token_info);
1087 -- ---------------------------------------------------------------------------
1089 {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1090 IF linked_place is not null THEN
1091 -- Recompute the ranks here as the ones from the linked place might
1092 -- have been shifted to accommodate surrounding boundaries.
1093 SELECT place_id, osm_id, class, type, extratags, rank_search,
1095 (compute_place_rank(country_code, osm_type, class, type, admin_level,
1096 (extratags->'capital') = 'yes', null)).*
1098 FROM placex WHERE place_id = linked_place;
1100 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1102 -- Use the linked point as the centre point of the geometry,
1103 -- but only if it is within the area of the boundary.
1104 geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1105 IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1106 NEW.centroid := geom;
1109 {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1110 IF location.address_rank > parent_address_level
1111 and location.address_rank < 26
1113 NEW.rank_address := location.address_rank;
1116 -- merge in extra tags
1117 NEW.extratags := hstore('linked_' || location.class, location.type)
1118 || coalesce(location.extratags, ''::hstore)
1119 || coalesce(NEW.extratags, ''::hstore);
1121 -- mark the linked place (excludes from search results)
1122 -- Force reindexing to remove any traces from the search indexes and
1123 -- reset the address rank if necessary.
1124 UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1125 WHERE place_id = location.place_id;
1127 SELECT wikipedia, importance
1128 FROM compute_importance(location.extratags, NEW.country_code,
1129 location.rank_search, NEW.centroid)
1130 INTO linked_wikipedia,linked_importance;
1132 -- Use the maximum importance if one could be computed from the linked object.
1133 IF linked_importance is not null AND
1134 (NEW.importance is null or NEW.importance < linked_importance)
1136 NEW.importance := linked_importance;
1139 -- No linked place? As a last resort check if the boundary is tagged with
1140 -- a place type and adapt the rank address.
1141 IF NEW.rank_address between 4 and 25 and NEW.extratags ? 'place' THEN
1142 SELECT address_rank INTO place_address_level
1143 FROM compute_place_rank(NEW.country_code, 'A', 'place',
1144 NEW.extratags->'place', 0::SMALLINT, False, null);
1145 IF place_address_level > parent_address_level and
1146 place_address_level < 26 THEN
1147 NEW.rank_address := place_address_level;
1152 {% if not disable_diff_updates %}
1153 IF OLD.rank_address != NEW.rank_address THEN
1154 -- After a rank shift all addresses containing us must be updated.
1155 UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1156 WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1157 and p.indexed_status = 0 and p.rank_address between 4 and 25;
1161 IF NEW.admin_level = 2
1162 AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1163 AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1165 -- Update the list of country names.
1166 -- Only take the name from the largest area for the given country code
1167 -- in the hope that this is the authoritative one.
1168 -- Also replace any old names so that all mapping mistakes can
1169 -- be fixed through regular OSM updates.
1171 SELECT osm_id FROM placex
1172 WHERE rank_search = 4 and osm_type = 'R'
1173 and country_code = NEW.country_code
1174 ORDER BY ST_Area(geometry) desc
1177 IF location.osm_id = NEW.osm_id THEN
1178 {% if debug %}RAISE WARNING 'Updating names for country ''%'' with: %', NEW.country_code, NEW.name;{% endif %}
1179 UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1184 -- For linear features we need the full geometry for determining the address
1185 -- because they may go through several administrative entities. Otherwise use
1186 -- the centroid for performance reasons.
1187 IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1188 geom := NEW.geometry;
1190 geom := NEW.centroid;
1193 IF NEW.rank_address = 0 THEN
1194 max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1195 -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1196 -- so use the geometry here too. Just make sure the areas don't become too
1198 IF NEW.class = 'natural' or max_rank > 10 THEN
1199 geom := NEW.geometry;
1201 ELSEIF NEW.rank_address > 25 THEN
1204 max_rank := NEW.rank_address;
1207 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1208 NEW.token_info, geom, NEW.centroid,
1210 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1212 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1214 NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1216 -- if we have a name add this to the name search table
1217 name_vector := token_get_name_search_tokens(NEW.token_info);
1218 IF array_length(name_vector, 1) is not NULL THEN
1219 -- Initialise the name vector using our name
1220 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1222 IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1223 result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1224 name_vector, NEW.rank_search, NEW.rank_address,
1225 NEW.postcode, NEW.geometry, NEW.centroid);
1226 {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1229 IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1230 result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1231 {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1234 IF NEW.rank_address between 16 and 27 THEN
1235 result := insertSearchName(NEW.partition, NEW.place_id,
1236 token_get_name_match_tokens(NEW.token_info),
1237 NEW.rank_search, NEW.rank_address, NEW.geometry);
1239 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1241 {% if not db.reverse_only %}
1242 INSERT INTO search_name (place_id, address_rank,
1243 importance, country_code, name_vector,
1244 nameaddress_vector, centroid)
1245 VALUES (NEW.place_id, NEW.rank_address,
1246 NEW.importance, NEW.country_code, name_vector,
1247 nameaddress_vector, NEW.centroid);
1251 IF NEW.postcode is null AND NEW.rank_search > 8
1252 AND (NEW.rank_address > 0
1253 OR ST_GeometryType(NEW.geometry) not in ('ST_LineString','ST_MultiLineString')
1254 OR ST_Length(NEW.geometry) < 0.02)
1256 NEW.postcode := get_nearest_postcode(NEW.country_code,
1257 CASE WHEN NEW.rank_address > 25
1258 THEN NEW.centroid ELSE NEW.geometry END);
1261 {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1263 NEW.token_info := token_strip_info(NEW.token_info);
1270 CREATE OR REPLACE FUNCTION placex_delete()
1278 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1280 IF OLD.linked_place_id is null THEN
1282 SET linked_place_id = NULL,
1283 indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
1284 WHERE linked_place_id = OLD.place_id;
1286 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1289 IF OLD.rank_address < 30 THEN
1291 -- mark everything linked to this place for re-indexing
1292 {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1293 UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id
1294 and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1296 {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1297 DELETE FROM place_addressline where address_place_id = OLD.place_id;
1299 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1300 b := deleteRoad(OLD.partition, OLD.place_id);
1302 {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1303 update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1304 {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1305 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1306 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1308 UPDATE location_postcodes SET indexed_status = 2 WHERE parent_place_id = OLD.place_id;
1311 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1313 IF OLD.rank_address < 26 THEN
1314 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1317 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1319 IF OLD.name is not null THEN
1320 {% if 'search_name' in db.tables %}
1321 DELETE from search_name WHERE place_id = OLD.place_id;
1323 b := deleteSearchName(OLD.partition, OLD.place_id);
1326 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1328 DELETE FROM place_addressline where place_id = OLD.place_id;
1330 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1332 -- remove from tables for special search
1333 classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1334 SELECT count(*) INTO result
1336 WHERE classtable NOT SIMILAR TO '%\W%'
1337 AND tablename = classtable and schemaname = current_schema();
1340 EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1343 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}