]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/utils.sql
Merge pull request #3997 from lonvia/fix-postcode-index
[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) 2026 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 COALESCE(b, '{}'::INTEGER[]);
50   END IF;
51   IF array_upper(b, 1) IS NULL THEN
52     RETURN COALESCE(a, '{}'::INTEGER[]);
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 ST_Contains(geom, location_postcodes.centroid)
157                  AND country_code = country
158            LIMIT 2) sub
159         INTO outcode, cnt;
160
161         IF cnt = 1 THEN
162             RETURN outcode;
163         END IF;
164
165         RETURN null;
166     END IF;
167
168     -- Otherwise: be fully within the coverage area of a postcode
169     FOR location IN
170       SELECT postcode
171         FROM location_postcodes p
172        WHERE ST_Covers(p.geometry, geom)
173              AND p.country_code = country
174        ORDER BY osm_id is null, ST_Distance(p.centroid, geom)
175        LIMIT 1
176     LOOP
177         RETURN location.postcode;
178     END LOOP;
179
180     RETURN NULL;
181 END;
182 $$
183 LANGUAGE plpgsql STABLE PARALLEL SAFE;
184
185
186 CREATE OR REPLACE FUNCTION get_country_code(place geometry)
187   RETURNS TEXT
188   AS $$
189 DECLARE
190   nearcountry RECORD;
191   countries TEXT[];
192 BEGIN
193 -- RAISE WARNING 'get_country_code, start: %', ST_AsText(place);
194
195   -- Try for a OSM polygon
196   SELECT array_agg(country_code) FROM location_area_country
197     WHERE country_code is not null and st_covers(geometry, place)
198     INTO countries;
199
200   IF array_length(countries, 1) = 1 THEN
201     RETURN countries[1];
202   END IF;
203
204   IF array_length(countries, 1) > 1 THEN
205     -- more than one country found, confirm against the fallback data what to choose
206     FOR nearcountry IN
207         SELECT country_code FROM country_osm_grid
208           WHERE ST_Covers(geometry, place) AND country_code = ANY(countries)
209           ORDER BY area ASC
210     LOOP
211         RETURN nearcountry.country_code;
212     END LOOP;
213     -- Still nothing? Choose the country code with the smallest partition number.
214     -- And failing that, just go by the alphabet.
215     FOR nearcountry IN
216         SELECT cc,
217                (SELECT partition FROM country_name WHERE country_code = cc) as partition
218         FROM unnest(countries) cc
219         ORDER BY partition, cc
220     LOOP
221         RETURN nearcountry.cc;
222     END LOOP;
223
224     -- Should never be reached.
225     RETURN countries[1];
226   END IF;
227
228 -- RAISE WARNING 'osm fallback: %', ST_AsText(place);
229
230   -- Try for OSM fallback data
231   -- The order is to deal with places like HongKong that are 'states' within another polygon
232   FOR nearcountry IN
233     SELECT country_code from country_osm_grid
234     WHERE st_covers(geometry, place) order by area asc limit 1
235   LOOP
236     RETURN nearcountry.country_code;
237   END LOOP;
238
239 -- RAISE WARNING 'near osm fallback: %', ST_AsText(place);
240
241   RETURN NULL;
242 END;
243 $$
244 LANGUAGE plpgsql STABLE PARALLEL SAFE;
245
246
247 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2))
248   RETURNS TEXT
249   AS $$
250 DECLARE
251   nearcountry RECORD;
252 BEGIN
253   FOR nearcountry IN
254     SELECT distinct country_default_language_code from country_name
255     WHERE country_code = search_country_code limit 1
256   LOOP
257     RETURN lower(nearcountry.country_default_language_code);
258   END LOOP;
259   RETURN NULL;
260 END;
261 $$
262 LANGUAGE plpgsql STABLE PARALLEL SAFE;
263
264
265 CREATE OR REPLACE FUNCTION get_partition(in_country_code VARCHAR(10))
266   RETURNS INTEGER
267   AS $$
268 DECLARE
269   nearcountry RECORD;
270 BEGIN
271   FOR nearcountry IN
272     SELECT partition from country_name where country_code = in_country_code
273   LOOP
274     RETURN nearcountry.partition;
275   END LOOP;
276   RETURN 0;
277 END;
278 $$
279 LANGUAGE plpgsql STABLE PARALLEL SAFE;
280
281
282 -- Find the parent of an address with addr:street/addr:place tag.
283 --
284 -- \param token_info Naming info with the address information.
285 -- \param partition  Partition where to search the parent.
286 -- \param centroid   Location of the address.
287 --
288 -- \return Place ID of the parent if one was found, NULL otherwise.
289 CREATE OR REPLACE FUNCTION find_parent_for_address(token_info JSONB,
290                                                    partition SMALLINT,
291                                                    centroid GEOMETRY)
292   RETURNS BIGINT
293   AS $$
294 DECLARE
295   parent_place_id BIGINT;
296 BEGIN
297   -- Check for addr:street attributes
298   parent_place_id := getNearestNamedRoadPlaceId(partition, centroid, token_info);
299   IF parent_place_id is not null THEN
300     {% if debug %}RAISE WARNING 'Get parent from addr:street: %', parent_place_id;{% endif %}
301     RETURN parent_place_id;
302   END IF;
303
304   -- Check for addr:place attributes.
305   parent_place_id := getNearestNamedPlacePlaceId(partition, centroid, token_info);
306   {% if debug %}RAISE WARNING 'Get parent from addr:place: %', parent_place_id;{% endif %}
307   RETURN parent_place_id;
308 END;
309 $$
310 LANGUAGE plpgsql STABLE PARALLEL SAFE;
311
312
313 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT)
314   RETURNS BOOLEAN
315   AS $$
316 DECLARE
317 BEGIN
318   DELETE FROM location_area where place_id = OLD_place_id;
319 -- TODO:location_area
320   RETURN true;
321 END;
322 $$
323 LANGUAGE plpgsql;
324
325
326 -- Return the bounding box of the geometry buffered by the given number
327 -- of meters.
328 CREATE OR REPLACE FUNCTION expand_by_meters(geom GEOMETRY, meters FLOAT)
329   RETURNS GEOMETRY
330   AS $$
331     SELECT ST_Envelope(ST_Buffer(geom::geography, meters, 1)::geometry)
332 $$
333 LANGUAGE sql IMMUTABLE PARALLEL SAFE;
334
335
336 -- Create a bounding box with an extent computed from the radius (in meters)
337 -- which in turn is derived from the given search rank.
338 CREATE OR REPLACE FUNCTION place_node_fuzzy_area(geom GEOMETRY, rank_search INTEGER)
339   RETURNS GEOMETRY
340   AS $$
341 DECLARE
342   radius FLOAT := 500;
343 BEGIN
344   IF rank_search <= 16 THEN -- city
345     radius := 15000;
346   ELSIF rank_search <= 18 THEN -- town
347     radius := 4000;
348   ELSIF rank_search <= 19 THEN -- village
349     radius := 2000;
350   ELSIF rank_search  <= 20 THEN -- hamlet
351     radius := 1000;
352   END IF;
353
354   RETURN expand_by_meters(geom, radius);
355 END;
356 $$
357 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
358
359
360 CREATE OR REPLACE FUNCTION add_location(place_id BIGINT, country_code varchar(2),
361                                         partition INTEGER, keywords INTEGER[],
362                                         rank_search INTEGER, rank_address INTEGER,
363                                         in_postcode TEXT, geometry GEOMETRY,
364                                         centroid GEOMETRY)
365   RETURNS BOOLEAN
366   AS $$
367 DECLARE
368   postcode TEXT;
369 BEGIN
370   -- add postcode only if it contains a single entry, i.e. ignore postcode lists
371   postcode := NULL;
372   IF in_postcode is not null AND in_postcode not similar to '%(,|;)%' THEN
373       postcode := upper(trim (in_postcode));
374   END IF;
375
376   IF ST_Dimension(geometry) = 2 THEN
377     RETURN insertLocationAreaLarge(partition, place_id, country_code, keywords,
378                                    rank_search, rank_address, false, postcode,
379                                    centroid, geometry);
380   END IF;
381
382   IF ST_Dimension(geometry) = 0 THEN
383     RETURN insertLocationAreaLarge(partition, place_id, country_code, keywords,
384                                    rank_search, rank_address, true, postcode,
385                                    centroid, place_node_fuzzy_area(geometry, rank_search));
386   END IF;
387
388   RETURN false;
389 END;
390 $$
391 LANGUAGE plpgsql;
392
393
394 CREATE OR REPLACE FUNCTION quad_split_geometry(geometry GEOMETRY, maxarea FLOAT,
395                                                maxdepth INTEGER)
396   RETURNS SETOF GEOMETRY
397   AS $$
398 DECLARE
399   xmin FLOAT;
400   ymin FLOAT;
401   xmax FLOAT;
402   ymax FLOAT;
403   xmid FLOAT;
404   ymid FLOAT;
405   secgeo GEOMETRY;
406   secbox GEOMETRY;
407   seg INTEGER;
408   geo RECORD;
409   area FLOAT;
410   remainingdepth INTEGER;
411 BEGIN
412 --  RAISE WARNING 'quad_split_geometry: maxarea=%, depth=%',maxarea,maxdepth;
413
414   IF not ST_IsValid(geometry) THEN
415     RETURN;
416   END IF;
417
418   IF ST_Dimension(geometry) != 2 OR maxdepth <= 1 THEN
419     RETURN NEXT geometry;
420     RETURN;
421   END IF;
422
423   remainingdepth := maxdepth - 1;
424   area := ST_AREA(geometry);
425   IF area < maxarea THEN
426     RETURN NEXT geometry;
427     RETURN;
428   END IF;
429
430   xmin := st_xmin(geometry);
431   xmax := st_xmax(geometry);
432   ymin := st_ymin(geometry);
433   ymax := st_ymax(geometry);
434   secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(ymin,xmin),ST_Point(ymax,xmax)),4326);
435
436   -- if the geometry completely covers the box don't bother to slice any more
437   IF ST_AREA(secbox) = area THEN
438     RETURN NEXT geometry;
439     RETURN;
440   END IF;
441
442   xmid := (xmin+xmax)/2;
443   ymid := (ymin+ymax)/2;
444
445   FOR seg IN 1..4 LOOP
446
447     IF seg = 1 THEN
448       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymin),ST_Point(xmid,ymid)),4326);
449     END IF;
450     IF seg = 2 THEN
451       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymid),ST_Point(xmid,ymax)),4326);
452     END IF;
453     IF seg = 3 THEN
454       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymin),ST_Point(xmax,ymid)),4326);
455     END IF;
456     IF seg = 4 THEN
457       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymid),ST_Point(xmax,ymax)),4326);
458     END IF;
459
460     secgeo := st_intersection(geometry, secbox);
461     IF NOT ST_IsEmpty(secgeo) AND ST_Dimension(secgeo) = 2 THEN
462       FOR geo IN SELECT quad_split_geometry(secgeo, maxarea, remainingdepth) as geom LOOP
463         IF NOT ST_IsEmpty(geo.geom) AND ST_Dimension(geo.geom) = 2 THEN
464           RETURN NEXT geo.geom;
465         END IF;
466       END LOOP;
467     END IF;
468   END LOOP;
469
470   RETURN;
471 END;
472 $$
473 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
474
475
476 CREATE OR REPLACE FUNCTION split_geometry(geometry GEOMETRY)
477   RETURNS SETOF GEOMETRY
478   AS $$
479 DECLARE
480   geo RECORD;
481 BEGIN
482   IF ST_GeometryType(geometry) = 'ST_MultiPolygon'
483      and ST_Area(geometry) * 10 > ST_Area(Box2D(geometry))
484   THEN
485     FOR geo IN
486         SELECT quad_split_geometry(g, 0.25, 20) as geom
487         FROM (SELECT (ST_Dump(geometry)).geom::geometry(Polygon, 4326) AS g) xx
488     LOOP
489       RETURN NEXT geo.geom;
490     END LOOP;
491   ELSE
492     FOR geo IN
493         SELECT quad_split_geometry(geometry, 0.25, 20) as geom
494     LOOP
495       RETURN NEXT geo.geom;
496     END LOOP;
497   END IF;
498   RETURN;
499 END;
500 $$
501 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
502
503 CREATE OR REPLACE FUNCTION simplify_large_polygons(geometry GEOMETRY)
504   RETURNS GEOMETRY
505   AS $$
506 BEGIN
507   IF ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
508      and ST_MemSize(geometry) > 3000000
509   THEN
510     geometry := ST_SimplifyPreserveTopology(geometry, 0.0001);
511   END IF;
512   RETURN geometry;
513 END;
514 $$
515 LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
516
517
518 CREATE OR REPLACE FUNCTION place_force_delete(placeid BIGINT)
519   RETURNS BOOLEAN
520   AS $$
521 DECLARE
522     osmid BIGINT;
523     osmtype character(1);
524     pclass text;
525     ptype text;
526 BEGIN
527   SELECT osm_type, osm_id, class, type FROM placex WHERE place_id = placeid INTO osmtype, osmid, pclass, ptype;
528   DELETE FROM import_polygon_delete where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
529   DELETE FROM import_polygon_error where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
530   -- force delete by directly entering it into the to-be-deleted table
531   INSERT INTO place_to_be_deleted (osm_type, osm_id, class, type, deferred)
532          VALUES(osmtype, osmid, pclass, ptype, false);
533   PERFORM flush_deleted_places();
534
535   RETURN TRUE;
536 END;
537 $$
538 LANGUAGE plpgsql;
539
540
541 CREATE OR REPLACE FUNCTION place_force_update(placeid BIGINT)
542   RETURNS BOOLEAN
543   AS $$
544 DECLARE
545   placegeom GEOMETRY;
546   geom GEOMETRY;
547   diameter FLOAT;
548   rank SMALLINT;
549 BEGIN
550   UPDATE placex SET indexed_status = 2 WHERE place_id = placeid;
551
552   SELECT geometry, rank_address INTO placegeom, rank
553     FROM placex WHERE place_id = placeid;
554
555   IF placegeom IS NOT NULL AND ST_IsValid(placegeom) THEN
556     IF ST_GeometryType(placegeom) in ('ST_Polygon','ST_MultiPolygon')
557        AND rank > 0
558     THEN
559       FOR geom IN SELECT split_geometry(placegeom) LOOP
560         UPDATE placex SET indexed_status = 2
561          WHERE ST_Intersects(geom, placex.geometry)
562                and indexed_status = 0
563                and ((rank_address = 0 and rank_search > rank) or rank_address > rank)
564                and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
565       END LOOP;
566     ELSE
567         diameter := update_place_diameter(rank);
568         IF diameter > 0 THEN
569           IF rank >= 26 THEN
570             -- roads may cause reparenting for >27 rank places
571             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter);
572           ELSEIF rank >= 16 THEN
573             -- up to rank 16, street-less addresses may need reparenting
574             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');
575           ELSE
576             -- for all other places the search terms may change as well
577             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);
578           END IF;
579         END IF;
580     END IF;
581     RETURN TRUE;
582   END IF;
583
584   RETURN FALSE;
585 END;
586 $$
587 LANGUAGE plpgsql;
588
589 CREATE OR REPLACE FUNCTION flush_deleted_places()
590   RETURNS INTEGER
591   AS $$
592 BEGIN
593   -- deleting large polygons can have a massive effect on the system - require manual intervention to let them through
594   INSERT INTO import_polygon_delete (osm_type, osm_id, class, type)
595     SELECT osm_type, osm_id, class, type FROM place_to_be_deleted WHERE deferred;
596
597   -- delete from place table
598   ALTER TABLE place DISABLE TRIGGER place_before_delete;
599   DELETE FROM place USING place_to_be_deleted
600     WHERE place.osm_type = place_to_be_deleted.osm_type
601           and place.osm_id = place_to_be_deleted.osm_id
602           and place.class = place_to_be_deleted.class
603           and place.type = place_to_be_deleted.type
604           and not deferred;
605   ALTER TABLE place ENABLE TRIGGER place_before_delete;
606
607   -- Mark for delete in the placex table
608   UPDATE placex SET indexed_status = 100 FROM place_to_be_deleted
609     WHERE placex.osm_type = 'N' and place_to_be_deleted.osm_type = 'N'
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 = 'W' and place_to_be_deleted.osm_type = 'W'
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   UPDATE placex SET indexed_status = 100 FROM place_to_be_deleted
621     WHERE placex.osm_type = 'R' and place_to_be_deleted.osm_type = 'R'
622           and placex.osm_id = place_to_be_deleted.osm_id
623           and placex.class = place_to_be_deleted.class
624           and placex.type = place_to_be_deleted.type
625           and not deferred;
626
627    -- Mark for delete in interpolations
628    UPDATE location_property_osmline SET indexed_status = 100 FROM place_to_be_deleted
629     WHERE place_to_be_deleted.osm_type = 'W'
630           and place_to_be_deleted.class = 'place'
631           and place_to_be_deleted.type = 'houses'
632           and location_property_osmline.osm_id = place_to_be_deleted.osm_id
633           and not deferred;
634
635    -- Clear todo list.
636    TRUNCATE TABLE place_to_be_deleted;
637
638    RETURN NULL;
639 END;
640 $$ LANGUAGE plpgsql;
641
642
643 CREATE OR REPLACE FUNCTION place_update_entrances(placeid BIGINT, osmid BIGINT)
644   RETURNS INTEGER
645   AS $$
646 DECLARE
647   entrance RECORD;
648   osm_ids BIGINT[];
649 BEGIN
650   osm_ids := '{}';
651   FOR entrance in SELECT osm_id, type, geometry, extratags
652       FROM place_entrance
653       WHERE osm_id IN (SELECT unnest(nodes) FROM planet_osm_ways WHERE id=osmid)
654   LOOP
655     osm_ids := array_append(osm_ids, entrance.osm_id);
656     INSERT INTO placex_entrance (place_id, osm_id, type, location, extratags)
657       VALUES (placeid, entrance.osm_id, entrance.type, entrance.geometry, entrance.extratags)
658       ON CONFLICT (place_id, osm_id) DO UPDATE
659         SET type = excluded.type, location = excluded.location, extratags = excluded.extratags;
660   END LOOP;
661
662   IF array_length(osm_ids, 1) > 0 THEN
663     DELETE FROM placex_entrance WHERE place_id=placeid AND NOT osm_id=ANY(osm_ids);
664   ELSE
665     DELETE FROM placex_entrance WHERE place_id=placeid;
666   END IF;
667
668   RETURN NULL;
669 END;
670 $$
671 LANGUAGE plpgsql;