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