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