]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/utils.sql
Merge pull request #2562 from lonvia/copyright-headers
[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) 2022 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 geometry_sector(partition INTEGER, place geometry)
11   RETURNS INTEGER
12   AS $$
13 DECLARE
14   NEWgeometry geometry;
15 BEGIN
16 --  RAISE WARNING '%',place;
17   NEWgeometry := ST_PointOnSurface(place);
18   RETURN (partition*1000000) + (500-ST_X(NEWgeometry)::integer)*1000 + (500-ST_Y(NEWgeometry)::integer);
19 END;
20 $$
21 LANGUAGE plpgsql IMMUTABLE;
22
23
24 CREATE OR REPLACE FUNCTION array_merge(a INTEGER[], b INTEGER[])
25   RETURNS INTEGER[]
26   AS $$
27 DECLARE
28   i INTEGER;
29   r INTEGER[];
30 BEGIN
31   IF array_upper(a, 1) IS NULL THEN
32     RETURN b;
33   END IF;
34   IF array_upper(b, 1) IS NULL THEN
35     RETURN a;
36   END IF;
37   r := a;
38   FOR i IN 1..array_upper(b, 1) LOOP  
39     IF NOT (ARRAY[b[i]] <@ r) THEN
40       r := r || b[i];
41     END IF;
42   END LOOP;
43   RETURN r;
44 END;
45 $$
46 LANGUAGE plpgsql IMMUTABLE;
47
48 -- Return the node members with a given label from a relation member list
49 -- as a set.
50 --
51 -- \param members      Member list in osm2pgsql middle format.
52 -- \param memberLabels Array of labels to accept.
53 --
54 -- \returns Set of OSM ids of nodes that are found.
55 --
56 CREATE OR REPLACE FUNCTION get_rel_node_members(members TEXT[],
57                                                 memberLabels TEXT[])
58   RETURNS SETOF BIGINT
59   AS $$
60 DECLARE
61   i INTEGER;
62 BEGIN
63   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
64     IF members[i+1] = ANY(memberLabels)
65        AND upper(substring(members[i], 1, 1))::char(1) = 'N'
66     THEN
67       RETURN NEXT substring(members[i], 2)::bigint;
68     END IF;
69   END LOOP;
70
71   RETURN;
72 END;
73 $$
74 LANGUAGE plpgsql IMMUTABLE;
75
76 -- Copy 'name' to or from the default language.
77 --
78 -- \param country_code     Country code of the object being named.
79 -- \param[inout] name      List of names of the object.
80 --
81 -- If the country named by country_code has a single default language,
82 -- then a `name` tag is copied to `name:<country_code>` if this tag does
83 -- not yet exist and vice versa.
84 CREATE OR REPLACE FUNCTION add_default_place_name(country_code VARCHAR(2),
85                                                   INOUT name HSTORE)
86   AS $$
87 DECLARE
88   default_language VARCHAR(10);
89 BEGIN
90   IF name is not null AND array_upper(akeys(name),1) > 1 THEN
91     default_language := get_country_language_code(country_code);
92     IF default_language IS NOT NULL THEN
93       IF name ? 'name' AND NOT name ? ('name:'||default_language) THEN
94         name := name || hstore(('name:'||default_language), (name -> 'name'));
95       ELSEIF name ? ('name:'||default_language) AND NOT name ? 'name' THEN
96         name := name || hstore('name', (name -> ('name:'||default_language)));
97       END IF;
98     END IF;
99   END IF;
100 END;
101 $$
102 LANGUAGE plpgsql IMMUTABLE;
103
104
105 -- Find the nearest artificial postcode for the given geometry.
106 -- TODO For areas there should not be more than two inside the geometry.
107 CREATE OR REPLACE FUNCTION get_nearest_postcode(country VARCHAR(2), geom GEOMETRY)
108   RETURNS TEXT
109   AS $$
110 DECLARE
111   outcode TEXT;
112   cnt INTEGER;
113 BEGIN
114     -- If the geometry is an area then only one postcode must be within
115     -- that area, otherwise consider the area as not having a postcode.
116     IF ST_GeometryType(geom) in ('ST_Polygon','ST_MultiPolygon') THEN
117         SELECT min(postcode), count(*) FROM
118               (SELECT postcode FROM location_postcode
119                 WHERE ST_Contains(geom, location_postcode.geometry) LIMIT 2) sub
120           INTO outcode, cnt;
121
122         IF cnt = 1 THEN
123             RETURN outcode;
124         ELSE
125             RETURN null;
126         END IF;
127     END IF;
128
129     SELECT postcode FROM location_postcode
130      WHERE ST_DWithin(geom, location_postcode.geometry, 0.05)
131           AND location_postcode.country_code = country
132      ORDER BY ST_Distance(geom, location_postcode.geometry) LIMIT 1
133     INTO outcode;
134
135     RETURN outcode;
136 END;
137 $$
138 LANGUAGE plpgsql STABLE;
139
140
141 CREATE OR REPLACE FUNCTION get_country_code(place geometry)
142   RETURNS TEXT
143   AS $$
144 DECLARE
145   place_centre GEOMETRY;
146   nearcountry RECORD;
147 BEGIN
148   place_centre := ST_PointOnSurface(place);
149
150 -- RAISE WARNING 'get_country_code, start: %', ST_AsText(place_centre);
151
152   -- Try for a OSM polygon
153   FOR nearcountry IN
154     SELECT country_code from location_area_country
155     WHERE country_code is not null and st_covers(geometry, place_centre) limit 1
156   LOOP
157     RETURN nearcountry.country_code;
158   END LOOP;
159
160 -- RAISE WARNING 'osm fallback: %', ST_AsText(place_centre);
161
162   -- Try for OSM fallback data
163   -- The order is to deal with places like HongKong that are 'states' within another polygon
164   FOR nearcountry IN
165     SELECT country_code from country_osm_grid
166     WHERE st_covers(geometry, place_centre) order by area asc limit 1
167   LOOP
168     RETURN nearcountry.country_code;
169   END LOOP;
170
171 -- RAISE WARNING 'near osm fallback: %', ST_AsText(place_centre);
172
173   -- 
174   FOR nearcountry IN
175     SELECT country_code from country_osm_grid
176     WHERE st_dwithin(geometry, place_centre, 0.5)
177     ORDER BY st_distance(geometry, place_centre) asc, area asc limit 1
178   LOOP
179     RETURN nearcountry.country_code;
180   END LOOP;
181
182   RETURN NULL;
183 END;
184 $$
185 LANGUAGE plpgsql STABLE;
186
187
188 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2))
189   RETURNS TEXT
190   AS $$
191 DECLARE
192   nearcountry RECORD;
193 BEGIN
194   FOR nearcountry IN
195     SELECT distinct country_default_language_code from country_name
196     WHERE country_code = search_country_code limit 1
197   LOOP
198     RETURN lower(nearcountry.country_default_language_code);
199   END LOOP;
200   RETURN NULL;
201 END;
202 $$
203 LANGUAGE plpgsql STABLE;
204
205
206 CREATE OR REPLACE FUNCTION get_partition(in_country_code VARCHAR(10))
207   RETURNS INTEGER
208   AS $$
209 DECLARE
210   nearcountry RECORD;
211 BEGIN
212   FOR nearcountry IN
213     SELECT partition from country_name where country_code = in_country_code
214   LOOP
215     RETURN nearcountry.partition;
216   END LOOP;
217   RETURN 0;
218 END;
219 $$
220 LANGUAGE plpgsql STABLE;
221
222
223 -- Find the parent of an address with addr:street/addr:place tag.
224 --
225 -- \param token_info Naming info with the address information.
226 -- \param partition  Partition where to search the parent.
227 -- \param centroid   Location of the address.
228 --
229 -- \return Place ID of the parent if one was found, NULL otherwise.
230 CREATE OR REPLACE FUNCTION find_parent_for_address(token_info JSONB,
231                                                    partition SMALLINT,
232                                                    centroid GEOMETRY)
233   RETURNS BIGINT
234   AS $$
235 DECLARE
236   parent_place_id BIGINT;
237 BEGIN
238   -- Check for addr:street attributes
239   parent_place_id := getNearestNamedRoadPlaceId(partition, centroid, token_info);
240   IF parent_place_id is not null THEN
241     {% if debug %}RAISE WARNING 'Get parent from addr:street: %', parent_place_id;{% endif %}
242     RETURN parent_place_id;
243   END IF;
244
245   -- Check for addr:place attributes.
246   parent_place_id := getNearestNamedPlacePlaceId(partition, centroid, token_info);
247   {% if debug %}RAISE WARNING 'Get parent from addr:place: %', parent_place_id;{% endif %}
248   RETURN parent_place_id;
249 END;
250 $$
251 LANGUAGE plpgsql STABLE;
252
253
254 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT)
255   RETURNS BOOLEAN
256   AS $$
257 DECLARE
258 BEGIN
259   DELETE FROM location_area where place_id = OLD_place_id;
260 -- TODO:location_area
261   RETURN true;
262 END;
263 $$
264 LANGUAGE plpgsql;
265
266 -- Create a bounding box with an extent computed from the radius (in meters)
267 -- which in turn is derived from the given search rank.
268 CREATE OR REPLACE FUNCTION place_node_fuzzy_area(geom GEOMETRY, rank_search INTEGER)
269   RETURNS GEOMETRY
270   AS $$
271 DECLARE
272   radius FLOAT := 500;
273 BEGIN
274   IF rank_search <= 16 THEN -- city
275     radius := 15000;
276   ELSIF rank_search <= 18 THEN -- town
277     radius := 4000;
278   ELSIF rank_search <= 19 THEN -- village
279     radius := 2000;
280   ELSIF rank_search  <= 20 THEN -- hamlet
281     radius := 1000;
282   END IF;
283
284   RETURN ST_Envelope(ST_Collect(
285                      ST_Project(geom, radius, 0.785398)::geometry,
286                      ST_Project(geom, radius, 3.9269908)::geometry));
287 END;
288 $$
289 LANGUAGE plpgsql IMMUTABLE;
290
291
292 CREATE OR REPLACE FUNCTION add_location(place_id BIGINT, country_code varchar(2),
293                                         partition INTEGER, keywords INTEGER[],
294                                         rank_search INTEGER, rank_address INTEGER,
295                                         in_postcode TEXT, geometry GEOMETRY,
296                                         centroid GEOMETRY)
297   RETURNS BOOLEAN
298   AS $$
299 DECLARE
300   locationid INTEGER;
301   secgeo GEOMETRY;
302   postcode TEXT;
303 BEGIN
304   PERFORM deleteLocationArea(partition, place_id, rank_search);
305
306   -- add postcode only if it contains a single entry, i.e. ignore postcode lists
307   postcode := NULL;
308   IF in_postcode is not null AND in_postcode not similar to '%(,|;)%' THEN
309       postcode := upper(trim (in_postcode));
310   END IF;
311
312   IF ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
313     FOR secgeo IN select split_geometry(geometry) AS geom LOOP
314       PERFORM insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, postcode, centroid, secgeo);
315     END LOOP;
316
317   ELSEIF ST_GeometryType(geometry) = 'ST_Point' THEN
318     secgeo := place_node_fuzzy_area(geometry, rank_search);
319     PERFORM insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, true, postcode, centroid, secgeo);
320
321   END IF;
322
323   RETURN true;
324 END;
325 $$
326 LANGUAGE plpgsql;
327
328
329 CREATE OR REPLACE FUNCTION quad_split_geometry(geometry GEOMETRY, maxarea FLOAT,
330                                                maxdepth INTEGER)
331   RETURNS SETOF GEOMETRY
332   AS $$
333 DECLARE
334   xmin FLOAT;
335   ymin FLOAT;
336   xmax FLOAT;
337   ymax FLOAT;
338   xmid FLOAT;
339   ymid FLOAT;
340   secgeo GEOMETRY;
341   secbox GEOMETRY;
342   seg INTEGER;
343   geo RECORD;
344   area FLOAT;
345   remainingdepth INTEGER;
346   added INTEGER;
347 BEGIN
348
349 --  RAISE WARNING 'quad_split_geometry: maxarea=%, depth=%',maxarea,maxdepth;
350
351   IF (ST_GeometryType(geometry) not in ('ST_Polygon','ST_MultiPolygon') OR NOT ST_IsValid(geometry)) THEN
352     RETURN NEXT geometry;
353     RETURN;
354   END IF;
355
356   remainingdepth := maxdepth - 1;
357   area := ST_AREA(geometry);
358   IF remainingdepth < 1 OR area < maxarea THEN
359     RETURN NEXT geometry;
360     RETURN;
361   END IF;
362
363   xmin := st_xmin(geometry);
364   xmax := st_xmax(geometry);
365   ymin := st_ymin(geometry);
366   ymax := st_ymax(geometry);
367   secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(ymin,xmin),ST_Point(ymax,xmax)),4326);
368
369   -- if the geometry completely covers the box don't bother to slice any more
370   IF ST_AREA(secbox) = area THEN
371     RETURN NEXT geometry;
372     RETURN;
373   END IF;
374
375   xmid := (xmin+xmax)/2;
376   ymid := (ymin+ymax)/2;
377
378   added := 0;
379   FOR seg IN 1..4 LOOP
380
381     IF seg = 1 THEN
382       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymin),ST_Point(xmid,ymid)),4326);
383     END IF;
384     IF seg = 2 THEN
385       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymid),ST_Point(xmid,ymax)),4326);
386     END IF;
387     IF seg = 3 THEN
388       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymin),ST_Point(xmax,ymid)),4326);
389     END IF;
390     IF seg = 4 THEN
391       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymid),ST_Point(xmax,ymax)),4326);
392     END IF;
393
394     IF st_intersects(geometry, secbox) THEN
395       secgeo := st_intersection(geometry, secbox);
396       IF NOT ST_IsEmpty(secgeo) AND ST_GeometryType(secgeo) in ('ST_Polygon','ST_MultiPolygon') THEN
397         FOR geo IN select quad_split_geometry(secgeo, maxarea, remainingdepth) as geom LOOP
398           IF NOT ST_IsEmpty(geo.geom) AND ST_GeometryType(geo.geom) in ('ST_Polygon','ST_MultiPolygon') THEN
399             added := added + 1;
400             RETURN NEXT geo.geom;
401           END IF;
402         END LOOP;
403       END IF;
404     END IF;
405   END LOOP;
406
407   RETURN;
408 END;
409 $$
410 LANGUAGE plpgsql IMMUTABLE;
411
412
413 CREATE OR REPLACE FUNCTION split_geometry(geometry GEOMETRY)
414   RETURNS SETOF GEOMETRY
415   AS $$
416 DECLARE
417   geo RECORD;
418 BEGIN
419   -- 10000000000 is ~~ 1x1 degree
420   FOR geo IN select quad_split_geometry(geometry, 0.25, 20) as geom LOOP
421     RETURN NEXT geo.geom;
422   END LOOP;
423   RETURN;
424 END;
425 $$
426 LANGUAGE plpgsql IMMUTABLE;
427
428
429 CREATE OR REPLACE FUNCTION place_force_delete(placeid BIGINT)
430   RETURNS BOOLEAN
431   AS $$
432 DECLARE
433     osmid BIGINT;
434     osmtype character(1);
435     pclass text;
436     ptype text;
437 BEGIN
438   SELECT osm_type, osm_id, class, type FROM placex WHERE place_id = placeid INTO osmtype, osmid, pclass, ptype;
439   DELETE FROM import_polygon_delete where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
440   DELETE FROM import_polygon_error where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
441   -- force delete from place/placex by making it a very small geometry
442   UPDATE place set geometry = ST_SetSRID(ST_Point(0,0), 4326) where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
443   DELETE FROM place where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
444
445   RETURN TRUE;
446 END;
447 $$
448 LANGUAGE plpgsql;
449
450
451 CREATE OR REPLACE FUNCTION place_force_update(placeid BIGINT)
452   RETURNS BOOLEAN
453   AS $$
454 DECLARE
455   placegeom GEOMETRY;
456   geom GEOMETRY;
457   diameter FLOAT;
458   rank SMALLINT;
459 BEGIN
460   UPDATE placex SET indexed_status = 2 WHERE place_id = placeid;
461
462   SELECT geometry, rank_address INTO placegeom, rank
463     FROM placex WHERE place_id = placeid;
464
465   IF placegeom IS NOT NULL AND ST_IsValid(placegeom) THEN
466     IF ST_GeometryType(placegeom) in ('ST_Polygon','ST_MultiPolygon')
467        AND rank > 0
468     THEN
469       FOR geom IN SELECT split_geometry(placegeom) LOOP
470         UPDATE placex SET indexed_status = 2
471          WHERE ST_Intersects(geom, placex.geometry)
472                and indexed_status = 0
473                and ((rank_address = 0 and rank_search > rank) or rank_address > rank)
474                and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
475       END LOOP;
476     ELSE
477         diameter := update_place_diameter(rank);
478         IF diameter > 0 THEN
479           IF rank >= 26 THEN
480             -- roads may cause reparenting for >27 rank places
481             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter);
482           ELSEIF rank >= 16 THEN
483             -- up to rank 16, street-less addresses may need reparenting
484             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');
485           ELSE
486             -- for all other places the search terms may change as well
487             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);
488           END IF;
489         END IF;
490     END IF;
491     RETURN TRUE;
492   END IF;
493
494   RETURN FALSE;
495 END;
496 $$
497 LANGUAGE plpgsql;