]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions.sql
updated wikipedia article code to allow for mutliple languages and remove code duplic...
[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_Centroid(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   IF NEW.rank_search >= 4 THEN
913     NEW.country_code := lower(get_country_code(NEW.geometry, NEW.country_code));
914   ELSE
915     NEW.country_code := NULL;
916   END IF;
917
918   NEW.partition := get_partition(NEW.geometry, NEW.country_code);
919   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
920
921   -- copy 'name' to or from the default language (if there is a default language)
922   IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
923     default_language := get_country_language_code(NEW.country_code);
924     IF default_language IS NOT NULL THEN
925       IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
926         NEW.name := NEW.name || (('name:'||default_language) => (NEW.name -> 'name'));
927       ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
928         NEW.name := NEW.name || ('name' => (NEW.name -> ('name:'||default_language)));
929       END IF;
930     END IF;
931   END IF;
932
933   IF NEW.admin_level > 15 THEN
934     NEW.admin_level := 15;
935   END IF;
936
937   IF NEW.housenumber IS NOT NULL THEN
938     i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
939   END IF;
940
941   IF NEW.osm_type = 'X' THEN
942     -- E'X'ternal records should already be in the right format so do nothing
943   ELSE
944     NEW.rank_search := 30;
945     NEW.rank_address := NEW.rank_search;
946
947     -- By doing in postgres we have the country available to us - currently only used for postcode
948     IF NEW.class in ('place','boundary') AND NEW.type in ('postcode','postal_code') THEN
949
950         IF NEW.postcode IS NULL THEN
951             -- most likely just a part of a multipolygon postcode boundary, throw it away
952             RETURN NULL;
953         END IF;
954
955         NEW.name := 'ref'=>NEW.postcode;
956
957         IF NEW.country_code = 'gb' THEN
958
959           IF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9][A-Z][A-Z])$' THEN
960             NEW.rank_search := 25;
961             NEW.rank_address := 5;
962           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9])$' THEN
963             NEW.rank_search := 23;
964             NEW.rank_address := 5;
965           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z])$' THEN
966             NEW.rank_search := 21;
967             NEW.rank_address := 5;
968           END IF;
969
970         ELSEIF NEW.country_code = 'de' THEN
971
972           IF NEW.postcode ~ '^([0-9]{5})$' THEN
973             NEW.rank_search := 21;
974             NEW.rank_address := 11;
975           END IF;
976
977         ELSE
978           -- Guess at the postcode format and coverage (!)
979           IF upper(NEW.postcode) ~ '^[A-Z0-9]{1,5}$' THEN -- Probably too short to be very local
980             NEW.rank_search := 21;
981             NEW.rank_address := 11;
982           ELSE
983             -- Does it look splitable into and area and local code?
984             postcode := substring(upper(NEW.postcode) from '^([- :A-Z0-9]+)([- :][A-Z0-9]+)$');
985
986             IF postcode IS NOT NULL THEN
987               NEW.rank_search := 25;
988               NEW.rank_address := 11;
989             ELSEIF NEW.postcode ~ '^[- :A-Z0-9]{6,}$' THEN
990               NEW.rank_search := 21;
991               NEW.rank_address := 11;
992             END IF;
993           END IF;
994         END IF;
995
996     ELSEIF NEW.class = 'place' THEN
997       IF NEW.type in ('continent') THEN
998         NEW.rank_search := 2;
999         NEW.rank_address := NEW.rank_search;
1000       ELSEIF NEW.type in ('sea') THEN
1001         NEW.rank_search := 2;
1002         NEW.rank_address := 0;
1003       ELSEIF NEW.type in ('country') THEN
1004         NEW.rank_search := 4;
1005         NEW.rank_address := NEW.rank_search;
1006       ELSEIF NEW.type in ('state') THEN
1007         NEW.rank_search := 8;
1008         NEW.rank_address := NEW.rank_search;
1009       ELSEIF NEW.type in ('region') THEN
1010         NEW.rank_search := 18; -- dropped from previous value of 10
1011         NEW.rank_address := 0; -- So badly miss-used that better to just drop it!
1012       ELSEIF NEW.type in ('county') THEN
1013         NEW.rank_search := 12;
1014         NEW.rank_address := NEW.rank_search;
1015       ELSEIF NEW.type in ('city') THEN
1016         NEW.rank_search := 16;
1017         NEW.rank_address := NEW.rank_search;
1018       ELSEIF NEW.type in ('island') THEN
1019         NEW.rank_search := 17;
1020         NEW.rank_address := 0;
1021       ELSEIF NEW.type in ('town') THEN
1022         NEW.rank_search := 18;
1023         NEW.rank_address := 16;
1024       ELSEIF NEW.type in ('village','hamlet','municipality','district','unincorporated_area','borough') THEN
1025         NEW.rank_search := 19;
1026         NEW.rank_address := 16;
1027       ELSEIF NEW.type in ('airport') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1028         NEW.rank_search := 18;
1029         NEW.rank_address := 17;
1030       ELSEIF NEW.type in ('moor') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1031         NEW.rank_search := 17;
1032         NEW.rank_address := 18;
1033       ELSEIF NEW.type in ('moor') THEN
1034         NEW.rank_search := 17;
1035         NEW.rank_address := 0;
1036       ELSEIF NEW.type in ('national_park') THEN
1037         NEW.rank_search := 18;
1038         NEW.rank_address := 18;
1039       ELSEIF NEW.type in ('suburb','croft','subdivision') THEN
1040         NEW.rank_search := 20;
1041         NEW.rank_address := NEW.rank_search;
1042       ELSEIF NEW.type in ('farm','locality','islet','isolated_dwelling','mountain_pass') THEN
1043         NEW.rank_search := 20;
1044         NEW.rank_address := 0;
1045         -- Irish townlands, tagged as place=locality and locality=townland
1046         IF (NEW.extratags -> 'locality') = 'townland' THEN
1047           NEW.rank_address := 20;
1048         END IF;
1049       ELSEIF NEW.type in ('hall_of_residence','neighbourhood','housing_estate','nature_reserve') THEN
1050         NEW.rank_search := 22;
1051         NEW.rank_address := 22;
1052       ELSEIF NEW.type in ('airport','street') THEN
1053         NEW.rank_search := 26;
1054         NEW.rank_address := NEW.rank_search;
1055       ELSEIF NEW.type in ('house','building') THEN
1056         NEW.rank_search := 30;
1057         NEW.rank_address := NEW.rank_search;
1058       ELSEIF NEW.type in ('houses') THEN
1059         -- can't guarantee all required nodes loaded yet due to caching in osm2pgsql
1060         -- insert new point into place for each derived building
1061         --i := create_interpolation(NEW.osm_id, NEW.housenumber);
1062         NEW.rank_search := 28;
1063         NEW.rank_address := 0;
1064       END IF;
1065
1066     ELSEIF NEW.class = 'boundary' THEN
1067       IF ST_GeometryType(NEW.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon') THEN
1068 --        RAISE WARNING 'invalid boundary %',NEW.osm_id;
1069         return NULL;
1070       END IF;
1071       NEW.rank_search := NEW.admin_level * 2;
1072       NEW.rank_address := NEW.rank_search;
1073     ELSEIF NEW.class = 'landuse' AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1074       NEW.rank_search := 22;
1075       NEW.rank_address := NEW.rank_search;
1076     -- any feature more than 5 square miles is probably worth indexing
1077     ELSEIF ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_Area(NEW.geometry) > 0.1 THEN
1078       NEW.rank_search := 22;
1079       NEW.rank_address := NEW.rank_search;
1080     ELSEIF NEW.class = 'highway' AND NEW.name is NULL AND 
1081            NEW.type in ('service','cycleway','path','footway','steps','bridleway','track','byway','motorway_link','primary_link','trunk_link','secondary_link','tertiary_link') THEN
1082 --      RAISE WARNING 'unnamed minor feature %',NEW.osm_id;
1083       RETURN NULL;
1084     ELSEIF NEW.class = 'railway' AND NEW.type in ('rail') THEN
1085       RETURN NULL;
1086     ELSEIF NEW.class = 'waterway' AND NEW.name is NULL THEN
1087       RETURN NULL;
1088     ELSEIF NEW.class = 'waterway' THEN
1089       NEW.rank_address := 17;
1090     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
1091       NEW.rank_search := 27;
1092       NEW.rank_address := NEW.rank_search;
1093     ELSEIF NEW.class = 'highway' AND NEW.osm_type != 'N' THEN
1094       NEW.rank_search := 26;
1095       NEW.rank_address := NEW.rank_search;
1096     ELSEIF NEW.class = 'natural' and NEW.type = 'sea' THEN
1097       NEW.rank_search := 4;
1098       NEW.rank_address := NEW.rank_search;
1099     ELSEIF NEW.class = 'natural' and NEW.type in ('coastline') THEN
1100       RETURN NULL;
1101     ELSEIF NEW.class = 'natural' and NEW.type in ('peak','volcano') THEN
1102       NEW.rank_search := 18;
1103       NEW.rank_address := 0;
1104     END IF;
1105
1106   END IF;
1107
1108   IF NEW.rank_search > 30 THEN
1109     NEW.rank_search := 30;
1110   END IF;
1111
1112   IF NEW.rank_address > 30 THEN
1113     NEW.rank_address := 30;
1114   END IF;
1115
1116   IF (NEW.extratags -> 'capital') = 'yes' THEN
1117     NEW.rank_search := NEW.rank_search -1;
1118   END IF;
1119
1120 -- Block import below rank 22
1121 --  IF NEW.rank_search > 22 THEN
1122 --    RETURN NULL;
1123 --  END IF;
1124
1125   RETURN NEW;  -- The following is not needed until doing diff updates, and slows the main index process down
1126
1127   IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
1128     -- Performance: We just can't handle re-indexing for country level changes
1129     IF st_area(NEW.geometry) < 1 THEN
1130       -- mark items within the geometry for re-indexing
1131 --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1132
1133       -- work around bug in postgis, this may have been fixed in 2.0.0 (see http://trac.osgeo.org/postgis/ticket/547)
1134       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1135        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);
1136       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1137        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);
1138     END IF;
1139   ELSE
1140     -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
1141     diameter := 0;
1142     -- 16 = city, anything higher than city is effectively ignored (polygon required!)
1143     IF NEW.type='postcode' THEN
1144       diameter := 0.05;
1145     ELSEIF NEW.rank_search < 16 THEN
1146       diameter := 0;
1147     ELSEIF NEW.rank_search < 18 THEN
1148       diameter := 0.1;
1149     ELSEIF NEW.rank_search < 20 THEN
1150       diameter := 0.05;
1151     ELSEIF NEW.rank_search = 21 THEN
1152       diameter := 0.001;
1153     ELSEIF NEW.rank_search < 24 THEN
1154       diameter := 0.02;
1155     ELSEIF NEW.rank_search < 26 THEN
1156       diameter := 0.002; -- 100 to 200 meters
1157     ELSEIF NEW.rank_search < 28 THEN
1158       diameter := 0.001; -- 50 to 100 meters
1159     END IF;
1160     IF diameter > 0 THEN
1161 --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
1162       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);
1163     END IF;
1164
1165   END IF;
1166
1167    -- add to tables for special search
1168    -- Note: won't work on initial import because the classtype tables
1169    -- do not yet exist. It won't hurt either.
1170   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
1171   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable INTO result;
1172   IF result THEN
1173     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
1174     USING NEW.place_id, ST_Centroid(NEW.geometry);
1175   END IF;
1176
1177
1178 --  IF NEW.rank_search < 26 THEN
1179 --    RAISE WARNING 'placex insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1180 --  END IF;
1181
1182   RETURN NEW;
1183
1184 END;
1185 $$
1186 LANGUAGE plpgsql;
1187
1188 CREATE OR REPLACE FUNCTION placex_update() RETURNS 
1189 TRIGGER
1190   AS $$
1191 DECLARE
1192
1193   place_centroid GEOMETRY;
1194
1195   search_maxdistance FLOAT[];
1196   search_mindistance FLOAT[];
1197   address_havelevel BOOLEAN[];
1198 --  search_scores wordscore[];
1199 --  search_scores_pos INTEGER;
1200
1201   i INTEGER;
1202   iMax FLOAT;
1203   location RECORD;
1204   way RECORD;
1205   relation RECORD;
1206   relation_members TEXT[];
1207   relMember RECORD;
1208   linkedplacex RECORD;
1209   search_diameter FLOAT;
1210   search_prevdiameter FLOAT;
1211   search_maxrank INTEGER;
1212   address_maxrank INTEGER;
1213   address_street_word_id INTEGER;
1214   parent_place_id_rank BIGINT;
1215   
1216   isin TEXT[];
1217   isin_tokens INT[];
1218
1219   location_rank_search INTEGER;
1220   location_distance FLOAT;
1221
1222   tagpairid INTEGER;
1223
1224   default_language TEXT;
1225   name_vector INTEGER[];
1226   nameaddress_vector INTEGER[];
1227
1228   linked_node_id BIGINT;
1229
1230   result BOOLEAN;
1231 BEGIN
1232
1233 --RAISE WARNING '%',NEW.place_id;
1234 --RAISE WARNING '%', NEW;
1235
1236   IF NEW.class = 'place' AND NEW.type = 'postcodearea' THEN
1237     -- Silently do nothing
1238     RETURN NEW;
1239   END IF;
1240
1241   -- deferred delete
1242   IF OLD.indexed_status = 100 THEN
1243     delete from placex where place_id = OLD.place_id;
1244     RETURN NULL;
1245   END IF;
1246
1247   IF NEW.indexed_status = 0 and OLD.indexed_status != 0 THEN
1248
1249     NEW.indexed_date = now();
1250
1251     IF NEW.class = 'place' AND NEW.type = 'houses' THEN
1252       i := create_interpolation(NEW.osm_id, NEW.housenumber);
1253       RETURN NEW;
1254     END IF;
1255
1256     IF OLD.indexed_status > 1 THEN
1257       result := deleteSearchName(NEW.partition, NEW.place_id);
1258       DELETE FROM place_addressline WHERE place_id = NEW.place_id;
1259       DELETE FROM place_boundingbox where place_id = NEW.place_id;
1260       result := deleteRoad(NEW.partition, NEW.place_id);
1261       result := deleteLocationArea(NEW.partition, NEW.place_id);
1262       UPDATE placex set linked_place_id = null where linked_place_id = NEW.place_id;
1263     END IF;
1264
1265     -- reclaculate country and partition (should probably have a country_code and calculated_country_code as seperate fields)
1266     IF NEW.rank_search >= 4 THEN
1267       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;
1268       NEW.country_code := lower(get_country_code(NEW.geometry, NEW.country_code));
1269     ELSE
1270       NEW.country_code := NULL;
1271     END IF;
1272     NEW.partition := get_partition(NEW.geometry, NEW.country_code);
1273     NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
1274
1275     -- Adding ourselves to the list simplifies address calculations later
1276     INSERT INTO place_addressline VALUES (NEW.place_id, NEW.place_id, true, true, 0, NEW.rank_address); 
1277
1278     -- What level are we searching from
1279     search_maxrank := NEW.rank_search;
1280
1281     -- Speed up searches - just use the centroid of the feature
1282     -- cheaper but less acurate
1283     place_centroid := ST_Centroid(NEW.geometry);
1284     NEW.centroid := null;
1285
1286     -- Thought this wasn't needed but when we add new languages to the country_name table
1287     -- we need to update the existing names
1288     IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
1289       default_language := get_country_language_code(NEW.country_code);
1290       IF default_language IS NOT NULL THEN
1291         IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
1292           NEW.name := NEW.name || (('name:'||default_language) => (NEW.name -> 'name'));
1293         ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
1294           NEW.name := NEW.name || ('name' => (NEW.name -> ('name:'||default_language)));
1295         END IF;
1296       END IF;
1297     END IF;
1298
1299     -- Initialise the name vector using our name
1300     name_vector := make_keywords(NEW.name);
1301     nameaddress_vector := '{}'::int[];
1302
1303     -- some tag combinations add a special id for search
1304     tagpairid := get_tagpair(NEW.class,NEW.type);
1305     IF tagpairid IS NOT NULL THEN
1306       name_vector := name_vector + tagpairid;
1307     END IF;
1308
1309     FOR i IN 1..28 LOOP
1310       address_havelevel[i] := false;
1311     END LOOP;
1312
1313     NEW.importance := null;
1314     select language||':'||title,importance from get_wikipedia_match(NEW.extratags) INTO NEW.wikipedia,NEW.importance;
1315     IF NEW.importance IS NULL THEN
1316       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;
1317     END IF;
1318
1319 --RAISE WARNING '% %', NEW.place_id, NEW.rank_search;
1320
1321     -- For low level elements we inherit from our parent road
1322     IF (NEW.rank_search > 27 OR (NEW.type = 'postcode' AND NEW.rank_search = 25)) THEN
1323
1324 --RAISE WARNING 'finding street for %', NEW;
1325
1326       NEW.parent_place_id := null;
1327
1328       -- to do that we have to find our parent road
1329       -- Copy data from linked items (points on ways, addr:street links, relations)
1330       -- Note that addr:street links can only be indexed once the street itself is indexed
1331       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'N' THEN
1332
1333         -- Is this node part of a relation?
1334         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id] and members @> ARRAY['n'||NEW.osm_id]
1335         LOOP
1336           -- At the moment we only process one type of relation - associatedStreet
1337           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1338             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1339               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1340 --RAISE WARNING 'node in relation %',relation;
1341                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1342                   and rank_search = 26 INTO NEW.parent_place_id;
1343               END IF;
1344             END LOOP;
1345           END IF;
1346         END LOOP;      
1347
1348 --RAISE WARNING 'x1';
1349         -- Is this node part of a way?
1350         FOR way IN select id from planet_osm_ways where nodes @> ARRAY[NEW.osm_id] LOOP
1351 --RAISE WARNING '%', way;
1352         FOR location IN select * from placex where osm_type = 'W' and osm_id = way.id
1353         LOOP
1354 --RAISE WARNING '%', location;
1355           -- Way IS a road then we are on it - that must be our road
1356           IF location.rank_search = 26 AND NEW.parent_place_id IS NULL THEN
1357 --RAISE WARNING 'node in way that is a street %',location;
1358             NEW.parent_place_id := location.place_id;
1359           END IF;
1360
1361           -- Is the WAY part of a relation
1362           IF NEW.parent_place_id IS NULL THEN
1363               FOR relation IN select * from planet_osm_rels where parts @> ARRAY[location.osm_id] and members @> ARRAY['w'||location.osm_id]
1364               LOOP
1365                 -- At the moment we only process one type of relation - associatedStreet
1366                 IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1367                   FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1368                     IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1369     --RAISE WARNING 'node in way that is in a relation %',relation;
1370                       SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1371                         and rank_search = 26 INTO NEW.parent_place_id;
1372                     END IF;
1373                   END LOOP;
1374                 END IF;
1375               END LOOP;
1376           END IF;    
1377           
1378           -- If the way contains an explicit name of a street copy it
1379           IF NEW.street IS NULL AND location.street IS NOT NULL THEN
1380 --RAISE WARNING 'node in way that has a streetname %',location;
1381             NEW.street := location.street;
1382           END IF;
1383
1384           -- If this way is a street interpolation line then it is probably as good as we are going to get
1385           IF NEW.parent_place_id IS NULL AND NEW.street IS NULL AND location.class = 'place' and location.type='houses' THEN
1386             -- Try and find a way that is close roughly parellel to this line
1387             FOR relation IN SELECT place_id FROM placex
1388               WHERE ST_DWithin(location.geometry, placex.geometry, 0.001) and placex.rank_search = 26
1389                 and st_geometrytype(location.geometry) in ('ST_LineString')
1390               ORDER BY (ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0))+
1391                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0.5))+
1392                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,1))) ASC limit 1
1393             LOOP
1394 --RAISE WARNING 'using nearest street to address interpolation line,0.001 %',relation;
1395               NEW.parent_place_id := relation.place_id;
1396             END LOOP;
1397           END IF;
1398
1399         END LOOP;
1400         END LOOP;
1401                 
1402       END IF;
1403
1404 --RAISE WARNING 'x2';
1405
1406       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'W' THEN
1407         -- Is this way part of a relation?
1408         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id] and members @> ARRAY['w'||NEW.osm_id]
1409         LOOP
1410           -- At the moment we only process one type of relation - associatedStreet
1411           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1412             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1413               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1414 --RAISE WARNING 'way that is in a relation %',relation;
1415                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer
1416                   and rank_search = 26 INTO NEW.parent_place_id;
1417               END IF;
1418             END LOOP;
1419           END IF;
1420         END LOOP;
1421       END IF;
1422       
1423 --RAISE WARNING 'x3 %',NEW.parent_place_id;
1424
1425       IF NEW.parent_place_id IS NULL AND NEW.street IS NOT NULL THEN
1426         address_street_word_id := get_name_id(make_standard_name(NEW.street));
1427         IF address_street_word_id IS NOT NULL THEN
1428           FOR location IN SELECT * from getNearestNamedRoadFeature(NEW.partition, place_centroid, address_street_word_id) LOOP
1429             NEW.parent_place_id := location.place_id;
1430           END LOOP;
1431         END IF;
1432       END IF;
1433
1434 --RAISE WARNING 'x4 %',NEW.parent_place_id;
1435       -- Still nothing, just use the nearest road
1436       IF NEW.parent_place_id IS NULL THEN
1437         FOR location IN SELECT place_id FROM getNearestRoadFeature(NEW.partition, place_centroid) LOOP
1438           NEW.parent_place_id := location.place_id;
1439         END LOOP;
1440       END IF;
1441
1442 --return NEW;
1443 --RAISE WARNING 'x6 %',NEW.parent_place_id;
1444
1445       -- If we didn't find any road fallback to standard method
1446       IF NEW.parent_place_id IS NOT NULL THEN
1447
1448         -- Add the street to the address as zero distance to force to front of list
1449 --        INSERT INTO place_addressline VALUES (NEW.place_id, NEW.parent_place_id, true, true, 0, 26);
1450         address_havelevel[26] := true;
1451
1452         -- Import address details from parent, reclculating distance in process
1453 --        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
1454 --          from place_addressline as x join placex on (address_place_id = placex.place_id)
1455 --          where x.place_id = NEW.parent_place_id and x.address_place_id != NEW.parent_place_id;
1456
1457         -- Get the details of the parent road
1458         select * from search_name where place_id = NEW.parent_place_id INTO location;
1459         NEW.country_code := location.country_code;
1460
1461 --RAISE WARNING '%', NEW.name;
1462         -- If there is no name it isn't searchable, don't bother to create a search record
1463         IF NEW.name is NULL THEN
1464           return NEW;
1465         END IF;
1466
1467         -- Merge address from parent
1468         nameaddress_vector := array_merge(nameaddress_vector, location.nameaddress_vector);
1469 --return NEW;
1470         -- Performance, it would be more acurate to do all the rest of the import process but it takes too long
1471         -- Just be happy with inheriting from parent road only
1472
1473         IF NEW.rank_search <= 25 THEN
1474           result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1475         END IF;
1476
1477         result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, NEW.importance, place_centroid);
1478
1479         return NEW;
1480       END IF;
1481
1482     END IF;
1483
1484 -- RAISE WARNING '  INDEXING: %',NEW;
1485
1486     IF NEW.osm_type = 'R' AND NEW.rank_search < 26 THEN
1487
1488       -- see if we have any special relation members
1489       select members from planet_osm_rels where id = NEW.osm_id INTO relation_members;
1490
1491       FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['label']) as member LOOP
1492
1493         select * from placex where osm_type = upper(substring(relMember.member,1,1)) 
1494           and osm_id = substring(relMember.member,2,10000)::integer order by rank_search desc limit 1 into linkedPlacex;
1495
1496         -- If we don't already have one use this as the centre point of the geometry
1497         IF NEW.centroid IS NULL THEN
1498           NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1499         END IF;
1500
1501         -- merge in the label name, re-init word vector
1502         NEW.name := linkedPlacex.name || NEW.name;
1503         name_vector := make_keywords(NEW.name);
1504
1505         -- merge in extra tags
1506         NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1507
1508         -- mark the linked place (excludes from search results)
1509         UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1510
1511       END LOOP;
1512
1513       IF NEW.centroid IS NULL THEN
1514
1515         FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['admin_center','admin_centre']) as member LOOP
1516
1517           select * from placex where osm_type = upper(substring(relMember.member,1,1)) 
1518             and osm_id = substring(relMember.member,2,10000)::integer order by rank_search desc limit 1 into linkedPlacex;
1519
1520           -- For an admin centre we also want a name match - still not perfect, for example 'new york, new york'
1521           -- But that can be fixed by explicitly setting the label in the data
1522           IF make_standard_name(NEW.name->'name') = make_standard_name(linkedPlacex.name->'name') 
1523             AND NEW.rank_search = linkedPlacex.rank_search THEN
1524
1525             -- If we don't already have one use this as the centre point of the geometry
1526             IF NEW.centroid IS NULL THEN
1527               NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1528             END IF;
1529
1530             -- merge in the name, re-init word vector
1531             NEW.name := linkedPlacex.name || NEW.name;
1532             name_vector := make_keywords(NEW.name);
1533
1534             -- merge in extra tags
1535             NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1536
1537             -- mark the linked place (excludes from search results)
1538             UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1539
1540             -- keep a note of the node id in case we need it for wikipedia in a bit
1541             linked_node_id := linkedPlacex.osm_id;
1542           END IF;
1543
1544         END LOOP;
1545
1546       END IF;
1547
1548       -- not found one yet? how about doing a name search
1549       IF NEW.centroid IS NULL AND (NEW.name->'name') is not null and make_standard_name(NEW.name->'name') != '' THEN
1550
1551         FOR linkedPlacex IN select placex.* from placex WHERE
1552           make_standard_name(name->'name') = make_standard_name(NEW.name->'name')
1553           AND placex.rank_search = NEW.rank_search
1554           AND placex.place_id != NEW.place_id
1555           AND placex.osm_type = 'N' AND placex.rank_search < 26
1556           AND st_contains(NEW.geometry, placex.geometry)
1557         LOOP
1558
1559           -- If we don't already have one use this as the centre point of the geometry
1560           IF NEW.centroid IS NULL THEN
1561             NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1562           END IF;
1563
1564           -- merge in the name, re-init word vector
1565           NEW.name := linkedPlacex.name || NEW.name;
1566           name_vector := make_keywords(NEW.name);
1567
1568           -- merge in extra tags
1569           NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1570
1571           -- mark the linked place (excludes from search results)
1572           UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1573
1574           -- keep a note of the node id in case we need it for wikipedia in a bit
1575           linked_node_id := linkedPlacex.osm_id;
1576         END LOOP;
1577       END IF;
1578
1579       IF NEW.centroid IS NOT NULL THEN
1580         place_centroid := NEW.centroid;
1581       END IF;
1582
1583       -- Did we gain a wikipedia tag in the process? then we need to recalculate our importance
1584       IF NEW.importance is null THEN
1585         select language||':'||title,importance from get_wikipedia_match(NEW.extratags) INTO NEW.wikipedia,NEW.importance;
1586       END IF;
1587       -- Still null? how about looking it up by the node id
1588       IF NEW.importance IS NULL THEN
1589         select language||':'||title,importance from wikipedia_article where osm_type = 'N' and osm_id = linked_node_id order by importance desc limit 1 INTO NEW.wikipedia,NEW.importance;
1590       END IF;
1591
1592     END IF;
1593
1594     NEW.parent_place_id = 0;
1595     parent_place_id_rank = 0;
1596
1597     -- convert isin to array of tokenids
1598     isin_tokens := '{}'::int[];
1599     IF NEW.isin IS NOT NULL THEN
1600       isin := regexp_split_to_array(NEW.isin, E'[;,]');
1601       IF array_upper(isin, 1) IS NOT NULL THEN
1602         FOR i IN 1..array_upper(isin, 1) LOOP
1603           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1604           IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1605             isin_tokens := isin_tokens || address_street_word_id;
1606           END IF;
1607         END LOOP;
1608       END IF;
1609     END IF;
1610     IF NEW.postcode IS NOT NULL THEN
1611       isin := regexp_split_to_array(NEW.postcode, E'[;,]');
1612       IF array_upper(isin, 1) IS NOT NULL THEN
1613         FOR i IN 1..array_upper(isin, 1) LOOP
1614           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1615           IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1616             isin_tokens := isin_tokens || address_street_word_id;
1617           END IF;
1618         END LOOP;
1619       END IF;
1620     END IF;
1621 --RAISE WARNING 'ISIN: %', isin_tokens;
1622
1623     -- Process area matches
1624     location_rank_search := 100;
1625     location_distance := 0;
1626 --RAISE WARNING '  getNearFeatures(%,''%'',%,''%'')',NEW.partition, place_centroid, search_maxrank, isin_tokens;
1627     FOR location IN SELECT * from getNearFeatures(NEW.partition, place_centroid, search_maxrank, isin_tokens) LOOP
1628
1629 --RAISE WARNING '  AREA: %',location;
1630
1631       IF location.rank_search < location_rank_search THEN
1632         location_rank_search := location.rank_search;
1633         location_distance := location.distance * 1.5;
1634       END IF;
1635
1636       IF location.distance < location_distance OR NOT location.isguess THEN
1637
1638         -- Add it to the list of search terms
1639         nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1640         INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, NOT address_havelevel[location.rank_address], location.distance, location.rank_address); 
1641         address_havelevel[location.rank_address] := true;
1642
1643 --RAISE WARNING '  Terms: (%) %',location, nameaddress_vector;
1644
1645         IF location.rank_address > parent_place_id_rank THEN
1646           NEW.parent_place_id = location.place_id;
1647           parent_place_id_rank = location.rank_address;
1648         END IF;
1649
1650       END IF;
1651
1652     END LOOP;
1653
1654     -- try using the isin value to find parent places
1655     IF array_upper(isin_tokens, 1) IS NOT NULL THEN
1656       FOR i IN 1..array_upper(isin_tokens, 1) LOOP
1657 --RAISE WARNING '  getNearestNamedFeature: % % % %',NEW.partition, place_centroid, search_maxrank, isin_tokens[i];
1658
1659         FOR location IN SELECT * from getNearestNamedFeature(NEW.partition, place_centroid, search_maxrank, isin_tokens[i]) LOOP
1660
1661 --RAISE WARNING '  ISIN: %',location;
1662
1663           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1664           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, false, NOT address_havelevel[location.rank_address], location.distance, location.rank_address);
1665           address_havelevel[location.rank_address] := true;
1666
1667           IF location.rank_address > parent_place_id_rank THEN
1668             NEW.parent_place_id = location.place_id;
1669             parent_place_id_rank = location.rank_address;
1670           END IF;
1671
1672         END LOOP;
1673
1674       END LOOP;
1675     END IF;
1676
1677     -- for long ways we should add search terms for the entire length
1678     IF st_length(NEW.geometry) > 0.05 THEN
1679
1680       location_rank_search := 100;
1681       location_distance := 0;
1682
1683       FOR location IN SELECT * from getNearFeatures(NEW.partition, NEW.geometry, search_maxrank, isin_tokens) LOOP
1684
1685         IF location.rank_search < location_rank_search THEN
1686           location_rank_search := location.rank_search;
1687           location_distance := location.distance * 1.5;
1688         END IF;
1689
1690         IF location.distance < location_distance THEN
1691
1692           -- Add it to the list of search terms
1693           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1694           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, false, location.distance, location.rank_address); 
1695
1696         END IF;
1697
1698       END LOOP;
1699
1700     END IF;
1701
1702     -- if we have a name add this to the name search table
1703     IF NEW.name IS NOT NULL THEN
1704
1705       IF NEW.rank_search <= 25 THEN
1706         result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1707       END IF;
1708
1709       IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1710         result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1711       END IF;
1712
1713       result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, NEW.importance, place_centroid);
1714
1715 --      INSERT INTO search_name values (NEW.place_id, NEW.rank_search, NEW.rank_search, 0, NEW.country_code, name_vector, nameaddress_vector, place_centroid);
1716     END IF;
1717
1718     -- If we've not managed to pick up a better one - default centroid
1719     IF NEW.centroid IS NULL THEN
1720       NEW.centroid := place_centroid;
1721     END IF;
1722
1723   END IF;
1724
1725   RETURN NEW;
1726 END;
1727 $$
1728 LANGUAGE plpgsql;
1729
1730 CREATE OR REPLACE FUNCTION placex_delete() RETURNS TRIGGER
1731   AS $$
1732 DECLARE
1733   b BOOLEAN;
1734   classtable TEXT;
1735 BEGIN
1736
1737   update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1738   update placex set indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1739
1740   IF OLD.rank_address < 30 THEN
1741
1742     -- mark everything linked to this place for re-indexing
1743     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1744       and placex.place_id = place_addressline.place_id and indexed_status = 0;
1745
1746     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1747
1748     b := deleteRoad(OLD.partition, OLD.place_id);
1749
1750     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1751
1752   END IF;
1753
1754   IF OLD.rank_address < 26 THEN
1755     b := deleteLocationArea(OLD.partition, OLD.place_id);
1756   END IF;
1757
1758   IF OLD.name is not null THEN
1759     b := deleteSearchName(OLD.partition, OLD.place_id);
1760   END IF;
1761
1762   DELETE FROM place_addressline where place_id = OLD.place_id;
1763
1764   -- remove from tables for special search
1765   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1766   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable INTO b;
1767   IF b THEN
1768     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1769   END IF;
1770
1771   RETURN OLD;
1772
1773 END;
1774 $$
1775 LANGUAGE plpgsql;
1776
1777 CREATE OR REPLACE FUNCTION place_delete() RETURNS TRIGGER
1778   AS $$
1779 DECLARE
1780   placeid BIGINT;
1781 BEGIN
1782
1783 --  RAISE WARNING 'delete: % % % %',OLD.osm_type,OLD.osm_id,OLD.class,OLD.type;
1784
1785   -- deleting large polygons can have a massive effect ont he system - require manual intervention to let them through
1786   IF st_area(OLD.geometry) > 2 THEN
1787     insert into import_polygon_delete values (OLD.osm_type,OLD.osm_id,OLD.class,OLD.type);
1788     RETURN NULL;
1789   END IF;
1790
1791   -- mark for delete
1792   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;
1793
1794 --  delete from placex where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1795   RETURN OLD;
1796
1797 END;
1798 $$
1799 LANGUAGE plpgsql;
1800
1801 CREATE OR REPLACE FUNCTION place_insert() RETURNS TRIGGER
1802   AS $$
1803 DECLARE
1804   i INTEGER;
1805   existing RECORD;
1806   existingplacex RECORD;
1807   existinggeometry GEOMETRY;
1808   existingplace_id BIGINT;
1809   result BOOLEAN;
1810   partition INTEGER;
1811 BEGIN
1812
1813   IF FALSE and NEW.osm_type = 'R' THEN
1814     RAISE WARNING '-----------------------------------------------------------------------------------';
1815     RAISE WARNING 'place_insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,st_area(NEW.geometry);
1816     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;
1817     RAISE WARNING '%', existingplacex;
1818   END IF;
1819
1820   -- Just block these - lots and pointless
1821   IF NEW.class = 'highway' and NEW.type in ('turning_circle','traffic_signals','mini_roundabout','noexit','crossing') THEN
1822     RETURN null;
1823   END IF;
1824   IF NEW.class in ('landuse','natural') and NEW.name is null THEN
1825     RETURN null;
1826   END IF;
1827
1828   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  
1829     INSERT INTO import_polygon_error values (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.country_code, 
1830       now(), ST_IsValidReason(NEW.geometry), null, NEW.geometry);
1831 --    RAISE WARNING 'Invalid Geometry: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1832     RETURN null;
1833   END IF;
1834
1835   -- Patch in additional country names
1836   IF NEW.admin_level = 2 AND NEW.type = 'administrative' AND NEW.country_code is not null THEN
1837     select country_name.name || NEW.name from country_name where country_name.country_code = lower(NEW.country_code) INTO NEW.name;
1838   END IF;
1839     
1840   -- Have we already done this place?
1841   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;
1842
1843   -- Get the existing place_id
1844   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;
1845
1846   -- Handle a place changing type by removing the old data
1847   -- My generated 'place' types are causing havok because they overlap with real keys
1848   -- TODO: move them to their own special purpose key/class to avoid collisions
1849   IF existing.osm_type IS NULL AND (NEW.type not in ('postcode','house','houses')) THEN
1850     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');
1851   END IF;
1852
1853 --  RAISE WARNING 'Existing: %',existing.place_id;
1854
1855   -- Log and discard 
1856   IF existing.geometry is not null AND st_isvalid(existing.geometry) 
1857     AND st_area(existing.geometry) > 0.02
1858     AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')
1859     AND st_area(NEW.geometry) < st_area(existing.geometry)*0.5
1860     THEN
1861     INSERT INTO import_polygon_error values (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.country_code, now(), 
1862       'Area reduced from '||st_area(existing.geometry)||' to '||st_area(NEW.geometry), existing.geometry, NEW.geometry);
1863     RETURN null;
1864   END IF;
1865
1866   DELETE from import_polygon_error where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1867   DELETE from import_polygon_delete where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1868
1869   -- 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
1870   IF existing.osm_type IS NULL 
1871      OR existingplacex.osm_type IS NULL
1872      OR coalesce(existing.admin_level, 100) != coalesce(NEW.admin_level, 100) 
1873      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
1874      OR (existing.geometry::text != NEW.geometry::text AND ST_Distance(ST_Centroid(existing.geometry),ST_Centroid(NEW.geometry)) > 0.01 AND NOT
1875      (ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')))
1876      THEN
1877
1878 --  IF existing.osm_type IS NULL THEN
1879 --    RAISE WARNING 'no existing place';
1880 --  END IF;
1881 --  IF existingplacex.osm_type IS NULL THEN
1882 --    RAISE WARNING 'no existing placex %', existingplacex;
1883 --  END IF;
1884
1885 --    RAISE WARNING 'delete and replace';
1886
1887     IF existing.osm_type IS NOT NULL THEN
1888 --      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;
1889       DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1890     END IF;   
1891
1892 --    RAISE WARNING 'delete and replace2';
1893
1894     -- No - process it as a new insertion (hopefully of low rank or it will be slow)
1895     insert into placex (osm_type, osm_id, class, type, name, admin_level, housenumber, 
1896       street, isin, postcode, country_code, extratags, geometry)
1897       values (NEW.osm_type
1898         ,NEW.osm_id
1899         ,NEW.class
1900         ,NEW.type
1901         ,NEW.name
1902         ,NEW.admin_level
1903         ,NEW.housenumber
1904         ,NEW.street
1905         ,NEW.isin
1906         ,NEW.postcode
1907         ,NEW.country_code
1908         ,NEW.extratags
1909         ,NEW.geometry
1910         );
1911
1912 --    RAISE WARNING 'insert done % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1913
1914     RETURN NEW;
1915   END IF;
1916
1917   -- Various ways to do the update
1918
1919   -- Debug, what's changed?
1920   IF FALSE THEN
1921     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') THEN
1922       RAISE WARNING 'update details, name: % % % %',NEW.osm_type,NEW.osm_id,existing.name::text,NEW.name::text;
1923     END IF;
1924     IF coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '') THEN
1925       RAISE WARNING 'update details, housenumber: % % % %',NEW.osm_type,NEW.osm_id,existing.housenumber,NEW.housenumber;
1926     END IF;
1927     IF coalesce(existing.street, '') != coalesce(NEW.street, '') THEN
1928       RAISE WARNING 'update details, street: % % % %',NEW.osm_type,NEW.osm_id,existing.street,NEW.street;
1929     END IF;
1930     IF coalesce(existing.isin, '') != coalesce(NEW.isin, '') THEN
1931       RAISE WARNING 'update details, isin: % % % %',NEW.osm_type,NEW.osm_id,existing.isin,NEW.isin;
1932     END IF;
1933     IF coalesce(existing.postcode, '') != coalesce(NEW.postcode, '') THEN
1934       RAISE WARNING 'update details, postcode: % % % %',NEW.osm_type,NEW.osm_id,existing.postcode,NEW.postcode;
1935     END IF;
1936     IF coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1937       RAISE WARNING 'update details, country_code: % % % %',NEW.osm_type,NEW.osm_id,existing.country_code,NEW.country_code;
1938     END IF;
1939   END IF;
1940
1941   -- Special case for polygon shape changes because they tend to be large and we can be a bit clever about how we handle them
1942   IF existing.geometry::text != NEW.geometry::text 
1943      AND ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon')
1944      AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') 
1945      THEN 
1946
1947     -- Get the version of the geometry actually used (in placex table)
1948     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;
1949
1950     -- Performance limit
1951     IF st_area(NEW.geometry) < 0.000000001 AND st_area(existinggeometry) < 1 THEN
1952
1953       -- 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
1954       update placex set indexed_status = 2 where indexed_status = 0 and 
1955           (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1956           AND NOT (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1957           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1958
1959       update placex set indexed_status = 2 where indexed_status = 0 and 
1960           (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1961           AND NOT (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1962           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1963
1964     END IF;
1965
1966   END IF;
1967
1968   -- Special case - if we are just adding extra words we hack them into the search_name table rather than reindexing
1969   IF FALSE AND existingplacex.rank_search < 26
1970      AND coalesce(existing.housenumber, '') = coalesce(NEW.housenumber, '')
1971      AND coalesce(existing.street, '') = coalesce(NEW.street, '')
1972      AND coalesce(existing.isin, '') = coalesce(NEW.isin, '')
1973      AND coalesce(existing.postcode, '') = coalesce(NEW.postcode, '')
1974      AND coalesce(existing.country_code, '') = coalesce(NEW.country_code, '')
1975      AND coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') 
1976      THEN
1977
1978     IF NOT update_location_nameonly(existingplacex.place_id, NEW.name) THEN
1979
1980       IF st_area(NEW.geometry) < 0.5 THEN
1981         UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
1982           and placex.place_id = place_addressline.place_id and indexed_status = 0
1983           and (rank_search < 28 or name is not null);
1984       END IF;
1985
1986     END IF;
1987   
1988   ELSE
1989
1990     -- Anything else has changed - reindex the lot
1991     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1992         OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
1993         OR coalesce(existing.street, '') != coalesce(NEW.street, '')
1994         OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
1995         OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
1996         OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1997
1998       -- performance, can't take the load of re-indexing a whole country / huge area
1999       IF st_area(NEW.geometry) < 0.5 THEN
2000 --        UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
2001 --          and placex.place_id = place_addressline.place_id and indexed_status = 0;
2002       END IF;
2003
2004     END IF;
2005
2006   END IF;
2007
2008   IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
2009      OR coalesce(existing.extratags::text, '') != coalesce(NEW.extratags::text, '')
2010      OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
2011      OR coalesce(existing.street, '') != coalesce(NEW.street, '')
2012      OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
2013      OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
2014      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
2015      OR existing.geometry::text != NEW.geometry::text
2016      THEN
2017
2018     update place set 
2019       name = NEW.name,
2020       housenumber  = NEW.housenumber,
2021       street = NEW.street,
2022       isin = NEW.isin,
2023       postcode = NEW.postcode,
2024       country_code = NEW.country_code,
2025       extratags = NEW.extratags,
2026       geometry = NEW.geometry
2027       where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
2028
2029     update placex set 
2030       name = NEW.name,
2031       housenumber = NEW.housenumber,
2032       street = NEW.street,
2033       isin = NEW.isin,
2034       postcode = NEW.postcode,
2035       country_code = NEW.country_code,
2036       parent_place_id = null,
2037       extratags = NEW.extratags,
2038       indexed_status = 2,    
2039       geometry = NEW.geometry
2040       where place_id = existingplacex.place_id;
2041
2042 -- now done as part of insert
2043 --    partition := get_partition(NEW.geometry, existingplacex.country_code);
2044 --    result := update_location(partition, existingplacex.place_id, existingplacex.country_code, NEW.name, existingplacex.rank_search, existingplacex.rank_address, NEW.geometry);
2045
2046   END IF;
2047
2048   -- Abort the add (we modified the existing place instead)
2049   RETURN NULL;
2050
2051 END; 
2052 $$ LANGUAGE plpgsql;
2053
2054 CREATE OR REPLACE FUNCTION get_name_by_language(name hstore, languagepref TEXT[]) RETURNS TEXT
2055   AS $$
2056 DECLARE
2057   search TEXT[];
2058   found BOOLEAN;
2059 BEGIN
2060
2061   IF name is null THEN
2062     RETURN null;
2063   END IF;
2064
2065   search := languagepref;
2066
2067   FOR j IN 1..array_upper(search, 1) LOOP
2068     IF name ? search[j] AND trim(name->search[j]) != '' THEN
2069       return trim(name->search[j]);
2070     END IF;
2071   END LOOP;
2072
2073   RETURN null;
2074 END;
2075 $$
2076 LANGUAGE plpgsql IMMUTABLE;
2077
2078 CREATE OR REPLACE FUNCTION get_connected_ways(way_ids INTEGER[]) RETURNS SETOF planet_osm_ways
2079   AS $$
2080 DECLARE
2081   searchnodes INTEGER[];
2082   location RECORD;
2083   j INTEGER;
2084 BEGIN
2085
2086   searchnodes := '{}';
2087   FOR j IN 1..array_upper(way_ids, 1) LOOP
2088     FOR location IN 
2089       select nodes from planet_osm_ways where id = way_ids[j] LIMIT 1
2090     LOOP
2091       IF not (ARRAY[location.nodes] <@ searchnodes) THEN
2092         searchnodes := searchnodes || location.nodes;
2093       END IF;
2094     END LOOP;
2095   END LOOP;
2096
2097   RETURN QUERY select * from planet_osm_ways where nodes && searchnodes and NOT ARRAY[id] <@ way_ids;
2098 END;
2099 $$
2100 LANGUAGE plpgsql IMMUTABLE;
2101
2102 CREATE OR REPLACE FUNCTION get_address_postcode(for_place_id BIGINT) RETURNS TEXT
2103   AS $$
2104 DECLARE
2105   result TEXT[];
2106   search TEXT[];
2107   for_postcode TEXT;
2108   found INTEGER;
2109   location RECORD;
2110 BEGIN
2111
2112   found := 1000;
2113   search := ARRAY['ref'];
2114   result := '{}';
2115
2116   select postcode from placex where place_id = for_place_id limit 1 into for_postcode;
2117
2118   FOR location IN 
2119     select rank_address,name,distance,length(name::text) as namelength 
2120       from place_addressline join placex on (address_place_id = placex.place_id) 
2121       where place_addressline.place_id = for_place_id and rank_address in (5,11)
2122       order by rank_address desc,rank_search desc,fromarea desc,distance asc,namelength desc
2123   LOOP
2124     IF array_upper(search, 1) IS NOT NULL AND array_upper(location.name, 1) IS NOT NULL THEN
2125       FOR j IN 1..array_upper(search, 1) LOOP
2126         FOR k IN 1..array_upper(location.name, 1) LOOP
2127           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
2128             result[(100 - location.rank_address)] := trim(location.name[k].value);
2129             found := location.rank_address;
2130           END IF;
2131         END LOOP;
2132       END LOOP;
2133     END IF;
2134   END LOOP;
2135
2136   RETURN array_to_string(result,', ');
2137 END;
2138 $$
2139 LANGUAGE plpgsql;
2140
2141 CREATE OR REPLACE FUNCTION get_address_by_language(for_place_id BIGINT, languagepref TEXT[]) RETURNS TEXT
2142   AS $$
2143 DECLARE
2144   result TEXT[];
2145   currresult TEXT;
2146   prevresult TEXT;
2147   location RECORD;
2148 BEGIN
2149
2150   result := '{}';
2151   prevresult := '';
2152
2153   FOR location IN select * from get_addressdata(for_place_id) where isaddress order by rank_address desc LOOP
2154     currresult := trim(get_name_by_language(location.name, languagepref));
2155     IF currresult != prevresult AND currresult IS NOT NULL THEN
2156       result[(100 - location.rank_address)] := trim(get_name_by_language(location.name, languagepref));
2157       prevresult := currresult;
2158     END IF;
2159   END LOOP;
2160
2161   RETURN array_to_string(result,', ');
2162 END;
2163 $$
2164 LANGUAGE plpgsql;
2165
2166 DROP TYPE addressline CASCADE;
2167 create type addressline as (
2168   place_id BIGINT,
2169   osm_type CHAR(1),
2170   osm_id INTEGER,
2171   name HSTORE,
2172   class TEXT,
2173   type TEXT,
2174   admin_level INTEGER,
2175   fromarea BOOLEAN,  
2176   isaddress BOOLEAN,  
2177   rank_address INTEGER,
2178   distance FLOAT
2179 );
2180
2181 CREATE OR REPLACE FUNCTION get_addressdata(in_place_id BIGINT) RETURNS setof addressline 
2182   AS $$
2183 DECLARE
2184   for_place_id BIGINT;
2185   result TEXT[];
2186   search TEXT[];
2187   found INTEGER;
2188   location RECORD;
2189   countrylocation RECORD;
2190   searchcountrycode varchar(2);
2191   searchhousenumber TEXT;
2192   searchhousename HSTORE;
2193   searchrankaddress INTEGER;
2194   searchpostcode TEXT;
2195   searchclass TEXT;
2196   searchtype TEXT;
2197   countryname HSTORE;
2198   hadcountry BOOLEAN;
2199 BEGIN
2200
2201   select parent_place_id,'us', housenumber, 30, postcode, null, 'place', 'house' from location_property_tiger 
2202     WHERE place_id = in_place_id 
2203     INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2204
2205   IF for_place_id IS NULL THEN
2206     select parent_place_id,'us', housenumber, 30, postcode, null, 'place', 'house' from location_property_aux
2207       WHERE place_id = in_place_id 
2208       INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2209   END IF;
2210
2211   IF for_place_id IS NULL THEN
2212     select parent_place_id, country_code, housenumber, rank_address, postcode, name, class, type from placex 
2213       WHERE place_id = in_place_id and rank_address = 30 
2214       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2215   END IF;
2216
2217   IF for_place_id IS NULL THEN
2218     for_place_id := in_place_id;
2219     select country_code, housenumber, rank_address, postcode, null from placex where place_id = for_place_id 
2220       INTO searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
2221   END IF;
2222
2223 --RAISE WARNING '% % % %',searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode;
2224
2225   found := 1000;
2226   hadcountry := false;
2227   FOR location IN 
2228     select placex.place_id, osm_type, osm_id,
2229       CASE WHEN class = 'place' and type = 'postcode' THEN 'name' => postcode ELSE name END as name,
2230       class, type, admin_level, true as fromarea, true as isaddress,
2231       CASE WHEN rank_address = 0 THEN 100 WHEN rank_address = 11 THEN 5 ELSE rank_address END as rank_address,
2232       0 as distance, country_code
2233       from placex
2234       where place_id = for_place_id 
2235   LOOP
2236 --RAISE WARNING '%',location;
2237     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2238       searchcountrycode := location.country_code;
2239     END IF;
2240     IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
2241       location.isaddress := FALSE;
2242     END IF;
2243     IF location.rank_address = 4 AND location.isaddress THEN
2244       hadcountry := true;
2245     END IF;
2246     IF location.rank_address < 4 AND NOT hadcountry THEN
2247       select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2248       IF countryname IS NOT NULL THEN
2249         countrylocation := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2250         RETURN NEXT countrylocation;
2251       END IF;
2252     END IF;
2253     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id, location.name, location.class, 
2254                            location.type, location.admin_level, location.fromarea, location.isaddress, location.rank_address, 
2255                            location.distance)::addressline;
2256     RETURN NEXT countrylocation;
2257     found := location.rank_address;
2258   END LOOP;
2259
2260   FOR location IN 
2261     select placex.place_id, osm_type, osm_id,
2262       CASE WHEN class = 'place' and type = 'postcode' THEN 'name' => postcode ELSE name END as name,
2263       class, type, admin_level, fromarea, isaddress,
2264       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,
2265       distance,country_code
2266       from place_addressline join placex on (address_place_id = placex.place_id) 
2267       where place_addressline.place_id = for_place_id 
2268       and (cached_rank_address > 0 AND cached_rank_address < searchrankaddress)
2269       and address_place_id != for_place_id
2270       and (placex.country_code IS NULL OR searchcountrycode IS NULL OR placex.country_code = searchcountrycode OR rank_address < 4)
2271       order by rank_address desc,isaddress desc,fromarea desc,distance asc,rank_search desc
2272   LOOP
2273 --RAISE WARNING '%',location;
2274     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2275       searchcountrycode := location.country_code;
2276     END IF;
2277     IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
2278       location.isaddress := FALSE;
2279     END IF;
2280     IF location.rank_address = 4 AND location.isaddress THEN
2281       hadcountry := true;
2282     END IF;
2283     IF location.rank_address < 4 AND NOT hadcountry THEN
2284       select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2285       IF countryname IS NOT NULL THEN
2286         countrylocation := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2287         RETURN NEXT countrylocation;
2288       END IF;
2289     END IF;
2290     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id, location.name, location.class, 
2291                            location.type, location.admin_level, location.fromarea, location.isaddress, location.rank_address, 
2292                            location.distance)::addressline;
2293     RETURN NEXT countrylocation;
2294     found := location.rank_address;
2295   END LOOP;
2296
2297   IF found > 4 THEN
2298     select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2299 --RAISE WARNING '% % %',found,searchcountrycode,countryname;
2300     IF countryname IS NOT NULL THEN
2301       location := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2302       RETURN NEXT location;
2303     END IF;
2304   END IF;
2305
2306   IF searchcountrycode IS NOT NULL THEN
2307     location := ROW(null, null, null, 'ref'=>searchcountrycode, 'place', 'country_code', null, true, false, 4, 0)::addressline;
2308     RETURN NEXT location;
2309   END IF;
2310
2311   IF searchhousename IS NOT NULL THEN
2312     location := ROW(in_place_id, null, null, searchhousename, searchclass, searchtype, null, true, true, 29, 0)::addressline;
2313 --    location := ROW(in_place_id, null, null, searchhousename, 'place', 'house_name', null, true, true, 29, 0)::addressline;
2314     RETURN NEXT location;
2315   END IF;
2316
2317   IF searchhousenumber IS NOT NULL THEN
2318     location := ROW(in_place_id, null, null, 'ref'=>searchhousenumber, 'place', 'house_number', null, true, true, 28, 0)::addressline;
2319     RETURN NEXT location;
2320   END IF;
2321
2322   IF searchpostcode IS NOT NULL THEN
2323     location := ROW(null, null, null, 'ref'=>searchpostcode, 'place', 'postcode', null, true, true, 5, 0)::addressline;
2324     RETURN NEXT location;
2325   END IF;
2326
2327   RETURN;
2328 END;
2329 $$
2330 LANGUAGE plpgsql;
2331
2332 CREATE OR REPLACE FUNCTION get_place_boundingbox(search_place_id BIGINT) RETURNS place_boundingbox
2333   AS $$
2334 DECLARE
2335   result place_boundingbox;
2336   numfeatures integer;
2337 BEGIN
2338   select * from place_boundingbox into result where place_id = search_place_id;
2339   IF result.place_id IS NULL THEN
2340 -- remove  isaddress = true because if there is a matching polygon it always wins
2341     select count(*) from place_addressline where address_place_id = search_place_id into numfeatures;
2342     insert into place_boundingbox select place_id,
2343              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2344              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2345              numfeatures, ST_Area(geometry),
2346              geometry as area from location_area where place_id = search_place_id;
2347     select * from place_boundingbox into result where place_id = search_place_id;
2348   END IF;
2349   IF result.place_id IS NULL THEN
2350 -- TODO 0.0001
2351     insert into place_boundingbox select address_place_id,
2352              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2353              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2354              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2355              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2356              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) 
2357              where address_place_id = search_place_id
2358 --               and (isaddress = true OR place_id = search_place_id)
2359                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2360              group by address_place_id limit 1;
2361     select * from place_boundingbox into result where place_id = search_place_id;
2362   END IF;
2363   return result;
2364 END;
2365 $$
2366 LANGUAGE plpgsql;
2367
2368 -- don't do the operation if it would be slow
2369 CREATE OR REPLACE FUNCTION get_place_boundingbox_quick(search_place_id BIGINT) RETURNS place_boundingbox
2370   AS $$
2371 DECLARE
2372   result place_boundingbox;
2373   numfeatures integer;
2374   rank integer;
2375 BEGIN
2376   select * from place_boundingbox into result where place_id = search_place_id;
2377   IF result IS NULL AND rank > 14 THEN
2378     select count(*) from place_addressline where address_place_id = search_place_id and isaddress = true into numfeatures;
2379     insert into place_boundingbox select place_id,
2380              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2381              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2382              numfeatures, ST_Area(geometry),
2383              geometry as area from location_area where place_id = search_place_id;
2384     select * from place_boundingbox into result where place_id = search_place_id;
2385   END IF;
2386   IF result IS NULL THEN
2387     select rank_search from placex where place_id = search_place_id into rank;
2388     IF rank > 20 THEN
2389 -- TODO 0.0001
2390       insert into place_boundingbox select address_place_id,
2391              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2392              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2393              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2394              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2395              from place_addressline join placex using (place_id) 
2396              where address_place_id = search_place_id 
2397                and (isaddress = true OR place_id = search_place_id)
2398                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2399              group by address_place_id limit 1;
2400       select * from place_boundingbox into result where place_id = search_place_id;
2401     END IF;
2402   END IF;
2403   return result;
2404 END;
2405 $$
2406 LANGUAGE plpgsql;
2407
2408 CREATE OR REPLACE FUNCTION update_place(search_place_id BIGINT) RETURNS BOOLEAN
2409   AS $$
2410 DECLARE
2411   result place_boundingbox;
2412   numfeatures integer;
2413 BEGIN
2414   update placex set 
2415       name = place.name,
2416       housenumber = place.housenumber,
2417       street = place.street,
2418       isin = place.isin,
2419       postcode = place.postcode,
2420       country_code = place.country_code,
2421       parent_place_id = null
2422       from place
2423       where placex.place_id = search_place_id 
2424         and place.osm_type = placex.osm_type and place.osm_id = placex.osm_id
2425         and place.class = placex.class and place.type = placex.type;
2426   update placex set indexed_status = 2 where place_id = search_place_id;
2427   update placex set indexed_status = 0 where place_id = search_place_id;
2428   return true;
2429 END;
2430 $$
2431 LANGUAGE plpgsql;
2432
2433 CREATE OR REPLACE FUNCTION get_searchrank_label(rank INTEGER) RETURNS TEXT
2434   AS $$
2435 DECLARE
2436 BEGIN
2437   IF rank < 2 THEN
2438     RETURN 'Continent';
2439   ELSEIF rank < 4 THEN
2440     RETURN 'Sea';
2441   ELSEIF rank < 8 THEN
2442     RETURN 'Country';
2443   ELSEIF rank < 12 THEN
2444     RETURN 'State';
2445   ELSEIF rank < 16 THEN
2446     RETURN 'County';
2447   ELSEIF rank = 16 THEN
2448     RETURN 'City';
2449   ELSEIF rank = 17 THEN
2450     RETURN 'Town / Island';
2451   ELSEIF rank = 18 THEN
2452     RETURN 'Village / Hamlet';
2453   ELSEIF rank = 20 THEN
2454     RETURN 'Suburb';
2455   ELSEIF rank = 21 THEN
2456     RETURN 'Postcode Area';
2457   ELSEIF rank = 22 THEN
2458     RETURN 'Croft / Farm / Locality / Islet';
2459   ELSEIF rank = 23 THEN
2460     RETURN 'Postcode Area';
2461   ELSEIF rank = 25 THEN
2462     RETURN 'Postcode Point';
2463   ELSEIF rank = 26 THEN
2464     RETURN 'Street / Major Landmark';
2465   ELSEIF rank = 27 THEN
2466     RETURN 'Minory Street / Path';
2467   ELSEIF rank = 28 THEN
2468     RETURN 'House / Building';
2469   ELSE
2470     RETURN 'Other: '||rank;
2471   END IF;
2472   
2473 END;
2474 $$
2475 LANGUAGE plpgsql;
2476
2477 CREATE OR REPLACE FUNCTION get_addressrank_label(rank INTEGER) RETURNS TEXT
2478   AS $$
2479 DECLARE
2480 BEGIN
2481   IF rank = 0 THEN
2482     RETURN 'None';
2483   ELSEIF rank < 2 THEN
2484     RETURN 'Continent';
2485   ELSEIF rank < 4 THEN
2486     RETURN 'Sea';
2487   ELSEIF rank = 5 THEN
2488     RETURN 'Postcode';
2489   ELSEIF rank < 8 THEN
2490     RETURN 'Country';
2491   ELSEIF rank < 12 THEN
2492     RETURN 'State';
2493   ELSEIF rank < 16 THEN
2494     RETURN 'County';
2495   ELSEIF rank = 16 THEN
2496     RETURN 'City';
2497   ELSEIF rank = 17 THEN
2498     RETURN 'Town / Village / Hamlet';
2499   ELSEIF rank = 20 THEN
2500     RETURN 'Suburb';
2501   ELSEIF rank = 21 THEN
2502     RETURN 'Postcode Area';
2503   ELSEIF rank = 22 THEN
2504     RETURN 'Croft / Farm / Locality / Islet';
2505   ELSEIF rank = 23 THEN
2506     RETURN 'Postcode Area';
2507   ELSEIF rank = 25 THEN
2508     RETURN 'Postcode Point';
2509   ELSEIF rank = 26 THEN
2510     RETURN 'Street / Major Landmark';
2511   ELSEIF rank = 27 THEN
2512     RETURN 'Minory Street / Path';
2513   ELSEIF rank = 28 THEN
2514     RETURN 'House / Building';
2515   ELSE
2516     RETURN 'Other: '||rank;
2517   END IF;
2518   
2519 END;
2520 $$
2521 LANGUAGE plpgsql;
2522
2523 CREATE OR REPLACE FUNCTION get_word_suggestion(srcword TEXT) RETURNS TEXT
2524   AS $$
2525 DECLARE
2526   trigramtoken TEXT;
2527   result TEXT;
2528 BEGIN
2529
2530   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2531   SELECT word FROM word WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 1 into result;
2532
2533   return result;
2534 END;
2535 $$
2536 LANGUAGE plpgsql;
2537
2538 CREATE OR REPLACE FUNCTION get_word_suggestions(srcword TEXT) RETURNS TEXT[]
2539   AS $$
2540 DECLARE
2541   trigramtoken TEXT;
2542   result TEXT[];
2543   r RECORD;
2544 BEGIN
2545
2546   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2547
2548   FOR r IN SELECT word,similarity(word_trigram, trigramtoken) as score FROM word 
2549     WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 4
2550   LOOP
2551     result[coalesce(array_upper(result,1)+1,1)] := r.word;
2552   END LOOP;
2553
2554   return result;
2555 END;
2556 $$
2557 LANGUAGE plpgsql;
2558
2559 CREATE OR REPLACE FUNCTION tigger_create_interpolation(linegeo GEOMETRY, in_startnumber INTEGER, 
2560   in_endnumber INTEGER, interpolationtype TEXT, 
2561   in_street TEXT, in_isin TEXT, in_postcode TEXT) RETURNS INTEGER
2562   AS $$
2563 DECLARE
2564   
2565   startnumber INTEGER;
2566   endnumber INTEGER;
2567   stepsize INTEGER;
2568   housenum INTEGER;
2569   newpoints INTEGER;
2570   numberrange INTEGER;
2571   rangestartnumber INTEGER;
2572   place_centroid GEOMETRY;
2573   out_partition INTEGER;
2574   out_parent_place_id BIGINT;
2575   location RECORD;
2576   address_street_word_id INTEGER;  
2577
2578 BEGIN
2579
2580   IF in_endnumber > in_startnumber THEN
2581     startnumber = in_startnumber;
2582     endnumber = in_endnumber;
2583   ELSE
2584     startnumber = in_endnumber;
2585     endnumber = in_startnumber;
2586   END IF;
2587
2588   numberrange := endnumber - startnumber;
2589   rangestartnumber := startnumber;
2590
2591   IF (interpolationtype = 'odd' AND startnumber%2 = 0) OR (interpolationtype = 'even' AND startnumber%2 = 1) THEN
2592     startnumber := startnumber + 1;
2593     stepsize := 2;
2594   ELSE
2595     IF (interpolationtype = 'odd' OR interpolationtype = 'even') THEN
2596       stepsize := 2;
2597     ELSE -- everything else assumed to be 'all'
2598       stepsize := 1;
2599     END IF;
2600   END IF;
2601
2602   -- Filter out really broken tiger data
2603   IF numberrange > 0 AND (numberrange::float/stepsize::float > 500) 
2604                     AND ST_length(linegeo)/(numberrange::float/stepsize::float) < 0.000001 THEN
2605     RAISE WARNING 'Road too short for number range % to % on %, % (%)',startnumber,endnumber,in_street,in_isin,
2606                   ST_length(linegeo)/(numberrange::float/stepsize::float);    
2607     RETURN 0;
2608   END IF;
2609
2610   place_centroid := ST_Centroid(linegeo);
2611   out_partition := get_partition(place_centroid, 'us');
2612   out_parent_place_id := null;
2613
2614   address_street_word_id := get_name_id(make_standard_name(in_street));
2615   IF address_street_word_id IS NOT NULL THEN
2616     FOR location IN SELECT * from getNearestNamedRoadFeature(out_partition, place_centroid, address_street_word_id) LOOP
2617       out_parent_place_id := location.place_id;
2618     END LOOP;
2619   END IF;
2620
2621   IF out_parent_place_id IS NULL THEN
2622     FOR location IN SELECT place_id FROM getNearestParellelRoadFeature(out_partition, linegeo) LOOP
2623       out_parent_place_id := location.place_id;
2624     END LOOP;    
2625   END IF;
2626
2627   IF out_parent_place_id IS NULL THEN
2628     FOR location IN SELECT place_id FROM getNearestRoadFeature(out_partition, place_centroid) LOOP
2629       out_parent_place_id := location.place_id;
2630     END LOOP;    
2631   END IF;
2632
2633   newpoints := 0;
2634   FOR housenum IN startnumber..endnumber BY stepsize LOOP
2635     insert into location_property_tiger (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2636     values (nextval('seq_place'), out_partition, out_parent_place_id, housenum, in_postcode,
2637       ST_Line_Interpolate_Point(linegeo, (housenum::float-rangestartnumber::float)/numberrange::float));
2638     newpoints := newpoints + 1;
2639   END LOOP;
2640
2641   RETURN newpoints;
2642 END;
2643 $$
2644 LANGUAGE plpgsql;
2645
2646 CREATE OR REPLACE FUNCTION aux_create_property(pointgeo GEOMETRY, in_housenumber TEXT, 
2647   in_street TEXT, in_isin TEXT, in_postcode TEXT, in_countrycode char(2)) RETURNS INTEGER
2648   AS $$
2649 DECLARE
2650
2651   newpoints INTEGER;
2652   place_centroid GEOMETRY;
2653   out_partition INTEGER;
2654   out_parent_place_id BIGINT;
2655   location RECORD;
2656   address_street_word_id INTEGER;  
2657   out_postcode TEXT;
2658
2659 BEGIN
2660
2661   place_centroid := ST_Centroid(pointgeo);
2662   out_partition := get_partition(place_centroid, in_countrycode);
2663   out_parent_place_id := null;
2664
2665   address_street_word_id := get_name_id(make_standard_name(in_street));
2666   IF address_street_word_id IS NOT NULL THEN
2667     FOR location IN SELECT * from getNearestNamedRoadFeature(out_partition, place_centroid, address_street_word_id) LOOP
2668       out_parent_place_id := location.place_id;
2669     END LOOP;
2670   END IF;
2671
2672   IF out_parent_place_id IS NULL THEN
2673     FOR location IN SELECT place_id FROM getNearestRoadFeature(out_partition, place_centroid) LOOP
2674       out_parent_place_id := location.place_id;
2675     END LOOP;    
2676   END IF;
2677
2678   out_postcode := in_postcode;
2679   IF out_postcode IS NULL THEN
2680     SELECT postcode from placex where place_id = out_parent_place_id INTO out_postcode;
2681   END IF;
2682   IF out_postcode IS NULL THEN
2683     out_postcode := getNearestPostcode(out_partition, place_centroid);
2684   END IF;
2685
2686   newpoints := 0;
2687   insert into location_property_aux (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2688     values (nextval('seq_place'), out_partition, out_parent_place_id, in_housenumber, out_postcode, place_centroid);
2689   newpoints := newpoints + 1;
2690
2691   RETURN newpoints;
2692 END;
2693 $$
2694 LANGUAGE plpgsql;
2695
2696 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], member TEXT) RETURNS TEXT[]
2697   AS $$
2698 DECLARE
2699   result TEXT[];
2700   i INTEGER;
2701 BEGIN
2702
2703   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2704     IF members[i+1] = member THEN
2705       result := result || members[i];
2706     END IF;
2707   END LOOP;
2708
2709   return result;
2710 END;
2711 $$
2712 LANGUAGE plpgsql;
2713
2714 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], memberLabels TEXT[]) RETURNS SETOF TEXT
2715   AS $$
2716 DECLARE
2717   i INTEGER;
2718 BEGIN
2719
2720   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2721     IF members[i+1] = ANY(memberLabels) THEN
2722       RETURN NEXT members[i];
2723     END IF;
2724   END LOOP;
2725
2726   RETURN;
2727 END;
2728 $$
2729 LANGUAGE plpgsql;
2730
2731 -- See: http://stackoverflow.com/questions/6410088/how-can-i-mimic-the-php-urldecode-function-in-postgresql
2732 CREATE OR REPLACE FUNCTION decode_url_part(p varchar) RETURNS varchar 
2733   AS $$
2734 SELECT convert_from(CAST(E'\\x' || array_to_string(ARRAY(
2735     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
2736     FROM regexp_matches($1, '%[0-9a-f][0-9a-f]|.', 'gi') AS r(m)
2737 ), '') AS bytea), 'UTF8');
2738 $$ 
2739 LANGUAGE SQL IMMUTABLE STRICT;
2740
2741 CREATE OR REPLACE FUNCTION catch_decode_url_part(p varchar) RETURNS varchar
2742   AS $$
2743 DECLARE
2744 BEGIN
2745   RETURN decode_url_part(p);
2746 EXCEPTION
2747   WHEN others THEN return null;
2748 END;
2749 $$
2750 LANGUAGE plpgsql IMMUTABLE;
2751
2752 DROP TYPE wikipedia_article_match CASCADE;
2753 create type wikipedia_article_match as (
2754   language TEXT,
2755   title TEXT,
2756   importance FLOAT
2757 );
2758
2759 CREATE OR REPLACE FUNCTION get_wikipedia_match(extratags HSTORE) RETURNS wikipedia_article_match
2760   AS $$
2761 DECLARE
2762   langs TEXT[];
2763   i INT;
2764   wiki_article TEXT;
2765   wiki_article_title TEXT;
2766   wiki_article_language TEXT;
2767   result wikipedia_article_match;
2768 BEGIN
2769   langs := ARRAY['','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'];
2770   i := 1;
2771   WHILE langs[i] IS NOT NULL LOOP
2772     wiki_article := extratags->(case when langs[i] = '' THEN 'wikipedia' ELSE 'wikipedia:'||langs[i] END);
2773     IF wiki_article is not null THEN
2774       wiki_article := replace(regexp_replace(wiki_article,E'(.*?)([a-z]+).wikipedia.org/wiki/',E'\\2:'),' ','_');
2775       wiki_article_title := split_part(wiki_article, ':', 2);
2776       IF wiki_article_title IS NULL OR wiki_article_title = '' THEN
2777         wiki_article_title := wiki_article;
2778         wiki_article_language := CASE WHEN langs[i] = '' THEN 'en' ELSE langs[i] END;
2779       ELSE
2780         wiki_article_language := lower(split_part(wiki_article, ':', 1));
2781       END IF;
2782
2783       select wikipedia_article.language,wikipedia_article.title,wikipedia_article.importance
2784         from wikipedia_article 
2785         where language = wiki_article_language and 
2786         (title = wiki_article_title OR title = catch_decode_url_part(wiki_article_title) OR title = replace(catch_decode_url_part(wiki_article_title),E'\\',''))
2787       UNION ALL
2788       select wikipedia_article.language,wikipedia_article.title,wikipedia_article.importance
2789         from wikipedia_redirect join wikipedia_article on (wikipedia_redirect.language = wikipedia_article.language and wikipedia_redirect.to_title = wikipedia_article.title)
2790         where wikipedia_redirect.language = wiki_article_language and 
2791         (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'\\',''))
2792       order by importance desc limit 1 INTO result;
2793
2794       IF result.language is not null THEN
2795         return result;
2796       END IF;
2797     END IF;
2798     i := i + 1;
2799   END LOOP;
2800   RETURN NULL;
2801 END;
2802 $$
2803 LANGUAGE plpgsql;