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