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