]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/place_triggers.sql
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / lib-sql / functions / place_triggers.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 CREATE OR REPLACE FUNCTION place_insert()
9   RETURNS TRIGGER
10   AS $$
11 DECLARE
12   i INTEGER;
13   country RECORD;
14   existing RECORD;
15   existingplacex RECORD;
16   existingline RECORD;
17   result BOOLEAN;
18 BEGIN
19   {% if debug %}
20     RAISE WARNING 'place_insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,st_area(NEW.geometry);
21   {% endif %}
22
23   -- Filter tuples with bad geometries.
24   IF ST_IsEmpty(NEW.geometry) OR NOT ST_IsValid(NEW.geometry) THEN
25     INSERT INTO import_polygon_error (osm_type, osm_id, class, type, name,
26                                       country_code, updated, errormessage,
27                                       prevgeometry, newgeometry)
28       VALUES (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name,
29               NEW.address->'country', now(), ST_IsValidReason(NEW.geometry),
30               null, NEW.geometry);
31     {% if debug %}
32       RAISE WARNING 'Invalid Geometry: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
33     {% endif %}
34     RETURN null;
35   END IF;
36
37   -- Have we already done this place?
38   SELECT * INTO existing
39     FROM place
40     WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
41           and class = NEW.class and type = NEW.type;
42
43   {% if debug %}RAISE WARNING 'Existing: %',existing.osm_id;{% endif %}
44
45   -- Handle a place changing type by removing the old data.
46   -- (This trigger is executed BEFORE INSERT of the NEW tuple.)
47   IF existing.osm_type IS NULL THEN
48     DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class;
49   END IF;
50
51   -- Remove any old logged data.
52   DELETE from import_polygon_error where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
53   DELETE from import_polygon_delete where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
54
55   -- ---- Interpolation Lines
56
57   IF NEW.class='place' and NEW.type='houses'
58      and NEW.osm_type='W' and ST_GeometryType(NEW.geometry) = 'ST_LineString'
59   THEN
60     -- Get the existing entry from the interpolation table.
61     SELECT * INTO existingline
62       FROM location_property_osmline WHERE osm_id = NEW.osm_id;
63
64     -- Update the interpolation table:
65     --   delete all old interpolation lines with same osm_id
66     --   and insert the new one(s) (they can be split up, if they have > 2 nodes)
67     IF existingline.osm_id IS NOT NULL THEN
68       DELETE FROM location_property_osmline where osm_id = NEW.osm_id;
69     END IF;
70
71     INSERT INTO location_property_osmline (osm_id, address, linegeo)
72       VALUES (NEW.osm_id, NEW.address, NEW.geometry);
73
74     -- Now invalidate all address nodes on the line.
75     -- They get their parent from the interpolation.
76     UPDATE placex p SET indexed_status = 2
77       FROM planet_osm_ways w
78       WHERE w.id = NEW.osm_id and p.osm_type = 'N' and p.osm_id = any(w.nodes);
79
80     -- If there is already an entry in place, just update that, if necessary.
81     IF existing.osm_type is not null THEN
82       IF coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
83          OR existing.geometry::text != NEW.geometry::text
84       THEN
85         UPDATE place
86           SET name = NEW.name,
87               address = NEW.address,
88               extratags = NEW.extratags,
89               admin_level = NEW.admin_level,
90               geometry = NEW.geometry
91           WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
92                 and class = NEW.class and type = NEW.type;
93        END IF;
94
95        RETURN NULL;
96     END IF;
97
98     RETURN NEW;
99   END IF;
100
101   -- ---- Postcode points.
102
103   IF NEW.class = 'place' AND NEW.type = 'postcode' THEN
104     -- Pure postcodes are never queried from placex so we don't add them.
105     -- location_postcodes is filled from the place table directly.
106
107     -- Remove any old placex entry.
108     DELETE FROM placex WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id;
109
110     IF existing.osm_type IS NOT NULL THEN
111       IF coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
112          OR existing.geometry::text != NEW.geometry::text
113       THEN
114         UPDATE place
115           SET name = NEW.name,
116               address = NEW.address,
117               extratags = NEW.extratags,
118               admin_level = NEW.admin_level,
119               geometry = NEW.geometry
120           WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
121                 and class = NEW.class and type = NEW.type;
122       END IF;
123
124       RETURN NULL;
125     END IF;
126
127     RETURN NEW;
128   END IF;
129
130   -- ---- All other place types.
131
132   -- Patch in additional country names
133   IF NEW.admin_level = 2 and NEW.type = 'administrative' and NEW.address ? 'country'
134   THEN
135     FOR country IN
136       SELECT name FROM country_name WHERE country_code = lower(NEW.address->'country')
137     LOOP
138       NEW.name = country.name || NEW.name;
139     END LOOP;
140   END IF;
141
142   -- When an area is changed from large to small: log and discard change
143   IF existing.geometry is not null AND ST_IsValid(existing.geometry)
144     AND ST_Area(existing.geometry) > 0.02
145     AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')
146     AND ST_Area(NEW.geometry) < ST_Area(existing.geometry) * 0.5
147   THEN
148     INSERT INTO import_polygon_error (osm_type, osm_id, class, type, name,
149                                       country_code, updated, errormessage,
150                                       prevgeometry, newgeometry)
151       VALUES (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name,
152               NEW.address->'country', now(),
153               'Area reduced from '||st_area(existing.geometry)||' to '||st_area(NEW.geometry),
154               existing.geometry, NEW.geometry);
155
156     RETURN null;
157   END IF;
158
159   -- Get the existing placex entry.
160   SELECT * INTO existingplacex
161     FROM placex
162     WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
163           and class = NEW.class and type = NEW.type;
164
165   {% if debug %}RAISE WARNING 'Existing PlaceX: %',existingplacex.place_id;{% endif %}
166
167   -- To paraphrase: if there isn't an existing item, OR if the admin level has changed
168   IF existingplacex.osm_type IS NULL
169      or (existingplacex.class = 'boundary'
170          and ((coalesce(existingplacex.admin_level, 15) != coalesce(NEW.admin_level, 15)
171                and existingplacex.type = 'administrative')
172               or existingplacex.type != NEW.type))
173   THEN
174     {% if config.get_bool('LIMIT_REINDEXING') %}
175     -- sanity check: ignore admin_level changes on places with too many active children
176     -- or we end up reindexing entire countries because somebody accidentally deleted admin_level
177     IF existingplacex.osm_type IS NOT NULL THEN
178       SELECT count(*) INTO i FROM
179         (SELECT 'a' FROM placex, place_addressline
180           WHERE address_place_id = existingplacex.place_id
181                 and placex.place_id = place_addressline.place_id
182                 and indexed_status = 0 and place_addressline.isaddress LIMIT 100001) sub;
183       IF i > 100000 THEN
184         RETURN null;
185       END IF;
186     END IF;
187     {% endif %}
188
189     IF existing.osm_type IS NOT NULL THEN
190       -- Pathological case caused by the triggerless copy into place during initial import
191       -- force delete even for large areas, it will be reinserted later
192       UPDATE place SET geometry = ST_SetSRID(ST_Point(0,0), 4326)
193         WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
194               and class = NEW.class and type = NEW.type;
195       DELETE FROM place
196         WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
197               and class = NEW.class and type = NEW.type;
198     END IF;
199
200     -- Process it as a new insertion
201     INSERT INTO placex (osm_type, osm_id, class, type, name,
202                         admin_level, address, extratags, geometry)
203       VALUES (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name,
204               NEW.admin_level, NEW.address, NEW.extratags, NEW.geometry);
205
206     {% if debug %}RAISE WARNING 'insert done % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,NEW.name;{% endif %}
207
208     RETURN NEW;
209   END IF;
210
211   -- Special case for polygon shape changes because they tend to be large
212   -- and we can be a bit clever about how we handle them
213   IF existing.geometry::text != NEW.geometry::text
214      AND ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon')
215      AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')
216   THEN
217     -- Performance limit
218     IF ST_Area(NEW.geometry) < 0.000000001 AND ST_Area(existingplacex.geometry) < 1
219     THEN
220       -- re-index points that have moved in / out of the polygon.
221       -- Could be done as a single query but postgres gets the index usage wrong.
222       update placex set indexed_status = 2 where indexed_status = 0
223           AND ST_Intersects(NEW.geometry, placex.geometry)
224           AND NOT ST_Intersects(existingplacex.geometry, placex.geometry)
225           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
226
227       update placex set indexed_status = 2 where indexed_status = 0
228           AND ST_Intersects(existingplacex.geometry, placex.geometry)
229           AND NOT ST_Intersects(NEW.geometry, placex.geometry)
230           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
231     END IF;
232   END IF;
233
234
235   -- Has something relevant changed?
236   IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
237      OR coalesce(existing.extratags::text, '') != coalesce(NEW.extratags::text, '')
238      OR coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
239      OR coalesce(existing.admin_level, 15) != coalesce(NEW.admin_level, 15)
240      OR existing.geometry::text != NEW.geometry::text
241   THEN
242     UPDATE place
243       SET name = NEW.name,
244           address = NEW.address,
245           extratags = NEW.extratags,
246           admin_level = NEW.admin_level,
247           geometry = NEW.geometry
248       WHERE osm_type = NEW.osm_type and osm_id = NEW.osm_id
249             and class = NEW.class and type = NEW.type;
250
251     -- Postcode areas are only kept, when there is an actual postcode assigned.
252     IF NEW.class = 'boundary' AND NEW.type = 'postal_code' THEN
253       IF NEW.address is NULL OR NOT NEW.address ? 'postcode' THEN
254         -- postcode was deleted, no longer retain in placex
255         DELETE FROM placex where place_id = existingplacex.place_id;
256         RETURN NULL;
257       END IF;
258
259       NEW.name := hstore('ref', NEW.address->'postcode');
260     END IF;
261
262     -- Boundaries must be areas.
263     IF NEW.class in ('boundary')
264        AND ST_GeometryType(NEW.geometry) not in ('ST_Polygon','ST_MultiPolygon')
265     THEN
266       DELETE FROM placex where place_id = existingplacex.place_id;
267       RETURN NULL;
268     END IF;
269
270     -- Update the placex entry in-place.
271     UPDATE placex
272       SET name = NEW.name,
273           address = NEW.address,
274           parent_place_id = null,
275           extratags = NEW.extratags,
276           admin_level = NEW.admin_level,
277           indexed_status = 2,
278           geometry = NEW.geometry
279       WHERE place_id = existingplacex.place_id;
280
281     -- If an address node which is part of a interpolation line changes
282     -- mark this line for reparenting.
283     -- (Already here, because interpolation lines are reindexed before nodes,
284     --  so in the second call it would be too late.)
285     IF NEW.osm_type='N'
286        and coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
287     THEN
288         result:= osmline_reinsert(NEW.osm_id, NEW.geometry);
289     END IF;
290
291     -- Invalidate linked places: they potentially get a new name and addresses.
292     IF existingplacex.linked_place_id is not NULL THEN
293       UPDATE placex x
294         SET name = p.name,
295             extratags = p.extratags,
296             indexed_status = 2
297         FROM place p
298         WHERE x.place_id = existingplacex.linked_place_id
299               and x.indexed_status = 0
300               and x.osm_type = p.osm_type
301               and x.osm_id = p.osm_id
302               and x.class = p.class;
303     END IF;
304
305     -- Invalidate dependent objects effected by name changes
306     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
307     THEN
308       IF existingplacex.rank_address between 26 and 27 THEN
309         -- When streets change their name, this may have an effect on POI objects
310         -- with addr:street tags.
311         UPDATE placex SET indexed_status = 2
312           WHERE indexed_status = 0 and address ? 'street'
313                 and parent_place_id = existingplacex.place_id;
314         UPDATE placex SET indexed_status = 2
315           WHERE indexed_status = 0 and rank_search = 30 and address ? 'street'
316                 and ST_DWithin(NEW.geometry, geometry, 0.002);
317       ELSEIF existingplacex.rank_address between 16 and 25 THEN
318         -- When places change their name, this may have an effect on POI objects
319         -- with addr:place tags.
320         UPDATE placex SET indexed_status = 2
321           WHERE indexed_status = 0 and address ? 'place' and rank_search = 30
322                 and parent_place_id = existingplacex.place_id;
323         -- No update of surrounding objects, potentially too expensive.
324       END IF;
325     END IF;
326   END IF;
327
328   -- Abort the insertion (we modified the existing place instead)
329   RETURN NULL;
330 END;
331 $$ LANGUAGE plpgsql;
332
333
334 CREATE OR REPLACE FUNCTION place_delete()
335   RETURNS TRIGGER
336   AS $$
337 DECLARE
338   has_rank BOOLEAN;
339 BEGIN
340
341   {% if debug %}RAISE WARNING 'delete: % % % %',OLD.osm_type,OLD.osm_id,OLD.class,OLD.type;{% endif %}
342
343   -- deleting large polygons can have a massive effect on the system - require manual intervention to let them through
344   IF st_area(OLD.geometry) > 2 and st_isvalid(OLD.geometry) THEN
345     SELECT bool_or(not (rank_address = 0 or rank_address > 25)) as ranked FROM placex WHERE osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type INTO has_rank;
346     IF has_rank THEN
347       insert into import_polygon_delete (osm_type, osm_id, class, type) values (OLD.osm_type,OLD.osm_id,OLD.class,OLD.type);
348       RETURN NULL;
349     END IF;
350   END IF;
351
352   -- mark for delete
353   UPDATE placex set indexed_status = 100 where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
354
355   -- interpolations are special
356   IF OLD.osm_type='W' and OLD.class = 'place' and OLD.type = 'houses' THEN
357     UPDATE location_property_osmline set indexed_status = 100 where osm_id = OLD.osm_id; -- osm_id = wayid (=old.osm_id)
358   END IF;
359
360   RETURN OLD;
361 END;
362 $$
363 LANGUAGE plpgsql;
364