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