1 -- SPDX-License-Identifier: GPL-2.0-only
3 -- This file is part of Nominatim. (https://nominatim.org)
5 -- Copyright (C) 2022 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;
33 IF not p.address ? '_inherited' THEN
34 result.address := p.address;
37 -- For POI nodes, check if the address should be derived from a surrounding
39 IF p.rank_search = 30 AND p.osm_type = 'N' THEN
40 IF p.address is null THEN
41 -- The additional && condition works around the misguided query
42 -- planner of postgis 3.0.
43 SELECT placex.address || hstore('_inherited', '') INTO result.address
45 WHERE ST_Covers(geometry, p.centroid)
46 and geometry && p.centroid
47 and placex.address is not null
48 and (placex.address ? 'housenumber' or placex.address ? 'street' or placex.address ? 'place')
49 and rank_search = 30 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
52 -- See if we can inherit additional address tags from an interpolation.
53 -- These will become permanent.
55 SELECT (address - 'interpolation'::text - 'housenumber'::text) as address
56 FROM place, planet_osm_ways w
57 WHERE place.osm_type = 'W' and place.address ? 'interpolation'
58 and place.geometry && p.geometry
59 and place.osm_id = w.id
60 and p.osm_id = any(w.nodes)
62 result.address := location.address || result.address;
67 -- remove internal and derived names
68 result.address := result.address - '_unlisted_place'::TEXT;
69 SELECT hstore(array_agg(key), array_agg(value)) INTO result.name
70 FROM each(p.name) WHERE key not like '\_%';
72 result.class := p.class;
73 result.type := p.type;
74 result.country_code := p.country_code;
75 result.rank_address := p.rank_address;
76 result.centroid_x := ST_X(p.centroid);
77 result.centroid_y := ST_Y(p.centroid);
79 -- Names of linked places need to be merged in, so search for a linkable
80 -- place already here.
81 SELECT * INTO location FROM find_linked_place(p);
83 IF location.place_id is not NULL THEN
84 result.linked_place_id := location.place_id;
86 IF location.name is not NULL THEN
87 {% if debug %}RAISE WARNING 'Names original: %, location: %', result.name, location.name;{% endif %}
88 -- Add all names from the place nodes that deviate from the name
89 -- in the relation with the prefix '_place_'. Deviation means that
90 -- either the value is different or a given key is missing completely
91 SELECT hstore(array_agg('_place_' || key), array_agg(value)) INTO extra_names
92 FROM each(location.name - result.name);
93 {% if debug %}RAISE WARNING 'Extra names: %', extra_names;{% endif %}
95 IF extra_names is not null THEN
96 result.name := result.name || extra_names;
99 {% if debug %}RAISE WARNING 'Final names: %', result.name;{% endif %}
106 LANGUAGE plpgsql STABLE;
109 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
118 SELECT members FROM planet_osm_rels
119 WHERE parts @> ARRAY[poi_osm_id]
120 and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
121 and tags @> ARRAY['associatedStreet']
123 FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
124 IF location.members[i+1] = 'street' THEN
126 SELECT place_id from placex
127 WHERE osm_type = upper(substring(location.members[i], 1, 1))::char(1)
128 and osm_id = substring(location.members[i], 2)::bigint
130 and rank_search between 26 and 27
132 RETURN parent.place_id;
141 LANGUAGE plpgsql STABLE;
144 -- Find the parent road of a POI.
146 -- \returns Place ID of parent object or NULL if none
148 -- Copy data from linked items (POIs on ways, addr:street links, relations).
150 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
152 poi_partition SMALLINT,
155 is_place_addr BOOLEAN)
159 parent_place_id BIGINT DEFAULT NULL;
162 {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
164 -- Is this object part of an associatedStreet relation?
165 parent_place_id := find_associated_street(poi_osm_type, poi_osm_id);
167 IF parent_place_id is null THEN
168 parent_place_id := find_parent_for_address(token_info, poi_partition, bbox);
171 IF parent_place_id is null and poi_osm_type = 'N' THEN
173 SELECT p.place_id, p.osm_id, p.rank_search, p.address,
174 coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
175 FROM placex p, planet_osm_ways w
176 WHERE p.osm_type = 'W' and p.rank_search >= 26
177 and p.geometry && bbox
178 and w.id = p.osm_id and poi_osm_id = any(w.nodes)
180 {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
182 -- Way IS a road then we are on it - that must be our road
183 IF location.rank_search < 28 THEN
184 {% if debug %}RAISE WARNING 'node in way that is a street %',location;{% endif %}
185 RETURN location.place_id;
188 parent_place_id := find_associated_street('W', location.osm_id);
192 IF parent_place_id is NULL THEN
193 IF is_place_addr THEN
194 -- The address is attached to a place we don't know.
195 -- Instead simply use the containing area with the largest rank.
197 SELECT place_id FROM placex
198 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
199 AND rank_address between 5 and 25
200 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
201 ORDER BY rank_address desc
203 RETURN location.place_id;
205 ELSEIF ST_Area(bbox) < 0.005 THEN
206 -- for smaller features get the nearest road
207 SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
208 {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
210 -- for larger features simply find the area with the largest rank that
211 -- contains the bbox, only use addressable features
213 SELECT place_id FROM placex
214 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
215 AND rank_address between 5 and 25
216 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
217 ORDER BY rank_address desc
219 RETURN location.place_id;
224 RETURN parent_place_id;
227 LANGUAGE plpgsql STABLE;
229 -- Try to find a linked place for the given object.
230 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
234 relation_members TEXT[];
236 linked_placex placex%ROWTYPE;
239 IF bnd.rank_search >= 26 or bnd.rank_address = 0
240 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
241 or bnd.type IN ('postcode', 'postal_code')
246 IF bnd.osm_type = 'R' THEN
247 -- see if we have any special relation members
248 SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
249 {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
251 -- Search for relation members with role 'lable'.
252 IF relation_members IS NOT NULL THEN
254 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
256 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
260 WHERE osm_type = 'N' and osm_id = rel_member.member
263 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
264 RETURN linked_placex;
271 IF bnd.name ? 'name' THEN
272 bnd_name := lower(bnd.name->'name');
273 IF bnd_name = '' THEN
278 -- If extratags has a place tag, look for linked nodes by their place type.
279 -- Area and node still have to have the same name.
280 IF bnd.extratags ? 'place' and bnd.extratags->'place' != 'postcode'
281 and bnd_name is not null
285 WHERE (position(lower(name->'name') in bnd_name) > 0
286 OR position(bnd_name in lower(name->'name')) > 0)
287 AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
288 AND placex.osm_type = 'N'
289 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
290 AND placex.rank_search < 26 -- needed to select the right index
291 AND ST_Covers(bnd.geometry, placex.geometry)
293 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
294 RETURN linked_placex;
298 IF bnd.extratags ? 'wikidata' THEN
301 WHERE placex.class = 'place' AND placex.osm_type = 'N'
302 AND placex.extratags ? 'wikidata' -- needed to select right index
303 AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
304 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
305 AND placex.rank_search < 26
306 AND _st_covers(bnd.geometry, placex.geometry)
307 ORDER BY lower(name->'name') = bnd_name desc
309 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
310 RETURN linked_placex;
314 -- Name searches can be done for ways as well as relations
315 IF bnd_name is not null THEN
316 {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
318 SELECT placex.* from placex
319 WHERE lower(name->'name') = bnd_name
320 AND ((bnd.rank_address > 0
321 and bnd.rank_address = (compute_place_rank(placex.country_code,
323 placex.type, 15::SMALLINT,
324 false, placex.postcode)).address_rank)
325 OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
326 AND placex.osm_type = 'N'
327 AND placex.class = 'place'
328 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
329 AND placex.rank_search < 26 -- needed to select the right index
330 AND placex.type != 'postcode'
331 AND ST_Covers(bnd.geometry, placex.geometry)
333 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
334 RETURN linked_placex;
341 LANGUAGE plpgsql STABLE;
344 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
345 in_partition SMALLINT,
346 parent_place_id BIGINT,
347 is_place_addr BOOLEAN,
351 OUT name_vector INTEGER[],
352 OUT nameaddress_vector INTEGER[])
355 parent_name_vector INTEGER[];
356 parent_address_vector INTEGER[];
357 addr_place_ids INTEGER[];
358 hnr_vector INTEGER[];
362 parent_address_place_ids BIGINT[];
364 nameaddress_vector := '{}'::INTEGER[];
366 SELECT s.name_vector, s.nameaddress_vector
367 INTO parent_name_vector, parent_address_vector
369 WHERE s.place_id = parent_place_id;
373 token_get_address_search_tokens(token_info, key) as search_tokens
374 FROM token_get_address_keys(token_info) as key,
375 LATERAL get_addr_tag_rank(key, country) as ranks
376 WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
378 addr_place := get_address_place(in_partition, geometry,
379 addr_item.from_rank, addr_item.to_rank,
380 addr_item.extent, token_info, addr_item.key);
382 IF addr_place is null THEN
383 -- No place found in OSM that matches. Make it at least searchable.
384 nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
386 IF parent_address_place_ids is null THEN
387 SELECT array_agg(parent_place_id) INTO parent_address_place_ids
388 FROM place_addressline
389 WHERE place_id = parent_place_id;
392 -- If the parent already lists the place in place_address line, then we
393 -- are done. Otherwise, add its own place_address line.
394 IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
395 nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
397 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
398 isaddress, distance, cached_rank_address)
399 VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
400 true, addr_place.distance, addr_place.rank_address);
405 name_vector := token_get_name_search_tokens(token_info);
407 -- Check if the parent covers all address terms.
408 -- If not, create a search name entry with the house number as the name.
409 -- This is unusual for the search_name table but prevents that the place
410 -- is returned when we only search for the street/place.
412 hnr_vector := token_get_housenumber_search_tokens(token_info);
414 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
415 name_vector := array_merge(name_vector, hnr_vector);
418 IF is_place_addr THEN
419 addr_place_ids := token_addr_place_search_tokens(token_info);
420 IF not addr_place_ids <@ parent_name_vector THEN
421 -- make sure addr:place terms are always searchable
422 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
423 -- If there is a housenumber, also add the place name as a name,
424 -- so we can search it by the usual housenumber+place algorithms.
425 IF hnr_vector is not null THEN
426 name_vector := array_merge(name_vector, addr_place_ids);
431 -- Cheating here by not recomputing all terms but simply using the ones
432 -- from the parent object.
433 nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
434 nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
441 -- Insert address of a place into the place_addressline table.
443 -- \param obj_place_id Place_id of the place to compute the address for.
444 -- \param partition Partition number where the place is in.
445 -- \param maxrank Rank of the place. All address features must have
446 -- a search rank lower than the given rank.
447 -- \param address Address terms for the place.
448 -- \param geometry Geometry to which the address objects should be close.
450 -- \retval parent_place_id Place_id of the address object that is the direct
452 -- \retval postcode Postcode computed from the address. This is the
453 -- addr:postcode of one of the address objects. If
454 -- more than one of has a postcode, the highest ranking
455 -- one is used. May be NULL.
456 -- \retval nameaddress_vector Search terms for the address. This is the sum
457 -- of name terms of all address objects.
458 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
465 OUT parent_place_id BIGINT,
467 OUT nameaddress_vector INT[])
470 address_havelevel BOOLEAN[];
472 location_isaddress BOOLEAN;
473 current_boundary GEOMETRY := NULL;
474 current_node_area GEOMETRY := NULL;
476 parent_place_rank INT := 0;
477 addr_place_ids BIGINT[] := '{}'::int[];
478 new_address_vector INT[];
482 parent_place_id := 0;
483 nameaddress_vector := '{}'::int[];
485 address_havelevel := array_fill(false, ARRAY[maxrank]);
489 FROM (SELECT extra.*, key
490 FROM token_get_address_keys(token_info) as key,
491 LATERAL get_addr_tag_rank(key, country) as extra) x,
492 LATERAL get_address_place(partition, geometry, from_rank, to_rank,
493 extent, token_info, key) as apl
494 ORDER BY rank_address, distance, isguess desc
496 IF location.place_id is null THEN
497 {% if not db.reverse_only %}
498 nameaddress_vector := array_merge(nameaddress_vector,
499 token_get_address_search_tokens(token_info,
503 {% if not db.reverse_only %}
504 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
507 location_isaddress := not address_havelevel[location.rank_address];
508 IF not address_havelevel[location.rank_address] THEN
509 address_havelevel[location.rank_address] := true;
510 IF parent_place_rank < location.rank_address THEN
511 parent_place_id := location.place_id;
512 parent_place_rank := location.rank_address;
516 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
517 isaddress, distance, cached_rank_address)
518 VALUES (obj_place_id, location.place_id, not location.isguess,
519 true, location.distance, location.rank_address);
521 addr_place_ids := addr_place_ids || location.place_id;
526 SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
527 WHERE not addr_place_ids @> ARRAY[place_id]
528 ORDER BY rank_address, isguess asc,
530 CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
531 WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
532 WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
535 -- Ignore all place nodes that do not fit in a lower level boundary.
536 CONTINUE WHEN location.isguess
537 and current_boundary is not NULL
538 and not ST_Contains(current_boundary, location.centroid);
540 -- If this is the first item in the rank, then assume it is the address.
541 location_isaddress := not address_havelevel[location.rank_address];
543 -- Further sanity checks to ensure that the address forms a sane hierarchy.
544 IF location_isaddress THEN
545 IF location.isguess and current_node_area is not NULL THEN
546 location_isaddress := ST_Contains(current_node_area, location.centroid);
548 IF not location.isguess and current_boundary is not NULL
549 and location.rank_address != 11 AND location.rank_address != 5 THEN
550 location_isaddress := ST_Contains(current_boundary, location.centroid);
554 IF location_isaddress THEN
555 address_havelevel[location.rank_address] := true;
556 parent_place_id := location.place_id;
558 -- Set postcode if we have one.
559 -- (Returned will be the highest ranking one.)
560 IF location.postcode is not NULL THEN
561 postcode = location.postcode;
564 -- Recompute the areas we need for hierarchy sanity checks.
565 IF location.rank_address != 11 AND location.rank_address != 5 THEN
566 IF location.isguess THEN
567 current_node_area := place_node_fuzzy_area(location.centroid,
568 location.rank_search);
570 current_node_area := NULL;
571 SELECT p.geometry FROM placex p
572 WHERE p.place_id = location.place_id INTO current_boundary;
577 -- Add it to the list of search terms
578 {% if not db.reverse_only %}
579 nameaddress_vector := array_merge(nameaddress_vector,
580 location.keywords::integer[]);
583 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
584 isaddress, distance, cached_rank_address)
585 VALUES (obj_place_id, location.place_id, not location.isguess,
586 location_isaddress, location.distance, location.rank_address);
593 CREATE OR REPLACE FUNCTION placex_insert()
600 country_code VARCHAR(2);
604 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
606 NEW.place_id := nextval('seq_place');
607 NEW.indexed_status := 1; --STATUS_NEW
609 NEW.centroid := ST_PointOnSurface(NEW.geometry);
610 NEW.country_code := lower(get_country_code(NEW.centroid));
612 NEW.partition := get_partition(NEW.country_code);
613 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
615 IF NEW.osm_type = 'X' THEN
616 -- E'X'ternal records should already be in the right format so do nothing
618 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
620 IF NEW.class in ('place','boundary')
621 AND NEW.type in ('postcode','postal_code')
623 IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
624 -- most likely just a part of a multipolygon postcode boundary, throw it away
628 NEW.name := hstore('ref', NEW.address->'postcode');
630 ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
631 AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
634 ELSEIF NEW.class = 'boundary' AND NOT is_area
637 ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
638 AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
643 SELECT * INTO NEW.rank_search, NEW.rank_address
644 FROM compute_place_rank(NEW.country_code,
645 CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
646 NEW.class, NEW.type, NEW.admin_level,
647 (NEW.extratags->'capital') = 'yes',
648 NEW.address->'postcode');
650 -- a country code make no sense below rank 4 (country)
651 IF NEW.rank_search < 4 THEN
652 NEW.country_code := NULL;
657 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
659 {% if not disable_diff_updates %}
660 -- The following is not needed until doing diff updates, and slows the main index process down
662 IF NEW.rank_address > 0 THEN
663 IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
664 -- Performance: We just can't handle re-indexing for country level changes
665 IF st_area(NEW.geometry) < 1 THEN
666 -- mark items within the geometry for re-indexing
667 -- RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
669 UPDATE placex SET indexed_status = 2
670 WHERE ST_Intersects(NEW.geometry, placex.geometry)
671 and indexed_status = 0
672 and ((rank_address = 0 and rank_search > NEW.rank_address)
673 or rank_address > NEW.rank_address
674 or (class = 'place' and osm_type = 'N')
676 and (rank_search < 28
678 or (NEW.rank_address >= 16 and address ? 'place'));
681 -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
682 diameter := update_place_diameter(NEW.rank_search);
684 -- RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
685 IF NEW.rank_search >= 26 THEN
686 -- roads may cause reparenting for >27 rank places
687 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
688 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
689 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and startnumber is not null and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
690 ELSEIF NEW.rank_search >= 16 THEN
691 -- up to rank 16, street-less addresses may need reparenting
692 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null or address ? 'place');
694 -- for all other places the search terms may change as well
695 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null);
702 -- add to tables for special search
703 -- Note: won't work on initial import because the classtype tables
704 -- do not yet exist. It won't hurt either.
705 classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
706 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
708 EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)'
709 USING NEW.place_id, ST_Centroid(NEW.geometry);
712 {% endif %} -- not disable_diff_updates
720 CREATE OR REPLACE FUNCTION placex_update()
726 relation_members TEXT[];
729 parent_address_level SMALLINT;
730 place_address_level SMALLINT;
734 name_vector INTEGER[];
735 nameaddress_vector INTEGER[];
736 addr_nameaddress_vector INTEGER[];
740 linked_node_id BIGINT;
741 linked_importance FLOAT;
742 linked_wikipedia TEXT;
744 is_place_address BOOLEAN;
748 IF OLD.indexed_status = 100 THEN
749 {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
750 delete from placex where place_id = OLD.place_id;
754 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
758 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
760 NEW.indexed_date = now();
762 {% if 'search_name' in db.tables %}
763 DELETE from search_name WHERE place_id = NEW.place_id;
765 result := deleteSearchName(NEW.partition, NEW.place_id);
766 DELETE FROM place_addressline WHERE place_id = NEW.place_id;
767 result := deleteRoad(NEW.partition, NEW.place_id);
768 result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
770 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
772 -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
773 -- the previous link status.
774 linked_place := NEW.linked_place_id;
775 NEW.linked_place_id := OLD.linked_place_id;
777 -- Remove linkage, if we have computed a different new linkee.
778 UPDATE placex SET linked_place_id = null, indexed_status = 2
779 WHERE linked_place_id = NEW.place_id
780 and (linked_place is null or linked_place_id != linked_place);
781 -- update not necessary for osmline, cause linked_place_id does not exist
783 -- Postcodes are just here to compute the centroids. They are not searchable
784 -- unless they are a boundary=postal_code.
785 -- There was an error in the style so that boundary=postal_code used to be
786 -- imported as place=postcode. That's why relations are allowed to pass here.
787 -- This can go away in a couple of versions.
788 IF NEW.class = 'place' and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
789 NEW.token_info := null;
793 -- Compute a preliminary centroid.
794 NEW.centroid := ST_PointOnSurface(NEW.geometry);
796 -- recalculate country and partition
797 IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
798 -- for countries, believe the mapped country code,
799 -- so that we remain in the right partition if the boundaries
801 NEW.country_code := lower(NEW.address->'country');
802 NEW.partition := get_partition(lower(NEW.country_code));
803 IF NEW.partition = 0 THEN
804 NEW.country_code := lower(get_country_code(NEW.centroid));
805 NEW.partition := get_partition(NEW.country_code);
808 IF NEW.rank_search >= 4 THEN
809 NEW.country_code := lower(get_country_code(NEW.centroid));
811 NEW.country_code := NULL;
813 NEW.partition := get_partition(NEW.country_code);
815 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
818 -- recompute the ranks, they might change when linking changes
819 SELECT * INTO NEW.rank_search, NEW.rank_address
820 FROM compute_place_rank(NEW.country_code,
821 CASE WHEN ST_GeometryType(NEW.geometry)
822 IN ('ST_Polygon','ST_MultiPolygon')
823 THEN 'A' ELSE NEW.osm_type END,
824 NEW.class, NEW.type, NEW.admin_level,
825 (NEW.extratags->'capital') = 'yes',
826 NEW.address->'postcode');
828 -- Short-cut out for linked places. Note that this must happen after the
829 -- address rank has been recomputed. The linking might nullify a shift in
831 IF NEW.linked_place_id is not null THEN
832 NEW.token_info := null;
833 {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
837 -- We must always increase the address level relative to the admin boundary.
838 IF NEW.class = 'boundary' and NEW.type = 'administrative'
839 and NEW.osm_type = 'R' and NEW.rank_address > 0
841 -- First, check that admin boundaries do not overtake each other rank-wise.
842 parent_address_level := 3;
845 (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
846 and extratags->'wikidata' = NEW.extratags->'wikidata'
847 THEN ST_Equals(geometry, NEW.geometry)
848 ELSE false END) as is_same
850 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
851 and admin_level < NEW.admin_level and admin_level > 3
852 and rank_address between 1 and 25 -- for index selection
853 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- for index selection
854 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
855 ORDER BY admin_level desc LIMIT 1
857 IF location.is_same THEN
858 -- Looks like the same boundary is replicated on multiple admin_levels.
859 -- Usual tagging in Poland. Remove our boundary from addresses.
860 NEW.rank_address := 0;
862 parent_address_level := location.rank_address;
863 IF location.rank_address >= NEW.rank_address THEN
864 IF location.rank_address >= 24 THEN
865 NEW.rank_address := 25;
867 NEW.rank_address := location.rank_address + 2;
873 IF NEW.rank_address > 9 THEN
874 -- Second check that the boundary is not completely contained in a
875 -- place area with a equal or higher address rank.
879 LATERAL compute_place_rank(country_code, 'A', class, type,
880 admin_level, False, null) prank
881 WHERE class = 'place' and rank_address between 1 and 23
882 and prank.address_rank >= NEW.rank_address
883 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
884 and geometry && NEW.geometry
885 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
886 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
887 ORDER BY prank.address_rank desc LIMIT 1
889 NEW.rank_address := location.rank_address + 2;
892 ELSEIF NEW.class = 'place'
893 and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
894 and NEW.rank_address between 16 and 23
896 -- For place areas make sure they are not completely contained in an area
897 -- with a equal or higher address rank.
901 LATERAL compute_place_rank(country_code, 'A', class, type,
902 admin_level, False, null) prank
903 WHERE prank.address_rank < 24
904 and rank_address between 1 and 25 -- select right index
905 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
906 and prank.address_rank >= NEW.rank_address
907 and geometry && NEW.geometry
908 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
909 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
910 ORDER BY prank.address_rank desc LIMIT 1
912 NEW.rank_address := location.rank_address + 2;
914 ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
915 and NEW.rank_address between 16 and 23
917 -- If a place node is contained in an admin or place boundary with the same
918 -- address level and has not been linked, then make the node a subpart
919 -- by increasing the address rank (city level and above).
923 LATERAL compute_place_rank(country_code, 'A', class, type,
924 admin_level, False, null) prank
926 and rank_address between 1 and 25 -- select right index
927 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
928 and ((class = 'place' and prank.address_rank = NEW.rank_address)
929 or (class = 'boundary' and rank_address = NEW.rank_address))
930 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
933 NEW.rank_address = NEW.rank_address + 2;
936 parent_address_level := 3;
939 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
941 NEW.postcode := null;
943 -- waterway ways are linked when they are part of a relation and have the same class/type
944 IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
945 FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
947 FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
948 IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
949 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
950 FOR linked_node_id IN SELECT place_id FROM placex
951 WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
952 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
953 and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
955 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
956 {% if 'search_name' in db.tables %}
957 DELETE FROM search_name WHERE place_id = linked_node_id;
963 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
966 NEW.importance := null;
967 SELECT wikipedia, importance
968 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
969 INTO NEW.wikipedia,NEW.importance;
971 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
973 -- ---------------------------------------------------------------------------
974 -- For low level elements we inherit from our parent road
975 IF NEW.rank_search > 27 THEN
977 {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
978 NEW.parent_place_id := null;
979 is_place_address := coalesce(not NEW.address ? 'street' and NEW.address ? 'place', FALSE);
981 -- We have to find our parent road.
982 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
984 ST_Envelope(NEW.geometry),
988 -- If we found the road take a shortcut here.
989 -- Otherwise fall back to the full address getting method below.
990 IF NEW.parent_place_id is not null THEN
992 -- Get the details of the parent road
993 SELECT p.country_code, p.postcode, p.name FROM placex p
994 WHERE p.place_id = NEW.parent_place_id INTO location;
996 IF is_place_address THEN
997 -- Check if the addr:place tag is part of the parent name
998 SELECT count(*) INTO i
999 FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
1001 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1005 NEW.country_code := location.country_code;
1006 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1008 -- determine postcode
1009 NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1011 get_nearest_postcode(NEW.country_code, NEW.centroid));
1013 IF NEW.name is not NULL THEN
1014 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1017 {% if not db.reverse_only %}
1018 IF NEW.name is not NULL OR NEW.address is not NULL THEN
1019 SELECT * INTO name_vector, nameaddress_vector
1020 FROM create_poi_search_terms(NEW.place_id,
1021 NEW.partition, NEW.parent_place_id,
1022 is_place_address, NEW.country_code,
1023 NEW.token_info, NEW.centroid);
1025 IF array_length(name_vector, 1) is not NULL THEN
1026 INSERT INTO search_name (place_id, search_rank, address_rank,
1027 importance, country_code, name_vector,
1028 nameaddress_vector, centroid)
1029 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1030 NEW.importance, NEW.country_code, name_vector,
1031 nameaddress_vector, NEW.centroid);
1032 {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1037 NEW.token_info := token_strip_info(NEW.token_info);
1044 -- ---------------------------------------------------------------------------
1046 {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1047 IF linked_place is not null THEN
1048 -- Recompute the ranks here as the ones from the linked place might
1049 -- have been shifted to accommodate surrounding boundaries.
1050 SELECT place_id, osm_id, class, type, extratags,
1052 (compute_place_rank(country_code, osm_type, class, type, admin_level,
1053 (extratags->'capital') = 'yes', null)).*
1055 FROM placex WHERE place_id = linked_place;
1057 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1059 -- Use the linked point as the centre point of the geometry,
1060 -- but only if it is within the area of the boundary.
1061 geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1062 IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1063 NEW.centroid := geom;
1066 {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1067 IF location.address_rank > parent_address_level
1068 and location.address_rank < 26
1070 NEW.rank_address := location.address_rank;
1073 -- merge in extra tags
1074 NEW.extratags := hstore('linked_' || location.class, location.type)
1075 || coalesce(location.extratags, ''::hstore)
1076 || coalesce(NEW.extratags, ''::hstore);
1078 -- mark the linked place (excludes from search results)
1079 -- Force reindexing to remove any traces from the search indexes and
1080 -- reset the address rank if necessary.
1081 UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1082 WHERE place_id = location.place_id;
1083 -- ensure that those places are not found anymore
1084 {% if 'search_name' in db.tables %}
1085 DELETE FROM search_name WHERE place_id = location.place_id;
1087 PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
1089 SELECT wikipedia, importance
1090 FROM compute_importance(location.extratags, NEW.country_code,
1091 'N', location.osm_id)
1092 INTO linked_wikipedia,linked_importance;
1094 -- Use the maximum importance if one could be computed from the linked object.
1095 IF linked_importance is not null AND
1096 (NEW.importance is null or NEW.importance < linked_importance)
1098 NEW.importance = linked_importance;
1101 -- No linked place? As a last resort check if the boundary is tagged with
1102 -- a place type and adapt the rank address.
1103 IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
1104 SELECT address_rank INTO place_address_level
1105 FROM compute_place_rank(NEW.country_code, 'A', 'place',
1106 NEW.extratags->'place', 0::SMALLINT, False, null);
1107 IF place_address_level > parent_address_level and
1108 place_address_level < 26 THEN
1109 NEW.rank_address := place_address_level;
1114 {% if not disable_diff_updates %}
1115 IF OLD.rank_address != NEW.rank_address THEN
1116 -- After a rank shift all addresses containing us must be updated.
1117 UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1118 WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1119 and p.indexed_status = 0 and p.rank_address between 4 and 25;
1123 IF NEW.admin_level = 2
1124 AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1125 AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1127 -- Update the list of country names.
1128 -- Only take the name from the largest area for the given country code
1129 -- in the hope that this is the authoritative one.
1130 -- Also replace any old names so that all mapping mistakes can
1131 -- be fixed through regular OSM updates.
1133 SELECT osm_id FROM placex
1134 WHERE rank_search = 4 and osm_type = 'R'
1135 and country_code = NEW.country_code
1136 ORDER BY ST_Area(geometry) desc
1139 IF location.osm_id = NEW.osm_id THEN
1140 {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1141 UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1146 -- For linear features we need the full geometry for determining the address
1147 -- because they may go through several administrative entities. Otherwise use
1148 -- the centroid for performance reasons.
1149 IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1150 geom := NEW.geometry;
1152 geom := NEW.centroid;
1155 IF NEW.rank_address = 0 THEN
1156 max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1157 -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1158 -- so use the geometry here too. Just make sure the areas don't become too
1160 IF NEW.class = 'natural' or max_rank > 10 THEN
1161 geom := NEW.geometry;
1163 ELSEIF NEW.rank_address > 25 THEN
1166 max_rank := NEW.rank_address;
1169 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1170 NEW.token_info, geom, NEW.centroid,
1172 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1174 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1176 NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1178 -- if we have a name add this to the name search table
1179 IF NEW.name IS NOT NULL THEN
1180 -- Initialise the name vector using our name
1181 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1182 name_vector := token_get_name_search_tokens(NEW.token_info);
1184 IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1185 result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1186 name_vector, NEW.rank_search, NEW.rank_address,
1187 NEW.postcode, NEW.geometry, NEW.centroid);
1188 {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1191 IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1192 result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1193 {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1196 IF NEW.rank_address between 16 and 27 THEN
1197 result := insertSearchName(NEW.partition, NEW.place_id,
1198 token_get_name_match_tokens(NEW.token_info),
1199 NEW.rank_search, NEW.rank_address, NEW.geometry);
1201 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1203 {% if not db.reverse_only %}
1204 INSERT INTO search_name (place_id, search_rank, address_rank,
1205 importance, country_code, name_vector,
1206 nameaddress_vector, centroid)
1207 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1208 NEW.importance, NEW.country_code, name_vector,
1209 nameaddress_vector, NEW.centroid);
1213 IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1214 NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1217 {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1219 NEW.token_info := token_strip_info(NEW.token_info);
1226 CREATE OR REPLACE FUNCTION placex_delete()
1233 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1235 IF OLD.linked_place_id is null THEN
1236 update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1237 {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1238 update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1239 {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1241 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1244 IF OLD.rank_address < 30 THEN
1246 -- mark everything linked to this place for re-indexing
1247 {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1248 UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id
1249 and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1251 {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1252 DELETE FROM place_addressline where address_place_id = OLD.place_id;
1254 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1255 b := deleteRoad(OLD.partition, OLD.place_id);
1257 {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1258 update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1259 {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1260 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1261 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1265 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1267 IF OLD.rank_address < 26 THEN
1268 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1271 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1273 IF OLD.name is not null THEN
1274 {% if 'search_name' in db.tables %}
1275 DELETE from search_name WHERE place_id = OLD.place_id;
1277 b := deleteSearchName(OLD.partition, OLD.place_id);
1280 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1282 DELETE FROM place_addressline where place_id = OLD.place_id;
1284 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1286 -- remove from tables for special search
1287 classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1288 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1290 EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1293 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}