]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/utils.sql
reorganise layout of location_postcode table
[nominatim.git] / lib-sql / functions / utils.sql
1 -- SPDX-License-Identifier: GPL-2.0-only
2 --
3 -- This file is part of Nominatim. (https://nominatim.org)
4 --
5 -- Copyright (C) 2025 by the Nominatim developer community.
6 -- For a full list of authors see the git log.
7
8 -- Assorted helper functions for the triggers.
9
10 CREATE OR REPLACE FUNCTION get_center_point(place GEOMETRY)
11   RETURNS GEOMETRY
12   AS $$
13 DECLARE
14   geom_type TEXT;
15 BEGIN
16   geom_type := ST_GeometryType(place);
17   IF geom_type = 'ST_Point' THEN
18     RETURN place;
19   END IF;
20   IF geom_type = 'ST_LineString' THEN
21     RETURN ST_ReducePrecision(ST_LineInterpolatePoint(place, 0.5), 0.0000001);
22   END IF;
23
24   RETURN ST_ReducePrecision(ST_PointOnSurface(place), 0.0000001);
25 END;
26 $$
27 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
28
29
30 CREATE OR REPLACE FUNCTION geometry_sector(partition INTEGER, place GEOMETRY)
31   RETURNS INTEGER
32   AS $$
33 BEGIN
34   RETURN (partition*1000000) + (500-ST_X(place)::INTEGER)*1000 + (500-ST_Y(place)::INTEGER);
35 END;
36 $$
37 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
38
39
40
41 CREATE OR REPLACE FUNCTION array_merge(a INTEGER[], b INTEGER[])
42   RETURNS INTEGER[]
43   AS $$
44 DECLARE
45   i INTEGER;
46   r INTEGER[];
47 BEGIN
48   IF array_upper(a, 1) IS NULL THEN
49     RETURN b;
50   END IF;
51   IF array_upper(b, 1) IS NULL THEN
52     RETURN a;
53   END IF;
54   r := a;
55   FOR i IN 1..array_upper(b, 1) LOOP  
56     IF NOT (ARRAY[b[i]] <@ r) THEN
57       r := r || b[i];
58     END IF;
59   END LOOP;
60   RETURN r;
61 END;
62 $$
63 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
64
65 -- Return the node members with a given label from a relation member list
66 -- as a set.
67 --
68 -- \param members      Member list in osm2pgsql middle format.
69 -- \param memberLabels Array of labels to accept.
70 --
71 -- \returns Set of OSM ids of nodes that are found.
72 --
73 CREATE OR REPLACE FUNCTION get_rel_node_members(members TEXT[],
74                                                 memberLabels TEXT[])
75   RETURNS SETOF BIGINT
76   AS $$
77 DECLARE
78   i INTEGER;
79 BEGIN
80   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
81     IF members[i+1] = ANY(memberLabels)
82        AND upper(substring(members[i], 1, 1))::char(1) = 'N'
83     THEN
84       RETURN NEXT substring(members[i], 2)::bigint;
85     END IF;
86   END LOOP;
87
88   RETURN;
89 END;
90 $$
91 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
92
93
94 CREATE OR REPLACE FUNCTION get_rel_node_members(members JSONB, memberLabels TEXT[])
95   RETURNS SETOF BIGINT
96   AS $$
97 DECLARE
98   member JSONB;
99 BEGIN
100   FOR member IN SELECT * FROM jsonb_array_elements(members)
101   LOOP
102     IF member->>'type' = 'N' and member->>'role' = ANY(memberLabels) THEN
103         RETURN NEXT (member->>'ref')::bigint;
104     END IF;
105   END LOOP;
106
107   RETURN;
108 END;
109 $$
110 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
111
112
113 -- Copy 'name' to or from the default language.
114 --
115 -- \param country_code     Country code of the object being named.
116 -- \param[inout] name      List of names of the object.
117 --
118 -- If the country named by country_code has a single default language,
119 -- then a `name` tag is copied to `name:<country_code>` if this tag does
120 -- not yet exist and vice versa.
121 CREATE OR REPLACE FUNCTION add_default_place_name(country_code VARCHAR(2),
122                                                   INOUT name HSTORE)
123   AS $$
124 DECLARE
125   default_language VARCHAR(10);
126 BEGIN
127   IF name is not null AND array_upper(akeys(name),1) > 1 THEN
128     default_language := get_country_language_code(country_code);
129     IF default_language IS NOT NULL THEN
130       IF name ? 'name' AND NOT name ? ('name:'||default_language) THEN
131         name := name || hstore(('name:'||default_language), (name -> 'name'));
132       ELSEIF name ? ('name:'||default_language) AND NOT name ? 'name' THEN
133         name := name || hstore('name', (name -> ('name:'||default_language)));
134       END IF;
135     END IF;
136   END IF;
137 END;
138 $$
139 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
140
141
142 -- Find the best-matching postcode for the given geometry
143 CREATE OR REPLACE FUNCTION get_nearest_postcode(country VARCHAR(2), geom GEOMETRY)
144   RETURNS TEXT
145   AS $$
146 DECLARE
147   outcode TEXT;
148   cnt INTEGER;
149   location RECORD;
150 BEGIN
151     -- If the geometry is an area then only one postcode must be within
152     -- that area, otherwise consider the area as not having a postcode.
153     IF ST_GeometryType(geom) in ('ST_Polygon','ST_MultiPolygon') THEN
154       SELECT min(postcode), count(*) FROM
155         (SELECT postcode FROM location_postcodes
156            WHERE geom && location_postcodes.geometry -- want to use the index
157                  AND ST_Contains(geom, location_postcodes.centroid)
158                  AND country_code = country
159            LIMIT 2) sub
160         INTO outcode, cnt;
161
162         IF cnt = 1 THEN
163             RETURN outcode;
164         END IF;
165
166         RETURN null;
167     END IF;
168
169     -- Otherwise: be fully within the coverage area of a postcode
170     FOR location IN
171       SELECT postcode
172         FROM location_postcodes p
173        WHERE ST_Covers(p.geometry, geom)
174              AND p.country_code = country
175        ORDER BY osm_id is null, ST_Distance(p.centroid, geom)
176        LIMIT 1
177     LOOP
178         RETURN location.postcode;
179     END LOOP;
180
181     RETURN NULL;
182 END;
183 $$
184 LANGUAGE plpgsql STABLE PARALLEL SAFE;
185
186
187 CREATE OR REPLACE FUNCTION get_country_code(place geometry)
188   RETURNS TEXT
189   AS $$
190 DECLARE
191   nearcountry RECORD;
192   countries TEXT[];
193 BEGIN
194 -- RAISE WARNING 'get_country_code, start: %', ST_AsText(place);
195
196   -- Try for a OSM polygon
197   SELECT array_agg(country_code) FROM location_area_country
198     WHERE country_code is not null and st_covers(geometry, place)
199     INTO countries;
200
201   IF array_length(countries, 1) = 1 THEN
202     RETURN countries[1];
203   END IF;
204
205   IF array_length(countries, 1) > 1 THEN
206     -- more than one country found, confirm against the fallback data what to choose
207     FOR nearcountry IN
208         SELECT country_code FROM country_osm_grid
209           WHERE ST_Covers(geometry, place) AND country_code = ANY(countries)
210           ORDER BY area ASC
211     LOOP
212         RETURN nearcountry.country_code;
213     END LOOP;
214     -- Still nothing? Choose the country code with the smallest partition number.
215     -- And failing that, just go by the alphabet.
216     FOR nearcountry IN
217         SELECT cc,
218                (SELECT partition FROM country_name WHERE country_code = cc) as partition
219         FROM unnest(countries) cc
220         ORDER BY partition, cc
221     LOOP
222         RETURN nearcountry.cc;
223     END LOOP;
224
225     -- Should never be reached.
226     RETURN countries[1];
227   END IF;
228
229 -- RAISE WARNING 'osm fallback: %', ST_AsText(place);
230
231   -- Try for OSM fallback data
232   -- The order is to deal with places like HongKong that are 'states' within another polygon
233   FOR nearcountry IN
234     SELECT country_code from country_osm_grid
235     WHERE st_covers(geometry, place) order by area asc limit 1
236   LOOP
237     RETURN nearcountry.country_code;
238   END LOOP;
239
240 -- RAISE WARNING 'near osm fallback: %', ST_AsText(place);
241
242   RETURN NULL;
243 END;
244 $$
245 LANGUAGE plpgsql STABLE PARALLEL SAFE;
246
247
248 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2))
249   RETURNS TEXT
250   AS $$
251 DECLARE
252   nearcountry RECORD;
253 BEGIN
254   FOR nearcountry IN
255     SELECT distinct country_default_language_code from country_name
256     WHERE country_code = search_country_code limit 1
257   LOOP
258     RETURN lower(nearcountry.country_default_language_code);
259   END LOOP;
260   RETURN NULL;
261 END;
262 $$
263 LANGUAGE plpgsql STABLE PARALLEL SAFE;
264
265
266 CREATE OR REPLACE FUNCTION get_partition(in_country_code VARCHAR(10))
267   RETURNS INTEGER
268   AS $$
269 DECLARE
270   nearcountry RECORD;
271 BEGIN
272   FOR nearcountry IN
273     SELECT partition from country_name where country_code = in_country_code
274   LOOP
275     RETURN nearcountry.partition;
276   END LOOP;
277   RETURN 0;
278 END;
279 $$
280 LANGUAGE plpgsql STABLE PARALLEL SAFE;
281
282
283 -- Find the parent of an address with addr:street/addr:place tag.
284 --
285 -- \param token_info Naming info with the address information.
286 -- \param partition  Partition where to search the parent.
287 -- \param centroid   Location of the address.
288 --
289 -- \return Place ID of the parent if one was found, NULL otherwise.
290 CREATE OR REPLACE FUNCTION find_parent_for_address(token_info JSONB,
291                                                    partition SMALLINT,
292                                                    centroid GEOMETRY)
293   RETURNS BIGINT
294   AS $$
295 DECLARE
296   parent_place_id BIGINT;
297 BEGIN
298   -- Check for addr:street attributes
299   parent_place_id := getNearestNamedRoadPlaceId(partition, centroid, token_info);
300   IF parent_place_id is not null THEN
301     {% if debug %}RAISE WARNING 'Get parent from addr:street: %', parent_place_id;{% endif %}
302     RETURN parent_place_id;
303   END IF;
304
305   -- Check for addr:place attributes.
306   parent_place_id := getNearestNamedPlacePlaceId(partition, centroid, token_info);
307   {% if debug %}RAISE WARNING 'Get parent from addr:place: %', parent_place_id;{% endif %}
308   RETURN parent_place_id;
309 END;
310 $$
311 LANGUAGE plpgsql STABLE PARALLEL SAFE;
312
313
314 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT)
315   RETURNS BOOLEAN
316   AS $$
317 DECLARE
318 BEGIN
319   DELETE FROM location_area where place_id = OLD_place_id;
320 -- TODO:location_area
321   RETURN true;
322 END;
323 $$
324 LANGUAGE plpgsql;
325
326 -- Create a bounding box with an extent computed from the radius (in meters)
327 -- which in turn is derived from the given search rank.
328 CREATE OR REPLACE FUNCTION place_node_fuzzy_area(geom GEOMETRY, rank_search INTEGER)
329   RETURNS GEOMETRY
330   AS $$
331 DECLARE
332   radius FLOAT := 500;
333 BEGIN
334   IF rank_search <= 16 THEN -- city
335     radius := 15000;
336   ELSIF rank_search <= 18 THEN -- town
337     radius := 4000;
338   ELSIF rank_search <= 19 THEN -- village
339     radius := 2000;
340   ELSIF rank_search  <= 20 THEN -- hamlet
341     radius := 1000;
342   END IF;
343
344   RETURN ST_Envelope(ST_Collect(
345                      ST_Project(geom::geography, radius, 0.785398)::geometry,
346                      ST_Project(geom::geography, radius, 3.9269908)::geometry));
347 END;
348 $$
349 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
350
351
352 CREATE OR REPLACE FUNCTION add_location(place_id BIGINT, country_code varchar(2),
353                                         partition INTEGER, keywords INTEGER[],
354                                         rank_search INTEGER, rank_address INTEGER,
355                                         in_postcode TEXT, geometry GEOMETRY,
356                                         centroid GEOMETRY)
357   RETURNS BOOLEAN
358   AS $$
359 DECLARE
360   postcode TEXT;
361 BEGIN
362   PERFORM deleteLocationArea(partition, place_id, rank_search);
363
364   -- add postcode only if it contains a single entry, i.e. ignore postcode lists
365   postcode := NULL;
366   IF in_postcode is not null AND in_postcode not similar to '%(,|;)%' THEN
367       postcode := upper(trim (in_postcode));
368   END IF;
369
370   IF ST_Dimension(geometry) = 2 THEN
371     RETURN insertLocationAreaLarge(partition, place_id, country_code, keywords,
372                                    rank_search, rank_address, false, postcode,
373                                    centroid, geometry);
374   END IF;
375
376   IF ST_Dimension(geometry) = 0 THEN
377     RETURN insertLocationAreaLarge(partition, place_id, country_code, keywords,
378                                    rank_search, rank_address, true, postcode,
379                                    centroid, place_node_fuzzy_area(geometry, rank_search));
380   END IF;
381
382   RETURN false;
383 END;
384 $$
385 LANGUAGE plpgsql;
386
387
388 CREATE OR REPLACE FUNCTION quad_split_geometry(geometry GEOMETRY, maxarea FLOAT,
389                                                maxdepth INTEGER)
390   RETURNS SETOF GEOMETRY
391   AS $$
392 DECLARE
393   xmin FLOAT;
394   ymin FLOAT;
395   xmax FLOAT;
396   ymax FLOAT;
397   xmid FLOAT;
398   ymid FLOAT;
399   secgeo GEOMETRY;
400   secbox GEOMETRY;
401   seg INTEGER;
402   geo RECORD;
403   area FLOAT;
404   remainingdepth INTEGER;
405 BEGIN
406 --  RAISE WARNING 'quad_split_geometry: maxarea=%, depth=%',maxarea,maxdepth;
407
408   IF not ST_IsValid(geometry) THEN
409     RETURN;
410   END IF;
411
412   IF ST_Dimension(geometry) != 2 OR maxdepth <= 1 THEN
413     RETURN NEXT geometry;
414     RETURN;
415   END IF;
416
417   remainingdepth := maxdepth - 1;
418   area := ST_AREA(geometry);
419   IF area < maxarea THEN
420     RETURN NEXT geometry;
421     RETURN;
422   END IF;
423
424   xmin := st_xmin(geometry);
425   xmax := st_xmax(geometry);
426   ymin := st_ymin(geometry);
427   ymax := st_ymax(geometry);
428   secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(ymin,xmin),ST_Point(ymax,xmax)),4326);
429
430   -- if the geometry completely covers the box don't bother to slice any more
431   IF ST_AREA(secbox) = area THEN
432     RETURN NEXT geometry;
433     RETURN;
434   END IF;
435
436   xmid := (xmin+xmax)/2;
437   ymid := (ymin+ymax)/2;
438
439   FOR seg IN 1..4 LOOP
440
441     IF seg = 1 THEN
442       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymin),ST_Point(xmid,ymid)),4326);
443     END IF;
444     IF seg = 2 THEN
445       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymid),ST_Point(xmid,ymax)),4326);
446     END IF;
447     IF seg = 3 THEN
448       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymin),ST_Point(xmax,ymid)),4326);
449     END IF;
450     IF seg = 4 THEN
451       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymid),ST_Point(xmax,ymax)),4326);
452     END IF;
453
454     secgeo := st_intersection(geometry, secbox);
455     IF NOT ST_IsEmpty(secgeo) AND ST_Dimension(secgeo) = 2 THEN
456       FOR geo IN SELECT quad_split_geometry(secgeo, maxarea, remainingdepth) as geom LOOP
457         IF NOT ST_IsEmpty(geo.geom) AND ST_Dimension(geo.geom) = 2 THEN
458           RETURN NEXT geo.geom;
459         END IF;
460       END LOOP;
461     END IF;
462   END LOOP;
463
464   RETURN;
465 END;
466 $$
467 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
468
469
470 CREATE OR REPLACE FUNCTION split_geometry(geometry GEOMETRY)
471   RETURNS SETOF GEOMETRY
472   AS $$
473 DECLARE
474   geo RECORD;
475 BEGIN
476   IF ST_GeometryType(geometry) = 'ST_MultiPolygon'
477      and ST_Area(geometry) * 10 > ST_Area(Box2D(geometry))
478   THEN
479     FOR geo IN
480         SELECT quad_split_geometry(g, 0.25, 20) as geom
481         FROM (SELECT (ST_Dump(geometry)).geom::geometry(Polygon, 4326) AS g) xx
482     LOOP
483       RETURN NEXT geo.geom;
484     END LOOP;
485   ELSE
486     FOR geo IN
487         SELECT quad_split_geometry(geometry, 0.25, 20) as geom
488     LOOP
489       RETURN NEXT geo.geom;
490     END LOOP;
491   END IF;
492   RETURN;
493 END;
494 $$
495 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
496
497 CREATE OR REPLACE FUNCTION simplify_large_polygons(geometry GEOMETRY)
498   RETURNS GEOMETRY
499   AS $$
500 BEGIN
501   IF ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
502      and ST_MemSize(geometry) > 3000000
503   THEN
504     geometry := ST_SimplifyPreserveTopology(geometry, 0.0001);
505   END IF;
506   RETURN geometry;
507 END;
508 $$
509 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
510
511
512 CREATE OR REPLACE FUNCTION place_force_delete(placeid BIGINT)
513   RETURNS BOOLEAN
514   AS $$
515 DECLARE
516     osmid BIGINT;
517     osmtype character(1);
518     pclass text;
519     ptype text;
520 BEGIN
521   SELECT osm_type, osm_id, class, type FROM placex WHERE place_id = placeid INTO osmtype, osmid, pclass, ptype;
522   DELETE FROM import_polygon_delete where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
523   DELETE FROM import_polygon_error where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
524   -- force delete by directly entering it into the to-be-deleted table
525   INSERT INTO place_to_be_deleted (osm_type, osm_id, class, type, deferred)
526          VALUES(osmtype, osmid, pclass, ptype, false);
527   PERFORM flush_deleted_places();
528
529   RETURN TRUE;
530 END;
531 $$
532 LANGUAGE plpgsql;
533
534
535 CREATE OR REPLACE FUNCTION place_force_update(placeid BIGINT)
536   RETURNS BOOLEAN
537   AS $$
538 DECLARE
539   placegeom GEOMETRY;
540   geom GEOMETRY;
541   diameter FLOAT;
542   rank SMALLINT;
543 BEGIN
544   UPDATE placex SET indexed_status = 2 WHERE place_id = placeid;
545
546   SELECT geometry, rank_address INTO placegeom, rank
547     FROM placex WHERE place_id = placeid;
548
549   IF placegeom IS NOT NULL AND ST_IsValid(placegeom) THEN
550     IF ST_GeometryType(placegeom) in ('ST_Polygon','ST_MultiPolygon')
551        AND rank > 0
552     THEN
553       FOR geom IN SELECT split_geometry(placegeom) LOOP
554         UPDATE placex SET indexed_status = 2
555          WHERE ST_Intersects(geom, placex.geometry)
556                and indexed_status = 0
557                and ((rank_address = 0 and rank_search > rank) or rank_address > rank)
558                and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
559       END LOOP;
560     ELSE
561         diameter := update_place_diameter(rank);
562         IF diameter > 0 THEN
563           IF rank >= 26 THEN
564             -- roads may cause reparenting for >27 rank places
565             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter);
566           ELSEIF rank >= 16 THEN
567             -- up to rank 16, street-less addresses may need reparenting
568             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null or address ? 'place');
569           ELSE
570             -- for all other places the search terms may change as well
571             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null);
572           END IF;
573         END IF;
574     END IF;
575     RETURN TRUE;
576   END IF;
577
578   RETURN FALSE;
579 END;
580 $$
581 LANGUAGE plpgsql;
582
583 CREATE OR REPLACE FUNCTION flush_deleted_places()
584   RETURNS INTEGER
585   AS $$
586 BEGIN
587   -- deleting large polygons can have a massive effect on the system - require manual intervention to let them through
588   INSERT INTO import_polygon_delete (osm_type, osm_id, class, type)
589     SELECT osm_type, osm_id, class, type FROM place_to_be_deleted WHERE deferred;
590
591   -- delete from place table
592   ALTER TABLE place DISABLE TRIGGER place_before_delete;
593   DELETE FROM place USING place_to_be_deleted
594     WHERE place.osm_type = place_to_be_deleted.osm_type
595           and place.osm_id = place_to_be_deleted.osm_id
596           and place.class = place_to_be_deleted.class
597           and place.type = place_to_be_deleted.type
598           and not deferred;
599   ALTER TABLE place ENABLE TRIGGER place_before_delete;
600
601   -- Mark for delete in the placex table
602   UPDATE placex SET indexed_status = 100 FROM place_to_be_deleted
603     WHERE placex.osm_type = 'N' and place_to_be_deleted.osm_type = 'N'
604           and placex.osm_id = place_to_be_deleted.osm_id
605           and placex.class = place_to_be_deleted.class
606           and placex.type = place_to_be_deleted.type
607           and not deferred;
608   UPDATE placex SET indexed_status = 100 FROM place_to_be_deleted
609     WHERE placex.osm_type = 'W' and place_to_be_deleted.osm_type = 'W'
610           and placex.osm_id = place_to_be_deleted.osm_id
611           and placex.class = place_to_be_deleted.class
612           and placex.type = place_to_be_deleted.type
613           and not deferred;
614   UPDATE placex SET indexed_status = 100 FROM place_to_be_deleted
615     WHERE placex.osm_type = 'R' and place_to_be_deleted.osm_type = 'R'
616           and placex.osm_id = place_to_be_deleted.osm_id
617           and placex.class = place_to_be_deleted.class
618           and placex.type = place_to_be_deleted.type
619           and not deferred;
620
621    -- Mark for delete in interpolations
622    UPDATE location_property_osmline SET indexed_status = 100 FROM place_to_be_deleted
623     WHERE place_to_be_deleted.osm_type = 'W'
624           and place_to_be_deleted.class = 'place'
625           and place_to_be_deleted.type = 'houses'
626           and location_property_osmline.osm_id = place_to_be_deleted.osm_id
627           and not deferred;
628
629    -- Clear todo list.
630    TRUNCATE TABLE place_to_be_deleted;
631
632    RETURN NULL;
633 END;
634 $$ LANGUAGE plpgsql;
635
636
637 CREATE OR REPLACE FUNCTION place_update_entrances(placeid BIGINT, osmid BIGINT)
638   RETURNS INTEGER
639   AS $$
640 DECLARE
641   entrance RECORD;
642   osm_ids BIGINT[];
643 BEGIN
644   osm_ids := '{}';
645   FOR entrance in SELECT osm_id, type, geometry, extratags
646       FROM place_entrance
647       WHERE osm_id IN (SELECT unnest(nodes) FROM planet_osm_ways WHERE id=osmid)
648   LOOP
649     osm_ids := array_append(osm_ids, entrance.osm_id);
650     INSERT INTO placex_entrance (place_id, osm_id, type, location, extratags)
651       VALUES (placeid, entrance.osm_id, entrance.type, entrance.geometry, entrance.extratags)
652       ON CONFLICT (place_id, osm_id) DO UPDATE
653         SET type = excluded.type, location = excluded.location, extratags = excluded.extratags;
654   END LOOP;
655
656   IF array_length(osm_ids, 1) > 0 THEN
657     DELETE FROM placex_entrance WHERE place_id=placeid AND NOT osm_id=ANY(osm_ids);
658   ELSE
659     DELETE FROM placex_entrance WHERE place_id=placeid;
660   END IF;
661
662   RETURN NULL;
663 END;
664 $$
665 LANGUAGE plpgsql;