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