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