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