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