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