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