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 ORDER BY rank_address desc
202 RETURN location.place_id;
204 ELSEIF ST_Area(bbox) < 0.005 THEN
205 -- for smaller features get the nearest road
206 SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
207 {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
209 -- for larger features simply find the area with the largest rank that
210 -- contains the bbox, only use addressable features
212 SELECT place_id FROM placex
213 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
214 AND rank_address between 5 and 25
215 ORDER BY rank_address desc
217 RETURN location.place_id;
222 RETURN parent_place_id;
225 LANGUAGE plpgsql STABLE;
227 -- Try to find a linked place for the given object.
228 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
232 relation_members TEXT[];
234 linked_placex placex%ROWTYPE;
237 IF bnd.rank_search >= 26 or bnd.rank_address = 0
238 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
239 or bnd.type IN ('postcode', 'postal_code')
244 IF bnd.osm_type = 'R' THEN
245 -- see if we have any special relation members
246 SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
247 {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
249 -- Search for relation members with role 'lable'.
250 IF relation_members IS NOT NULL THEN
252 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
254 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
258 WHERE osm_type = 'N' and osm_id = rel_member.member
261 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
262 RETURN linked_placex;
269 IF bnd.name ? 'name' THEN
270 bnd_name := lower(bnd.name->'name');
271 IF bnd_name = '' THEN
276 -- If extratags has a place tag, look for linked nodes by their place type.
277 -- Area and node still have to have the same name.
278 IF bnd.extratags ? 'place' and bnd_name is not null THEN
281 WHERE (position(lower(name->'name') in bnd_name) > 0
282 OR position(bnd_name in lower(name->'name')) > 0)
283 AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
284 AND placex.osm_type = 'N'
285 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
286 AND placex.rank_search < 26 -- needed to select the right index
287 AND placex.type != 'postcode'
288 AND ST_Covers(bnd.geometry, placex.geometry)
290 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
291 RETURN linked_placex;
295 IF bnd.extratags ? 'wikidata' THEN
298 WHERE placex.class = 'place' AND placex.osm_type = 'N'
299 AND placex.extratags ? 'wikidata' -- needed to select right index
300 AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
301 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
302 AND placex.rank_search < 26
303 AND _st_covers(bnd.geometry, placex.geometry)
304 ORDER BY lower(name->'name') = bnd_name desc
306 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
307 RETURN linked_placex;
311 -- Name searches can be done for ways as well as relations
312 IF bnd_name is not null THEN
313 {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
315 SELECT placex.* from placex
316 WHERE lower(name->'name') = bnd_name
317 AND ((bnd.rank_address > 0
318 and bnd.rank_address = (compute_place_rank(placex.country_code,
320 placex.type, 15::SMALLINT,
321 false, placex.postcode)).address_rank)
322 OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
323 AND placex.osm_type = 'N'
324 AND placex.class = 'place'
325 AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
326 AND placex.rank_search < 26 -- needed to select the right index
327 AND placex.type != 'postcode'
328 AND ST_Covers(bnd.geometry, placex.geometry)
330 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
331 RETURN linked_placex;
338 LANGUAGE plpgsql STABLE;
341 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
342 in_partition SMALLINT,
343 parent_place_id BIGINT,
344 is_place_addr BOOLEAN,
348 OUT name_vector INTEGER[],
349 OUT nameaddress_vector INTEGER[])
352 parent_name_vector INTEGER[];
353 parent_address_vector INTEGER[];
354 addr_place_ids INTEGER[];
355 hnr_vector INTEGER[];
359 parent_address_place_ids BIGINT[];
361 nameaddress_vector := '{}'::INTEGER[];
363 SELECT s.name_vector, s.nameaddress_vector
364 INTO parent_name_vector, parent_address_vector
366 WHERE s.place_id = parent_place_id;
370 token_get_address_search_tokens(token_info, key) as search_tokens
371 FROM token_get_address_keys(token_info) as key,
372 LATERAL get_addr_tag_rank(key, country) as ranks
373 WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
375 addr_place := get_address_place(in_partition, geometry,
376 addr_item.from_rank, addr_item.to_rank,
377 addr_item.extent, token_info, addr_item.key);
379 IF addr_place is null THEN
380 -- No place found in OSM that matches. Make it at least searchable.
381 nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
383 IF parent_address_place_ids is null THEN
384 SELECT array_agg(parent_place_id) INTO parent_address_place_ids
385 FROM place_addressline
386 WHERE place_id = parent_place_id;
389 -- If the parent already lists the place in place_address line, then we
390 -- are done. Otherwise, add its own place_address line.
391 IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
392 nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
394 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
395 isaddress, distance, cached_rank_address)
396 VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
397 true, addr_place.distance, addr_place.rank_address);
402 name_vector := token_get_name_search_tokens(token_info);
404 -- Check if the parent covers all address terms.
405 -- If not, create a search name entry with the house number as the name.
406 -- This is unusual for the search_name table but prevents that the place
407 -- is returned when we only search for the street/place.
409 hnr_vector := token_get_housenumber_search_tokens(token_info);
411 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
412 name_vector := array_merge(name_vector, hnr_vector);
415 IF is_place_addr THEN
416 addr_place_ids := token_addr_place_search_tokens(token_info);
417 IF not addr_place_ids <@ parent_name_vector THEN
418 -- make sure addr:place terms are always searchable
419 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
420 -- If there is a housenumber, also add the place name as a name,
421 -- so we can search it by the usual housenumber+place algorithms.
422 IF hnr_vector is not null THEN
423 name_vector := array_merge(name_vector, addr_place_ids);
428 -- Cheating here by not recomputing all terms but simply using the ones
429 -- from the parent object.
430 nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
431 nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
438 -- Insert address of a place into the place_addressline table.
440 -- \param obj_place_id Place_id of the place to compute the address for.
441 -- \param partition Partition number where the place is in.
442 -- \param maxrank Rank of the place. All address features must have
443 -- a search rank lower than the given rank.
444 -- \param address Address terms for the place.
445 -- \param geometry Geometry to which the address objects should be close.
447 -- \retval parent_place_id Place_id of the address object that is the direct
449 -- \retval postcode Postcode computed from the address. This is the
450 -- addr:postcode of one of the address objects. If
451 -- more than one of has a postcode, the highest ranking
452 -- one is used. May be NULL.
453 -- \retval nameaddress_vector Search terms for the address. This is the sum
454 -- of name terms of all address objects.
455 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
462 OUT parent_place_id BIGINT,
464 OUT nameaddress_vector INT[])
467 address_havelevel BOOLEAN[];
469 location_isaddress BOOLEAN;
470 current_boundary GEOMETRY := NULL;
471 current_node_area GEOMETRY := NULL;
473 parent_place_rank INT := 0;
474 addr_place_ids BIGINT[] := '{}'::int[];
475 new_address_vector INT[];
479 parent_place_id := 0;
480 nameaddress_vector := '{}'::int[];
482 address_havelevel := array_fill(false, ARRAY[maxrank]);
486 FROM (SELECT extra.*, key
487 FROM token_get_address_keys(token_info) as key,
488 LATERAL get_addr_tag_rank(key, country) as extra) x,
489 LATERAL get_address_place(partition, geometry, from_rank, to_rank,
490 extent, token_info, key) as apl
491 ORDER BY rank_address, distance, isguess desc
493 IF location.place_id is null THEN
494 {% if not db.reverse_only %}
495 nameaddress_vector := array_merge(nameaddress_vector,
496 token_get_address_search_tokens(token_info,
500 {% if not db.reverse_only %}
501 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
504 location_isaddress := not address_havelevel[location.rank_address];
505 IF not address_havelevel[location.rank_address] THEN
506 address_havelevel[location.rank_address] := true;
507 IF parent_place_rank < location.rank_address THEN
508 parent_place_id := location.place_id;
509 parent_place_rank := location.rank_address;
513 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
514 isaddress, distance, cached_rank_address)
515 VALUES (obj_place_id, location.place_id, not location.isguess,
516 true, location.distance, location.rank_address);
518 addr_place_ids := addr_place_ids || location.place_id;
523 SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
524 WHERE not addr_place_ids @> ARRAY[place_id]
525 ORDER BY rank_address, isguess asc,
527 CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
528 WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
529 WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
532 -- Ignore all place nodes that do not fit in a lower level boundary.
533 CONTINUE WHEN location.isguess
534 and current_boundary is not NULL
535 and not ST_Contains(current_boundary, location.centroid);
537 -- If this is the first item in the rank, then assume it is the address.
538 location_isaddress := not address_havelevel[location.rank_address];
540 -- Further sanity checks to ensure that the address forms a sane hierarchy.
541 IF location_isaddress THEN
542 IF location.isguess and current_node_area is not NULL THEN
543 location_isaddress := ST_Contains(current_node_area, location.centroid);
545 IF not location.isguess and current_boundary is not NULL
546 and location.rank_address != 11 AND location.rank_address != 5 THEN
547 location_isaddress := ST_Contains(current_boundary, location.centroid);
551 IF location_isaddress THEN
552 address_havelevel[location.rank_address] := true;
553 parent_place_id := location.place_id;
555 -- Set postcode if we have one.
556 -- (Returned will be the highest ranking one.)
557 IF location.postcode is not NULL THEN
558 postcode = location.postcode;
561 -- Recompute the areas we need for hierarchy sanity checks.
562 IF location.rank_address != 11 AND location.rank_address != 5 THEN
563 IF location.isguess THEN
564 current_node_area := place_node_fuzzy_area(location.centroid,
565 location.rank_search);
567 current_node_area := NULL;
568 SELECT p.geometry FROM placex p
569 WHERE p.place_id = location.place_id INTO current_boundary;
574 -- Add it to the list of search terms
575 {% if not db.reverse_only %}
576 nameaddress_vector := array_merge(nameaddress_vector,
577 location.keywords::integer[]);
580 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
581 isaddress, distance, cached_rank_address)
582 VALUES (obj_place_id, location.place_id, not location.isguess,
583 location_isaddress, location.distance, location.rank_address);
590 CREATE OR REPLACE FUNCTION placex_insert()
597 country_code VARCHAR(2);
601 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
603 NEW.place_id := nextval('seq_place');
604 NEW.indexed_status := 1; --STATUS_NEW
606 NEW.centroid := ST_PointOnSurface(NEW.geometry);
607 NEW.country_code := lower(get_country_code(NEW.centroid));
609 NEW.partition := get_partition(NEW.country_code);
610 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
612 IF NEW.osm_type = 'X' THEN
613 -- E'X'ternal records should already be in the right format so do nothing
615 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
617 IF NEW.class in ('place','boundary')
618 AND NEW.type in ('postcode','postal_code')
620 IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
621 -- most likely just a part of a multipolygon postcode boundary, throw it away
625 NEW.name := hstore('ref', NEW.address->'postcode');
627 ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
628 AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
631 ELSEIF NEW.class = 'boundary' AND NOT is_area
634 ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
635 AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
640 SELECT * INTO NEW.rank_search, NEW.rank_address
641 FROM compute_place_rank(NEW.country_code,
642 CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
643 NEW.class, NEW.type, NEW.admin_level,
644 (NEW.extratags->'capital') = 'yes',
645 NEW.address->'postcode');
647 -- a country code make no sense below rank 4 (country)
648 IF NEW.rank_search < 4 THEN
649 NEW.country_code := NULL;
654 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
656 {% if not disable_diff_updates %}
657 -- The following is not needed until doing diff updates, and slows the main index process down
659 IF NEW.rank_address > 0 THEN
660 IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
661 -- Performance: We just can't handle re-indexing for country level changes
662 IF st_area(NEW.geometry) < 1 THEN
663 -- mark items within the geometry for re-indexing
664 -- RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
666 UPDATE placex SET indexed_status = 2
667 WHERE ST_Intersects(NEW.geometry, placex.geometry)
668 and indexed_status = 0
669 and ((rank_address = 0 and rank_search > NEW.rank_address)
670 or rank_address > NEW.rank_address
671 or (class = 'place' and osm_type = 'N')
673 and (rank_search < 28
675 or (NEW.rank_address >= 16 and address ? 'place'));
678 -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
679 diameter := update_place_diameter(NEW.rank_search);
681 -- RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
682 IF NEW.rank_search >= 26 THEN
683 -- roads may cause reparenting for >27 rank places
684 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
685 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
686 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);
687 ELSEIF NEW.rank_search >= 16 THEN
688 -- up to rank 16, street-less addresses may need reparenting
689 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');
691 -- for all other places the search terms may change as well
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);
699 -- add to tables for special search
700 -- Note: won't work on initial import because the classtype tables
701 -- do not yet exist. It won't hurt either.
702 classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
703 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
705 EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)'
706 USING NEW.place_id, ST_Centroid(NEW.geometry);
709 {% endif %} -- not disable_diff_updates
717 CREATE OR REPLACE FUNCTION placex_update()
723 relation_members TEXT[];
726 parent_address_level SMALLINT;
727 place_address_level SMALLINT;
731 name_vector INTEGER[];
732 nameaddress_vector INTEGER[];
733 addr_nameaddress_vector INTEGER[];
737 linked_node_id BIGINT;
738 linked_importance FLOAT;
739 linked_wikipedia TEXT;
741 is_place_address BOOLEAN;
745 IF OLD.indexed_status = 100 THEN
746 {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
747 delete from placex where place_id = OLD.place_id;
751 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
755 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
757 NEW.indexed_date = now();
759 {% if 'search_name' in db.tables %}
760 DELETE from search_name WHERE place_id = NEW.place_id;
762 result := deleteSearchName(NEW.partition, NEW.place_id);
763 DELETE FROM place_addressline WHERE place_id = NEW.place_id;
764 result := deleteRoad(NEW.partition, NEW.place_id);
765 result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
767 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
769 -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
770 -- the previous link status.
771 linked_place := NEW.linked_place_id;
772 NEW.linked_place_id := OLD.linked_place_id;
774 -- Remove linkage, if we have computed a different new linkee.
775 UPDATE placex SET linked_place_id = null, indexed_status = 2
776 WHERE linked_place_id = NEW.place_id
777 and (linked_place is null or linked_place_id != linked_place);
778 -- update not necessary for osmline, cause linked_place_id does not exist
780 -- Postcodes are just here to compute the centroids. They are not searchable
781 -- unless they are a boundary=postal_code.
782 -- There was an error in the style so that boundary=postal_code used to be
783 -- imported as place=postcode. That's why relations are allowed to pass here.
784 -- This can go away in a couple of versions.
785 IF NEW.class = 'place' and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
786 NEW.token_info := null;
790 -- Compute a preliminary centroid.
791 NEW.centroid := ST_PointOnSurface(NEW.geometry);
793 -- recalculate country and partition
794 IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
795 -- for countries, believe the mapped country code,
796 -- so that we remain in the right partition if the boundaries
798 NEW.country_code := lower(NEW.address->'country');
799 NEW.partition := get_partition(lower(NEW.country_code));
800 IF NEW.partition = 0 THEN
801 NEW.country_code := lower(get_country_code(NEW.centroid));
802 NEW.partition := get_partition(NEW.country_code);
805 IF NEW.rank_search >= 4 THEN
806 NEW.country_code := lower(get_country_code(NEW.centroid));
808 NEW.country_code := NULL;
810 NEW.partition := get_partition(NEW.country_code);
812 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
815 -- recompute the ranks, they might change when linking changes
816 SELECT * INTO NEW.rank_search, NEW.rank_address
817 FROM compute_place_rank(NEW.country_code,
818 CASE WHEN ST_GeometryType(NEW.geometry)
819 IN ('ST_Polygon','ST_MultiPolygon')
820 THEN 'A' ELSE NEW.osm_type END,
821 NEW.class, NEW.type, NEW.admin_level,
822 (NEW.extratags->'capital') = 'yes',
823 NEW.address->'postcode');
825 -- Short-cut out for linked places. Note that this must happen after the
826 -- address rank has been recomputed. The linking might nullify a shift in
828 IF NEW.linked_place_id is not null THEN
829 NEW.token_info := null;
830 {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
834 -- We must always increase the address level relative to the admin boundary.
835 IF NEW.class = 'boundary' and NEW.type = 'administrative'
836 and NEW.osm_type = 'R' and NEW.rank_address > 0
838 -- First, check that admin boundaries do not overtake each other rank-wise.
839 parent_address_level := 3;
842 (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
843 and extratags->'wikidata' = NEW.extratags->'wikidata'
844 THEN ST_Equals(geometry, NEW.geometry)
845 ELSE false END) as is_same
847 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
848 and admin_level < NEW.admin_level and admin_level > 3
850 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
851 ORDER BY admin_level desc LIMIT 1
853 IF location.is_same THEN
854 -- Looks like the same boundary is replicated on multiple admin_levels.
855 -- Usual tagging in Poland. Remove our boundary from addresses.
856 NEW.rank_address := 0;
858 parent_address_level := location.rank_address;
859 IF location.rank_address >= NEW.rank_address THEN
860 IF location.rank_address >= 24 THEN
861 NEW.rank_address := 25;
863 NEW.rank_address := location.rank_address + 2;
869 IF NEW.rank_address > 9 THEN
870 -- Second check that the boundary is not completely contained in a
871 -- place area with a equal or higher address rank.
875 LATERAL compute_place_rank(country_code, 'A', class, type,
876 admin_level, False, null) prank
877 WHERE class = 'place' and rank_address < 24
878 and prank.address_rank >= NEW.rank_address
879 and geometry && NEW.geometry
880 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
881 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
882 ORDER BY prank.address_rank desc LIMIT 1
884 NEW.rank_address := location.rank_address + 2;
887 ELSEIF NEW.class = 'place'
888 and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
889 and NEW.rank_address between 16 and 23
891 -- For place areas make sure they are not completely contained in an area
892 -- with a equal or higher address rank.
896 LATERAL compute_place_rank(country_code, 'A', class, type,
897 admin_level, False, null) prank
898 WHERE prank.address_rank < 24
899 and prank.address_rank >= NEW.rank_address
900 and geometry && NEW.geometry
901 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
902 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
903 ORDER BY prank.address_rank desc LIMIT 1
905 NEW.rank_address := location.rank_address + 2;
907 ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
908 and NEW.rank_address between 16 and 23
910 -- If a place node is contained in an admin or place boundary with the same
911 -- address level and has not been linked, then make the node a subpart
912 -- by increasing the address rank (city level and above).
916 LATERAL compute_place_rank(country_code, 'A', class, type,
917 admin_level, False, null) prank
919 and ((class = 'place' and prank.address_rank = NEW.rank_address)
920 or (class = 'boundary' and rank_address = NEW.rank_address))
921 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
924 NEW.rank_address = NEW.rank_address + 2;
927 parent_address_level := 3;
930 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
932 NEW.postcode := null;
934 -- waterway ways are linked when they are part of a relation and have the same class/type
935 IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
936 FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
938 FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
939 IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
940 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
941 FOR linked_node_id IN SELECT place_id FROM placex
942 WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
943 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
944 and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
946 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
947 {% if 'search_name' in db.tables %}
948 DELETE FROM search_name WHERE place_id = linked_node_id;
954 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
957 NEW.importance := null;
958 SELECT wikipedia, importance
959 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
960 INTO NEW.wikipedia,NEW.importance;
962 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
964 -- ---------------------------------------------------------------------------
965 -- For low level elements we inherit from our parent road
966 IF NEW.rank_search > 27 THEN
968 {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
969 NEW.parent_place_id := null;
970 is_place_address := coalesce(not NEW.address ? 'street' and NEW.address ? 'place', FALSE);
972 -- We have to find our parent road.
973 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
975 ST_Envelope(NEW.geometry),
979 -- If we found the road take a shortcut here.
980 -- Otherwise fall back to the full address getting method below.
981 IF NEW.parent_place_id is not null THEN
983 -- Get the details of the parent road
984 SELECT p.country_code, p.postcode, p.name FROM placex p
985 WHERE p.place_id = NEW.parent_place_id INTO location;
987 IF is_place_address THEN
988 -- Check if the addr:place tag is part of the parent name
989 SELECT count(*) INTO i
990 FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
992 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
996 NEW.country_code := location.country_code;
997 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
999 -- determine postcode
1000 NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1002 get_nearest_postcode(NEW.country_code, NEW.centroid));
1004 IF NEW.name is not NULL THEN
1005 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1008 {% if not db.reverse_only %}
1009 IF NEW.name is not NULL OR NEW.address is not NULL THEN
1010 SELECT * INTO name_vector, nameaddress_vector
1011 FROM create_poi_search_terms(NEW.place_id,
1012 NEW.partition, NEW.parent_place_id,
1013 is_place_address, NEW.country_code,
1014 NEW.token_info, NEW.centroid);
1016 IF array_length(name_vector, 1) is not NULL THEN
1017 INSERT INTO search_name (place_id, search_rank, address_rank,
1018 importance, country_code, name_vector,
1019 nameaddress_vector, centroid)
1020 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1021 NEW.importance, NEW.country_code, name_vector,
1022 nameaddress_vector, NEW.centroid);
1023 {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1028 NEW.token_info := token_strip_info(NEW.token_info);
1035 -- ---------------------------------------------------------------------------
1037 {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1038 IF linked_place is not null THEN
1039 -- Recompute the ranks here as the ones from the linked place might
1040 -- have been shifted to accommodate surrounding boundaries.
1041 SELECT place_id, osm_id, class, type, extratags,
1043 (compute_place_rank(country_code, osm_type, class, type, admin_level,
1044 (extratags->'capital') = 'yes', null)).*
1046 FROM placex WHERE place_id = linked_place;
1048 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1050 -- Use the linked point as the centre point of the geometry,
1051 -- but only if it is within the area of the boundary.
1052 geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1053 IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1054 NEW.centroid := geom;
1057 {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1058 IF location.address_rank > parent_address_level
1059 and location.address_rank < 26
1061 NEW.rank_address := location.address_rank;
1064 -- merge in extra tags
1065 NEW.extratags := hstore('linked_' || location.class, location.type)
1066 || coalesce(location.extratags, ''::hstore)
1067 || coalesce(NEW.extratags, ''::hstore);
1069 -- mark the linked place (excludes from search results)
1070 -- Force reindexing to remove any traces from the search indexes and
1071 -- reset the address rank if necessary.
1072 UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1073 WHERE place_id = location.place_id;
1074 -- ensure that those places are not found anymore
1075 {% if 'search_name' in db.tables %}
1076 DELETE FROM search_name WHERE place_id = location.place_id;
1078 PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
1080 SELECT wikipedia, importance
1081 FROM compute_importance(location.extratags, NEW.country_code,
1082 'N', location.osm_id)
1083 INTO linked_wikipedia,linked_importance;
1085 -- Use the maximum importance if one could be computed from the linked object.
1086 IF linked_importance is not null AND
1087 (NEW.importance is null or NEW.importance < linked_importance)
1089 NEW.importance = linked_importance;
1092 -- No linked place? As a last resort check if the boundary is tagged with
1093 -- a place type and adapt the rank address.
1094 IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
1095 SELECT address_rank INTO place_address_level
1096 FROM compute_place_rank(NEW.country_code, 'A', 'place',
1097 NEW.extratags->'place', 0::SMALLINT, False, null);
1098 IF place_address_level > parent_address_level and
1099 place_address_level < 26 THEN
1100 NEW.rank_address := place_address_level;
1105 {% if not disable_diff_updates %}
1106 IF OLD.rank_address != NEW.rank_address THEN
1107 -- After a rank shift all addresses containing us must be updated.
1108 UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1109 WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1110 and p.indexed_status = 0 and p.rank_address between 4 and 25;
1114 IF NEW.admin_level = 2
1115 AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1116 AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1118 -- Update the list of country names.
1119 -- Only take the name from the largest area for the given country code
1120 -- in the hope that this is the authoritative one.
1121 -- Also replace any old names so that all mapping mistakes can
1122 -- be fixed through regular OSM updates.
1124 SELECT osm_id FROM placex
1125 WHERE rank_search = 4 and osm_type = 'R'
1126 and country_code = NEW.country_code
1127 ORDER BY ST_Area(geometry) desc
1130 IF location.osm_id = NEW.osm_id THEN
1131 {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1132 UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1137 -- For linear features we need the full geometry for determining the address
1138 -- because they may go through several administrative entities. Otherwise use
1139 -- the centroid for performance reasons.
1140 IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1141 geom := NEW.geometry;
1143 geom := NEW.centroid;
1146 IF NEW.rank_address = 0 THEN
1147 max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1148 -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1149 -- so use the geometry here too. Just make sure the areas don't become too
1151 IF NEW.class = 'natural' or max_rank > 10 THEN
1152 geom := NEW.geometry;
1154 ELSEIF NEW.rank_address > 25 THEN
1157 max_rank := NEW.rank_address;
1160 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1161 NEW.token_info, geom, NEW.centroid,
1163 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1165 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1167 NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1169 -- if we have a name add this to the name search table
1170 IF NEW.name IS NOT NULL THEN
1171 -- Initialise the name vector using our name
1172 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1173 name_vector := token_get_name_search_tokens(NEW.token_info);
1175 IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1176 result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1177 name_vector, NEW.rank_search, NEW.rank_address,
1178 NEW.postcode, NEW.geometry, NEW.centroid);
1179 {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1182 IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1183 result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1184 {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1187 IF NEW.rank_address between 16 and 27 THEN
1188 result := insertSearchName(NEW.partition, NEW.place_id,
1189 token_get_name_match_tokens(NEW.token_info),
1190 NEW.rank_search, NEW.rank_address, NEW.geometry);
1192 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1194 {% if not db.reverse_only %}
1195 INSERT INTO search_name (place_id, search_rank, address_rank,
1196 importance, country_code, name_vector,
1197 nameaddress_vector, centroid)
1198 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1199 NEW.importance, NEW.country_code, name_vector,
1200 nameaddress_vector, NEW.centroid);
1204 IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1205 NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1208 {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1210 NEW.token_info := token_strip_info(NEW.token_info);
1217 CREATE OR REPLACE FUNCTION placex_delete()
1224 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1226 IF OLD.linked_place_id is null THEN
1227 update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1228 {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1229 update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1230 {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1232 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1235 IF OLD.rank_address < 30 THEN
1237 -- mark everything linked to this place for re-indexing
1238 {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1239 UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id
1240 and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1242 {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1243 DELETE FROM place_addressline where address_place_id = OLD.place_id;
1245 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1246 b := deleteRoad(OLD.partition, OLD.place_id);
1248 {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1249 update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1250 {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1251 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1252 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1256 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1258 IF OLD.rank_address < 26 THEN
1259 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1262 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1264 IF OLD.name is not null THEN
1265 {% if 'search_name' in db.tables %}
1266 DELETE from search_name WHERE place_id = OLD.place_id;
1268 b := deleteSearchName(OLD.partition, OLD.place_id);
1271 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1273 DELETE FROM place_addressline where place_id = OLD.place_id;
1275 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1277 -- remove from tables for special search
1278 classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1279 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1281 EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1284 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}