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