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
22 -- Retrieve the data needed by the indexer for updating the place.
23 CREATE OR REPLACE FUNCTION placex_indexing_prepare(p placex)
24 RETURNS prepare_update_info
28 result prepare_update_info;
31 -- For POI nodes, check if the address should be derived from a surrounding
33 IF p.rank_search < 30 OR p.osm_type != 'N' THEN
34 result.address := p.address;
35 ELSEIF p.address is null THEN
36 -- The additional && condition works around the misguided query
37 -- planner of postgis 3.0.
38 SELECT placex.address || hstore('_inherited', '') INTO result.address
40 WHERE ST_Covers(geometry, p.centroid)
41 and geometry && p.centroid
42 and placex.address is not null
43 and (placex.address ? 'housenumber' or placex.address ? 'street' or placex.address ? 'place')
44 and rank_search = 30 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
47 result.address := p.address;
48 -- See if we can inherit addtional address tags from an interpolation.
49 -- These will become permanent.
51 SELECT (address - 'interpolation'::text - 'housenumber'::text) as address
52 FROM place, planet_osm_ways w
53 WHERE place.osm_type = 'W' and place.address ? 'interpolation'
54 and place.geometry && p.geometry
55 and place.osm_id = w.id
56 and p.osm_id = any(w.nodes)
58 result.address := location.address || result.address;
62 -- remove internal and derived names
63 result.address := result.address - '_unlisted_place'::TEXT;
64 SELECT hstore(array_agg(key), array_agg(value)) INTO result.name
65 FROM each(p.name) WHERE key not like '\_%';
67 result.class := p.class;
68 result.type := p.type;
69 result.country_code := p.country_code;
70 result.rank_address := p.rank_address;
72 -- Names of linked places need to be merged in, so search for a linkable
73 -- place already here.
74 SELECT * INTO location FROM find_linked_place(p);
76 IF location.place_id is not NULL THEN
77 result.linked_place_id := location.place_id;
79 IF location.name is not NULL THEN
80 {% if debug %}RAISE WARNING 'Names original: %, location: %', result.name, location.name;{% endif %}
81 -- Add all names from the place nodes that deviate from the name
82 -- in the relation with the prefix '_place_'. Deviation means that
83 -- either the value is different or a given key is missing completely
84 SELECT hstore(array_agg('_place_' || key), array_agg(value)) INTO extra_names
85 FROM each(location.name - result.name);
86 {% if debug %}RAISE WARNING 'Extra names: %', extra_names;{% endif %}
88 IF extra_names is not null THEN
89 result.name := result.name || extra_names;
92 {% if debug %}RAISE WARNING 'Final names: %', result.name;{% endif %}
99 LANGUAGE plpgsql STABLE;
102 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
111 SELECT members FROM planet_osm_rels
112 WHERE parts @> ARRAY[poi_osm_id]
113 and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
114 and tags @> ARRAY['associatedStreet']
116 FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
117 IF location.members[i+1] = 'street' THEN
119 SELECT place_id from placex
120 WHERE osm_type = 'W' and osm_id = substring(location.members[i],2)::bigint
122 and rank_search between 26 and 27
124 RETURN parent.place_id;
133 LANGUAGE plpgsql STABLE;
136 -- Find the parent road of a POI.
138 -- \returns Place ID of parent object or NULL if none
140 -- Copy data from linked items (POIs on ways, addr:street links, relations).
142 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
144 poi_partition SMALLINT,
147 is_place_addr BOOLEAN)
151 parent_place_id BIGINT DEFAULT NULL;
154 {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
156 -- Is this object part of an associatedStreet relation?
157 parent_place_id := find_associated_street(poi_osm_type, poi_osm_id);
159 IF parent_place_id is null THEN
160 parent_place_id := find_parent_for_address(token_info, poi_partition, bbox);
163 IF parent_place_id is null and poi_osm_type = 'N' THEN
165 SELECT p.place_id, p.osm_id, p.rank_search, p.address,
166 coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
167 FROM placex p, planet_osm_ways w
168 WHERE p.osm_type = 'W' and p.rank_search >= 26
169 and p.geometry && bbox
170 and w.id = p.osm_id and poi_osm_id = any(w.nodes)
172 {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
174 -- Way IS a road then we are on it - that must be our road
175 IF location.rank_search < 28 THEN
176 {% if debug %}RAISE WARNING 'node in way that is a street %',location;{% endif %}
177 RETURN location.place_id;
180 parent_place_id := find_associated_street('W', location.osm_id);
184 IF parent_place_id is NULL THEN
185 IF is_place_addr THEN
186 -- The address is attached to a place we don't know.
187 -- Instead simply use the containing area with the largest rank.
189 SELECT place_id FROM placex
190 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
191 AND rank_address between 5 and 25
192 ORDER BY rank_address desc
194 RETURN location.place_id;
196 ELSEIF ST_Area(bbox) < 0.005 THEN
197 -- for smaller features get the nearest road
198 SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
199 {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
201 -- for larger features simply find the area with the largest rank that
202 -- contains the bbox, only use addressable features
204 SELECT place_id FROM placex
205 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
206 AND rank_address between 5 and 25
207 ORDER BY rank_address desc
209 RETURN location.place_id;
214 RETURN parent_place_id;
217 LANGUAGE plpgsql STABLE;
219 -- Try to find a linked place for the given object.
220 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
224 relation_members TEXT[];
226 linked_placex placex%ROWTYPE;
229 IF bnd.rank_search >= 26 or bnd.rank_address = 0
230 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
231 or bnd.type IN ('postcode', 'postal_code')
236 IF bnd.osm_type = 'R' THEN
237 -- see if we have any special relation members
238 SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
239 {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
241 -- Search for relation members with role 'lable'.
242 IF relation_members IS NOT NULL THEN
244 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
246 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
250 WHERE osm_type = 'N' and osm_id = rel_member.member
253 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
254 RETURN linked_placex;
261 IF bnd.name ? 'name' THEN
262 bnd_name := lower(bnd.name->'name');
263 IF bnd_name = '' THEN
268 -- If extratags has a place tag, look for linked nodes by their place type.
269 -- Area and node still have to have the same name.
270 IF bnd.extratags ? 'place' and bnd_name is not null THEN
273 WHERE (position(lower(name->'name') in bnd_name) > 0
274 OR position(bnd_name in lower(name->'name')) > 0)
275 AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
276 AND placex.osm_type = 'N'
277 AND placex.linked_place_id is null
278 AND placex.rank_search < 26 -- needed to select the right index
279 AND placex.type != 'postcode'
280 AND ST_Covers(bnd.geometry, placex.geometry)
282 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
283 RETURN linked_placex;
287 IF bnd.extratags ? 'wikidata' THEN
290 WHERE placex.class = 'place' AND placex.osm_type = 'N'
291 AND placex.extratags ? 'wikidata' -- needed to select right index
292 AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
293 AND placex.linked_place_id is null
294 AND placex.rank_search < 26
295 AND _st_covers(bnd.geometry, placex.geometry)
296 ORDER BY lower(name->'name') = bnd_name desc
298 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
299 RETURN linked_placex;
303 -- Name searches can be done for ways as well as relations
304 IF bnd_name is not null THEN
305 {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
307 SELECT placex.* from placex
308 WHERE lower(name->'name') = bnd_name
309 AND ((bnd.rank_address > 0
310 and bnd.rank_address = (compute_place_rank(placex.country_code,
312 placex.type, 15::SMALLINT,
313 false, placex.postcode)).address_rank)
314 OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
315 AND placex.osm_type = 'N'
316 AND placex.class = 'place'
317 AND placex.linked_place_id is null
318 AND placex.rank_search < 26 -- needed to select the right index
319 AND placex.type != 'postcode'
320 AND ST_Covers(bnd.geometry, placex.geometry)
322 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
323 RETURN linked_placex;
330 LANGUAGE plpgsql STABLE;
333 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
334 in_partition SMALLINT,
335 parent_place_id BIGINT,
336 is_place_addr BOOLEAN,
340 OUT name_vector INTEGER[],
341 OUT nameaddress_vector INTEGER[])
344 parent_name_vector INTEGER[];
345 parent_address_vector INTEGER[];
346 addr_place_ids INTEGER[];
347 hnr_vector INTEGER[];
351 parent_address_place_ids BIGINT[];
353 nameaddress_vector := '{}'::INTEGER[];
355 SELECT s.name_vector, s.nameaddress_vector
356 INTO parent_name_vector, parent_address_vector
358 WHERE s.place_id = parent_place_id;
362 token_get_address_search_tokens(token_info, key) as search_tokens
363 FROM token_get_address_keys(token_info) as key,
364 LATERAL get_addr_tag_rank(key, country) as ranks
365 WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
367 addr_place := get_address_place(in_partition, geometry,
368 addr_item.from_rank, addr_item.to_rank,
369 addr_item.extent, token_info, addr_item.key);
371 IF addr_place is null THEN
372 -- No place found in OSM that matches. Make it at least searchable.
373 nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
375 IF parent_address_place_ids is null THEN
376 SELECT array_agg(parent_place_id) INTO parent_address_place_ids
377 FROM place_addressline
378 WHERE place_id = parent_place_id;
381 -- If the parent already lists the place in place_address line, then we
382 -- are done. Otherwise, add its own place_address line.
383 IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
384 nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
386 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
387 isaddress, distance, cached_rank_address)
388 VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
389 true, addr_place.distance, addr_place.rank_address);
394 name_vector := token_get_name_search_tokens(token_info);
396 -- Check if the parent covers all address terms.
397 -- If not, create a search name entry with the house number as the name.
398 -- This is unusual for the search_name table but prevents that the place
399 -- is returned when we only search for the street/place.
401 hnr_vector := token_get_housenumber_search_tokens(token_info);
403 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
404 name_vector := array_merge(name_vector, hnr_vector);
407 IF is_place_addr THEN
408 addr_place_ids := token_addr_place_search_tokens(token_info);
409 IF not addr_place_ids <@ parent_name_vector THEN
410 -- make sure addr:place terms are always searchable
411 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
412 -- If there is a housenumber, also add the place name as a name,
413 -- so we can search it by the usual housenumber+place algorithms.
414 IF hnr_vector is not null THEN
415 name_vector := array_merge(name_vector, addr_place_ids);
420 -- Cheating here by not recomputing all terms but simply using the ones
421 -- from the parent object.
422 nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
423 nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
430 -- Insert address of a place into the place_addressline table.
432 -- \param obj_place_id Place_id of the place to compute the address for.
433 -- \param partition Partition number where the place is in.
434 -- \param maxrank Rank of the place. All address features must have
435 -- a search rank lower than the given rank.
436 -- \param address Address terms for the place.
437 -- \param geometry Geometry to which the address objects should be close.
439 -- \retval parent_place_id Place_id of the address object that is the direct
441 -- \retval postcode Postcode computed from the address. This is the
442 -- addr:postcode of one of the address objects. If
443 -- more than one of has a postcode, the highest ranking
444 -- one is used. May be NULL.
445 -- \retval nameaddress_vector Search terms for the address. This is the sum
446 -- of name terms of all address objects.
447 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
454 OUT parent_place_id BIGINT,
456 OUT nameaddress_vector INT[])
459 address_havelevel BOOLEAN[];
461 location_isaddress BOOLEAN;
462 current_boundary GEOMETRY := NULL;
463 current_node_area GEOMETRY := NULL;
465 parent_place_rank INT := 0;
466 addr_place_ids BIGINT[] := '{}'::int[];
467 new_address_vector INT[];
471 parent_place_id := 0;
472 nameaddress_vector := '{}'::int[];
474 address_havelevel := array_fill(false, ARRAY[maxrank]);
478 FROM (SELECT extra.*, key
479 FROM token_get_address_keys(token_info) as key,
480 LATERAL get_addr_tag_rank(key, country) as extra) x,
481 LATERAL get_address_place(partition, geometry, from_rank, to_rank,
482 extent, token_info, key) as apl
483 ORDER BY rank_address, distance, isguess desc
485 IF location.place_id is null THEN
486 {% if not db.reverse_only %}
487 nameaddress_vector := array_merge(nameaddress_vector,
488 token_get_address_search_tokens(token_info,
492 {% if not db.reverse_only %}
493 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
496 location_isaddress := not address_havelevel[location.rank_address];
497 IF not address_havelevel[location.rank_address] THEN
498 address_havelevel[location.rank_address] := true;
499 IF parent_place_rank < location.rank_address THEN
500 parent_place_id := location.place_id;
501 parent_place_rank := location.rank_address;
505 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
506 isaddress, distance, cached_rank_address)
507 VALUES (obj_place_id, location.place_id, not location.isguess,
508 true, location.distance, location.rank_address);
510 addr_place_ids := addr_place_ids || location.place_id;
515 SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
516 WHERE not addr_place_ids @> ARRAY[place_id]
517 ORDER BY rank_address, isguess asc,
519 CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
520 WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
521 WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
524 -- Ignore all place nodes that do not fit in a lower level boundary.
525 CONTINUE WHEN location.isguess
526 and current_boundary is not NULL
527 and not ST_Contains(current_boundary, location.centroid);
529 -- If this is the first item in the rank, then assume it is the address.
530 location_isaddress := not address_havelevel[location.rank_address];
532 -- Further sanity checks to ensure that the address forms a sane hierarchy.
533 IF location_isaddress THEN
534 IF location.isguess and current_node_area is not NULL THEN
535 location_isaddress := ST_Contains(current_node_area, location.centroid);
537 IF not location.isguess and current_boundary is not NULL
538 and location.rank_address != 11 AND location.rank_address != 5 THEN
539 location_isaddress := ST_Contains(current_boundary, location.centroid);
543 IF location_isaddress THEN
544 address_havelevel[location.rank_address] := true;
545 parent_place_id := location.place_id;
547 -- Set postcode if we have one.
548 -- (Returned will be the highest ranking one.)
549 IF location.postcode is not NULL THEN
550 postcode = location.postcode;
553 -- Recompute the areas we need for hierarchy sanity checks.
554 IF location.rank_address != 11 AND location.rank_address != 5 THEN
555 IF location.isguess THEN
556 current_node_area := place_node_fuzzy_area(location.centroid,
557 location.rank_search);
559 current_node_area := NULL;
560 SELECT p.geometry FROM placex p
561 WHERE p.place_id = location.place_id INTO current_boundary;
566 -- Add it to the list of search terms
567 {% if not db.reverse_only %}
568 nameaddress_vector := array_merge(nameaddress_vector,
569 location.keywords::integer[]);
572 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
573 isaddress, distance, cached_rank_address)
574 VALUES (obj_place_id, location.place_id, not location.isguess,
575 location_isaddress, location.distance, location.rank_address);
582 CREATE OR REPLACE FUNCTION placex_insert()
589 country_code VARCHAR(2);
593 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
595 NEW.place_id := nextval('seq_place');
596 NEW.indexed_status := 1; --STATUS_NEW
598 NEW.centroid := ST_PointOnSurface(NEW.geometry);
599 NEW.country_code := lower(get_country_code(NEW.centroid));
601 NEW.partition := get_partition(NEW.country_code);
602 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
604 IF NEW.osm_type = 'X' THEN
605 -- E'X'ternal records should already be in the right format so do nothing
607 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
609 IF NEW.class in ('place','boundary')
610 AND NEW.type in ('postcode','postal_code')
612 IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
613 -- most likely just a part of a multipolygon postcode boundary, throw it away
617 NEW.name := hstore('ref', NEW.address->'postcode');
619 ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
620 AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
623 ELSEIF NEW.class = 'boundary' AND NOT is_area
626 ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
627 AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
632 SELECT * INTO NEW.rank_search, NEW.rank_address
633 FROM compute_place_rank(NEW.country_code,
634 CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
635 NEW.class, NEW.type, NEW.admin_level,
636 (NEW.extratags->'capital') = 'yes',
637 NEW.address->'postcode');
639 -- a country code make no sense below rank 4 (country)
640 IF NEW.rank_search < 4 THEN
641 NEW.country_code := NULL;
646 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
648 {% if not disable_diff_updates %}
649 -- The following is not needed until doing diff updates, and slows the main index process down
651 IF NEW.rank_address > 0 THEN
652 IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
653 -- Performance: We just can't handle re-indexing for country level changes
654 IF st_area(NEW.geometry) < 1 THEN
655 -- mark items within the geometry for re-indexing
656 -- RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
658 UPDATE placex SET indexed_status = 2
659 WHERE ST_Intersects(NEW.geometry, placex.geometry)
660 and indexed_status = 0
661 and ((rank_address = 0 and rank_search > NEW.rank_address)
662 or rank_address > NEW.rank_address
663 or (class = 'place' and osm_type = 'N')
665 and (rank_search < 28
667 or (NEW.rank_address >= 16 and address ? 'place'));
670 -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
671 diameter := update_place_diameter(NEW.rank_search);
673 -- RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
674 IF NEW.rank_search >= 26 THEN
675 -- roads may cause reparenting for >27 rank places
676 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
677 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
678 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);
679 ELSEIF NEW.rank_search >= 16 THEN
680 -- up to rank 16, street-less addresses may need reparenting
681 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');
683 -- for all other places the search terms may change as well
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) and (rank_search < 28 or name is not null);
691 -- add to tables for special search
692 -- Note: won't work on initial import because the classtype tables
693 -- do not yet exist. It won't hurt either.
694 classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
695 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
697 EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)'
698 USING NEW.place_id, ST_Centroid(NEW.geometry);
701 {% endif %} -- not disable_diff_updates
709 CREATE OR REPLACE FUNCTION placex_update()
715 relation_members TEXT[];
718 parent_address_level SMALLINT;
719 place_address_level SMALLINT;
723 name_vector INTEGER[];
724 nameaddress_vector INTEGER[];
725 addr_nameaddress_vector INTEGER[];
729 linked_node_id BIGINT;
730 linked_importance FLOAT;
731 linked_wikipedia TEXT;
733 is_place_address BOOLEAN;
737 IF OLD.indexed_status = 100 THEN
738 {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
739 delete from placex where place_id = OLD.place_id;
743 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
747 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
749 NEW.indexed_date = now();
751 {% if 'search_name' in db.tables %}
752 DELETE from search_name WHERE place_id = NEW.place_id;
754 result := deleteSearchName(NEW.partition, NEW.place_id);
755 DELETE FROM place_addressline WHERE place_id = NEW.place_id;
756 result := deleteRoad(NEW.partition, NEW.place_id);
757 result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
758 UPDATE placex set linked_place_id = null, indexed_status = 2
759 where linked_place_id = NEW.place_id;
760 -- update not necessary for osmline, cause linked_place_id does not exist
762 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
764 -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
765 -- the previous link status.
766 linked_place := NEW.linked_place_id;
767 NEW.linked_place_id := OLD.linked_place_id;
769 IF NEW.linked_place_id is not null THEN
770 NEW.token_info := null;
771 {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
775 -- Postcodes are just here to compute the centroids. They are not searchable
776 -- unless they are a boundary=postal_code.
777 -- There was an error in the style so that boundary=postal_code used to be
778 -- imported as place=postcode. That's why relations are allowed to pass here.
779 -- This can go away in a couple of versions.
780 IF NEW.class = 'place' and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
781 NEW.token_info := null;
785 -- Compute a preliminary centroid.
786 NEW.centroid := ST_PointOnSurface(NEW.geometry);
788 -- recalculate country and partition
789 IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
790 -- for countries, believe the mapped country code,
791 -- so that we remain in the right partition if the boundaries
793 NEW.country_code := lower(NEW.address->'country');
794 NEW.partition := get_partition(lower(NEW.country_code));
795 IF NEW.partition = 0 THEN
796 NEW.country_code := lower(get_country_code(NEW.centroid));
797 NEW.partition := get_partition(NEW.country_code);
800 IF NEW.rank_search >= 4 THEN
801 NEW.country_code := lower(get_country_code(NEW.centroid));
803 NEW.country_code := NULL;
805 NEW.partition := get_partition(NEW.country_code);
807 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
810 -- recompute the ranks, they might change when linking changes
811 SELECT * INTO NEW.rank_search, NEW.rank_address
812 FROM compute_place_rank(NEW.country_code,
813 CASE WHEN ST_GeometryType(NEW.geometry)
814 IN ('ST_Polygon','ST_MultiPolygon')
815 THEN 'A' ELSE NEW.osm_type END,
816 NEW.class, NEW.type, NEW.admin_level,
817 (NEW.extratags->'capital') = 'yes',
818 NEW.address->'postcode');
819 -- We must always increase the address level relative to the admin boundary.
820 IF NEW.class = 'boundary' and NEW.type = 'administrative'
821 and NEW.osm_type = 'R' and NEW.rank_address > 0
823 -- First, check that admin boundaries do not overtake each other rank-wise.
824 parent_address_level := 3;
827 (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
828 and extratags->'wikidata' = NEW.extratags->'wikidata'
829 THEN ST_Equals(geometry, NEW.geometry)
830 ELSE false END) as is_same
832 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
833 and admin_level < NEW.admin_level and admin_level > 3
835 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
836 ORDER BY admin_level desc LIMIT 1
838 IF location.is_same THEN
839 -- Looks like the same boundary is replicated on multiple admin_levels.
840 -- Usual tagging in Poland. Remove our boundary from addresses.
841 NEW.rank_address := 0;
843 parent_address_level := location.rank_address;
844 IF location.rank_address >= NEW.rank_address THEN
845 IF location.rank_address >= 24 THEN
846 NEW.rank_address := 25;
848 NEW.rank_address := location.rank_address + 2;
854 IF NEW.rank_address > 9 THEN
855 -- Second check that the boundary is not completely contained in a
856 -- place area with a higher address rank
858 SELECT rank_address FROM placex
859 WHERE class = 'place' and rank_address < 24
860 and rank_address > NEW.rank_address
861 and geometry && NEW.geometry
862 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
863 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
864 ORDER BY rank_address desc LIMIT 1
866 NEW.rank_address := location.rank_address + 2;
869 ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
870 and NEW.rank_address between 16 and 23
872 -- If a place node is contained in a admin boundary with the same address level
873 -- and has not been linked, then make the node a subpart by increasing the
874 -- address rank (city level and above).
876 SELECT rank_address FROM placex
877 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
878 and rank_address = NEW.rank_address
879 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
882 NEW.rank_address = NEW.rank_address + 2;
885 parent_address_level := 3;
888 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
890 NEW.postcode := null;
892 -- waterway ways are linked when they are part of a relation and have the same class/type
893 IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
894 FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
896 FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
897 IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
898 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
899 FOR linked_node_id IN SELECT place_id FROM placex
900 WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
901 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
902 and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
904 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
905 {% if 'search_name' in db.tables %}
906 DELETE FROM search_name WHERE place_id = linked_node_id;
912 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
915 NEW.importance := null;
916 SELECT wikipedia, importance
917 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
918 INTO NEW.wikipedia,NEW.importance;
920 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
922 -- ---------------------------------------------------------------------------
923 -- For low level elements we inherit from our parent road
924 IF NEW.rank_search > 27 THEN
926 {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
927 NEW.parent_place_id := null;
928 is_place_address := coalesce(not NEW.address ? 'street' and NEW.address ? 'place', FALSE);
930 -- We have to find our parent road.
931 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
933 ST_Envelope(NEW.geometry),
937 -- If we found the road take a shortcut here.
938 -- Otherwise fall back to the full address getting method below.
939 IF NEW.parent_place_id is not null THEN
941 -- Get the details of the parent road
942 SELECT p.country_code, p.postcode, p.name FROM placex p
943 WHERE p.place_id = NEW.parent_place_id INTO location;
945 IF is_place_address THEN
946 -- Check if the addr:place tag is part of the parent name
947 SELECT count(*) INTO i
948 FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
950 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
954 NEW.country_code := location.country_code;
955 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
957 -- determine postcode
958 NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
960 get_nearest_postcode(NEW.country_code, NEW.centroid));
962 IF NEW.name is not NULL THEN
963 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
966 {% if not db.reverse_only %}
967 IF NEW.name is not NULL OR NEW.address is not NULL THEN
968 SELECT * INTO name_vector, nameaddress_vector
969 FROM create_poi_search_terms(NEW.place_id,
970 NEW.partition, NEW.parent_place_id,
971 is_place_address, NEW.country_code,
972 NEW.token_info, NEW.centroid);
974 IF array_length(name_vector, 1) is not NULL THEN
975 INSERT INTO search_name (place_id, search_rank, address_rank,
976 importance, country_code, name_vector,
977 nameaddress_vector, centroid)
978 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
979 NEW.importance, NEW.country_code, name_vector,
980 nameaddress_vector, NEW.centroid);
981 {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
986 NEW.token_info := token_strip_info(NEW.token_info);
987 -- If the address was inherited from a surrounding building,
988 -- do not add it permanently to the table.
989 IF NEW.address ? '_inherited' THEN
990 IF NEW.address ? '_unlisted_place' THEN
991 NEW.address := hstore('_unlisted_place', NEW.address->'_unlisted_place');
1002 -- ---------------------------------------------------------------------------
1004 {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1005 IF linked_place is not null THEN
1006 SELECT * INTO location FROM placex WHERE place_id = linked_place;
1008 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1010 -- Use the linked point as the centre point of the geometry,
1011 -- but only if it is within the area of the boundary.
1012 geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1013 IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1014 NEW.centroid := geom;
1017 {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.rank_address;{% endif %}
1018 IF location.rank_address > parent_address_level
1019 and location.rank_address < 26
1021 NEW.rank_address := location.rank_address;
1024 -- merge in extra tags
1025 NEW.extratags := hstore('linked_' || location.class, location.type)
1026 || coalesce(location.extratags, ''::hstore)
1027 || coalesce(NEW.extratags, ''::hstore);
1029 -- mark the linked place (excludes from search results)
1030 UPDATE placex set linked_place_id = NEW.place_id
1031 WHERE place_id = location.place_id;
1032 -- ensure that those places are not found anymore
1033 {% if 'search_name' in db.tables %}
1034 DELETE FROM search_name WHERE place_id = location.place_id;
1036 PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
1038 SELECT wikipedia, importance
1039 FROM compute_importance(location.extratags, NEW.country_code,
1040 'N', location.osm_id)
1041 INTO linked_wikipedia,linked_importance;
1043 -- Use the maximum importance if one could be computed from the linked object.
1044 IF linked_importance is not null AND
1045 (NEW.importance is null or NEW.importance < linked_importance)
1047 NEW.importance = linked_importance;
1050 -- No linked place? As a last resort check if the boundary is tagged with
1051 -- a place type and adapt the rank address.
1052 IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
1053 SELECT address_rank INTO place_address_level
1054 FROM compute_place_rank(NEW.country_code, 'A', 'place',
1055 NEW.extratags->'place', 0::SMALLINT, False, null);
1056 IF place_address_level > parent_address_level and
1057 place_address_level < 26 THEN
1058 NEW.rank_address := place_address_level;
1063 IF NEW.admin_level = 2
1064 AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1065 AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1067 -- Update the list of country names.
1068 -- Only take the name from the largest area for the given country code
1069 -- in the hope that this is the authoritive one.
1070 -- Also replace any old names so that all mapping mistakes can
1071 -- be fixed through regular OSM updates.
1073 SELECT osm_id FROM placex
1074 WHERE rank_search = 4 and osm_type = 'R'
1075 and country_code = NEW.country_code
1076 ORDER BY ST_Area(geometry) desc
1079 IF location.osm_id = NEW.osm_id THEN
1080 {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1081 UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1086 -- For linear features we need the full geometry for determining the address
1087 -- because they may go through several administrative entities. Otherwise use
1088 -- the centroid for performance reasons.
1089 IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1090 geom := NEW.geometry;
1092 geom := NEW.centroid;
1095 IF NEW.rank_address = 0 THEN
1096 max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1097 -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1098 -- so use the geometry here too. Just make sure the areas don't become too
1100 IF NEW.class = 'natural' or max_rank > 10 THEN
1101 geom := NEW.geometry;
1103 ELSEIF NEW.rank_address > 25 THEN
1106 max_rank := NEW.rank_address;
1109 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1110 NEW.token_info, geom, NEW.centroid,
1112 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1114 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1116 NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
1119 -- if we have a name add this to the name search table
1120 IF NEW.name IS NOT NULL THEN
1121 -- Initialise the name vector using our name
1122 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1123 name_vector := token_get_name_search_tokens(NEW.token_info);
1125 IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1126 result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1127 name_vector, NEW.rank_search, NEW.rank_address,
1128 NEW.postcode, NEW.geometry, NEW.centroid);
1129 {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1132 IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1133 result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1134 {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1137 IF NEW.rank_address between 16 and 27 THEN
1138 result := insertSearchName(NEW.partition, NEW.place_id,
1139 token_get_name_match_tokens(NEW.token_info),
1140 NEW.rank_search, NEW.rank_address, NEW.geometry);
1142 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1144 {% if not db.reverse_only %}
1145 INSERT INTO search_name (place_id, search_rank, address_rank,
1146 importance, country_code, name_vector,
1147 nameaddress_vector, centroid)
1148 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1149 NEW.importance, NEW.country_code, name_vector,
1150 nameaddress_vector, NEW.centroid);
1154 IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1155 NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1158 {% if debug %}RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;{% endif %}
1160 NEW.token_info := token_strip_info(NEW.token_info);
1167 CREATE OR REPLACE FUNCTION placex_delete()
1174 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1176 IF OLD.linked_place_id is null THEN
1177 update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1178 {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1179 update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1180 {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1182 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1185 IF OLD.rank_address < 30 THEN
1187 -- mark everything linked to this place for re-indexing
1188 {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1189 UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id
1190 and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1192 {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1193 DELETE FROM place_addressline where address_place_id = OLD.place_id;
1195 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1196 b := deleteRoad(OLD.partition, OLD.place_id);
1198 {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1199 update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1200 {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1201 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1202 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1206 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1208 IF OLD.rank_address < 26 THEN
1209 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1212 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1214 IF OLD.name is not null THEN
1215 {% if 'search_name' in db.tables %}
1216 DELETE from search_name WHERE place_id = OLD.place_id;
1218 b := deleteSearchName(OLD.partition, OLD.place_id);
1221 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1223 DELETE FROM place_addressline where place_id = OLD.place_id;
1225 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1227 -- remove from tables for special search
1228 classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1229 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1231 EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1234 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}