]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions.sql
908236b1ae4f855e5858660b1935fac27c937417
[nominatim.git] / sql / functions.sql
1 -- Splits the line at the given point and returns the two parts
2 -- in a multilinestring.
3 CREATE OR REPLACE FUNCTION split_line_on_node(line GEOMETRY, point GEOMETRY)
4 RETURNS GEOMETRY
5   AS $$
6 BEGIN
7   RETURN ST_Split(ST_Snap(line, point, 0.0005), point);
8 END;
9 $$
10 LANGUAGE plpgsql;
11
12
13 CREATE OR REPLACE FUNCTION geometry_sector(partition INTEGER, place geometry) RETURNS INTEGER
14   AS $$
15 DECLARE
16   NEWgeometry geometry;
17 BEGIN
18 --  RAISE WARNING '%',place;
19   NEWgeometry := ST_PointOnSurface(place);
20   RETURN (partition*1000000) + (500-ST_X(NEWgeometry)::integer)*1000 + (500-ST_Y(NEWgeometry)::integer);
21 END;
22 $$
23 LANGUAGE plpgsql IMMUTABLE;
24
25
26 CREATE OR REPLACE FUNCTION array_merge(a INTEGER[], b INTEGER[])
27   RETURNS INTEGER[]
28   AS $$
29 DECLARE
30   i INTEGER;
31   r INTEGER[];
32 BEGIN
33   IF array_upper(a, 1) IS NULL THEN
34     RETURN b;
35   END IF;
36   IF array_upper(b, 1) IS NULL THEN
37     RETURN a;
38   END IF;
39   r := a;
40   FOR i IN 1..array_upper(b, 1) LOOP  
41     IF NOT (ARRAY[b[i]] <@ r) THEN
42       r := r || b[i];
43     END IF;
44   END LOOP;
45   RETURN r;
46 END;
47 $$
48 LANGUAGE plpgsql IMMUTABLE;
49
50 CREATE OR REPLACE FUNCTION reverse_place_diameter(rank_search SMALLINT)
51   RETURNS FLOAT
52   AS $$
53 BEGIN
54   IF rank_search <= 4 THEN
55     RETURN 5.0;
56   ELSIF rank_search <= 8 THEN
57     RETURN 1.8;
58   ELSIF rank_search <= 12 THEN
59     RETURN 0.6;
60   ELSIF rank_search <= 17 THEN
61     RETURN 0.16;
62   ELSIF rank_search <= 18 THEN
63     RETURN 0.08;
64   ELSIF rank_search <= 19 THEN
65     RETURN 0.04;
66   END IF;
67
68   RETURN 0.02;
69 END;
70 $$
71 LANGUAGE plpgsql IMMUTABLE;
72
73 CREATE OR REPLACE FUNCTION get_postcode_rank(country_code VARCHAR(2), postcode TEXT,
74                                       OUT rank_search SMALLINT, OUT rank_address SMALLINT)
75 AS $$
76 DECLARE
77   part TEXT;
78 BEGIN
79     rank_search := 30;
80     rank_address := 30;
81     postcode := upper(postcode);
82
83     IF country_code = 'gb' THEN
84         IF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9][A-Z][A-Z])$' THEN
85             rank_search := 25;
86             rank_address := 5;
87         ELSEIF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9])$' THEN
88             rank_search := 23;
89             rank_address := 5;
90         ELSEIF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z])$' THEN
91             rank_search := 21;
92             rank_address := 5;
93         END IF;
94
95     ELSEIF country_code = 'sg' THEN
96         IF postcode ~ '^([0-9]{6})$' THEN
97             rank_search := 25;
98             rank_address := 11;
99         END IF;
100
101     ELSEIF country_code = 'de' THEN
102         IF postcode ~ '^([0-9]{5})$' THEN
103             rank_search := 21;
104             rank_address := 11;
105         END IF;
106
107     ELSE
108         -- Guess at the postcode format and coverage (!)
109         IF postcode ~ '^[A-Z0-9]{1,5}$' THEN -- Probably too short to be very local
110             rank_search := 21;
111             rank_address := 11;
112         ELSE
113             -- Does it look splitable into and area and local code?
114             part := substring(postcode from '^([- :A-Z0-9]+)([- :][A-Z0-9]+)$');
115
116             IF part IS NOT NULL THEN
117                 rank_search := 25;
118                 rank_address := 11;
119             ELSEIF postcode ~ '^[- :A-Z0-9]{6,}$' THEN
120                 rank_search := 21;
121                 rank_address := 11;
122             END IF;
123         END IF;
124     END IF;
125
126 END;
127 $$
128 LANGUAGE plpgsql IMMUTABLE;
129
130 -- Find the nearest artificial postcode for the given geometry.
131 -- TODO For areas there should not be more than two inside the geometry.
132 CREATE OR REPLACE FUNCTION get_nearest_postcode(country VARCHAR(2), geom GEOMETRY) RETURNS TEXT
133   AS $$
134 DECLARE
135   outcode TEXT;
136   cnt INTEGER;
137 BEGIN
138     -- If the geometry is an area then only one postcode must be within
139     -- that area, otherwise consider the area as not having a postcode.
140     IF ST_GeometryType(geom) in ('ST_Polygon','ST_MultiPolygon') THEN
141         SELECT min(postcode), count(*) FROM
142               (SELECT postcode FROM location_postcode
143                 WHERE ST_Contains(geom, location_postcode.geometry) LIMIT 2) sub
144           INTO outcode, cnt;
145
146         IF cnt = 1 THEN
147             RETURN outcode;
148         ELSE
149             RETURN null;
150         END IF;
151     END IF;
152
153     SELECT postcode FROM location_postcode
154      WHERE ST_DWithin(geom, location_postcode.geometry, 0.05)
155           AND location_postcode.country_code = country
156      ORDER BY ST_Distance(geom, location_postcode.geometry) LIMIT 1
157     INTO outcode;
158
159     RETURN outcode;
160 END;
161 $$
162 LANGUAGE plpgsql;
163
164
165 CREATE OR REPLACE FUNCTION get_country_code(place geometry) RETURNS TEXT
166   AS $$
167 DECLARE
168   place_centre GEOMETRY;
169   nearcountry RECORD;
170 BEGIN
171   place_centre := ST_PointOnSurface(place);
172
173 -- RAISE WARNING 'get_country_code, start: %', ST_AsText(place_centre);
174
175   -- Try for a OSM polygon
176   FOR nearcountry IN select country_code from location_area_country where country_code is not null and st_covers(geometry, place_centre) limit 1
177   LOOP
178     RETURN nearcountry.country_code;
179   END LOOP;
180
181 -- RAISE WARNING 'osm fallback: %', ST_AsText(place_centre);
182
183   -- Try for OSM fallback data
184   -- The order is to deal with places like HongKong that are 'states' within another polygon
185   FOR nearcountry IN select country_code from country_osm_grid where st_covers(geometry, place_centre) order by area asc limit 1
186   LOOP
187     RETURN nearcountry.country_code;
188   END LOOP;
189
190 -- RAISE WARNING 'near osm fallback: %', ST_AsText(place_centre);
191
192   -- 
193   FOR nearcountry IN select country_code from country_osm_grid where st_dwithin(geometry, place_centre, 0.5) order by st_distance(geometry, place_centre) asc, area asc limit 1
194   LOOP
195     RETURN nearcountry.country_code;
196   END LOOP;
197
198   RETURN NULL;
199 END;
200 $$
201 LANGUAGE plpgsql IMMUTABLE;
202
203 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2)) RETURNS TEXT
204   AS $$
205 DECLARE
206   nearcountry RECORD;
207 BEGIN
208   FOR nearcountry IN select distinct country_default_language_code from country_name where country_code = search_country_code limit 1
209   LOOP
210     RETURN lower(nearcountry.country_default_language_code);
211   END LOOP;
212   RETURN NULL;
213 END;
214 $$
215 LANGUAGE plpgsql IMMUTABLE;
216
217 CREATE OR REPLACE FUNCTION get_country_language_codes(search_country_code VARCHAR(2)) RETURNS TEXT[]
218   AS $$
219 DECLARE
220   nearcountry RECORD;
221 BEGIN
222   FOR nearcountry IN select country_default_language_codes from country_name where country_code = search_country_code limit 1
223   LOOP
224     RETURN lower(nearcountry.country_default_language_codes);
225   END LOOP;
226   RETURN NULL;
227 END;
228 $$
229 LANGUAGE plpgsql IMMUTABLE;
230
231 CREATE OR REPLACE FUNCTION get_partition(in_country_code VARCHAR(10)) RETURNS INTEGER
232   AS $$
233 DECLARE
234   nearcountry RECORD;
235 BEGIN
236   FOR nearcountry IN select partition from country_name where country_code = in_country_code
237   LOOP
238     RETURN nearcountry.partition;
239   END LOOP;
240   RETURN 0;
241 END;
242 $$
243 LANGUAGE plpgsql IMMUTABLE;
244
245 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT) RETURNS BOOLEAN
246   AS $$
247 DECLARE
248 BEGIN
249   DELETE FROM location_area where place_id = OLD_place_id;
250 -- TODO:location_area
251   RETURN true;
252 END;
253 $$
254 LANGUAGE plpgsql;
255
256 CREATE OR REPLACE FUNCTION add_location(
257     place_id BIGINT,
258     country_code varchar(2),
259     partition INTEGER,
260     keywords INTEGER[],
261     rank_search INTEGER,
262     rank_address INTEGER,
263     in_postcode TEXT,
264     geometry GEOMETRY
265   ) 
266   RETURNS BOOLEAN
267   AS $$
268 DECLARE
269   locationid INTEGER;
270   centroid GEOMETRY;
271   diameter FLOAT;
272   x BOOLEAN;
273   splitGeom RECORD;
274   secgeo GEOMETRY;
275   postcode TEXT;
276 BEGIN
277
278   IF rank_search > 25 THEN
279     RAISE EXCEPTION 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
280   END IF;
281
282   x := deleteLocationArea(partition, place_id, rank_search);
283
284   -- add postcode only if it contains a single entry, i.e. ignore postcode lists
285   postcode := NULL;
286   IF in_postcode is not null AND in_postcode not similar to '%(,|;)%' THEN
287       postcode := upper(trim (in_postcode));
288   END IF;
289
290   IF ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
291     centroid := ST_Centroid(geometry);
292
293     FOR secgeo IN select split_geometry(geometry) AS geom LOOP
294       x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, postcode, centroid, secgeo);
295     END LOOP;
296
297   ELSE
298
299     diameter := 0.02;
300     IF rank_address = 0 THEN
301       diameter := 0.02;
302     ELSEIF rank_search <= 14 THEN
303       diameter := 1.2;
304     ELSEIF rank_search <= 15 THEN
305       diameter := 1;
306     ELSEIF rank_search <= 16 THEN
307       diameter := 0.5;
308     ELSEIF rank_search <= 17 THEN
309       diameter := 0.2;
310     ELSEIF rank_search <= 21 THEN
311       diameter := 0.05;
312     ELSEIF rank_search = 25 THEN
313       diameter := 0.005;
314     END IF;
315
316 --    RAISE WARNING 'adding % diameter %', place_id, diameter;
317
318     secgeo := ST_Buffer(geometry, diameter);
319     x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, true, postcode, ST_Centroid(geometry), secgeo);
320
321   END IF;
322
323   RETURN true;
324 END;
325 $$
326 LANGUAGE plpgsql;
327
328
329 -- find the parent road of the cut road parts
330 CREATE OR REPLACE FUNCTION get_interpolation_parent(wayid BIGINT, street TEXT, place TEXT,
331                                                     partition INTEGER, centroid GEOMETRY, geom GEOMETRY)
332 RETURNS BIGINT AS $$
333 DECLARE
334   addr_street TEXT;
335   addr_place TEXT;
336   parent_place_id BIGINT;
337   address_street_word_ids INTEGER[];
338
339   waynodes BIGINT[];
340
341   location RECORD;
342 BEGIN
343   addr_street = street;
344   addr_place = place;
345
346   IF addr_street is null and addr_place is null THEN
347     select nodes from planet_osm_ways where id = wayid INTO waynodes;
348     FOR location IN SELECT placex.address from placex
349                     where osm_type = 'N' and osm_id = ANY(waynodes)
350                           and placex.address is not null
351                           and (placex.address ? 'street' or placex.address ? 'place')
352                           and indexed_status < 100
353                     limit 1 LOOP
354       addr_street = location.address->'street';
355       addr_place = location.address->'place';
356     END LOOP;
357   END IF;
358
359   IF addr_street IS NOT NULL THEN
360     address_street_word_ids := get_name_ids(make_standard_name(addr_street));
361     IF address_street_word_ids IS NOT NULL THEN
362       FOR location IN SELECT place_id from getNearestNamedRoadFeature(partition, centroid, address_street_word_ids) LOOP
363         parent_place_id := location.place_id;
364       END LOOP;
365     END IF;
366   END IF;
367
368   IF parent_place_id IS NULL AND addr_place IS NOT NULL THEN
369     address_street_word_ids := get_name_ids(make_standard_name(addr_place));
370     IF address_street_word_ids IS NOT NULL THEN
371       FOR location IN SELECT place_id from getNearestNamedPlaceFeature(partition, centroid, address_street_word_ids) LOOP
372         parent_place_id := location.place_id;
373       END LOOP;
374     END IF;
375   END IF;
376
377   IF parent_place_id is null THEN
378     FOR location IN SELECT place_id FROM placex
379         WHERE ST_DWithin(geom, placex.geometry, 0.001) and placex.rank_search = 26
380         ORDER BY (ST_distance(placex.geometry, ST_LineInterpolatePoint(geom,0))+
381                   ST_distance(placex.geometry, ST_LineInterpolatePoint(geom,0.5))+
382                   ST_distance(placex.geometry, ST_LineInterpolatePoint(geom,1))) ASC limit 1
383     LOOP
384       parent_place_id := location.place_id;
385     END LOOP;
386   END IF;
387
388   IF parent_place_id is null THEN
389     RETURN 0;
390   END IF;
391
392   RETURN parent_place_id;
393 END;
394 $$
395 LANGUAGE plpgsql;
396
397 CREATE OR REPLACE FUNCTION osmline_reinsert(node_id BIGINT, geom GEOMETRY)
398   RETURNS BOOLEAN
399   AS $$
400 DECLARE
401   existingline RECORD;
402 BEGIN
403    SELECT w.id FROM planet_osm_ways w, location_property_osmline p
404      WHERE p.linegeo && geom and p.osm_id = w.id and p.indexed_status = 0
405            and node_id = any(w.nodes) INTO existingline;
406
407    IF existingline.id is not NULL THEN
408        DELETE FROM location_property_osmline WHERE osm_id = existingline.id;
409        INSERT INTO location_property_osmline (osm_id, address, linegeo)
410          SELECT osm_id, address, geometry FROM place
411            WHERE osm_type = 'W' and osm_id = existingline.id;
412    END IF;
413
414    RETURN true;
415 END;
416 $$
417 LANGUAGE plpgsql;
418
419
420 CREATE OR REPLACE FUNCTION osmline_insert() RETURNS TRIGGER
421   AS $$
422 BEGIN
423   NEW.place_id := nextval('seq_place');
424   NEW.indexed_date := now();
425
426   IF NEW.indexed_status IS NULL THEN
427       IF NEW.address is NULL OR NOT NEW.address ? 'interpolation'
428          OR NEW.address->'interpolation' NOT IN ('odd', 'even', 'all') THEN
429           -- other interpolation types than odd/even/all (e.g. numeric ones) are not supported
430           RETURN NULL;
431       END IF;
432
433       NEW.indexed_status := 1; --STATUS_NEW
434       NEW.country_code := lower(get_country_code(NEW.linegeo));
435
436       NEW.partition := get_partition(NEW.country_code);
437       NEW.geometry_sector := geometry_sector(NEW.partition, NEW.linegeo);
438   END IF;
439
440   RETURN NEW;
441 END;
442 $$
443 LANGUAGE plpgsql;
444
445
446 CREATE OR REPLACE FUNCTION placex_insert() RETURNS TRIGGER
447   AS $$
448 DECLARE
449   i INTEGER;
450   postcode TEXT;
451   result BOOLEAN;
452   is_area BOOLEAN;
453   country_code VARCHAR(2);
454   default_language VARCHAR(10);
455   diameter FLOAT;
456   classtable TEXT;
457   classtype TEXT;
458 BEGIN
459   --DEBUG: RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
460
461   NEW.place_id := nextval('seq_place');
462   NEW.indexed_status := 1; --STATUS_NEW
463
464   NEW.country_code := lower(get_country_code(NEW.geometry));
465
466   NEW.partition := get_partition(NEW.country_code);
467   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
468
469   -- copy 'name' to or from the default language (if there is a default language)
470   IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
471     default_language := get_country_language_code(NEW.country_code);
472     IF default_language IS NOT NULL THEN
473       IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
474         NEW.name := NEW.name || hstore(('name:'||default_language), (NEW.name -> 'name'));
475       ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
476         NEW.name := NEW.name || hstore('name', (NEW.name -> ('name:'||default_language)));
477       END IF;
478     END IF;
479   END IF;
480
481   IF NEW.osm_type = 'X' THEN
482     -- E'X'ternal records should already be in the right format so do nothing
483   ELSE
484     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
485
486     IF NEW.class in ('place','boundary')
487        AND NEW.type in ('postcode','postal_code') THEN
488
489       IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
490           -- most likely just a part of a multipolygon postcode boundary, throw it away
491           RETURN NULL;
492       END IF;
493
494       NEW.name := hstore('ref', NEW.address->'postcode');
495
496       SELECT * FROM get_postcode_rank(NEW.country_code, NEW.address->'postcode')
497         INTO NEW.rank_search, NEW.rank_address;
498
499       IF NOT is_area THEN
500           NEW.rank_address := 0;
501       END IF;
502     ELSEIF NEW.class = 'boundary' AND NOT is_area THEN
503         return NULL;
504     ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
505            AND NEW.admin_level <= 4 AND NEW.osm_type = 'W' THEN
506         return NULL;
507     ELSEIF NEW.class = 'railway' AND NEW.type in ('rail') THEN
508         return NULL;
509     ELSEIF NEW.osm_type = 'N' AND NEW.class = 'highway' THEN
510         NEW.rank_search = 30;
511         NEW.rank_address = 0;
512     ELSEIF NEW.class = 'landuse' AND NOT is_area THEN
513         NEW.rank_search = 30;
514         NEW.rank_address = 0;
515     ELSE
516       -- do table lookup stuff
517       IF NEW.class = 'boundary' and NEW.type = 'administrative' THEN
518         classtype = NEW.type || NEW.admin_level::TEXT;
519       ELSE
520         classtype = NEW.type;
521       END IF;
522       SELECT l.rank_search, l.rank_address FROM address_levels l
523        WHERE (l.country_code = NEW.country_code or l.country_code is NULL)
524              AND l.class = NEW.class AND (l.type = classtype or l.type is NULL)
525        ORDER BY l.country_code, l.class, l.type LIMIT 1
526         INTO NEW.rank_search, NEW.rank_address;
527
528       IF NEW.rank_search is NULL THEN
529         NEW.rank_search := 30;
530       END IF;
531
532       IF NEW.rank_address is NULL THEN
533         NEW.rank_address := 30;
534       END IF;
535     END IF;
536
537     -- some postcorrections
538     IF NEW.class = 'waterway' AND NEW.osm_type = 'R' THEN
539         -- Slightly promote waterway relations so that they are processed
540         -- before their members.
541         NEW.rank_search := NEW.rank_search - 1;
542     END IF;
543
544     IF (NEW.extratags -> 'capital') = 'yes' THEN
545       NEW.rank_search := NEW.rank_search - 1;
546     END IF;
547
548   END IF;
549
550   -- a country code make no sense below rank 4 (country)
551   IF NEW.rank_search < 4 THEN
552     NEW.country_code := NULL;
553   END IF;
554
555   --DEBUG: RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
556
557   RETURN NEW; -- %DIFFUPDATES% The following is not needed until doing diff updates, and slows the main index process down
558
559   IF NEW.osm_type = 'N' and NEW.rank_search > 28 THEN
560       -- might be part of an interpolation
561       result := osmline_reinsert(NEW.osm_id, NEW.geometry);
562   ELSEIF NEW.rank_address > 0 THEN
563     IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
564       -- Performance: We just can't handle re-indexing for country level changes
565       IF st_area(NEW.geometry) < 1 THEN
566         -- mark items within the geometry for re-indexing
567   --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
568
569         -- work around bug in postgis, this may have been fixed in 2.0.0 (see http://trac.osgeo.org/postgis/ticket/547)
570         update placex set indexed_status = 2 where (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
571          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'));
572         update placex set indexed_status = 2 where (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
573          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'));
574       END IF;
575     ELSE
576       -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
577       diameter := 0;
578       -- 16 = city, anything higher than city is effectively ignored (polygon required!)
579       IF NEW.type='postcode' THEN
580         diameter := 0.05;
581       ELSEIF NEW.rank_search < 16 THEN
582         diameter := 0;
583       ELSEIF NEW.rank_search < 18 THEN
584         diameter := 0.1;
585       ELSEIF NEW.rank_search < 20 THEN
586         diameter := 0.05;
587       ELSEIF NEW.rank_search = 21 THEN
588         diameter := 0.001;
589       ELSEIF NEW.rank_search < 24 THEN
590         diameter := 0.02;
591       ELSEIF NEW.rank_search < 26 THEN
592         diameter := 0.002; -- 100 to 200 meters
593       ELSEIF NEW.rank_search < 28 THEN
594         diameter := 0.001; -- 50 to 100 meters
595       END IF;
596       IF diameter > 0 THEN
597   --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
598         IF NEW.rank_search >= 26 THEN
599           -- roads may cause reparenting for >27 rank places
600           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
601           -- reparenting also for OSM Interpolation Lines (and for Tiger?)
602           update location_property_osmline set indexed_status = 2 where indexed_status = 0 and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
603         ELSEIF NEW.rank_search >= 16 THEN
604           -- up to rank 16, street-less addresses may need reparenting
605           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');
606         ELSE
607           -- for all other places the search terms may change as well
608           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);
609         END IF;
610       END IF;
611     END IF;
612   END IF;
613
614
615    -- add to tables for special search
616    -- Note: won't work on initial import because the classtype tables
617    -- do not yet exist. It won't hurt either.
618   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
619   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
620   IF result THEN
621     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
622     USING NEW.place_id, ST_Centroid(NEW.geometry);
623   END IF;
624
625   RETURN NEW;
626
627 END;
628 $$
629 LANGUAGE plpgsql;
630
631 CREATE OR REPLACE FUNCTION osmline_update() RETURNS 
632 TRIGGER
633   AS $$
634 DECLARE
635   place_centroid GEOMETRY;
636   waynodes BIGINT[];
637   prevnode RECORD;
638   nextnode RECORD;
639   startnumber INTEGER;
640   endnumber INTEGER;
641   housenum INTEGER;
642   linegeo GEOMETRY;
643   splitline GEOMETRY;
644   sectiongeo GEOMETRY;
645   interpol_postcode TEXT;
646   postcode TEXT;
647 BEGIN
648   -- deferred delete
649   IF OLD.indexed_status = 100 THEN
650     delete from location_property_osmline where place_id = OLD.place_id;
651     RETURN NULL;
652   END IF;
653
654   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
655     RETURN NEW;
656   END IF;
657
658   NEW.interpolationtype = NEW.address->'interpolation';
659
660   place_centroid := ST_PointOnSurface(NEW.linegeo);
661   NEW.parent_place_id = get_interpolation_parent(NEW.osm_id, NEW.address->'street',
662                                                  NEW.address->'place',
663                                                  NEW.partition, place_centroid, NEW.linegeo);
664
665   IF NEW.address is not NULL AND NEW.address ? 'postcode' AND NEW.address->'postcode' not similar to '%(,|;)%' THEN
666     interpol_postcode := NEW.address->'postcode';
667     housenum := getorcreate_postcode_id(NEW.address->'postcode');
668   ELSE
669     interpol_postcode := NULL;
670   END IF;
671
672   -- if the line was newly inserted, split the line as necessary
673   IF OLD.indexed_status = 1 THEN
674       select nodes from planet_osm_ways where id = NEW.osm_id INTO waynodes;
675
676       IF array_upper(waynodes, 1) IS NULL THEN
677         RETURN NEW;
678       END IF;
679
680       linegeo := NEW.linegeo;
681       startnumber := NULL;
682
683       FOR nodeidpos in 1..array_upper(waynodes, 1) LOOP
684
685         select osm_id, address, geometry
686           from place where osm_type = 'N' and osm_id = waynodes[nodeidpos]::BIGINT
687                            and address is not NULL and address ? 'housenumber' limit 1 INTO nextnode;
688         --RAISE NOTICE 'Nextnode.place_id: %s', nextnode.place_id;
689         IF nextnode.osm_id IS NOT NULL THEN
690           --RAISE NOTICE 'place_id is not null';
691           IF nodeidpos > 1 and nodeidpos < array_upper(waynodes, 1) THEN
692             -- Make sure that the point is actually on the line. That might
693             -- be a bit paranoid but ensures that the algorithm still works
694             -- should osm2pgsql attempt to repair geometries.
695             splitline := split_line_on_node(linegeo, nextnode.geometry);
696             sectiongeo := ST_GeometryN(splitline, 1);
697             linegeo := ST_GeometryN(splitline, 2);
698           ELSE
699             sectiongeo = linegeo;
700           END IF;
701           endnumber := substring(nextnode.address->'housenumber','[0-9]+')::integer;
702
703           IF startnumber IS NOT NULL AND endnumber IS NOT NULL
704              AND startnumber != endnumber
705              AND ST_GeometryType(sectiongeo) = 'ST_LineString' THEN
706
707             IF (startnumber > endnumber) THEN
708               housenum := endnumber;
709               endnumber := startnumber;
710               startnumber := housenum;
711               sectiongeo := ST_Reverse(sectiongeo);
712             END IF;
713
714             -- determine postcode
715             postcode := coalesce(interpol_postcode,
716                                  prevnode.address->'postcode',
717                                  nextnode.address->'postcode',
718                                  postcode);
719
720             IF postcode is NULL THEN
721                 SELECT placex.postcode FROM placex WHERE place_id = NEW.parent_place_id INTO postcode;
722             END IF;
723             IF postcode is NULL THEN
724                 postcode := get_nearest_postcode(NEW.country_code, nextnode.geometry);
725             END IF;
726
727             IF NEW.startnumber IS NULL THEN
728                 NEW.startnumber := startnumber;
729                 NEW.endnumber := endnumber;
730                 NEW.linegeo := sectiongeo;
731                 NEW.postcode := upper(trim(postcode));
732              ELSE
733               insert into location_property_osmline
734                      (linegeo, partition, osm_id, parent_place_id,
735                       startnumber, endnumber, interpolationtype,
736                       address, postcode, country_code,
737                       geometry_sector, indexed_status)
738               values (sectiongeo, NEW.partition, NEW.osm_id, NEW.parent_place_id,
739                       startnumber, endnumber, NEW.interpolationtype,
740                       NEW.address, postcode,
741                       NEW.country_code, NEW.geometry_sector, 0);
742              END IF;
743           END IF;
744
745           -- early break if we are out of line string,
746           -- might happen when a line string loops back on itself
747           IF ST_GeometryType(linegeo) != 'ST_LineString' THEN
748               RETURN NEW;
749           END IF;
750
751           startnumber := substring(nextnode.address->'housenumber','[0-9]+')::integer;
752           prevnode := nextnode;
753         END IF;
754       END LOOP;
755   END IF;
756
757   -- marking descendants for reparenting is not needed, because there are
758   -- actually no descendants for interpolation lines
759   RETURN NEW;
760 END;
761 $$
762 LANGUAGE plpgsql;
763
764 -- Trigger for updates of location_postcode
765 --
766 -- Computes the parent object the postcode most likely refers to.
767 -- This will be the place that determines the address displayed when
768 -- searching for this postcode.
769 CREATE OR REPLACE FUNCTION postcode_update() RETURNS
770 TRIGGER
771   AS $$
772 DECLARE
773   partition SMALLINT;
774   location RECORD;
775 BEGIN
776     IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
777         RETURN NEW;
778     END IF;
779
780     NEW.indexed_date = now();
781
782     partition := get_partition(NEW.country_code);
783
784     SELECT * FROM get_postcode_rank(NEW.country_code, NEW.postcode)
785       INTO NEW.rank_search, NEW.rank_address;
786
787     NEW.parent_place_id = 0;
788     FOR location IN
789       SELECT place_id
790         FROM getNearFeatures(partition, NEW.geometry, NEW.rank_search, '{}'::int[])
791         WHERE NOT isguess ORDER BY rank_address DESC LIMIT 1
792     LOOP
793         NEW.parent_place_id = location.place_id;
794     END LOOP;
795
796     RETURN NEW;
797 END;
798 $$
799 LANGUAGE plpgsql;
800
801 CREATE OR REPLACE FUNCTION placex_update() RETURNS
802 TRIGGER
803   AS $$
804 DECLARE
805
806   place_centroid GEOMETRY;
807   near_centroid GEOMETRY;
808
809   search_maxdistance FLOAT[];
810   search_mindistance FLOAT[];
811   address_havelevel BOOLEAN[];
812
813   i INTEGER;
814   iMax FLOAT;
815   location RECORD;
816   way RECORD;
817   relation RECORD;
818   relation_members TEXT[];
819   relMember RECORD;
820   linkedplacex RECORD;
821   addr_item RECORD;
822   search_diameter FLOAT;
823   search_prevdiameter FLOAT;
824   search_maxrank INTEGER;
825   address_maxrank INTEGER;
826   address_street_word_id INTEGER;
827   address_street_word_ids INTEGER[];
828   parent_place_id_rank BIGINT;
829
830   addr_street TEXT;
831   addr_place TEXT;
832
833   isin TEXT[];
834   isin_tokens INT[];
835
836   location_rank_search INTEGER;
837   location_distance FLOAT;
838   location_parent GEOMETRY;
839   location_isaddress BOOLEAN;
840   location_keywords INTEGER[];
841
842   default_language TEXT;
843   name_vector INTEGER[];
844   nameaddress_vector INTEGER[];
845
846   linked_node_id BIGINT;
847   linked_importance FLOAT;
848   linked_wikipedia TEXT;
849
850   result BOOLEAN;
851 BEGIN
852   -- deferred delete
853   IF OLD.indexed_status = 100 THEN
854     --DEBUG: RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;
855     delete from placex where place_id = OLD.place_id;
856     RETURN NULL;
857   END IF;
858
859   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
860     RETURN NEW;
861   END IF;
862
863   --DEBUG: RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;
864
865   NEW.indexed_date = now();
866
867   IF NOT %REVERSE-ONLY% THEN
868     DELETE from search_name WHERE place_id = NEW.place_id;
869   END IF;
870   result := deleteSearchName(NEW.partition, NEW.place_id);
871   DELETE FROM place_addressline WHERE place_id = NEW.place_id;
872   result := deleteRoad(NEW.partition, NEW.place_id);
873   result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
874   UPDATE placex set linked_place_id = null, indexed_status = 2
875          where linked_place_id = NEW.place_id;
876   -- update not necessary for osmline, cause linked_place_id does not exist
877
878   IF NEW.linked_place_id is not null THEN
879     --DEBUG: RAISE WARNING 'place already linked to %', NEW.linked_place_id;
880     RETURN NEW;
881   END IF;
882
883   --DEBUG: RAISE WARNING 'Copy over address tags';
884   -- housenumber is a computed field, so start with an empty value
885   NEW.housenumber := NULL;
886   IF NEW.address is not NULL THEN
887       IF NEW.address ? 'conscriptionnumber' THEN
888         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'conscriptionnumber'));
889         IF NEW.address ? 'streetnumber' THEN
890             i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
891             NEW.housenumber := (NEW.address->'conscriptionnumber') || '/' || (NEW.address->'streetnumber');
892         ELSE
893             NEW.housenumber := NEW.address->'conscriptionnumber';
894         END IF;
895       ELSEIF NEW.address ? 'streetnumber' THEN
896         NEW.housenumber := NEW.address->'streetnumber';
897         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
898       ELSEIF NEW.address ? 'housenumber' THEN
899         NEW.housenumber := NEW.address->'housenumber';
900         i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
901       END IF;
902
903       addr_street := NEW.address->'street';
904       addr_place := NEW.address->'place';
905
906       IF NEW.address ? 'postcode' and NEW.address->'postcode' not similar to '%(,|;)%' THEN
907         i := getorcreate_postcode_id(NEW.address->'postcode');
908       END IF;
909   END IF;
910
911   -- Speed up searches - just use the centroid of the feature
912   -- cheaper but less acurate
913   place_centroid := ST_PointOnSurface(NEW.geometry);
914   -- For searching near features rather use the centroid
915   near_centroid := ST_Envelope(NEW.geometry);
916   NEW.centroid := null;
917   NEW.postcode := null;
918   --DEBUG: RAISE WARNING 'Computing preliminary centroid at %',ST_AsText(place_centroid);
919
920   -- recalculate country and partition
921   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
922     -- for countries, believe the mapped country code,
923     -- so that we remain in the right partition if the boundaries
924     -- suddenly expand.
925     NEW.country_code := lower(NEW.address->'country');
926     NEW.partition := get_partition(lower(NEW.country_code));
927     IF NEW.partition = 0 THEN
928       NEW.country_code := lower(get_country_code(place_centroid));
929       NEW.partition := get_partition(NEW.country_code);
930     END IF;
931   ELSE
932     IF NEW.rank_search >= 4 THEN
933       NEW.country_code := lower(get_country_code(place_centroid));
934     ELSE
935       NEW.country_code := NULL;
936     END IF;
937     NEW.partition := get_partition(NEW.country_code);
938   END IF;
939   --DEBUG: RAISE WARNING 'Country updated: "%"', NEW.country_code;
940
941   -- waterway ways are linked when they are part of a relation and have the same class/type
942   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
943       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
944       LOOP
945           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
946               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
947                 --DEBUG: RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];
948                 FOR linked_node_id IN SELECT place_id FROM placex
949                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
950                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
951                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
952                 LOOP
953                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
954                 END LOOP;
955               END IF;
956           END LOOP;
957       END LOOP;
958       --DEBUG: RAISE WARNING 'Waterway processed';
959   END IF;
960
961   -- What level are we searching from
962   search_maxrank := NEW.rank_search;
963
964   -- Thought this wasn't needed but when we add new languages to the country_name table
965   -- we need to update the existing names
966   IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
967     default_language := get_country_language_code(NEW.country_code);
968     IF default_language IS NOT NULL THEN
969       IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
970         NEW.name := NEW.name || hstore(('name:'||default_language), (NEW.name -> 'name'));
971       ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
972         NEW.name := NEW.name || hstore('name', (NEW.name -> ('name:'||default_language)));
973       END IF;
974     END IF;
975   END IF;
976   --DEBUG: RAISE WARNING 'Local names updated';
977
978   -- Initialise the name vector using our name
979   name_vector := make_keywords(NEW.name);
980   nameaddress_vector := '{}'::int[];
981
982   FOR i IN 1..28 LOOP
983     address_havelevel[i] := false;
984   END LOOP;
985
986   NEW.importance := null;
987   SELECT wikipedia, importance
988     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
989     INTO NEW.wikipedia,NEW.importance;
990
991 --DEBUG: RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;
992
993   -- ---------------------------------------------------------------------------
994   -- For low level elements we inherit from our parent road
995   IF (NEW.rank_search > 27 OR (NEW.type = 'postcode' AND NEW.rank_search = 25)) THEN
996
997     --DEBUG: RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;
998
999     -- We won't get a better centroid, besides these places are too small to care
1000     NEW.centroid := place_centroid;
1001
1002     NEW.parent_place_id := null;
1003
1004     -- if we have a POI and there is no address information,
1005     -- see if we can get it from a surrounding building
1006     IF NEW.osm_type = 'N' AND addr_street IS NULL AND addr_place IS NULL
1007        AND NEW.housenumber IS NULL THEN
1008       FOR location IN select address from placex where ST_Covers(geometry, place_centroid)
1009             and address is not null
1010             and (address ? 'housenumber' or address ? 'street' or address ? 'place')
1011             and rank_search > 28 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
1012             limit 1
1013       LOOP
1014         NEW.housenumber := location.address->'housenumber';
1015         addr_street := location.address->'street';
1016         addr_place := location.address->'place';
1017         --DEBUG: RAISE WARNING 'Found surrounding building % %', location.osm_type, location.osm_id;
1018       END LOOP;
1019     END IF;
1020
1021     -- We have to find our parent road.
1022     -- Copy data from linked items (points on ways, addr:street links, relations)
1023
1024     -- Is this object part of a relation?
1025     FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id] and members @> ARRAY[lower(NEW.osm_type)||NEW.osm_id]
1026     LOOP
1027       -- At the moment we only process one type of relation - associatedStreet
1028       IF relation.tags @> ARRAY['associatedStreet'] THEN
1029         FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1030           IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1031 --RAISE WARNING 'node in relation %',relation;
1032             SELECT place_id from placex where osm_type = 'W'
1033               and osm_id = substring(relation.members[i],2,200)::bigint
1034               and rank_search = 26 and name is not null INTO NEW.parent_place_id;
1035           END IF;
1036         END LOOP;
1037       END IF;
1038     END LOOP;
1039     --DEBUG: RAISE WARNING 'Checked for street relation (%)', NEW.parent_place_id;
1040
1041     -- Note that addr:street links can only be indexed once the street itself is indexed
1042     IF NEW.parent_place_id IS NULL AND addr_street IS NOT NULL THEN
1043       address_street_word_ids := get_name_ids(make_standard_name(addr_street));
1044       IF address_street_word_ids IS NOT NULL THEN
1045         SELECT place_id from getNearestNamedRoadFeature(NEW.partition, near_centroid, address_street_word_ids) INTO NEW.parent_place_id;
1046       END IF;
1047     END IF;
1048     --DEBUG: RAISE WARNING 'Checked for addr:street (%)', NEW.parent_place_id;
1049
1050     IF NEW.parent_place_id IS NULL AND addr_place IS NOT NULL THEN
1051       address_street_word_ids := get_name_ids(make_standard_name(addr_place));
1052       IF address_street_word_ids IS NOT NULL THEN
1053         SELECT place_id from getNearestNamedPlaceFeature(NEW.partition, near_centroid, address_street_word_ids) INTO NEW.parent_place_id;
1054       END IF;
1055     END IF;
1056     --DEBUG: RAISE WARNING 'Checked for addr:place (%)', NEW.parent_place_id;
1057
1058     -- Is this node part of an interpolation?
1059     IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'N' THEN
1060       SELECT q.parent_place_id FROM location_property_osmline q, planet_osm_ways x
1061         WHERE q.linegeo && NEW.geometry and x.id = q.osm_id and NEW.osm_id = any(x.nodes)
1062         LIMIT 1 INTO NEW.parent_place_id;
1063     END IF;
1064     --DEBUG: RAISE WARNING 'Checked for interpolation (%)', NEW.parent_place_id;
1065
1066     -- Is this node part of a way?
1067     IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'N' THEN
1068
1069       FOR location IN
1070         SELECT p.place_id, p.osm_id, p.rank_search, p.address from placex p, planet_osm_ways w
1071          WHERE p.osm_type = 'W' and p.rank_search >= 26 and p.geometry && NEW.geometry and w.id = p.osm_id and NEW.osm_id = any(w.nodes)
1072       LOOP
1073         --DEBUG: RAISE WARNING 'Node is part of way % ', location.osm_id;
1074
1075         -- Way IS a road then we are on it - that must be our road
1076         IF location.rank_search < 28 THEN
1077 --RAISE WARNING 'node in way that is a street %',location;
1078           NEW.parent_place_id := location.place_id;
1079           EXIT;
1080         END IF;
1081         --DEBUG: RAISE WARNING 'Checked if way is street (%)', NEW.parent_place_id;
1082
1083         -- If the way mentions a street or place address, try that for parenting.
1084         IF location.address is not null THEN
1085           IF location.address ? 'street' THEN
1086             address_street_word_ids := get_name_ids(make_standard_name(location.address->'street'));
1087             IF address_street_word_ids IS NOT NULL THEN
1088               SELECT place_id from getNearestNamedRoadFeature(NEW.partition, near_centroid, address_street_word_ids) INTO NEW.parent_place_id;
1089               EXIT WHEN NEW.parent_place_id is not NULL;
1090             END IF;
1091           END IF;
1092           --DEBUG: RAISE WARNING 'Checked for addr:street in way (%)', NEW.parent_place_id;
1093
1094           IF location.address ? 'place' THEN
1095             address_street_word_ids := get_name_ids(make_standard_name(location.address->'place'));
1096             IF address_street_word_ids IS NOT NULL THEN
1097               SELECT place_id from getNearestNamedPlaceFeature(NEW.partition, near_centroid, address_street_word_ids) INTO NEW.parent_place_id;
1098               EXIT WHEN NEW.parent_place_id is not NULL;
1099             END IF;
1100           END IF;
1101         --DEBUG: RAISE WARNING 'Checked for addr:place in way (%)', NEW.parent_place_id;
1102         END IF;
1103
1104         -- Is the WAY part of a relation
1105         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[location.osm_id] and members @> ARRAY['w'||location.osm_id]
1106         LOOP
1107           -- At the moment we only process one type of relation - associatedStreet
1108           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1109             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1110               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1111 --RAISE WARNING 'node in way that is in a relation %',relation;
1112                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::bigint 
1113                   and rank_search = 26 and name is not null INTO NEW.parent_place_id;
1114               END IF;
1115             END LOOP;
1116           END IF;
1117         END LOOP;
1118         EXIT WHEN NEW.parent_place_id is not null;
1119         --DEBUG: RAISE WARNING 'Checked for street relation in way (%)', NEW.parent_place_id;
1120
1121       END LOOP;
1122     END IF;
1123
1124     -- Still nothing, just use the nearest road
1125     IF NEW.parent_place_id IS NULL THEN
1126       SELECT place_id FROM getNearestRoadFeature(NEW.partition, near_centroid) INTO NEW.parent_place_id;
1127     END IF;
1128     --DEBUG: RAISE WARNING 'Checked for nearest way (%)', NEW.parent_place_id;
1129
1130
1131     -- If we didn't find any road fallback to standard method
1132     IF NEW.parent_place_id IS NOT NULL THEN
1133
1134       -- Get the details of the parent road
1135       SELECT p.country_code, p.postcode FROM placex p
1136        WHERE p.place_id = NEW.parent_place_id INTO location;
1137
1138       NEW.country_code := location.country_code;
1139       --DEBUG: RAISE WARNING 'Got parent details from search name';
1140
1141       -- determine postcode
1142       IF NEW.rank_search > 4 THEN
1143           IF NEW.address is not null AND NEW.address ? 'postcode' THEN
1144               NEW.postcode = upper(trim(NEW.address->'postcode'));
1145           ELSE
1146              NEW.postcode := location.postcode;
1147           END IF;
1148           IF NEW.postcode is null THEN
1149             NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1150           END IF;
1151       END IF;
1152
1153       -- If there is no name it isn't searchable, don't bother to create a search record
1154       IF NEW.name is NULL THEN
1155         --DEBUG: RAISE WARNING 'Not a searchable place % %', NEW.osm_type, NEW.osm_id;
1156         return NEW;
1157       END IF;
1158
1159       -- Performance, it would be more acurate to do all the rest of the import
1160       -- process but it takes too long
1161       -- Just be happy with inheriting from parent road only
1162       IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1163         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);
1164         --DEBUG: RAISE WARNING 'Place added to location table';
1165       END IF;
1166
1167       result := insertSearchName(NEW.partition, NEW.place_id, name_vector,
1168                                  NEW.rank_search, NEW.rank_address, NEW.geometry);
1169
1170       IF NOT %REVERSE-ONLY% THEN
1171           -- Merge address from parent
1172           SELECT s.name_vector, s.nameaddress_vector FROM search_name s
1173            WHERE s.place_id = NEW.parent_place_id INTO location;
1174
1175           nameaddress_vector := array_merge(nameaddress_vector,
1176                                             location.nameaddress_vector);
1177           nameaddress_vector := array_merge(nameaddress_vector, location.name_vector);
1178
1179           INSERT INTO search_name (place_id, search_rank, address_rank,
1180                                    importance, country_code, name_vector,
1181                                    nameaddress_vector, centroid)
1182                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1183                          NEW.importance, NEW.country_code, name_vector,
1184                          nameaddress_vector, place_centroid);
1185           --DEBUG: RAISE WARNING 'Place added to search table';
1186         END IF;
1187
1188       return NEW;
1189     END IF;
1190
1191   END IF;
1192
1193   -- ---------------------------------------------------------------------------
1194   -- Full indexing
1195   --DEBUG: RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;
1196
1197   IF NEW.osm_type = 'R' AND NEW.rank_search < 26 THEN
1198
1199     -- see if we have any special relation members
1200     select members from planet_osm_rels where id = NEW.osm_id INTO relation_members;
1201     --DEBUG: RAISE WARNING 'Got relation members';
1202
1203     IF relation_members IS NOT NULL THEN
1204       FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['label']) as member LOOP
1205         --DEBUG: RAISE WARNING 'Found label member %', relMember.member;
1206
1207         FOR linkedPlacex IN select * from placex where osm_type = upper(substring(relMember.member,1,1))::char(1) 
1208           and osm_id = substring(relMember.member,2,10000)::bigint
1209           and class = 'place' order by rank_search desc limit 1 LOOP
1210
1211           -- If we don't already have one use this as the centre point of the geometry
1212           IF NEW.centroid IS NULL THEN
1213             NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1214           END IF;
1215
1216           -- merge in the label name, re-init word vector
1217           IF NOT linkedPlacex.name IS NULL THEN
1218             NEW.name := linkedPlacex.name || NEW.name;
1219             name_vector := array_merge(name_vector, make_keywords(linkedPlacex.name));
1220           END IF;
1221
1222           -- merge in extra tags
1223           NEW.extratags := hstore(linkedPlacex.class, linkedPlacex.type) || coalesce(linkedPlacex.extratags, ''::hstore) || coalesce(NEW.extratags, ''::hstore);
1224
1225           -- mark the linked place (excludes from search results)
1226           UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1227
1228           select wikipedia, importance
1229             FROM compute_importance(linkedPlacex.extratags, NEW.country_code,
1230                                     'N', linkedPlacex.osm_id)
1231             INTO linked_wikipedia,linked_importance;
1232           --DEBUG: RAISE WARNING 'Linked label member';
1233         END LOOP;
1234
1235       END LOOP;
1236
1237       IF NEW.centroid IS NULL THEN
1238
1239         FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['admin_center','admin_centre']) as member LOOP
1240           --DEBUG: RAISE WARNING 'Found admin_center member %', relMember.member;
1241
1242           FOR linkedPlacex IN select * from placex where osm_type = upper(substring(relMember.member,1,1))::char(1) 
1243             and osm_id = substring(relMember.member,2,10000)::bigint
1244             and class = 'place' order by rank_search desc limit 1 LOOP
1245
1246             -- For an admin centre we also want a name match - still not perfect, for example 'new york, new york'
1247             -- But that can be fixed by explicitly setting the label in the data
1248             IF make_standard_name(NEW.name->'name') = make_standard_name(linkedPlacex.name->'name') 
1249               AND NEW.rank_address = linkedPlacex.rank_address THEN
1250
1251               -- If we don't already have one use this as the centre point of the geometry
1252               IF NEW.centroid IS NULL THEN
1253                 NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1254               END IF;
1255
1256               -- merge in the name, re-init word vector
1257               IF NOT linkedPlacex.name IS NULL THEN
1258                 NEW.name := linkedPlacex.name || NEW.name;
1259                 name_vector := make_keywords(NEW.name);
1260               END IF;
1261
1262               -- merge in extra tags
1263               NEW.extratags := hstore(linkedPlacex.class, linkedPlacex.type) || coalesce(linkedPlacex.extratags, ''::hstore) || coalesce(NEW.extratags, ''::hstore);
1264
1265               -- mark the linked place (excludes from search results)
1266               UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1267
1268               select wikipedia, importance
1269                 FROM compute_importance(linkedPlacex.extratags, NEW.country_code,
1270                                         'N', linkedPlacex.osm_id)
1271                 INTO linked_wikipedia,linked_importance;
1272               --DEBUG: RAISE WARNING 'Linked admin_center';
1273             END IF;
1274
1275           END LOOP;
1276
1277         END LOOP;
1278
1279       END IF;
1280     END IF;
1281
1282   END IF;
1283
1284   -- Name searches can be done for ways as well as relations
1285   IF NEW.osm_type in ('W','R') AND NEW.rank_search < 26 AND NEW.rank_address > 0 THEN
1286
1287     -- not found one yet? how about doing a name search
1288     IF NEW.centroid IS NULL AND (NEW.name->'name') is not null and make_standard_name(NEW.name->'name') != '' THEN
1289
1290       --DEBUG: RAISE WARNING 'Looking for nodes with matching names';
1291       FOR linkedPlacex IN select placex.* from placex WHERE
1292         make_standard_name(name->'name') = make_standard_name(NEW.name->'name')
1293         AND placex.rank_address = NEW.rank_address
1294         AND placex.place_id != NEW.place_id
1295         AND placex.osm_type = 'N'::char(1) AND placex.rank_search < 26
1296         AND st_covers(NEW.geometry, placex.geometry)
1297       LOOP
1298         --DEBUG: RAISE WARNING 'Found matching place node %', linkedPlacex.osm_id;
1299         -- If we don't already have one use this as the centre point of the geometry
1300         IF NEW.centroid IS NULL THEN
1301           NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1302         END IF;
1303
1304         -- merge in the name, re-init word vector
1305         NEW.name := linkedPlacex.name || NEW.name;
1306         name_vector := make_keywords(NEW.name);
1307
1308         -- merge in extra tags
1309         NEW.extratags := hstore(linkedPlacex.class, linkedPlacex.type) || coalesce(linkedPlacex.extratags, ''::hstore) || coalesce(NEW.extratags, ''::hstore);
1310
1311         -- mark the linked place (excludes from search results)
1312         UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1313
1314         select wikipedia, importance
1315           FROM compute_importance(linkedPlacex.extratags, NEW.country_code,
1316                                   'N', linkedPlacex.osm_id)
1317           INTO linked_wikipedia,linked_importance;
1318         --DEBUG: RAISE WARNING 'Linked named place';
1319       END LOOP;
1320     END IF;
1321
1322     IF NEW.centroid IS NOT NULL THEN
1323       place_centroid := NEW.centroid;
1324       -- Place might have had only a name tag before but has now received translations
1325       -- from the linked place. Make sure a name tag for the default language exists in
1326       -- this case. 
1327       IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
1328         default_language := get_country_language_code(NEW.country_code);
1329         IF default_language IS NOT NULL THEN
1330           IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
1331             NEW.name := NEW.name || hstore(('name:'||default_language), (NEW.name -> 'name'));
1332           ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
1333             NEW.name := NEW.name || hstore('name', (NEW.name -> ('name:'||default_language)));
1334           END IF;
1335         END IF;
1336       END IF;
1337       --DEBUG: RAISE WARNING 'Names updated from linked places';
1338     END IF;
1339
1340     -- Use the maximum importance if a one could be computed from the linked object.
1341     IF linked_importance is not null AND
1342         (NEW.importance is null or NEW.importance < linked_importance) THEN
1343         NEW.importance = linked_importance;
1344     END IF;
1345   END IF;
1346
1347   -- make sure all names are in the word table
1348   IF NEW.admin_level = 2 AND NEW.class = 'boundary' AND NEW.type = 'administrative' AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R' THEN
1349     perform create_country(NEW.name, lower(NEW.country_code));
1350     --DEBUG: RAISE WARNING 'Country names updated';
1351   END IF;
1352
1353   NEW.parent_place_id = 0;
1354   parent_place_id_rank = 0;
1355
1356
1357   -- convert address store to array of tokenids
1358   --DEBUG: RAISE WARNING 'Starting address search';
1359   isin_tokens := '{}'::int[];
1360   IF NEW.address IS NOT NULL THEN
1361     FOR addr_item IN SELECT * FROM each(NEW.address)
1362     LOOP
1363       IF addr_item.key IN ('city', 'tiger:county', 'state', 'suburb', 'province', 'district', 'region', 'county', 'municipality', 'hamlet', 'village', 'subdistrict', 'town', 'neighbourhood', 'quarter', 'parish') THEN
1364         address_street_word_id := get_name_id(make_standard_name(addr_item.value));
1365         IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1366           isin_tokens := isin_tokens || address_street_word_id;
1367         END IF;
1368         IF NOT %REVERSE-ONLY% THEN
1369           address_street_word_id := get_word_id(make_standard_name(addr_item.value));
1370           IF address_street_word_id IS NOT NULL THEN
1371             nameaddress_vector := array_merge(nameaddress_vector, ARRAY[address_street_word_id]);
1372           END IF;
1373         END IF;
1374       END IF;
1375       IF addr_item.key = 'is_in' THEN
1376         -- is_in items need splitting
1377         isin := regexp_split_to_array(addr_item.value, E'[;,]');
1378         IF array_upper(isin, 1) IS NOT NULL THEN
1379           FOR i IN 1..array_upper(isin, 1) LOOP
1380             address_street_word_id := get_name_id(make_standard_name(isin[i]));
1381             IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1382               isin_tokens := isin_tokens || address_street_word_id;
1383             END IF;
1384
1385             -- merge word into address vector
1386             IF NOT %REVERSE-ONLY% THEN
1387               address_street_word_id := get_word_id(make_standard_name(isin[i]));
1388               IF address_street_word_id IS NOT NULL THEN
1389                 nameaddress_vector := array_merge(nameaddress_vector, ARRAY[address_street_word_id]);
1390               END IF;
1391             END IF;
1392           END LOOP;
1393         END IF;
1394       END IF;
1395     END LOOP;
1396   END IF;
1397   IF NOT %REVERSE-ONLY% THEN
1398     nameaddress_vector := array_merge(nameaddress_vector, isin_tokens);
1399   END IF;
1400
1401 -- RAISE WARNING 'ISIN: %', isin_tokens;
1402
1403   -- Process area matches
1404   location_rank_search := 0;
1405   location_distance := 0;
1406   location_parent := NULL;
1407   -- added ourself as address already
1408   address_havelevel[NEW.rank_address] := true;
1409   --DEBUG: RAISE WARNING '  getNearFeatures(%,''%'',%,''%'')',NEW.partition, place_centroid, search_maxrank, isin_tokens;
1410   FOR location IN
1411     SELECT * from getNearFeatures(NEW.partition,
1412                                   CASE WHEN NEW.rank_search >= 26
1413                                              AND NEW.rank_search < 30
1414                                        THEN NEW.geometry
1415                                        ELSE place_centroid END,
1416                                   search_maxrank, isin_tokens)
1417   LOOP
1418     IF location.rank_address != location_rank_search THEN
1419       location_rank_search := location.rank_address;
1420       IF location.isguess THEN
1421         location_distance := location.distance * 1.5;
1422       ELSE
1423         IF location.rank_address <= 12 THEN
1424           -- for county and above, if we have an area consider that exact
1425           -- (It would be nice to relax the constraint for places close to
1426           --  the boundary but we'd need the exact geometry for that. Too
1427           --  expensive.)
1428           location_distance = 0;
1429         ELSE
1430           -- Below county level remain slightly fuzzy.
1431           location_distance := location.distance * 0.5;
1432         END IF;
1433       END IF;
1434     ELSE
1435       CONTINUE WHEN location.keywords <@ location_keywords;
1436     END IF;
1437
1438     IF location.distance < location_distance OR NOT location.isguess THEN
1439       location_keywords := location.keywords;
1440
1441       location_isaddress := NOT address_havelevel[location.rank_address];
1442       IF location_isaddress AND location.isguess AND location_parent IS NOT NULL THEN
1443           location_isaddress := ST_Contains(location_parent,location.centroid);
1444       END IF;
1445
1446       -- RAISE WARNING '% isaddress: %', location.place_id, location_isaddress;
1447       -- Add it to the list of search terms
1448       IF NOT %REVERSE-ONLY% THEN
1449           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1450       END IF;
1451       INSERT INTO place_addressline (place_id, address_place_id, fromarea, isaddress, distance, cached_rank_address)
1452         VALUES (NEW.place_id, location.place_id, true, location_isaddress, location.distance, location.rank_address);
1453
1454       IF location_isaddress THEN
1455         -- add postcode if we have one
1456         -- (If multiple postcodes are available, we end up with the highest ranking one.)
1457         IF location.postcode is not null THEN
1458             NEW.postcode = location.postcode;
1459         END IF;
1460
1461         address_havelevel[location.rank_address] := true;
1462         IF NOT location.isguess THEN
1463           SELECT geometry FROM placex WHERE place_id = location.place_id INTO location_parent;
1464         END IF;
1465
1466         IF location.rank_address > parent_place_id_rank THEN
1467           NEW.parent_place_id = location.place_id;
1468           parent_place_id_rank = location.rank_address;
1469         END IF;
1470
1471       END IF;
1472
1473     --DEBUG: RAISE WARNING '  Terms: (%) %',location, nameaddress_vector;
1474
1475     END IF;
1476
1477   END LOOP;
1478   --DEBUG: RAISE WARNING 'address computed';
1479
1480   IF NEW.address is not null AND NEW.address ? 'postcode' 
1481      AND NEW.address->'postcode' not similar to '%(,|;)%' THEN
1482     NEW.postcode := upper(trim(NEW.address->'postcode'));
1483   END IF;
1484
1485   IF NEW.postcode is null AND NEW.rank_search > 8 THEN
1486     NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
1487   END IF;
1488
1489   -- if we have a name add this to the name search table
1490   IF NEW.name IS NOT NULL THEN
1491
1492     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1493       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);
1494       --DEBUG: RAISE WARNING 'added to location (full)';
1495     END IF;
1496
1497     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1498       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1499       --DEBUG: RAISE WARNING 'insert into road location table (full)';
1500     END IF;
1501
1502     result := insertSearchName(NEW.partition, NEW.place_id, name_vector,
1503                                NEW.rank_search, NEW.rank_address, NEW.geometry);
1504     --DEBUG: RAISE WARNING 'added to search name (full)';
1505
1506     IF NOT %REVERSE-ONLY% THEN
1507         INSERT INTO search_name (place_id, search_rank, address_rank,
1508                                  importance, country_code, name_vector,
1509                                  nameaddress_vector, centroid)
1510                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
1511                        NEW.importance, NEW.country_code, name_vector,
1512                        nameaddress_vector, place_centroid);
1513     END IF;
1514
1515   END IF;
1516
1517   -- If we've not managed to pick up a better one - default centroid
1518   IF NEW.centroid IS NULL THEN
1519     NEW.centroid := place_centroid;
1520   END IF;
1521
1522   --DEBUG: RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;
1523
1524   RETURN NEW;
1525 END;
1526 $$
1527 LANGUAGE plpgsql;
1528
1529 CREATE OR REPLACE FUNCTION placex_delete() RETURNS TRIGGER
1530   AS $$
1531 DECLARE
1532   b BOOLEAN;
1533   classtable TEXT;
1534 BEGIN
1535   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1536
1537   update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1538   --DEBUG: RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;
1539   update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1540   --DEBUG: RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;
1541
1542   IF OLD.rank_address < 30 THEN
1543
1544     -- mark everything linked to this place for re-indexing
1545     --DEBUG: RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;
1546     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1547       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1548
1549     --DEBUG: RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;
1550     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1551
1552     --DEBUG: RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;
1553     b := deleteRoad(OLD.partition, OLD.place_id);
1554
1555     --DEBUG: RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;
1556     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1557     --DEBUG: RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;
1558     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1559     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1560
1561   END IF;
1562
1563   --DEBUG: RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;
1564
1565   IF OLD.rank_address < 26 THEN
1566     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1567   END IF;
1568
1569   --DEBUG: RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;
1570
1571   IF OLD.name is not null THEN
1572     IF NOT %REVERSE-ONLY% THEN
1573       DELETE from search_name WHERE place_id = OLD.place_id;
1574     END IF;
1575     b := deleteSearchName(OLD.partition, OLD.place_id);
1576   END IF;
1577
1578   --DEBUG: RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;
1579
1580   DELETE FROM place_addressline where place_id = OLD.place_id;
1581
1582   --DEBUG: RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;
1583
1584   -- remove from tables for special search
1585   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1586   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1587   IF b THEN
1588     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1589   END IF;
1590
1591   --DEBUG: RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;
1592
1593   RETURN OLD;
1594
1595 END;
1596 $$
1597 LANGUAGE plpgsql;
1598
1599 CREATE OR REPLACE FUNCTION place_delete() RETURNS TRIGGER
1600   AS $$
1601 DECLARE
1602   has_rank BOOLEAN;
1603 BEGIN
1604
1605   --DEBUG: RAISE WARNING 'delete: % % % %',OLD.osm_type,OLD.osm_id,OLD.class,OLD.type;
1606
1607   -- deleting large polygons can have a massive effect on the system - require manual intervention to let them through
1608   IF st_area(OLD.geometry) > 2 and st_isvalid(OLD.geometry) THEN
1609     SELECT bool_or(not (rank_address = 0 or rank_address > 26)) as ranked FROM placex WHERE osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type INTO has_rank;
1610     IF has_rank THEN
1611       insert into import_polygon_delete (osm_type, osm_id, class, type) values (OLD.osm_type,OLD.osm_id,OLD.class,OLD.type);
1612       RETURN NULL;
1613     END IF;
1614   END IF;
1615
1616   -- mark for delete
1617   UPDATE placex set indexed_status = 100 where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1618
1619   -- interpolations are special
1620   IF OLD.osm_type='W' and OLD.class = 'place' and OLD.type = 'houses' THEN
1621     UPDATE location_property_osmline set indexed_status = 100 where osm_id = OLD.osm_id; -- osm_id = wayid (=old.osm_id)
1622   END IF;
1623
1624   RETURN OLD;
1625
1626 END;
1627 $$
1628 LANGUAGE plpgsql;
1629
1630 CREATE OR REPLACE FUNCTION place_insert() RETURNS TRIGGER
1631   AS $$
1632 DECLARE
1633   i INTEGER;
1634   existing RECORD;
1635   existingplacex RECORD;
1636   existingline RECORD;
1637   existinggeometry GEOMETRY;
1638   existingplace_id BIGINT;
1639   result BOOLEAN;
1640   partition INTEGER;
1641 BEGIN
1642
1643   --DEBUG: RAISE WARNING '-----------------------------------------------------------------------------------';
1644   --DEBUG: RAISE WARNING 'place_insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,st_area(NEW.geometry);
1645   -- filter wrong tupels
1646   IF ST_IsEmpty(NEW.geometry) OR NOT ST_IsValid(NEW.geometry) OR ST_X(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') THEN  
1647     INSERT INTO import_polygon_error (osm_type, osm_id, class, type, name, country_code, updated, errormessage, prevgeometry, newgeometry)
1648       VALUES (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.address->'country', now(), ST_IsValidReason(NEW.geometry), null, NEW.geometry);
1649 --    RAISE WARNING 'Invalid Geometry: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1650     RETURN null;
1651   END IF;
1652
1653   -- decide, whether it is an osm interpolation line => insert intoosmline, or else just placex
1654   IF NEW.class='place' and NEW.type='houses' and NEW.osm_type='W' and ST_GeometryType(NEW.geometry) = 'ST_LineString' THEN
1655     -- Have we already done this place?
1656     select * from place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type INTO existing;
1657
1658     -- Get the existing place_id
1659     select * from location_property_osmline where osm_id = NEW.osm_id INTO existingline;
1660
1661     -- Handle a place changing type by removing the old data (this trigger is executed BEFORE INSERT of the NEW tupel)
1662     IF existing.osm_type IS NULL THEN
1663       DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class;
1664     END IF;
1665
1666     DELETE from import_polygon_error where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1667     DELETE from import_polygon_delete where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1668
1669     -- update method for interpolation lines: delete all old interpolation lines with same osm_id (update on place) and insert the new one(s) (they can be split up, if they have > 2 nodes)
1670     IF existingline.osm_id IS NOT NULL THEN
1671       delete from location_property_osmline where osm_id = NEW.osm_id;
1672     END IF;
1673
1674     -- for interpolations invalidate all nodes on the line
1675     update placex p set indexed_status = 2
1676       from planet_osm_ways w
1677       where w.id = NEW.osm_id and p.osm_type = 'N' and p.osm_id = any(w.nodes);
1678
1679
1680     INSERT INTO location_property_osmline (osm_id, address, linegeo)
1681       VALUES (NEW.osm_id, NEW.address, NEW.geometry);
1682
1683
1684     IF existing.osm_type IS NULL THEN
1685       return NEW;
1686     END IF;
1687
1688     IF coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
1689        OR (coalesce(existing.extratags, ''::hstore) != coalesce(NEW.extratags, ''::hstore))
1690        OR existing.geometry::text != NEW.geometry::text
1691        THEN
1692
1693       update place set 
1694         name = NEW.name,
1695         address = NEW.address,
1696         extratags = NEW.extratags,
1697         admin_level = NEW.admin_level,
1698         geometry = NEW.geometry
1699         where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1700     END IF;
1701
1702     RETURN NULL;
1703
1704   ELSE -- insert to placex
1705
1706     -- Patch in additional country names
1707     IF NEW.admin_level = 2 AND NEW.type = 'administrative'
1708           AND NEW.address is not NULL AND NEW.address ? 'country' THEN
1709         SELECT name FROM country_name WHERE country_code = lower(NEW.address->'country') INTO existing;
1710         IF existing.name IS NOT NULL THEN
1711             NEW.name = existing.name || NEW.name;
1712         END IF;
1713     END IF;
1714       
1715     -- Have we already done this place?
1716     select * from place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type INTO existing;
1717
1718     -- Get the existing place_id
1719     select * from placex where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type INTO existingplacex;
1720
1721     -- Handle a place changing type by removing the old data
1722     -- My generated 'place' types are causing havok because they overlap with real keys
1723     -- TODO: move them to their own special purpose key/class to avoid collisions
1724     IF existing.osm_type IS NULL THEN
1725       DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class;
1726     END IF;
1727
1728     --DEBUG: RAISE WARNING 'Existing: %',existing.osm_id;
1729     --DEBUG: RAISE WARNING 'Existing PlaceX: %',existingplacex.place_id;
1730
1731     -- Log and discard 
1732     IF existing.geometry is not null AND st_isvalid(existing.geometry) 
1733       AND st_area(existing.geometry) > 0.02
1734       AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')
1735       AND st_area(NEW.geometry) < st_area(existing.geometry)*0.5
1736       THEN
1737       INSERT INTO import_polygon_error (osm_type, osm_id, class, type, name, country_code, updated, errormessage, prevgeometry, newgeometry)
1738         VALUES (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.address->'country', now(), 
1739         'Area reduced from '||st_area(existing.geometry)||' to '||st_area(NEW.geometry), existing.geometry, NEW.geometry);
1740       RETURN null;
1741     END IF;
1742
1743     DELETE from import_polygon_error where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1744     DELETE from import_polygon_delete where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1745
1746     -- To paraphrase, if there isn't an existing item, OR if the admin level has changed
1747     IF existingplacex.osm_type IS NULL OR
1748         (existingplacex.class = 'boundary' AND
1749           ((coalesce(existingplacex.admin_level, 15) != coalesce(NEW.admin_level, 15) AND existingplacex.type = 'administrative') OR
1750           (existingplacex.type != NEW.type)))
1751     THEN
1752
1753       IF existingplacex.osm_type IS NOT NULL THEN
1754         -- sanity check: ignore admin_level changes on places with too many active children
1755         -- or we end up reindexing entire countries because somebody accidentally deleted admin_level
1756         --LIMIT INDEXING: SELECT count(*) FROM (SELECT 'a' FROM placex , place_addressline where address_place_id = existingplacex.place_id and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress LIMIT 100001) sub INTO i;
1757         --LIMIT INDEXING: IF i > 100000 THEN
1758         --LIMIT INDEXING:  RETURN null;
1759         --LIMIT INDEXING: END IF;
1760       END IF;
1761
1762       IF existing.osm_type IS NOT NULL THEN
1763         -- pathological case caused by the triggerless copy into place during initial import
1764         -- force delete even for large areas, it will be reinserted later
1765         UPDATE place set geometry = ST_SetSRID(ST_Point(0,0), 4326) where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1766         DELETE from place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1767       END IF;
1768
1769       -- No - process it as a new insertion (hopefully of low rank or it will be slow)
1770       insert into placex (osm_type, osm_id, class, type, name,
1771                           admin_level, address, extratags, geometry)
1772         values (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name,
1773                 NEW.admin_level, NEW.address, NEW.extratags, NEW.geometry);
1774
1775       --DEBUG: RAISE WARNING 'insert done % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,NEW.name;
1776
1777       RETURN NEW;
1778     END IF;
1779
1780     -- Special case for polygon shape changes because they tend to be large and we can be a bit clever about how we handle them
1781     IF existing.geometry::text != NEW.geometry::text 
1782        AND ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon')
1783        AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') 
1784        THEN 
1785
1786       -- Get the version of the geometry actually used (in placex table)
1787       select geometry from placex where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type into existinggeometry;
1788
1789       -- Performance limit
1790       IF st_area(NEW.geometry) < 0.000000001 AND st_area(existinggeometry) < 1 THEN
1791
1792         -- re-index points that have moved in / out of the polygon, could be done as a single query but postgres gets the index usage wrong
1793         update placex set indexed_status = 2 where indexed_status = 0 and 
1794             (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1795             AND NOT (st_covers(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1796             AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1797
1798         update placex set indexed_status = 2 where indexed_status = 0 and 
1799             (st_covers(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1800             AND NOT (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1801             AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1802
1803       END IF;
1804
1805     END IF;
1806
1807
1808     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1809        OR coalesce(existing.extratags::text, '') != coalesce(NEW.extratags::text, '')
1810        OR coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
1811        OR coalesce(existing.admin_level, 15) != coalesce(NEW.admin_level, 15)
1812        OR existing.geometry::text != NEW.geometry::text
1813        THEN
1814
1815       update place set 
1816         name = NEW.name,
1817         address = NEW.address,
1818         extratags = NEW.extratags,
1819         admin_level = NEW.admin_level,
1820         geometry = NEW.geometry
1821         where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1822
1823
1824       IF NEW.class in ('place','boundary') AND NEW.type in ('postcode','postal_code') THEN
1825           IF NEW.address is NULL OR NOT NEW.address ? 'postcode' THEN
1826               -- postcode was deleted, no longer retain in placex
1827               DELETE FROM placex where place_id = existingplacex.place_id;
1828               RETURN NULL;
1829           END IF;
1830
1831           NEW.name := hstore('ref', NEW.address->'postcode');
1832       END IF;
1833
1834       IF NEW.class in ('boundary')
1835          AND ST_GeometryType(NEW.geometry) not in ('ST_Polygon','ST_MultiPolygon') THEN
1836           DELETE FROM placex where place_id = existingplacex.place_id;
1837           RETURN NULL;
1838       END IF;
1839
1840       update placex set 
1841         name = NEW.name,
1842         address = NEW.address,
1843         parent_place_id = null,
1844         extratags = NEW.extratags,
1845         admin_level = NEW.admin_level,
1846         indexed_status = 2,
1847         geometry = NEW.geometry
1848         where place_id = existingplacex.place_id;
1849       -- if a node(=>house), which is part of a interpolation line, changes (e.g. the street attribute) => mark this line for reparenting 
1850       -- (already here, because interpolation lines are reindexed before nodes, so in the second call it would be too late)
1851       IF NEW.osm_type='N'
1852          and (coalesce(existing.address, ''::hstore) != coalesce(NEW.address, ''::hstore)
1853              or existing.geometry::text != NEW.geometry::text)
1854       THEN
1855           result:= osmline_reinsert(NEW.osm_id, NEW.geometry);
1856       END IF;
1857
1858       -- linked places should get potential new naming and addresses
1859       IF existingplacex.linked_place_id is not NULL THEN
1860         update placex x set
1861           name = p.name,
1862           extratags = p.extratags,
1863           indexed_status = 2
1864         from place p
1865         where x.place_id = existingplacex.linked_place_id
1866               and x.indexed_status = 0
1867               and x.osm_type = p.osm_type
1868               and x.osm_id = p.osm_id
1869               and x.class = p.class;
1870       END IF;
1871
1872     END IF;
1873
1874     -- Abort the add (we modified the existing place instead)
1875     RETURN NULL;
1876   END IF;
1877
1878 END;
1879 $$ LANGUAGE plpgsql;
1880
1881
1882 CREATE OR REPLACE FUNCTION get_name_by_language(name hstore, languagepref TEXT[]) RETURNS TEXT
1883   AS $$
1884 DECLARE
1885   result TEXT;
1886 BEGIN
1887   IF name is null THEN
1888     RETURN null;
1889   END IF;
1890
1891   FOR j IN 1..array_upper(languagepref,1) LOOP
1892     IF name ? languagepref[j] THEN
1893       result := trim(name->languagepref[j]);
1894       IF result != '' THEN
1895         return result;
1896       END IF;
1897     END IF;
1898   END LOOP;
1899
1900   -- anything will do as a fallback - just take the first name type thing there is
1901   RETURN trim((avals(name))[1]);
1902 END;
1903 $$
1904 LANGUAGE plpgsql IMMUTABLE;
1905
1906 --housenumber only needed for tiger data
1907 CREATE OR REPLACE FUNCTION get_address_by_language(for_place_id BIGINT, housenumber INTEGER, languagepref TEXT[]) RETURNS TEXT
1908   AS $$
1909 DECLARE
1910   result TEXT[];
1911   currresult TEXT;
1912   prevresult TEXT;
1913   location RECORD;
1914 BEGIN
1915
1916   result := '{}';
1917   prevresult := '';
1918
1919   FOR location IN select * from get_addressdata(for_place_id, housenumber) where isaddress order by rank_address desc LOOP
1920     currresult := trim(get_name_by_language(location.name, languagepref));
1921     IF currresult != prevresult AND currresult IS NOT NULL AND result[(100 - location.rank_address)] IS NULL THEN
1922       result[(100 - location.rank_address)] := trim(get_name_by_language(location.name, languagepref));
1923       prevresult := currresult;
1924     END IF;
1925   END LOOP;
1926
1927   RETURN array_to_string(result,', ');
1928 END;
1929 $$
1930 LANGUAGE plpgsql;
1931
1932 DROP TYPE IF EXISTS addressline CASCADE;
1933 create type addressline as (
1934   place_id BIGINT,
1935   osm_type CHAR(1),
1936   osm_id BIGINT,
1937   name HSTORE,
1938   class TEXT,
1939   type TEXT,
1940   admin_level INTEGER,
1941   fromarea BOOLEAN,  
1942   isaddress BOOLEAN,  
1943   rank_address INTEGER,
1944   distance FLOAT
1945 );
1946
1947 -- Compute the list of address parts for the given place.
1948 --
1949 -- If in_housenumber is greator or equal 0, look for an interpolation.
1950 CREATE OR REPLACE FUNCTION get_addressdata(in_place_id BIGINT, in_housenumber INTEGER) RETURNS setof addressline 
1951   AS $$
1952 DECLARE
1953   for_place_id BIGINT;
1954   result TEXT[];
1955   search TEXT[];
1956   found INTEGER;
1957   location RECORD;
1958   countrylocation RECORD;
1959   searchcountrycode varchar(2);
1960   searchhousenumber TEXT;
1961   searchhousename HSTORE;
1962   searchrankaddress INTEGER;
1963   searchpostcode TEXT;
1964   postcode_isaddress BOOL;
1965   searchclass TEXT;
1966   searchtype TEXT;
1967   countryname HSTORE;
1968 BEGIN
1969   -- The place ein question might not have a direct entry in place_addressline.
1970   -- Look for the parent of such places then and save if in for_place_id.
1971
1972   postcode_isaddress := true;
1973
1974   -- first query osmline (interpolation lines)
1975   IF in_housenumber >= 0 THEN
1976     SELECT parent_place_id, country_code, in_housenumber::text, 30, postcode,
1977            null, 'place', 'house'
1978       FROM location_property_osmline
1979       WHERE place_id = in_place_id AND in_housenumber>=startnumber
1980             AND in_housenumber <= endnumber
1981       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress,
1982            searchpostcode, searchhousename, searchclass, searchtype;
1983   END IF;
1984
1985   --then query tiger data
1986   -- %NOTIGERDATA% IF 0 THEN
1987   IF for_place_id IS NULL AND in_housenumber >= 0 THEN
1988     SELECT parent_place_id, 'us', in_housenumber::text, 30, postcode, null,
1989            'place', 'house'
1990       FROM location_property_tiger
1991       WHERE place_id = in_place_id AND in_housenumber >= startnumber
1992             AND in_housenumber <= endnumber
1993       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress,
1994            searchpostcode, searchhousename, searchclass, searchtype;
1995   END IF;
1996   -- %NOTIGERDATA% END IF;
1997
1998   -- %NOAUXDATA% IF 0 THEN
1999   IF for_place_id IS NULL THEN
2000     SELECT parent_place_id, 'us', housenumber, 30, postcode, null, 'place', 'house'
2001       FROM location_property_aux
2002       WHERE place_id = in_place_id
2003       INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress,
2004            searchpostcode, searchhousename, searchclass, searchtype;
2005   END IF;
2006   -- %NOAUXDATA% END IF;
2007
2008   -- postcode table
2009   IF for_place_id IS NULL THEN
2010     SELECT parent_place_id, country_code, rank_search, postcode, 'place', 'postcode'
2011       FROM location_postcode
2012       WHERE place_id = in_place_id
2013       INTO for_place_id, searchcountrycode, searchrankaddress, searchpostcode,
2014            searchclass, searchtype;
2015   END IF;
2016
2017   -- POI objects in the placex table
2018   IF for_place_id IS NULL THEN
2019     SELECT parent_place_id, country_code, housenumber, rank_search, postcode,
2020            name, class, type
2021       FROM placex
2022       WHERE place_id = in_place_id and rank_search > 27
2023       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress,
2024            searchpostcode, searchhousename, searchclass, searchtype;
2025   END IF;
2026
2027   -- If for_place_id is still NULL at this point then the object has its own
2028   -- entry in place_address line. However, still check if there is not linked
2029   -- place we should be using instead.
2030   IF for_place_id IS NULL THEN
2031     select coalesce(linked_place_id, place_id),  country_code,
2032            housenumber, rank_search, postcode, null
2033       from placex where place_id = in_place_id
2034       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
2035   END IF;
2036
2037 --RAISE WARNING '% % % %',searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode;
2038
2039   found := 1000; -- the lowest rank_address included
2040
2041   -- Return the record for the base entry.
2042   FOR location IN
2043     SELECT placex.place_id, osm_type, osm_id, name,
2044            class, type, admin_level,
2045            type not in ('postcode', 'postal_code') as isaddress,
2046            CASE WHEN rank_address = 0 THEN 100
2047                 WHEN rank_address = 11 THEN 5
2048                 ELSE rank_address END as rank_address,
2049            0 as distance, country_code, postcode
2050       FROM placex
2051       WHERE place_id = for_place_id
2052   LOOP
2053 --RAISE WARNING '%',location;
2054     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2055       searchcountrycode := location.country_code;
2056     END IF;
2057     IF location.rank_address < 4 THEN
2058       -- no country locations for ranks higher than country
2059       searchcountrycode := NULL;
2060     END IF;
2061     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id,
2062                            location.name, location.class, location.type,
2063                            location.admin_level, true, location.isaddress,
2064                            location.rank_address, location.distance)::addressline;
2065     RETURN NEXT countrylocation;
2066     found := location.rank_address;
2067   END LOOP;
2068
2069   FOR location IN
2070     SELECT placex.place_id, osm_type, osm_id, name,
2071            CASE WHEN extratags ? 'place' THEN 'place' ELSE class END as class,
2072            CASE WHEN extratags ? 'place' THEN extratags->'place' ELSE type END as type,
2073            admin_level, fromarea, isaddress,
2074            CASE WHEN rank_address = 11 THEN 5 ELSE rank_address END as rank_address,
2075            distance, country_code, postcode
2076       FROM place_addressline join placex on (address_place_id = placex.place_id)
2077       WHERE place_addressline.place_id = for_place_id
2078             AND (cached_rank_address >= 4 AND cached_rank_address < searchrankaddress)
2079             AND linked_place_id is null
2080             AND (placex.country_code IS NULL OR searchcountrycode IS NULL
2081                  OR placex.country_code = searchcountrycode)
2082       ORDER BY rank_address desc, isaddress desc, fromarea desc,
2083                distance asc, rank_search desc
2084   LOOP
2085 --RAISE WARNING '%',location;
2086     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2087       searchcountrycode := location.country_code;
2088     END IF;
2089     IF location.type in ('postcode', 'postal_code') THEN
2090       postcode_isaddress := false;
2091       IF location.osm_type != 'R' THEN
2092         location.isaddress := FALSE;
2093       END IF;
2094     END IF;
2095     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id,
2096                            location.name, location.class, location.type,
2097                            location.admin_level, location.fromarea,
2098                            location.isaddress, location.rank_address,
2099                            location.distance)::addressline;
2100     RETURN NEXT countrylocation;
2101     found := location.rank_address;
2102   END LOOP;
2103
2104   -- If no country was included yet, add the name information from country_name.
2105   IF found > 4 THEN
2106     SELECT name FROM country_name
2107       WHERE country_code = searchcountrycode LIMIT 1 INTO countryname;
2108 --RAISE WARNING '% % %',found,searchcountrycode,countryname;
2109     IF countryname IS NOT NULL THEN
2110       location := ROW(null, null, null, countryname, 'place', 'country',
2111                       null, true, true, 4, 0)::addressline;
2112       RETURN NEXT location;
2113     END IF;
2114   END IF;
2115
2116   -- Finally add some artificial rows.
2117   IF searchcountrycode IS NOT NULL THEN
2118     location := ROW(null, null, null, hstore('ref', searchcountrycode),
2119                     'place', 'country_code', null, true, false, 4, 0)::addressline;
2120     RETURN NEXT location;
2121   END IF;
2122
2123   IF searchhousename IS NOT NULL THEN
2124     location := ROW(in_place_id, null, null, searchhousename, searchclass,
2125                     searchtype, null, true, true, 29, 0)::addressline;
2126     RETURN NEXT location;
2127   END IF;
2128
2129   IF searchhousenumber IS NOT NULL THEN
2130     location := ROW(in_place_id, null, null, hstore('ref', searchhousenumber),
2131                     'place', 'house_number', null, true, true, 28, 0)::addressline;
2132     RETURN NEXT location;
2133   END IF;
2134
2135   IF searchpostcode IS NOT NULL THEN
2136     location := ROW(null, null, null, hstore('ref', searchpostcode), 'place',
2137                     'postcode', null, false, postcode_isaddress, 5, 0)::addressline;
2138     RETURN NEXT location;
2139   END IF;
2140
2141   RETURN;
2142 END;
2143 $$
2144 LANGUAGE plpgsql;
2145
2146
2147 CREATE OR REPLACE FUNCTION aux_create_property(pointgeo GEOMETRY, in_housenumber TEXT, 
2148   in_street TEXT, in_isin TEXT, in_postcode TEXT, in_countrycode char(2)) RETURNS INTEGER
2149   AS $$
2150 DECLARE
2151
2152   newpoints INTEGER;
2153   place_centroid GEOMETRY;
2154   out_partition INTEGER;
2155   out_parent_place_id BIGINT;
2156   location RECORD;
2157   address_street_word_id INTEGER;  
2158   out_postcode TEXT;
2159
2160 BEGIN
2161
2162   place_centroid := ST_Centroid(pointgeo);
2163   out_partition := get_partition(in_countrycode);
2164   out_parent_place_id := null;
2165
2166   address_street_word_id := get_name_id(make_standard_name(in_street));
2167   IF address_street_word_id IS NOT NULL THEN
2168     FOR location IN SELECT * from getNearestNamedRoadFeature(out_partition, place_centroid, address_street_word_id) LOOP
2169       out_parent_place_id := location.place_id;
2170     END LOOP;
2171   END IF;
2172
2173   IF out_parent_place_id IS NULL THEN
2174     FOR location IN SELECT place_id FROM getNearestRoadFeature(out_partition, place_centroid) LOOP
2175       out_parent_place_id := location.place_id;
2176     END LOOP;
2177   END IF;
2178
2179   out_postcode := in_postcode;
2180   IF out_postcode IS NULL THEN
2181     SELECT postcode from placex where place_id = out_parent_place_id INTO out_postcode;
2182   END IF;
2183   -- XXX look into postcode table
2184
2185   newpoints := 0;
2186   insert into location_property_aux (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2187     values (nextval('seq_place'), out_partition, out_parent_place_id, in_housenumber, out_postcode, place_centroid);
2188   newpoints := newpoints + 1;
2189
2190   RETURN newpoints;
2191 END;
2192 $$
2193 LANGUAGE plpgsql;
2194
2195 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], member TEXT) RETURNS TEXT[]
2196   AS $$
2197 DECLARE
2198   result TEXT[];
2199   i INTEGER;
2200 BEGIN
2201
2202   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2203     IF members[i+1] = member THEN
2204       result := result || members[i];
2205     END IF;
2206   END LOOP;
2207
2208   return result;
2209 END;
2210 $$
2211 LANGUAGE plpgsql;
2212
2213 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], memberLabels TEXT[]) RETURNS SETOF TEXT
2214   AS $$
2215 DECLARE
2216   i INTEGER;
2217 BEGIN
2218
2219   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2220     IF members[i+1] = ANY(memberLabels) THEN
2221       RETURN NEXT members[i];
2222     END IF;
2223   END LOOP;
2224
2225   RETURN;
2226 END;
2227 $$
2228 LANGUAGE plpgsql;
2229
2230 -- See: http://stackoverflow.com/questions/6410088/how-can-i-mimic-the-php-urldecode-function-in-postgresql
2231 CREATE OR REPLACE FUNCTION decode_url_part(p varchar) RETURNS varchar 
2232   AS $$
2233 SELECT convert_from(CAST(E'\\x' || array_to_string(ARRAY(
2234     SELECT CASE WHEN length(r.m[1]) = 1 THEN encode(convert_to(r.m[1], 'SQL_ASCII'), 'hex') ELSE substring(r.m[1] from 2 for 2) END
2235     FROM regexp_matches($1, '%[0-9a-f][0-9a-f]|.', 'gi') AS r(m)
2236 ), '') AS bytea), 'UTF8');
2237 $$ 
2238 LANGUAGE SQL IMMUTABLE STRICT;
2239
2240 CREATE OR REPLACE FUNCTION catch_decode_url_part(p varchar) RETURNS varchar
2241   AS $$
2242 DECLARE
2243 BEGIN
2244   RETURN decode_url_part(p);
2245 EXCEPTION
2246   WHEN others THEN return null;
2247 END;
2248 $$
2249 LANGUAGE plpgsql IMMUTABLE;
2250
2251 DROP TYPE IF EXISTS wikipedia_article_match CASCADE;
2252 create type wikipedia_article_match as (
2253   language TEXT,
2254   title TEXT,
2255   importance FLOAT
2256 );
2257
2258 CREATE OR REPLACE FUNCTION get_wikipedia_match(extratags HSTORE, country_code varchar(2)) RETURNS wikipedia_article_match
2259   AS $$
2260 DECLARE
2261   langs TEXT[];
2262   i INT;
2263   wiki_article TEXT;
2264   wiki_article_title TEXT;
2265   wiki_article_language TEXT;
2266   result wikipedia_article_match;
2267 BEGIN
2268   langs := ARRAY['english','country','ar','bg','ca','cs','da','de','en','es','eo','eu','fa','fr','ko','hi','hr','id','it','he','lt','hu','ms','nl','ja','no','pl','pt','kk','ro','ru','sk','sl','sr','fi','sv','tr','uk','vi','vo','war','zh'];
2269   i := 1;
2270   WHILE langs[i] IS NOT NULL LOOP
2271     wiki_article := extratags->(case when langs[i] in ('english','country') THEN 'wikipedia' ELSE 'wikipedia:'||langs[i] END);
2272     IF wiki_article is not null THEN
2273       wiki_article := regexp_replace(wiki_article,E'^(.*?)([a-z]{2,3}).wikipedia.org/wiki/',E'\\2:');
2274       wiki_article := regexp_replace(wiki_article,E'^(.*?)([a-z]{2,3}).wikipedia.org/w/index.php\\?title=',E'\\2:');
2275       wiki_article := regexp_replace(wiki_article,E'^(.*?)/([a-z]{2,3})/wiki/',E'\\2:');
2276       --wiki_article := regexp_replace(wiki_article,E'^(.*?)([a-z]{2,3})[=:]',E'\\2:');
2277       wiki_article := replace(wiki_article,' ','_');
2278       IF strpos(wiki_article, ':') IN (3,4) THEN
2279         wiki_article_language := lower(trim(split_part(wiki_article, ':', 1)));
2280         wiki_article_title := trim(substr(wiki_article, strpos(wiki_article, ':')+1));
2281       ELSE
2282         wiki_article_title := trim(wiki_article);
2283         wiki_article_language := CASE WHEN langs[i] = 'english' THEN 'en' WHEN langs[i] = 'country' THEN get_country_language_code(country_code) ELSE langs[i] END;
2284       END IF;
2285
2286       select wikipedia_article.language,wikipedia_article.title,wikipedia_article.importance
2287         from wikipedia_article 
2288         where language = wiki_article_language and 
2289         (title = wiki_article_title OR title = catch_decode_url_part(wiki_article_title) OR title = replace(catch_decode_url_part(wiki_article_title),E'\\',''))
2290       UNION ALL
2291       select wikipedia_article.language,wikipedia_article.title,wikipedia_article.importance
2292         from wikipedia_redirect join wikipedia_article on (wikipedia_redirect.language = wikipedia_article.language and wikipedia_redirect.to_title = wikipedia_article.title)
2293         where wikipedia_redirect.language = wiki_article_language and 
2294         (from_title = wiki_article_title OR from_title = catch_decode_url_part(wiki_article_title) OR from_title = replace(catch_decode_url_part(wiki_article_title),E'\\',''))
2295       order by importance desc limit 1 INTO result;
2296
2297       IF result.language is not null THEN
2298         return result;
2299       END IF;
2300     END IF;
2301     i := i + 1;
2302   END LOOP;
2303   RETURN NULL;
2304 END;
2305 $$
2306 LANGUAGE plpgsql;
2307
2308 DROP TYPE IF EXISTS place_importance CASCADE;
2309 create type place_importance as (
2310   importance FLOAT,
2311   wikipedia TEXT
2312 );
2313
2314 CREATE OR REPLACE FUNCTION compute_importance(extratags HSTORE, country_code varchar(2), osm_type varchar(1), osm_id BIGINT)
2315   RETURNS place_importance
2316   AS $$
2317 DECLARE
2318   match RECORD;
2319   result place_importance;
2320 BEGIN
2321   FOR match IN SELECT * FROM get_wikipedia_match(extratags, country_code)
2322                WHERE language is not NULL
2323   LOOP
2324     result.importance := match.importance;
2325     result.wikipedia := match.language || ':' || match.title;
2326     RETURN result;
2327   END LOOP;
2328
2329   IF extratags ? 'wikidata' THEN
2330     FOR match IN SELECT * FROM wikipedia_article
2331                   WHERE wd_page_title = extratags->'wikidata'
2332                   ORDER BY language = 'en' DESC, langcount DESC LIMIT 1 LOOP
2333       result.importance := match.importance;
2334       result.wikipedia := match.language || ':' || match.title;
2335       RETURN result;
2336     END LOOP;
2337   END IF;
2338
2339   RETURN null;
2340 END;
2341 $$
2342 LANGUAGE plpgsql;
2343
2344 CREATE OR REPLACE FUNCTION quad_split_geometry(geometry GEOMETRY, maxarea FLOAT, maxdepth INTEGER) 
2345   RETURNS SETOF GEOMETRY
2346   AS $$
2347 DECLARE
2348   xmin FLOAT;
2349   ymin FLOAT;
2350   xmax FLOAT;
2351   ymax FLOAT;
2352   xmid FLOAT;
2353   ymid FLOAT;
2354   secgeo GEOMETRY;
2355   secbox GEOMETRY;
2356   seg INTEGER;
2357   geo RECORD;
2358   area FLOAT;
2359   remainingdepth INTEGER;
2360   added INTEGER;
2361   
2362 BEGIN
2363
2364 --  RAISE WARNING 'quad_split_geometry: maxarea=%, depth=%',maxarea,maxdepth;
2365
2366   IF (ST_GeometryType(geometry) not in ('ST_Polygon','ST_MultiPolygon') OR NOT ST_IsValid(geometry)) THEN
2367     RETURN NEXT geometry;
2368     RETURN;
2369   END IF;
2370
2371   remainingdepth := maxdepth - 1;
2372   area := ST_AREA(geometry);
2373   IF remainingdepth < 1 OR area < maxarea THEN
2374     RETURN NEXT geometry;
2375     RETURN;
2376   END IF;
2377
2378   xmin := st_xmin(geometry);
2379   xmax := st_xmax(geometry);
2380   ymin := st_ymin(geometry);
2381   ymax := st_ymax(geometry);
2382   secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(ymin,xmin),ST_Point(ymax,xmax)),4326);
2383
2384   -- if the geometry completely covers the box don't bother to slice any more
2385   IF ST_AREA(secbox) = area THEN
2386     RETURN NEXT geometry;
2387     RETURN;
2388   END IF;
2389
2390   xmid := (xmin+xmax)/2;
2391   ymid := (ymin+ymax)/2;
2392
2393   added := 0;
2394   FOR seg IN 1..4 LOOP
2395
2396     IF seg = 1 THEN
2397       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymin),ST_Point(xmid,ymid)),4326);
2398     END IF;
2399     IF seg = 2 THEN
2400       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymid),ST_Point(xmid,ymax)),4326);
2401     END IF;
2402     IF seg = 3 THEN
2403       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymin),ST_Point(xmax,ymid)),4326);
2404     END IF;
2405     IF seg = 4 THEN
2406       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymid),ST_Point(xmax,ymax)),4326);
2407     END IF;
2408
2409     IF st_intersects(geometry, secbox) THEN
2410       secgeo := st_intersection(geometry, secbox);
2411       IF NOT ST_IsEmpty(secgeo) AND ST_GeometryType(secgeo) in ('ST_Polygon','ST_MultiPolygon') THEN
2412         FOR geo IN select quad_split_geometry(secgeo, maxarea, remainingdepth) as geom LOOP
2413           IF NOT ST_IsEmpty(geo.geom) AND ST_GeometryType(geo.geom) in ('ST_Polygon','ST_MultiPolygon') THEN
2414             added := added + 1;
2415             RETURN NEXT geo.geom;
2416           END IF;
2417         END LOOP;
2418       END IF;
2419     END IF;
2420   END LOOP;
2421
2422   RETURN;
2423 END;
2424 $$
2425 LANGUAGE plpgsql;
2426
2427 CREATE OR REPLACE FUNCTION split_geometry(geometry GEOMETRY) 
2428   RETURNS SETOF GEOMETRY
2429   AS $$
2430 DECLARE
2431   geo RECORD;
2432 BEGIN
2433   -- 10000000000 is ~~ 1x1 degree
2434   FOR geo IN select quad_split_geometry(geometry, 0.25, 20) as geom LOOP
2435     RETURN NEXT geo.geom;
2436   END LOOP;
2437   RETURN;
2438 END;
2439 $$
2440 LANGUAGE plpgsql;
2441
2442
2443 CREATE OR REPLACE FUNCTION place_force_delete(placeid BIGINT) RETURNS BOOLEAN
2444   AS $$
2445 DECLARE
2446     osmid BIGINT;
2447     osmtype character(1);
2448     pclass text;
2449     ptype text;
2450 BEGIN
2451   SELECT osm_type, osm_id, class, type FROM placex WHERE place_id = placeid INTO osmtype, osmid, pclass, ptype;
2452   DELETE FROM import_polygon_delete where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
2453   DELETE FROM import_polygon_error where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
2454   -- force delete from place/placex by making it a very small geometry
2455   UPDATE place set geometry = ST_SetSRID(ST_Point(0,0), 4326) where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
2456   DELETE FROM place where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
2457
2458   RETURN TRUE;
2459 END;
2460 $$
2461 LANGUAGE plpgsql;
2462
2463 CREATE OR REPLACE FUNCTION place_force_update(placeid BIGINT) RETURNS BOOLEAN
2464   AS $$
2465 DECLARE
2466   placegeom GEOMETRY;
2467   geom GEOMETRY;
2468   diameter FLOAT;
2469   rank INTEGER;
2470 BEGIN
2471   UPDATE placex SET indexed_status = 2 WHERE place_id = placeid;
2472   SELECT geometry, rank_search FROM placex WHERE place_id = placeid INTO placegeom, rank;
2473   IF placegeom IS NOT NULL AND ST_IsValid(placegeom) THEN
2474     IF ST_GeometryType(placegeom) in ('ST_Polygon','ST_MultiPolygon') THEN
2475       FOR geom IN select split_geometry(placegeom) FROM placex WHERE place_id = placeid LOOP
2476         update placex set indexed_status = 2 where (st_covers(geom, placex.geometry) OR ST_Intersects(geom, placex.geometry)) 
2477         AND rank_search > rank and indexed_status = 0 and ST_geometrytype(placex.geometry) = 'ST_Point' and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
2478         update placex set indexed_status = 2 where (st_covers(geom, placex.geometry) OR ST_Intersects(geom, placex.geometry)) 
2479         AND rank_search > rank and indexed_status = 0 and ST_geometrytype(placex.geometry) != 'ST_Point' and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
2480       END LOOP;
2481     ELSE
2482         diameter := 0;
2483         IF rank = 11 THEN
2484           diameter := 0.05;
2485         ELSEIF rank < 18 THEN
2486           diameter := 0.1;
2487         ELSEIF rank < 20 THEN
2488           diameter := 0.05;
2489         ELSEIF rank = 21 THEN
2490           diameter := 0.001;
2491         ELSEIF rank < 24 THEN
2492           diameter := 0.02;
2493         ELSEIF rank < 26 THEN
2494           diameter := 0.002; -- 100 to 200 meters
2495         ELSEIF rank < 28 THEN
2496           diameter := 0.001; -- 50 to 100 meters
2497         END IF;
2498         IF diameter > 0 THEN
2499           IF rank >= 26 THEN
2500             -- roads may cause reparenting for >27 rank places
2501             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter);
2502           ELSEIF rank >= 16 THEN
2503             -- up to rank 16, street-less addresses may need reparenting
2504             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null or address ? 'place');
2505           ELSE
2506             -- for all other places the search terms may change as well
2507             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null);
2508           END IF;
2509         END IF;
2510     END IF;
2511     RETURN TRUE;
2512   END IF;
2513
2514   RETURN FALSE;
2515 END;
2516 $$
2517 LANGUAGE plpgsql;