1 -- Trigger functions for the placex table.
3 -- Information returned by update preparation.
4 DROP TYPE IF EXISTS prepare_update_info CASCADE;
5 CREATE TYPE prepare_update_info AS (
12 linked_place_id BIGINT
15 -- Retrieve the data needed by the indexer for updating the place.
16 CREATE OR REPLACE FUNCTION placex_indexing_prepare(p placex)
17 RETURNS prepare_update_info
21 result prepare_update_info;
23 -- For POI nodes, check if the address should be derived from a surrounding
25 IF p.rank_search < 30 OR p.osm_type != 'N' OR p.address is not null THEN
26 result.address := p.address;
28 -- The additional && condition works around the misguided query
29 -- planner of postgis 3.0.
30 SELECT placex.address || hstore('_inherited', '') INTO result.address
32 WHERE ST_Covers(geometry, p.centroid)
33 and geometry && p.centroid
34 and placex.address is not null
35 and (placex.address ? 'housenumber' or placex.address ? 'street' or placex.address ? 'place')
36 and rank_search = 30 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
40 result.address := result.address - '_unlisted_place'::TEXT;
41 result.name := p.name;
42 result.class := p.class;
43 result.type := p.type;
44 result.country_code := p.country_code;
45 result.rank_address := p.rank_address;
47 -- Names of linked places need to be merged in, so search for a linkable
48 -- place already here.
49 SELECT * INTO location FROM find_linked_place(p);
51 IF location.place_id is not NULL THEN
52 result.linked_place_id := location.place_id;
54 IF NOT location.name IS NULL THEN
55 result.name := location.name || result.name;
62 LANGUAGE plpgsql STABLE;
65 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
74 SELECT members FROM planet_osm_rels
75 WHERE parts @> ARRAY[poi_osm_id]
76 and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
77 and tags @> ARRAY['associatedStreet']
79 FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
80 IF location.members[i+1] = 'street' THEN
82 SELECT place_id from placex
83 WHERE osm_type = 'W' and osm_id = substring(location.members[i],2)::bigint
85 and rank_search between 26 and 27
87 RETURN parent.place_id;
96 LANGUAGE plpgsql STABLE;
99 -- Find the parent road of a POI.
101 -- \returns Place ID of parent object or NULL if none
103 -- Copy data from linked items (POIs on ways, addr:street links, relations).
105 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
107 poi_partition SMALLINT,
110 is_place_addr BOOLEAN)
114 parent_place_id BIGINT DEFAULT NULL;
117 {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
119 -- Is this object part of an associatedStreet relation?
120 parent_place_id := find_associated_street(poi_osm_type, poi_osm_id);
122 IF parent_place_id is null THEN
123 parent_place_id := find_parent_for_address(token_info, poi_partition, bbox);
126 IF parent_place_id is null and poi_osm_type = 'N' THEN
127 -- Is this node part of an interpolation?
129 SELECT q.parent_place_id
130 FROM location_property_osmline q, planet_osm_ways x
131 WHERE q.linegeo && bbox and x.id = q.osm_id
132 and poi_osm_id = any(x.nodes)
135 {% if debug %}RAISE WARNING 'Get parent from interpolation: %', location.parent_place_id;{% endif %}
136 RETURN location.parent_place_id;
140 SELECT p.place_id, p.osm_id, p.rank_search, p.address,
141 coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
142 FROM placex p, planet_osm_ways w
143 WHERE p.osm_type = 'W' and p.rank_search >= 26
144 and p.geometry && bbox
145 and w.id = p.osm_id and poi_osm_id = any(w.nodes)
147 {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
149 -- Way IS a road then we are on it - that must be our road
150 IF location.rank_search < 28 THEN
151 {% if debug %}RAISE WARNING 'node in way that is a street %',location;{% endif %}
152 RETURN location.place_id;
155 parent_place_id := find_associated_street('W', location.osm_id);
159 IF parent_place_id is NULL THEN
160 IF is_place_addr THEN
161 -- The address is attached to a place we don't know.
162 -- Instead simply use the containing area with the largest rank.
164 SELECT place_id FROM placex
165 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
166 AND rank_address between 5 and 25
167 ORDER BY rank_address desc
169 RETURN location.place_id;
171 ELSEIF ST_Area(bbox) < 0.005 THEN
172 -- for smaller features get the nearest road
173 SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
174 {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
176 -- for larger features simply find the area with the largest rank that
177 -- contains the bbox, only use addressable features
179 SELECT place_id FROM placex
180 WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
181 AND rank_address between 5 and 25
182 ORDER BY rank_address desc
184 RETURN location.place_id;
189 RETURN parent_place_id;
192 LANGUAGE plpgsql STABLE;
194 -- Try to find a linked place for the given object.
195 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
199 relation_members TEXT[];
201 linked_placex placex%ROWTYPE;
204 IF bnd.rank_search >= 26 or bnd.rank_address = 0
205 or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
206 or bnd.type IN ('postcode', 'postal_code')
211 IF bnd.osm_type = 'R' THEN
212 -- see if we have any special relation members
213 SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
214 {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
216 -- Search for relation members with role 'lable'.
217 IF relation_members IS NOT NULL THEN
219 SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
221 {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
225 WHERE osm_type = 'N' and osm_id = rel_member.member
228 {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
229 RETURN linked_placex;
236 IF bnd.name ? 'name' THEN
237 bnd_name := lower(bnd.name->'name');
238 IF bnd_name = '' THEN
243 -- If extratags has a place tag, look for linked nodes by their place type.
244 -- Area and node still have to have the same name.
245 IF bnd.extratags ? 'place' and bnd_name is not null THEN
248 WHERE (position(lower(name->'name') in bnd_name) > 0
249 OR position(bnd_name in lower(name->'name')) > 0)
250 AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
251 AND placex.osm_type = 'N'
252 AND placex.linked_place_id is null
253 AND placex.rank_search < 26 -- needed to select the right index
254 AND placex.type != 'postcode'
255 AND ST_Covers(bnd.geometry, placex.geometry)
257 {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
258 RETURN linked_placex;
262 IF bnd.extratags ? 'wikidata' THEN
265 WHERE placex.class = 'place' AND placex.osm_type = 'N'
266 AND placex.extratags ? 'wikidata' -- needed to select right index
267 AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
268 AND placex.linked_place_id is null
269 AND placex.rank_search < 26
270 AND _st_covers(bnd.geometry, placex.geometry)
271 ORDER BY lower(name->'name') = bnd_name desc
273 {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
274 RETURN linked_placex;
278 -- Name searches can be done for ways as well as relations
279 IF bnd_name is not null THEN
280 {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
282 SELECT placex.* from placex
283 WHERE lower(name->'name') = bnd_name
284 AND ((bnd.rank_address > 0
285 and bnd.rank_address = (compute_place_rank(placex.country_code,
287 placex.type, 15::SMALLINT,
288 false, placex.postcode)).address_rank)
289 OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
290 AND placex.osm_type = 'N'
291 AND placex.class = 'place'
292 AND placex.linked_place_id is null
293 AND placex.rank_search < 26 -- needed to select the right index
294 AND placex.type != 'postcode'
295 AND ST_Covers(bnd.geometry, placex.geometry)
297 {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
298 RETURN linked_placex;
305 LANGUAGE plpgsql STABLE;
308 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
309 in_partition SMALLINT,
310 parent_place_id BIGINT,
311 is_place_addr BOOLEAN,
315 OUT name_vector INTEGER[],
316 OUT nameaddress_vector INTEGER[])
319 parent_name_vector INTEGER[];
320 parent_address_vector INTEGER[];
321 addr_place_ids INTEGER[];
322 hnr_vector INTEGER[];
326 parent_address_place_ids BIGINT[];
328 nameaddress_vector := '{}'::INTEGER[];
330 SELECT s.name_vector, s.nameaddress_vector
331 INTO parent_name_vector, parent_address_vector
333 WHERE s.place_id = parent_place_id;
336 SELECT (get_addr_tag_rank(key, country)).*, key,
337 token_get_address_search_tokens(token_info, key) as search_tokens
338 FROM token_get_address_keys(token_info) as key
339 WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
341 addr_place := get_address_place(in_partition, geometry,
342 addr_item.from_rank, addr_item.to_rank,
343 addr_item.extent, token_info, addr_item.key);
345 IF addr_place is null THEN
346 -- No place found in OSM that matches. Make it at least searchable.
347 nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
349 IF parent_address_place_ids is null THEN
350 SELECT array_agg(parent_place_id) INTO parent_address_place_ids
351 FROM place_addressline
352 WHERE place_id = parent_place_id;
355 -- If the parent already lists the place in place_address line, then we
356 -- are done. Otherwise, add its own place_address line.
357 IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
358 nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
360 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
361 isaddress, distance, cached_rank_address)
362 VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
363 true, addr_place.distance, addr_place.rank_address);
368 name_vector := token_get_name_search_tokens(token_info);
370 -- Check if the parent covers all address terms.
371 -- If not, create a search name entry with the house number as the name.
372 -- This is unusual for the search_name table but prevents that the place
373 -- is returned when we only search for the street/place.
375 hnr_vector := token_get_housenumber_search_tokens(token_info);
377 IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
378 name_vector := array_merge(name_vector, hnr_vector);
381 IF is_place_addr THEN
382 addr_place_ids := token_addr_place_search_tokens(token_info);
383 IF not addr_place_ids <@ parent_name_vector THEN
384 -- make sure addr:place terms are always searchable
385 nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
386 -- If there is a housenumber, also add the place name as a name,
387 -- so we can search it by the usual housenumber+place algorithms.
388 IF hnr_vector is not null THEN
389 name_vector := array_merge(name_vector, addr_place_ids);
394 -- Cheating here by not recomputing all terms but simply using the ones
395 -- from the parent object.
396 nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
397 nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
404 -- Insert address of a place into the place_addressline table.
406 -- \param obj_place_id Place_id of the place to compute the address for.
407 -- \param partition Partition number where the place is in.
408 -- \param maxrank Rank of the place. All address features must have
409 -- a search rank lower than the given rank.
410 -- \param address Address terms for the place.
411 -- \param geometry Geometry to which the address objects should be close.
413 -- \retval parent_place_id Place_id of the address object that is the direct
415 -- \retval postcode Postcode computed from the address. This is the
416 -- addr:postcode of one of the address objects. If
417 -- more than one of has a postcode, the highest ranking
418 -- one is used. May be NULL.
419 -- \retval nameaddress_vector Search terms for the address. This is the sum
420 -- of name terms of all address objects.
421 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
427 OUT parent_place_id BIGINT,
429 OUT nameaddress_vector INT[])
432 address_havelevel BOOLEAN[];
434 location_isaddress BOOLEAN;
435 current_boundary GEOMETRY := NULL;
436 current_node_area GEOMETRY := NULL;
438 parent_place_rank INT := 0;
439 addr_place_ids BIGINT[] := '{}'::int[];
440 new_address_vector INT[];
444 parent_place_id := 0;
445 nameaddress_vector := '{}'::int[];
447 address_havelevel := array_fill(false, ARRAY[maxrank]);
450 SELECT (get_address_place(partition, geometry, from_rank, to_rank,
451 extent, token_info, key)).*, key
452 FROM (SELECT (get_addr_tag_rank(key, country)).*, key
453 FROM token_get_address_keys(token_info) as key) x
454 ORDER BY rank_address, distance, isguess desc
456 IF location.place_id is null THEN
457 {% if not db.reverse_only %}
458 nameaddress_vector := array_merge(nameaddress_vector,
459 token_get_address_search_tokens(token_info,
463 {% if not db.reverse_only %}
464 nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
467 location_isaddress := not address_havelevel[location.rank_address];
468 IF not address_havelevel[location.rank_address] THEN
469 address_havelevel[location.rank_address] := true;
470 IF parent_place_rank < location.rank_address THEN
471 parent_place_id := location.place_id;
472 parent_place_rank := location.rank_address;
476 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
477 isaddress, distance, cached_rank_address)
478 VALUES (obj_place_id, location.place_id, not location.isguess,
479 true, location.distance, location.rank_address);
481 addr_place_ids := addr_place_ids || location.place_id;
486 SELECT * FROM getNearFeatures(partition, geometry, maxrank)
487 WHERE not addr_place_ids @> ARRAY[place_id]
488 ORDER BY rank_address, isguess asc,
490 CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
491 WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
492 WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
495 -- Ignore all place nodes that do not fit in a lower level boundary.
496 CONTINUE WHEN location.isguess
497 and current_boundary is not NULL
498 and not ST_Contains(current_boundary, location.centroid);
500 -- If this is the first item in the rank, then assume it is the address.
501 location_isaddress := not address_havelevel[location.rank_address];
503 -- Further sanity checks to ensure that the address forms a sane hierarchy.
504 IF location_isaddress THEN
505 IF location.isguess and current_node_area is not NULL THEN
506 location_isaddress := ST_Contains(current_node_area, location.centroid);
508 IF not location.isguess and current_boundary is not NULL
509 and location.rank_address != 11 AND location.rank_address != 5 THEN
510 location_isaddress := ST_Contains(current_boundary, location.centroid);
514 IF location_isaddress THEN
515 address_havelevel[location.rank_address] := true;
516 parent_place_id := location.place_id;
518 -- Set postcode if we have one.
519 -- (Returned will be the highest ranking one.)
520 IF location.postcode is not NULL THEN
521 postcode = location.postcode;
524 -- Recompute the areas we need for hierarchy sanity checks.
525 IF location.rank_address != 11 AND location.rank_address != 5 THEN
526 IF location.isguess THEN
527 current_node_area := place_node_fuzzy_area(location.centroid,
528 location.rank_search);
530 current_node_area := NULL;
531 SELECT p.geometry FROM placex p
532 WHERE p.place_id = location.place_id INTO current_boundary;
537 -- Add it to the list of search terms
538 {% if not db.reverse_only %}
539 nameaddress_vector := array_merge(nameaddress_vector,
540 location.keywords::integer[]);
543 INSERT INTO place_addressline (place_id, address_place_id, fromarea,
544 isaddress, distance, cached_rank_address)
545 VALUES (obj_place_id, location.place_id, not location.isguess,
546 location_isaddress, location.distance, location.rank_address);
553 CREATE OR REPLACE FUNCTION placex_insert()
560 country_code VARCHAR(2);
564 {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
566 NEW.place_id := nextval('seq_place');
567 NEW.indexed_status := 1; --STATUS_NEW
569 NEW.centroid := ST_PointOnSurface(NEW.geometry);
570 NEW.country_code := lower(get_country_code(NEW.centroid));
572 NEW.partition := get_partition(NEW.country_code);
573 NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
575 IF NEW.osm_type = 'X' THEN
576 -- E'X'ternal records should already be in the right format so do nothing
578 is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
580 IF NEW.class in ('place','boundary')
581 AND NEW.type in ('postcode','postal_code')
583 IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
584 -- most likely just a part of a multipolygon postcode boundary, throw it away
588 NEW.name := hstore('ref', NEW.address->'postcode');
590 ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
591 AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
594 ELSEIF NEW.class = 'boundary' AND NOT is_area
597 ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
598 AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
603 SELECT * INTO NEW.rank_search, NEW.rank_address
604 FROM compute_place_rank(NEW.country_code,
605 CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
606 NEW.class, NEW.type, NEW.admin_level,
607 (NEW.extratags->'capital') = 'yes',
608 NEW.address->'postcode');
610 -- a country code make no sense below rank 4 (country)
611 IF NEW.rank_search < 4 THEN
612 NEW.country_code := NULL;
617 {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
619 {% if not disable_diff_updates %}
620 -- The following is not needed until doing diff updates, and slows the main index process down
622 IF NEW.osm_type = 'N' and NEW.rank_search > 28 THEN
623 -- might be part of an interpolation
624 result := osmline_reinsert(NEW.osm_id, NEW.geometry);
625 ELSEIF NEW.rank_address > 0 THEN
626 IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
627 -- Performance: We just can't handle re-indexing for country level changes
628 IF st_area(NEW.geometry) < 1 THEN
629 -- mark items within the geometry for re-indexing
630 -- RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
632 UPDATE placex SET indexed_status = 2
633 WHERE ST_Intersects(NEW.geometry, placex.geometry)
634 and indexed_status = 0
635 and ((rank_address = 0 and rank_search > NEW.rank_address)
636 or rank_address > NEW.rank_address
637 or (class = 'place' and osm_type = 'N')
639 and (rank_search < 28
641 or (NEW.rank_address >= 16 and address ? 'place'));
644 -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
645 diameter := update_place_diameter(NEW.rank_search);
647 -- RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
648 IF NEW.rank_search >= 26 THEN
649 -- roads may cause reparenting for >27 rank places
650 update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
651 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
652 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
653 ELSEIF NEW.rank_search >= 16 THEN
654 -- up to rank 16, street-less addresses may need reparenting
655 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');
657 -- for all other places the search terms may change as well
658 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);
665 -- add to tables for special search
666 -- Note: won't work on initial import because the classtype tables
667 -- do not yet exist. It won't hurt either.
668 classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
669 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
671 EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)'
672 USING NEW.place_id, ST_Centroid(NEW.geometry);
675 {% endif %} -- not disable_diff_updates
683 CREATE OR REPLACE FUNCTION placex_update()
689 relation_members TEXT[];
692 parent_address_level SMALLINT;
693 place_address_level SMALLINT;
697 name_vector INTEGER[];
698 nameaddress_vector INTEGER[];
699 addr_nameaddress_vector INTEGER[];
703 linked_node_id BIGINT;
704 linked_importance FLOAT;
705 linked_wikipedia TEXT;
707 is_place_address BOOLEAN;
711 IF OLD.indexed_status = 100 THEN
712 {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
713 delete from placex where place_id = OLD.place_id;
717 IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
721 {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
723 NEW.indexed_date = now();
725 {% if 'search_name' in db.tables %}
726 DELETE from search_name WHERE place_id = NEW.place_id;
728 result := deleteSearchName(NEW.partition, NEW.place_id);
729 DELETE FROM place_addressline WHERE place_id = NEW.place_id;
730 result := deleteRoad(NEW.partition, NEW.place_id);
731 result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
732 UPDATE placex set linked_place_id = null, indexed_status = 2
733 where linked_place_id = NEW.place_id;
734 -- update not necessary for osmline, cause linked_place_id does not exist
736 NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
738 -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
739 -- the previous link status.
740 linked_place := NEW.linked_place_id;
741 NEW.linked_place_id := OLD.linked_place_id;
743 IF NEW.linked_place_id is not null THEN
744 NEW.token_info := null;
745 {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
749 -- Postcodes are just here to compute the centroids. They are not searchable
750 -- unless they are a boundary=postal_code.
751 -- There was an error in the style so that boundary=postal_code used to be
752 -- imported as place=postcode. That's why relations are allowed to pass here.
753 -- This can go away in a couple of versions.
754 IF NEW.class = 'place' and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
755 NEW.token_info := null;
759 -- Compute a preliminary centroid.
760 NEW.centroid := ST_PointOnSurface(NEW.geometry);
762 -- recalculate country and partition
763 IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
764 -- for countries, believe the mapped country code,
765 -- so that we remain in the right partition if the boundaries
767 NEW.country_code := lower(NEW.address->'country');
768 NEW.partition := get_partition(lower(NEW.country_code));
769 IF NEW.partition = 0 THEN
770 NEW.country_code := lower(get_country_code(NEW.centroid));
771 NEW.partition := get_partition(NEW.country_code);
774 IF NEW.rank_search >= 4 THEN
775 NEW.country_code := lower(get_country_code(NEW.centroid));
777 NEW.country_code := NULL;
779 NEW.partition := get_partition(NEW.country_code);
781 {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
784 -- recompute the ranks, they might change when linking changes
785 SELECT * INTO NEW.rank_search, NEW.rank_address
786 FROM compute_place_rank(NEW.country_code,
787 CASE WHEN ST_GeometryType(NEW.geometry)
788 IN ('ST_Polygon','ST_MultiPolygon')
789 THEN 'A' ELSE NEW.osm_type END,
790 NEW.class, NEW.type, NEW.admin_level,
791 (NEW.extratags->'capital') = 'yes',
792 NEW.address->'postcode');
793 -- We must always increase the address level relative to the admin boundary.
794 IF NEW.class = 'boundary' and NEW.type = 'administrative'
795 and NEW.osm_type = 'R' and NEW.rank_address > 0
797 -- First, check that admin boundaries do not overtake each other rank-wise.
798 parent_address_level := 3;
801 (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
802 and extratags->'wikidata' = NEW.extratags->'wikidata'
803 THEN ST_Equals(geometry, NEW.geometry)
804 ELSE false END) as is_same
806 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
807 and admin_level < NEW.admin_level and admin_level > 3
809 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
810 ORDER BY admin_level desc LIMIT 1
812 IF location.is_same THEN
813 -- Looks like the same boundary is replicated on multiple admin_levels.
814 -- Usual tagging in Poland. Remove our boundary from addresses.
815 NEW.rank_address := 0;
817 parent_address_level := location.rank_address;
818 IF location.rank_address >= NEW.rank_address THEN
819 IF location.rank_address >= 24 THEN
820 NEW.rank_address := 25;
822 NEW.rank_address := location.rank_address + 2;
828 IF NEW.rank_address > 9 THEN
829 -- Second check that the boundary is not completely contained in a
830 -- place area with a higher address rank
832 SELECT rank_address FROM placex
833 WHERE class = 'place' and rank_address < 24
834 and rank_address > NEW.rank_address
835 and geometry && NEW.geometry
836 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
837 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
838 ORDER BY rank_address desc LIMIT 1
840 NEW.rank_address := location.rank_address + 2;
843 ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
844 and NEW.rank_address between 16 and 23
846 -- If a place node is contained in a admin boundary with the same address level
847 -- and has not been linked, then make the node a subpart by increasing the
848 -- address rank (city level and above).
850 SELECT rank_address FROM placex
851 WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
852 and rank_address = NEW.rank_address
853 and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
856 NEW.rank_address = NEW.rank_address + 2;
859 parent_address_level := 3;
862 NEW.housenumber := token_normalized_housenumber(NEW.token_info);
864 NEW.postcode := null;
866 -- waterway ways are linked when they are part of a relation and have the same class/type
867 IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
868 FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
870 FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
871 IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
872 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
873 FOR linked_node_id IN SELECT place_id FROM placex
874 WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
875 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
876 and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
878 UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
879 {% if 'search_name' in db.tables %}
880 DELETE FROM search_name WHERE place_id = linked_node_id;
886 {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
889 NEW.importance := null;
890 SELECT wikipedia, importance
891 FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
892 INTO NEW.wikipedia,NEW.importance;
894 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
896 -- ---------------------------------------------------------------------------
897 -- For low level elements we inherit from our parent road
898 IF NEW.rank_search > 27 THEN
900 {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
901 NEW.parent_place_id := null;
902 is_place_address := coalesce(not NEW.address ? 'street' and NEW.address ? 'place', FALSE);
904 -- We have to find our parent road.
905 NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
907 ST_Envelope(NEW.geometry),
911 -- If we found the road take a shortcut here.
912 -- Otherwise fall back to the full address getting method below.
913 IF NEW.parent_place_id is not null THEN
915 -- Get the details of the parent road
916 SELECT p.country_code, p.postcode, p.name FROM placex p
917 WHERE p.place_id = NEW.parent_place_id INTO location;
919 IF is_place_address THEN
920 -- Check if the addr:place tag is part of the parent name
921 SELECT count(*) INTO i
922 FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
924 NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
928 NEW.country_code := location.country_code;
929 {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
931 -- determine postcode
932 NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
934 get_nearest_postcode(NEW.country_code, NEW.centroid));
936 IF NEW.name is not NULL THEN
937 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
940 {% if not db.reverse_only %}
941 IF NEW.name is not NULL OR NEW.address is not NULL THEN
942 SELECT * INTO name_vector, nameaddress_vector
943 FROM create_poi_search_terms(NEW.place_id,
944 NEW.partition, NEW.parent_place_id,
945 is_place_address, NEW.country_code,
946 NEW.token_info, NEW.centroid);
948 IF array_length(name_vector, 1) is not NULL THEN
949 INSERT INTO search_name (place_id, search_rank, address_rank,
950 importance, country_code, name_vector,
951 nameaddress_vector, centroid)
952 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
953 NEW.importance, NEW.country_code, name_vector,
954 nameaddress_vector, NEW.centroid);
955 {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
960 NEW.token_info := token_strip_info(NEW.token_info);
961 -- If the address was inherited from a surrounding building,
962 -- do not add it permanently to the table.
963 IF NEW.address ? '_inherited' THEN
964 IF NEW.address ? '_unlisted_place' THEN
965 NEW.address := hstore('_unlisted_place', NEW.address->'_unlisted_place');
976 -- ---------------------------------------------------------------------------
978 {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
979 IF linked_place is not null THEN
980 SELECT * INTO location FROM placex WHERE place_id = linked_place;
982 {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
984 -- Use the linked point as the centre point of the geometry,
985 -- but only if it is within the area of the boundary.
986 geom := coalesce(location.centroid, ST_Centroid(location.geometry));
987 IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
988 NEW.centroid := geom;
991 {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.rank_address;{% endif %}
992 IF location.rank_address > parent_address_level
993 and location.rank_address < 26
995 NEW.rank_address := location.rank_address;
998 -- merge in extra tags
999 NEW.extratags := hstore('linked_' || location.class, location.type)
1000 || coalesce(location.extratags, ''::hstore)
1001 || coalesce(NEW.extratags, ''::hstore);
1003 -- mark the linked place (excludes from search results)
1004 UPDATE placex set linked_place_id = NEW.place_id
1005 WHERE place_id = location.place_id;
1006 -- ensure that those places are not found anymore
1007 {% if 'search_name' in db.tables %}
1008 DELETE FROM search_name WHERE place_id = location.place_id;
1010 PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
1012 SELECT wikipedia, importance
1013 FROM compute_importance(location.extratags, NEW.country_code,
1014 'N', location.osm_id)
1015 INTO linked_wikipedia,linked_importance;
1017 -- Use the maximum importance if one could be computed from the linked object.
1018 IF linked_importance is not null AND
1019 (NEW.importance is null or NEW.importance < linked_importance)
1021 NEW.importance = linked_importance;
1024 -- No linked place? As a last resort check if the boundary is tagged with
1025 -- a place type and adapt the rank address.
1026 IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
1027 SELECT address_rank INTO place_address_level
1028 FROM compute_place_rank(NEW.country_code, 'A', 'place',
1029 NEW.extratags->'place', 0::SMALLINT, False, null);
1030 IF place_address_level > parent_address_level and
1031 place_address_level < 26 THEN
1032 NEW.rank_address := place_address_level;
1037 IF NEW.admin_level = 2
1038 AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1039 AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1041 -- Update the list of country names. Adding an additional sanity
1042 -- check here: make sure the country does overlap with the area where
1043 -- we expect it to be as per static country grid.
1045 SELECT country_code FROM country_osm_grid
1046 WHERE ST_Covers(geometry, NEW.centroid) and country_code = NEW.country_code
1049 {% if debug %}RAISE WARNING 'Updating names for country '%' with: %', NEW.country_code, NEW.name;{% endif %}
1050 UPDATE country_name SET name = name || NEW.name WHERE country_code = NEW.country_code;
1054 -- For linear features we need the full geometry for determining the address
1055 -- because they may go through several administrative entities. Otherwise use
1056 -- the centroid for performance reasons.
1057 IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1058 geom := NEW.geometry;
1060 geom := NEW.centroid;
1063 IF NEW.rank_address = 0 THEN
1064 max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1065 -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1066 -- so use the geometry here too. Just make sure the areas don't become too
1068 IF NEW.class = 'natural' or max_rank > 10 THEN
1069 geom := NEW.geometry;
1071 ELSEIF NEW.rank_address > 25 THEN
1074 max_rank := NEW.rank_address;
1077 SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1078 NEW.token_info, geom, NEW.country_code)
1079 INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1081 {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1083 NEW.postcode := coalesce(token_normalized_postcode(NEW.address->'postcode'),
1086 -- if we have a name add this to the name search table
1087 IF NEW.name IS NOT NULL THEN
1088 -- Initialise the name vector using our name
1089 NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1090 name_vector := token_get_name_search_tokens(NEW.token_info);
1092 IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1093 result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1094 name_vector, NEW.rank_search, NEW.rank_address,
1095 NEW.postcode, NEW.geometry, NEW.centroid);
1096 {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1099 IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1100 result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1101 {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1104 IF NEW.rank_address between 16 and 27 THEN
1105 result := insertSearchName(NEW.partition, NEW.place_id,
1106 token_get_name_match_tokens(NEW.token_info),
1107 NEW.rank_search, NEW.rank_address, NEW.geometry);
1109 {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1111 {% if not db.reverse_only %}
1112 INSERT INTO search_name (place_id, search_rank, address_rank,
1113 importance, country_code, name_vector,
1114 nameaddress_vector, centroid)
1115 VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1116 NEW.importance, NEW.country_code, name_vector,
1117 nameaddress_vector, NEW.centroid);
1121 IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1122 NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1125 {% if debug %}RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;{% endif %}
1127 NEW.token_info := token_strip_info(NEW.token_info);
1134 CREATE OR REPLACE FUNCTION placex_delete()
1141 -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1143 IF OLD.linked_place_id is null THEN
1144 update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1145 {% if debug %}RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1146 update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1147 {% if debug %}RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1149 update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1152 IF OLD.rank_address < 30 THEN
1154 -- mark everything linked to this place for re-indexing
1155 {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1156 UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id
1157 and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1159 {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1160 DELETE FROM place_addressline where address_place_id = OLD.place_id;
1162 {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1163 b := deleteRoad(OLD.partition, OLD.place_id);
1165 {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1166 update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1167 {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1168 -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1169 update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1173 {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1175 IF OLD.rank_address < 26 THEN
1176 b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1179 {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1181 IF OLD.name is not null THEN
1182 {% if 'search_name' in db.tables %}
1183 DELETE from search_name WHERE place_id = OLD.place_id;
1185 b := deleteSearchName(OLD.partition, OLD.place_id);
1188 {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1190 DELETE FROM place_addressline where place_id = OLD.place_id;
1192 {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1194 -- remove from tables for special search
1195 classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1196 SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1198 EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1201 {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}