]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions/placex_triggers.sql
detect and remove admin boundary duplicates
[nominatim.git] / sql / functions / placex_triggers.sql
1 -- Trigger functions for the placex table.
2
3 -- Find the parent road of a POI.
4 --
5 -- \returns Place ID of parent object or NULL if none
6 --
7 -- Copy data from linked items (POIs on ways, addr:street links, relations).
8 --
9 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
10                                                poi_osm_id BIGINT,
11                                                poi_partition SMALLINT,
12                                                bbox GEOMETRY,
13                                                addr_street TEXT,
14                                                addr_place TEXT,
15                                                fallback BOOL = true)
16   RETURNS BIGINT
17   AS $$
18 DECLARE
19   parent_place_id BIGINT DEFAULT NULL;
20   location RECORD;
21   parent RECORD;
22 BEGIN
23     --DEBUG: RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;
24
25     -- Is this object part of an associatedStreet relation?
26     FOR location IN
27       SELECT members FROM planet_osm_rels
28       WHERE parts @> ARRAY[poi_osm_id]
29         and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
30         and tags @> ARRAY['associatedStreet']
31     LOOP
32       FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
33         IF location.members[i+1] = 'street' THEN
34           FOR parent IN
35             SELECT place_id from placex
36              WHERE osm_type = 'W' and osm_id = substring(location.members[i],2)::bigint
37                and name is not null
38                and rank_search between 26 and 27
39           LOOP
40             RETURN parent.place_id;
41           END LOOP;
42         END IF;
43       END LOOP;
44     END LOOP;
45
46     parent_place_id := find_parent_for_address(addr_street, addr_place,
47                                                poi_partition, bbox);
48     IF parent_place_id is not null THEN
49       RETURN parent_place_id;
50     END IF;
51
52     IF poi_osm_type = 'N' THEN
53       -- Is this node part of an interpolation?
54       FOR parent IN
55         SELECT q.parent_place_id
56           FROM location_property_osmline q, planet_osm_ways x
57          WHERE q.linegeo && bbox and x.id = q.osm_id
58                and poi_osm_id = any(x.nodes)
59          LIMIT 1
60       LOOP
61         --DEBUG: RAISE WARNING 'Get parent from interpolation: %', parent.parent_place_id;
62         RETURN parent.parent_place_id;
63       END LOOP;
64
65       -- Is this node part of any other way?
66       FOR location IN
67         SELECT p.place_id, p.osm_id, p.rank_search, p.address,
68                coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
69           FROM placex p, planet_osm_ways w
70          WHERE p.osm_type = 'W' and p.rank_search >= 26
71                and p.geometry && bbox
72                and w.id = p.osm_id and poi_osm_id = any(w.nodes)
73       LOOP
74         --DEBUG: RAISE WARNING 'Node is part of way % ', location.osm_id;
75
76         -- Way IS a road then we are on it - that must be our road
77         IF location.rank_search < 28 THEN
78           --DEBUG: RAISE WARNING 'node in way that is a street %',location;
79           return location.place_id;
80         END IF;
81
82         SELECT find_parent_for_poi('W', location.osm_id, poi_partition,
83                                    location.centroid,
84                                    location.address->'street',
85                                    location.address->'place',
86                                    false)
87           INTO parent_place_id;
88         IF parent_place_id is not null THEN
89           RETURN parent_place_id;
90         END IF;
91       END LOOP;
92     END IF;
93
94     IF fallback THEN
95       IF addr_street is null and addr_place is not null THEN
96         -- The address is attached to a place we don't know.
97         -- Instead simply use the containing area with the largest rank.
98         FOR location IN
99           SELECT place_id FROM placex
100             WHERE bbox @ geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
101                   AND rank_address between 5 and 25
102             ORDER BY rank_address desc
103         LOOP
104             RETURN location.place_id;
105         END LOOP;
106       ELSEIF ST_Area(bbox) < 0.005 THEN
107         -- for smaller features get the nearest road
108         SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
109         --DEBUG: RAISE WARNING 'Checked for nearest way (%)', parent_place_id;
110       ELSE
111         -- for larger features simply find the area with the largest rank that
112         -- contains the bbox, only use addressable features
113         FOR location IN
114           SELECT place_id FROM placex
115             WHERE bbox @ geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
116                   AND rank_address between 5 and 25
117             ORDER BY rank_address desc
118         LOOP
119             RETURN location.place_id;
120         END LOOP;
121       END IF;
122     END IF;
123
124     RETURN parent_place_id;
125 END;
126 $$
127 LANGUAGE plpgsql STABLE;
128
129 -- Try to find a linked place for the given object.
130 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
131   RETURNS placex
132   AS $$
133 DECLARE
134   relation_members TEXT[];
135   rel_member RECORD;
136   linked_placex placex%ROWTYPE;
137   bnd_name TEXT;
138 BEGIN
139   IF bnd.rank_search >= 26 or bnd.rank_address = 0
140      or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
141   THEN
142     RETURN NULL;
143   END IF;
144
145   IF bnd.osm_type = 'R' THEN
146     -- see if we have any special relation members
147     SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
148     --DEBUG: RAISE WARNING 'Got relation members';
149
150     -- Search for relation members with role 'lable'.
151     IF relation_members IS NOT NULL THEN
152       FOR rel_member IN
153         SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
154       LOOP
155         --DEBUG: RAISE WARNING 'Found label member %', rel_member.member;
156
157         FOR linked_placex IN
158           SELECT * from placex
159           WHERE osm_type = 'N' and osm_id = rel_member.member
160             and class = 'place'
161         LOOP
162           --DEBUG: RAISE WARNING 'Linked label member';
163           RETURN linked_placex;
164         END LOOP;
165
166       END LOOP;
167     END IF;
168   END IF;
169
170   IF bnd.name ? 'name' THEN
171     bnd_name := make_standard_name(bnd.name->'name');
172     IF bnd_name = '' THEN
173       bnd_name := NULL;
174     END IF;
175   END IF;
176
177   -- If extratags has a place tag, look for linked nodes by their place type.
178   -- Area and node still have to have the same name.
179   IF bnd.extratags ? 'place' and bnd_name is not null THEN
180     FOR linked_placex IN
181       SELECT * FROM placex
182       WHERE make_standard_name(name->'name') = bnd_name
183         AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
184         AND placex.osm_type = 'N'
185         AND placex.rank_search < 26 -- needed to select the right index
186         AND _st_covers(bnd.geometry, placex.geometry)
187     LOOP
188       --DEBUG: RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;
189       RETURN linked_placex;
190     END LOOP;
191   END IF;
192
193   IF bnd.extratags ? 'wikidata' THEN
194     FOR linked_placex IN
195       SELECT * FROM placex
196       WHERE placex.class = 'place' AND placex.osm_type = 'N'
197         AND placex.extratags ? 'wikidata' -- needed to select right index
198         AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
199         AND placex.rank_search < 26
200         AND _st_covers(bnd.geometry, placex.geometry)
201       ORDER BY make_standard_name(name->'name') = bnd_name desc
202     LOOP
203       --DEBUG: RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;
204       RETURN linked_placex;
205     END LOOP;
206   END IF;
207
208   -- Name searches can be done for ways as well as relations
209   IF bnd_name is not null THEN
210     --DEBUG: RAISE WARNING 'Looking for nodes with matching names';
211     FOR linked_placex IN
212       SELECT placex.* from placex
213       WHERE make_standard_name(name->'name') = bnd_name
214         AND ((bnd.rank_address > 0
215               and bnd.rank_address = (compute_place_rank(placex.country_code,
216                                                          'N', placex.class,
217                                                          placex.type, 15::SMALLINT,
218                                                          false, placex.postcode)).address_rank)
219              OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
220         AND placex.osm_type = 'N'
221         AND placex.rank_search < 26 -- needed to select the right index
222         AND _st_covers(bnd.geometry, placex.geometry)
223     LOOP
224       --DEBUG: RAISE WARNING 'Found matching place node %', linked_placex.osm_id;
225       RETURN linked_placex;
226     END LOOP;
227   END IF;
228
229   RETURN NULL;
230 END;
231 $$
232 LANGUAGE plpgsql STABLE;
233
234
235 -- Insert address of a place into the place_addressline table.
236 --
237 -- \param obj_place_id  Place_id of the place to compute the address for.
238 -- \param partition     Partition number where the place is in.
239 -- \param maxrank       Rank of the place. All address features must have
240 --                      a search rank lower than the given rank.
241 -- \param address       Address terms for the place.
242 -- \param geometry      Geometry to which the address objects should be close.
243 --
244 -- \retval parent_place_id  Place_id of the address object that is the direct
245 --                          ancestor.
246 -- \retval postcode         Postcode computed from the address. This is the
247 --                          addr:postcode of one of the address objects. If
248 --                          more than one of has a postcode, the highest ranking
249 --                          one is used. May be NULL.
250 -- \retval nameaddress_vector  Search terms for the address. This is the sum
251 --                             of name terms of all address objects.
252 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
253                                                partition SMALLINT,
254                                                maxrank SMALLINT,
255                                                address HSTORE,
256                                                geometry GEOMETRY,
257                                                OUT parent_place_id BIGINT,
258                                                OUT postcode TEXT,
259                                                OUT nameaddress_vector INT[])
260   AS $$
261 DECLARE
262   address_havelevel BOOLEAN[];
263
264   location_isaddress BOOLEAN;
265   current_boundary GEOMETRY := NULL;
266   current_node_area GEOMETRY := NULL;
267
268   location RECORD;
269   addr_item RECORD;
270
271   isin_tokens INT[];
272 BEGIN
273   parent_place_id := 0;
274   nameaddress_vector := '{}'::int[];
275   isin_tokens := '{}'::int[];
276
277   ---- convert address store to array of tokenids
278   IF address IS NOT NULL THEN
279     FOR addr_item IN SELECT * FROM each(address)
280     LOOP
281       IF addr_item.key IN ('city', 'tiger:county', 'state', 'suburb', 'province',
282                            'district', 'region', 'county', 'municipality',
283                            'hamlet', 'village', 'subdistrict', 'town',
284                            'neighbourhood', 'quarter', 'parish')
285       THEN
286         isin_tokens := array_merge(isin_tokens,
287                                    word_ids_from_name(addr_item.value));
288         IF NOT %REVERSE-ONLY% THEN
289           nameaddress_vector := array_merge(nameaddress_vector,
290                                             addr_ids_from_name(addr_item.value));
291         END IF;
292       END IF;
293     END LOOP;
294   END IF;
295   IF NOT %REVERSE-ONLY% THEN
296     nameaddress_vector := array_merge(nameaddress_vector, isin_tokens);
297   END IF;
298
299   ---- now compute the address terms
300   FOR i IN 1..maxrank LOOP
301     address_havelevel[i] := false;
302   END LOOP;
303
304   FOR location IN
305     SELECT * FROM getNearFeatures(partition, geometry, maxrank)
306     ORDER BY rank_address, isin_tokens && keywords desc, isguess asc,
307              distance *
308                CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
309                     WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
310                     WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
311                     ELSE 1 END ASC
312   LOOP
313     -- Ignore all place nodes that do not fit in a lower level boundary.
314     CONTINUE WHEN location.isguess
315                   and current_boundary is not NULL
316                   and not ST_Contains(current_boundary, location.centroid);
317
318     -- If this is the first item in the rank, then assume it is the address.
319     location_isaddress := not address_havelevel[location.rank_address];
320
321     -- Further sanity checks to ensure that the address forms a sane hierarchy.
322     IF location_isaddress THEN
323       IF location.isguess and current_node_area is not NULL THEN
324         location_isaddress := ST_Contains(current_node_area, location.centroid);
325       END IF;
326       IF not location.isguess and current_boundary is not NULL
327          and location.rank_address != 11 AND location.rank_address != 5 THEN
328         location_isaddress := ST_Contains(current_boundary, location.centroid);
329       END IF;
330     END IF;
331
332     IF location_isaddress THEN
333       address_havelevel[location.rank_address] := true;
334       parent_place_id := location.place_id;
335
336       -- Set postcode if we have one.
337       -- (Returned will be the highest ranking one.)
338       IF location.postcode is not NULL THEN
339         postcode = location.postcode;
340       END IF;
341
342       -- Recompute the areas we need for hierarchy sanity checks.
343       IF location.rank_address != 11 AND location.rank_address != 5 THEN
344         IF location.isguess THEN
345           current_node_area := place_node_fuzzy_area(location.centroid,
346                                                      location.rank_search);
347         ELSE
348           current_node_area := NULL;
349           SELECT p.geometry FROM placex p
350               WHERE p.place_id = location.place_id INTO current_boundary;
351         END IF;
352       END IF;
353     END IF;
354
355     -- Add it to the list of search terms
356     IF NOT %REVERSE-ONLY% THEN
357       nameaddress_vector := array_merge(nameaddress_vector,
358                                         location.keywords::integer[]);
359     END IF;
360
361     INSERT INTO place_addressline (place_id, address_place_id, fromarea,
362                                      isaddress, distance, cached_rank_address)
363         VALUES (obj_place_id, location.place_id, not location.isguess,
364                 location_isaddress, location.distance, location.rank_address);
365   END LOOP;
366 END;
367 $$
368 LANGUAGE plpgsql;
369
370
371 CREATE OR REPLACE FUNCTION placex_insert()
372   RETURNS TRIGGER
373   AS $$
374 DECLARE
375   postcode TEXT;
376   result BOOLEAN;
377   is_area BOOLEAN;
378   country_code VARCHAR(2);
379   diameter FLOAT;
380   classtable TEXT;
381 BEGIN
382   --DEBUG: RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
383
384   NEW.place_id := nextval('seq_place');
385   NEW.indexed_status := 1; --STATUS_NEW
386
387   NEW.country_code := lower(get_country_code(NEW.geometry));
388
389   NEW.partition := get_partition(NEW.country_code);
390   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
391
392   IF NEW.osm_type = 'X' THEN
393     -- E'X'ternal records should already be in the right format so do nothing
394   ELSE
395     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
396
397     IF NEW.class in ('place','boundary')
398        AND NEW.type in ('postcode','postal_code')
399     THEN
400       IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
401           -- most likely just a part of a multipolygon postcode boundary, throw it away
402           RETURN NULL;
403       END IF;
404
405       NEW.name := hstore('ref', NEW.address->'postcode');
406
407     ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
408            AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
409     THEN
410         RETURN NULL;
411     ELSEIF NEW.class = 'boundary' AND NOT is_area
412     THEN
413         RETURN NULL;
414     ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
415            AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
416     THEN
417         RETURN NULL;
418     END IF;
419
420     SELECT * INTO NEW.rank_search, NEW.rank_address
421       FROM compute_place_rank(NEW.country_code,
422                               CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
423                               NEW.class, NEW.type, NEW.admin_level,
424                               (NEW.extratags->'capital') = 'yes',
425                               NEW.address->'postcode');
426
427     -- a country code make no sense below rank 4 (country)
428     IF NEW.rank_search < 4 THEN
429       NEW.country_code := NULL;
430     END IF;
431
432   END IF;
433
434   --DEBUG: RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
435
436   RETURN NEW; -- %DIFFUPDATES% The following is not needed until doing diff updates, and slows the main index process down
437
438   IF NEW.osm_type = 'N' and NEW.rank_search > 28 THEN
439       -- might be part of an interpolation
440       result := osmline_reinsert(NEW.osm_id, NEW.geometry);
441   ELSEIF NEW.rank_address > 0 THEN
442     IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
443       -- Performance: We just can't handle re-indexing for country level changes
444       IF st_area(NEW.geometry) < 1 THEN
445         -- mark items within the geometry for re-indexing
446   --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
447
448         UPDATE placex SET indexed_status = 2
449          WHERE ST_Intersects(NEW.geometry, placex.geometry)
450                and indexed_status = 0
451                and ((rank_address = 0 and rank_search > NEW.rank_address)
452                     or rank_address > NEW.rank_address
453                     or (class = 'place' and osm_type = 'N')
454                    )
455                and (rank_search < 28
456                     or name is not null
457                     or (NEW.rank_address >= 16 and address ? 'place'));
458       END IF;
459     ELSE
460       -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
461       diameter := update_place_diameter(NEW.rank_search);
462       IF diameter > 0 THEN
463   --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
464         IF NEW.rank_search >= 26 THEN
465           -- roads may cause reparenting for >27 rank places
466           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
467           -- reparenting also for OSM Interpolation Lines (and for Tiger?)
468           update location_property_osmline set indexed_status = 2 where indexed_status = 0 and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
469         ELSEIF NEW.rank_search >= 16 THEN
470           -- up to rank 16, street-less addresses may need reparenting
471           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null or address ? 'place');
472         ELSE
473           -- for all other places the search terms may change as well
474           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null);
475         END IF;
476       END IF;
477     END IF;
478   END IF;
479
480
481    -- add to tables for special search
482    -- Note: won't work on initial import because the classtype tables
483    -- do not yet exist. It won't hurt either.
484   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
485   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
486   IF result THEN
487     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
488     USING NEW.place_id, ST_Centroid(NEW.geometry);
489   END IF;
490
491   RETURN NEW;
492
493 END;
494 $$
495 LANGUAGE plpgsql;
496
497 CREATE OR REPLACE FUNCTION placex_update()
498   RETURNS TRIGGER
499   AS $$
500 DECLARE
501   i INTEGER;
502   location RECORD;
503   relation_members TEXT[];
504
505   centroid GEOMETRY;
506   parent_address_level SMALLINT;
507   place_address_level SMALLINT;
508
509   addr_street TEXT;
510   addr_place TEXT;
511
512   name_vector INTEGER[];
513   nameaddress_vector INTEGER[];
514   addr_nameaddress_vector INTEGER[];
515
516   inherited_address HSTORE;
517
518   linked_node_id BIGINT;
519   linked_importance FLOAT;
520   linked_wikipedia TEXT;
521
522   result BOOLEAN;
523 BEGIN
524   -- deferred delete
525   IF OLD.indexed_status = 100 THEN
526     --DEBUG: RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;
527     delete from placex where place_id = OLD.place_id;
528     RETURN NULL;
529   END IF;
530
531   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
532     RETURN NEW;
533   END IF;
534
535   --DEBUG: RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;
536
537   NEW.indexed_date = now();
538
539   IF NOT %REVERSE-ONLY% THEN
540     DELETE from search_name WHERE place_id = NEW.place_id;
541   END IF;
542   result := deleteSearchName(NEW.partition, NEW.place_id);
543   DELETE FROM place_addressline WHERE place_id = NEW.place_id;
544   result := deleteRoad(NEW.partition, NEW.place_id);
545   result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
546   UPDATE placex set linked_place_id = null, indexed_status = 2
547          where linked_place_id = NEW.place_id;
548   -- update not necessary for osmline, cause linked_place_id does not exist
549
550   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
551   NEW.address := NEW.address - '_unlisted_place'::TEXT;
552
553   IF NEW.linked_place_id is not null THEN
554     --DEBUG: RAISE WARNING 'place already linked to %', NEW.linked_place_id;
555     RETURN NEW;
556   END IF;
557
558   -- Postcodes are just here to compute the centroids. They are not searchable
559   -- unless they are a boundary=postal_code.
560   -- There was an error in the style so that boundary=postal_code used to be
561   -- imported as place=postcode. That's why relations are allowed to pass here.
562   -- This can go away in a couple of versions.
563   IF NEW.class = 'place'  and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
564     RETURN NEW;
565   END IF;
566
567   -- Speed up searches - just use the centroid of the feature
568   -- cheaper but less acurate
569   NEW.centroid := ST_PointOnSurface(NEW.geometry);
570   --DEBUG: RAISE WARNING 'Computing preliminary centroid at %',ST_AsText(NEW.centroid);
571
572   -- recompute the ranks, they might change when linking changes
573   SELECT * INTO NEW.rank_search, NEW.rank_address
574     FROM compute_place_rank(NEW.country_code,
575                             CASE WHEN ST_GeometryType(NEW.geometry)
576                                         IN ('ST_Polygon','ST_MultiPolygon')
577                             THEN 'A' ELSE NEW.osm_type END,
578                             NEW.class, NEW.type, NEW.admin_level,
579                             (NEW.extratags->'capital') = 'yes',
580                             NEW.address->'postcode');
581   -- We must always increase the address level relative to the admin boundary.
582   IF NEW.class = 'boundary' and NEW.type = 'administrative'
583      and NEW.osm_type = 'R' and NEW.rank_address > 0
584   THEN
585     -- First, check that admin boundaries do not overtake each other rank-wise.
586     parent_address_level := 3;
587     FOR location IN
588       SELECT rank_address, extratags FROM placex
589       WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
590             and admin_level < NEW.admin_level and admin_level > 3
591             and rank_address > 0
592             and ST_Covers(geometry, NEW.geometry)
593       ORDER BY admin_level desc LIMIT 1
594     LOOP
595       IF location.extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
596          and location.extratags->'wikidata' = NEW.extratags->'wikidata'
597       THEN
598         -- Looks like the same boundary is replicated on multiple admin_levels.
599         -- Usual tagging in Poland. Remove our boundary from addresses.
600         NEW.rank_address := 0;
601       ELSE
602         parent_address_level := location.rank_address;
603         IF location.rank_address >= NEW.rank_address THEN
604           IF location.rank_address >= 24 THEN
605             NEW.rank_address := 25;
606           ELSE
607             NEW.rank_address := location.rank_address + 2;
608           END IF;
609         END IF;
610       END IF;
611     END LOOP;
612
613     IF NEW.rank_address > 9 THEN
614         -- Second check that the boundary is not completely contained in a
615         -- place area with a higher address rank
616         FOR location IN
617           SELECT rank_address FROM placex
618           WHERE class = 'place' and rank_address < 24
619                 and rank_address > NEW.rank_address
620                 and geometry && NEW.geometry
621                 and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
622                 and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
623           ORDER BY rank_address desc LIMIT 1
624         LOOP
625           NEW.rank_address := location.rank_address + 2;
626         END LOOP;
627     END IF;
628   ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
629      and NEW.rank_address between 16 and 23
630   THEN
631     -- If a place node is contained in a admin boundary with the same address level
632     -- and has not been linked, then make the node a subpart by increasing the
633     -- address rank (city level and above).
634     FOR location IN
635         SELECT rank_address FROM placex
636         WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
637               and rank_address = NEW.rank_address
638               and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
639         LIMIT 1
640     LOOP
641       NEW.rank_address = NEW.rank_address + 2;
642     END LOOP;
643   ELSE
644     parent_address_level := 3;
645   END IF;
646
647   --DEBUG: RAISE WARNING 'Copy over address tags';
648   -- housenumber is a computed field, so start with an empty value
649   NEW.housenumber := NULL;
650   IF NEW.address is not NULL THEN
651       IF NEW.address ? 'conscriptionnumber' THEN
652         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'conscriptionnumber'));
653         IF NEW.address ? 'streetnumber' THEN
654             i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
655             NEW.housenumber := (NEW.address->'conscriptionnumber') || '/' || (NEW.address->'streetnumber');
656         ELSE
657             NEW.housenumber := NEW.address->'conscriptionnumber';
658         END IF;
659       ELSEIF NEW.address ? 'streetnumber' THEN
660         NEW.housenumber := NEW.address->'streetnumber';
661         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
662       ELSEIF NEW.address ? 'housenumber' THEN
663         NEW.housenumber := NEW.address->'housenumber';
664         i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
665       END IF;
666
667       addr_street := NEW.address->'street';
668       addr_place := NEW.address->'place';
669
670       IF NEW.address ? 'postcode' and NEW.address->'postcode' not similar to '%(:|,|;)%' THEN
671         i := getorcreate_postcode_id(NEW.address->'postcode');
672       END IF;
673   END IF;
674
675   NEW.postcode := null;
676
677   -- recalculate country and partition
678   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
679     -- for countries, believe the mapped country code,
680     -- so that we remain in the right partition if the boundaries
681     -- suddenly expand.
682     NEW.country_code := lower(NEW.address->'country');
683     NEW.partition := get_partition(lower(NEW.country_code));
684     IF NEW.partition = 0 THEN
685       NEW.country_code := lower(get_country_code(NEW.centroid));
686       NEW.partition := get_partition(NEW.country_code);
687     END IF;
688   ELSE
689     IF NEW.rank_search >= 4 THEN
690       NEW.country_code := lower(get_country_code(NEW.centroid));
691     ELSE
692       NEW.country_code := NULL;
693     END IF;
694     NEW.partition := get_partition(NEW.country_code);
695   END IF;
696   --DEBUG: RAISE WARNING 'Country updated: "%"', NEW.country_code;
697
698   -- waterway ways are linked when they are part of a relation and have the same class/type
699   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
700       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
701       LOOP
702           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
703               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
704                 --DEBUG: RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];
705                 FOR linked_node_id IN SELECT place_id FROM placex
706                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
707                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
708                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
709                 LOOP
710                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
711                   IF NOT %REVERSE-ONLY% THEN
712                     DELETE FROM search_name WHERE place_id = linked_node_id;
713                   END IF;
714                 END LOOP;
715               END IF;
716           END LOOP;
717       END LOOP;
718       --DEBUG: RAISE WARNING 'Waterway processed';
719   END IF;
720
721   NEW.importance := null;
722   SELECT wikipedia, importance
723     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
724     INTO NEW.wikipedia,NEW.importance;
725
726 --DEBUG: RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;
727
728   -- ---------------------------------------------------------------------------
729   -- For low level elements we inherit from our parent road
730   IF NEW.rank_search > 27 THEN
731
732     --DEBUG: RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;
733     NEW.parent_place_id := null;
734
735     -- if we have a POI and there is no address information,
736     -- see if we can get it from a surrounding building
737     inherited_address := ''::HSTORE;
738     IF NEW.osm_type = 'N' AND addr_street IS NULL AND addr_place IS NULL
739        AND NEW.housenumber IS NULL THEN
740       FOR location IN
741         -- The additional && condition works around the misguided query
742         -- planner of postgis 3.0.
743         SELECT address from placex where ST_Covers(geometry, NEW.centroid)
744             and geometry && NEW.centroid
745             and (address ? 'housenumber' or address ? 'street' or address ? 'place')
746             and rank_search > 28 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
747             limit 1
748       LOOP
749         NEW.housenumber := location.address->'housenumber';
750         addr_street := location.address->'street';
751         addr_place := location.address->'place';
752         inherited_address := location.address;
753       END LOOP;
754     END IF;
755
756     -- We have to find our parent road.
757     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
758                                                NEW.partition,
759                                                ST_Envelope(NEW.geometry),
760                                                addr_street, addr_place);
761
762     -- If we found the road take a shortcut here.
763     -- Otherwise fall back to the full address getting method below.
764     IF NEW.parent_place_id is not null THEN
765
766       -- Get the details of the parent road
767       SELECT p.country_code, p.postcode, p.name FROM placex p
768        WHERE p.place_id = NEW.parent_place_id INTO location;
769
770       IF addr_street is null and addr_place is not null THEN
771         -- Check if the addr:place tag is part of the parent name
772         SELECT count(*) INTO i
773           FROM svals(location.name) AS pname WHERE pname = addr_place;
774         IF i = 0 THEN
775           NEW.address = NEW.address || hstore('_unlisted_place', addr_place);
776         END IF;
777       END IF;
778
779       NEW.country_code := location.country_code;
780       --DEBUG: RAISE WARNING 'Got parent details from search name';
781
782       -- determine postcode
783       IF NEW.address is not null AND NEW.address ? 'postcode' THEN
784           NEW.postcode = upper(trim(NEW.address->'postcode'));
785       ELSE
786          NEW.postcode := location.postcode;
787       END IF;
788       IF NEW.postcode is null THEN
789         NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
790       END IF;
791
792       IF NEW.name is not NULL THEN
793           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
794           name_vector := make_keywords(NEW.name);
795
796           IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
797             result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
798                                    name_vector, NEW.rank_search, NEW.rank_address,
799                                    upper(trim(NEW.address->'postcode')), NEW.geometry,
800                                    NEW.centroid);
801             --DEBUG: RAISE WARNING 'Place added to location table';
802           END IF;
803
804       END IF;
805
806       IF NOT %REVERSE-ONLY% THEN
807         SELECT * INTO name_vector, nameaddress_vector
808           FROM create_poi_search_terms(NEW.parent_place_id,
809                                        inherited_address || NEW.address,
810                                        NEW.housenumber, name_vector);
811
812         IF array_length(name_vector, 1) is not NULL THEN
813           INSERT INTO search_name (place_id, search_rank, address_rank,
814                                    importance, country_code, name_vector,
815                                    nameaddress_vector, centroid)
816                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
817                          NEW.importance, NEW.country_code, name_vector,
818                          nameaddress_vector, NEW.centroid);
819           --DEBUG: RAISE WARNING 'Place added to search table';
820         END IF;
821       END IF;
822
823       RETURN NEW;
824     END IF;
825
826   END IF;
827
828   -- ---------------------------------------------------------------------------
829   -- Full indexing
830   --DEBUG: RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;
831   SELECT * INTO location FROM find_linked_place(NEW);
832   IF location.place_id is not null THEN
833     --DEBUG: RAISE WARNING 'Linked %', location;
834
835     -- Use the linked point as the centre point of the geometry,
836     -- but only if it is within the area of the boundary.
837     centroid := coalesce(location.centroid, ST_Centroid(location.geometry));
838     IF centroid is not NULL AND ST_Within(centroid, NEW.geometry) THEN
839         NEW.centroid := centroid;
840     END IF;
841
842     --DEBUG: RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.rank_address;
843     IF location.rank_address > parent_address_level
844        and location.rank_address < 26
845     THEN
846       NEW.rank_address := location.rank_address;
847     END IF;
848
849     -- merge in the label name
850     IF NOT location.name IS NULL THEN
851       NEW.name := location.name || NEW.name;
852     END IF;
853
854     -- merge in extra tags
855     NEW.extratags := hstore('linked_' || location.class, location.type)
856                      || coalesce(location.extratags, ''::hstore)
857                      || coalesce(NEW.extratags, ''::hstore);
858
859     -- mark the linked place (excludes from search results)
860     UPDATE placex set linked_place_id = NEW.place_id
861       WHERE place_id = location.place_id;
862     -- ensure that those places are not found anymore
863     IF NOT %REVERSE-ONLY% THEN
864       DELETE FROM search_name WHERE place_id = location.place_id;
865     END IF;
866     PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
867
868     SELECT wikipedia, importance
869       FROM compute_importance(location.extratags, NEW.country_code,
870                               'N', location.osm_id)
871       INTO linked_wikipedia,linked_importance;
872
873     -- Use the maximum importance if one could be computed from the linked object.
874     IF linked_importance is not null AND
875        (NEW.importance is null or NEW.importance < linked_importance)
876     THEN
877       NEW.importance = linked_importance;
878     END IF;
879   ELSE
880     -- No linked place? As a last resort check if the boundary is tagged with
881     -- a place type and adapt the rank address.
882     IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
883       SELECT address_rank INTO place_address_level
884         FROM compute_place_rank(NEW.country_code, 'A', 'place',
885                                 NEW.extratags->'place', 0::SMALLINT, False, null);
886       IF place_address_level > parent_address_level and
887          place_address_level < 26 THEN
888         NEW.rank_address := place_address_level;
889       END IF;
890     END IF;
891   END IF;
892
893   -- Initialise the name vector using our name
894   NEW.name := add_default_place_name(NEW.country_code, NEW.name);
895   name_vector := make_keywords(NEW.name);
896
897   -- make sure all names are in the word table
898   IF NEW.admin_level = 2
899      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
900      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
901   THEN
902     PERFORM create_country(NEW.name, lower(NEW.country_code));
903     --DEBUG: RAISE WARNING 'Country names updated';
904   END IF;
905
906   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition,
907                                     CASE WHEN NEW.rank_address = 0 THEN NEW.rank_search
908                                          WHEN NEW.rank_address > 25 THEN 25::smallint
909                                          ELSE NEW.rank_address END,
910                                     NEW.address,
911                                     CASE WHEN NEW.rank_search >= 26
912                                              AND NEW.rank_search < 30
913                                       THEN NEW.geometry ELSE NEW.centroid END)
914     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
915
916   --DEBUG: RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;
917
918   IF NEW.address is not null AND NEW.address ? 'postcode' 
919      AND NEW.address->'postcode' not similar to '%(,|;)%' THEN
920     NEW.postcode := upper(trim(NEW.address->'postcode'));
921   END IF;
922
923   IF NEW.postcode is null AND NEW.rank_search > 8 THEN
924     NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
925   END IF;
926
927   -- if we have a name add this to the name search table
928   IF NEW.name IS NOT NULL THEN
929
930     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
931       result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, upper(trim(NEW.address->'postcode')), NEW.geometry, NEW.centroid);
932       --DEBUG: RAISE WARNING 'added to location (full)';
933     END IF;
934
935     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
936       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
937       --DEBUG: RAISE WARNING 'insert into road location table (full)';
938     END IF;
939
940     result := insertSearchName(NEW.partition, NEW.place_id, name_vector,
941                                NEW.rank_search, NEW.rank_address, NEW.geometry);
942     --DEBUG: RAISE WARNING 'added to search name (full)';
943
944     IF NOT %REVERSE-ONLY% THEN
945         INSERT INTO search_name (place_id, search_rank, address_rank,
946                                  importance, country_code, name_vector,
947                                  nameaddress_vector, centroid)
948                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
949                        NEW.importance, NEW.country_code, name_vector,
950                        nameaddress_vector, NEW.centroid);
951     END IF;
952
953   END IF;
954
955   --DEBUG: RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;
956
957   RETURN NEW;
958 END;
959 $$
960 LANGUAGE plpgsql;
961
962
963 CREATE OR REPLACE FUNCTION placex_delete()
964   RETURNS TRIGGER
965   AS $$
966 DECLARE
967   b BOOLEAN;
968   classtable TEXT;
969 BEGIN
970   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
971
972   IF OLD.linked_place_id is null THEN
973     update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
974     --DEBUG: RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;
975     update placex set linked_place_id = null where linked_place_id = OLD.place_id;
976     --DEBUG: RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;
977   ELSE
978     update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
979   END IF;
980
981   IF OLD.rank_address < 30 THEN
982
983     -- mark everything linked to this place for re-indexing
984     --DEBUG: RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;
985     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
986       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
987
988     --DEBUG: RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;
989     DELETE FROM place_addressline where address_place_id = OLD.place_id;
990
991     --DEBUG: RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;
992     b := deleteRoad(OLD.partition, OLD.place_id);
993
994     --DEBUG: RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;
995     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
996     --DEBUG: RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;
997     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
998     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
999
1000   END IF;
1001
1002   --DEBUG: RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;
1003
1004   IF OLD.rank_address < 26 THEN
1005     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1006   END IF;
1007
1008   --DEBUG: RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;
1009
1010   IF OLD.name is not null THEN
1011     IF NOT %REVERSE-ONLY% THEN
1012       DELETE from search_name WHERE place_id = OLD.place_id;
1013     END IF;
1014     b := deleteSearchName(OLD.partition, OLD.place_id);
1015   END IF;
1016
1017   --DEBUG: RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;
1018
1019   DELETE FROM place_addressline where place_id = OLD.place_id;
1020
1021   --DEBUG: RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;
1022
1023   -- remove from tables for special search
1024   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1025   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1026   IF b THEN
1027     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1028   END IF;
1029
1030   --DEBUG: RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;
1031
1032   RETURN OLD;
1033
1034 END;
1035 $$
1036 LANGUAGE plpgsql;