]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions.sql
e443849ada96150e1d762d0530bcf58cd1fe1fa1
[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     result := result | w;
332
333     words := string_to_array(s, ' ');
334     IF array_upper(words, 1) IS NOT NULL THEN
335       FOR j IN 1..array_upper(words, 1) LOOP
336         IF (words[j] != '') THEN
337           w = getorcreate_word_id(words[j]);
338           IF NOT (ARRAY[w] && result) THEN
339             result := result | w;
340           END IF;
341         END IF;
342       END LOOP;
343     END IF;
344
345     words := regexp_split_to_array(item.value, E'[,;()]');
346     IF array_upper(words, 1) != 1 THEN
347       FOR j IN 1..array_upper(words, 1) LOOP
348         s := make_standard_name(words[j]);
349         IF s != '' THEN
350           w := getorcreate_word_id(s);
351           IF NOT (ARRAY[w] && result) THEN
352             result := result | w;
353           END IF;
354         END IF;
355       END LOOP;
356     END IF;
357
358     s := regexp_replace(item.value, '市$', '');
359     IF s != item.value THEN
360       s := make_standard_name(s);
361       IF s != '' THEN
362         w := getorcreate_name_id(s, item.value);
363         IF NOT (ARRAY[w] && result) THEN
364           result := result | w;
365         END IF;
366       END IF;
367     END IF;
368
369   END LOOP;
370
371   RETURN result;
372 END;
373 $$
374 LANGUAGE plpgsql IMMUTABLE;
375
376 CREATE OR REPLACE FUNCTION make_keywords(src TEXT) RETURNS INTEGER[]
377   AS $$
378 DECLARE
379   result INTEGER[];
380   s TEXT;
381   w INTEGER;
382   words TEXT[];
383   i INTEGER;
384   j INTEGER;
385 BEGIN
386   result := '{}'::INTEGER[];
387
388   s := make_standard_name(src);
389   w := getorcreate_name_id(s);
390
391   IF NOT (ARRAY[w] && result) THEN
392     result := result || w;
393   END IF;
394
395   words := string_to_array(s, ' ');
396   IF array_upper(words, 1) IS NOT NULL THEN
397     FOR j IN 1..array_upper(words, 1) LOOP
398       IF (words[j] != '') THEN
399         w = getorcreate_word_id(words[j]);
400         IF NOT (ARRAY[w] && result) THEN
401           result := result || w;
402         END IF;
403       END IF;
404     END LOOP;
405   END IF;
406
407   RETURN result;
408 END;
409 $$
410 LANGUAGE plpgsql IMMUTABLE;
411
412 CREATE OR REPLACE FUNCTION get_word_score(wordscores wordscore[], words text[]) RETURNS integer
413   AS $$
414 DECLARE
415   idxword integer;
416   idxscores integer;
417   result integer;
418 BEGIN
419   IF (wordscores is null OR words is null) THEN
420     RETURN 0;
421   END IF;
422
423   result := 0;
424   FOR idxword in 1 .. array_upper(words, 1) LOOP
425     FOR idxscores in 1 .. array_upper(wordscores, 1) LOOP
426       IF wordscores[idxscores].word = words[idxword] THEN
427         result := result + wordscores[idxscores].score;
428       END IF;
429     END LOOP;
430   END LOOP;
431
432   RETURN result;
433 END;
434 $$
435 LANGUAGE plpgsql IMMUTABLE;
436
437 CREATE OR REPLACE FUNCTION get_country_code(place geometry) RETURNS TEXT
438   AS $$
439 DECLARE
440   place_centre GEOMETRY;
441   nearcountry RECORD;
442 BEGIN
443   place_centre := ST_Centroid(place);
444
445 --RAISE WARNING 'start: %', ST_AsText(place_centre);
446
447   -- Try for a OSM polygon first
448   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
449   LOOP
450     RETURN nearcountry.country_code;
451   END LOOP;
452
453 --RAISE WARNING 'osm fallback: %', ST_AsText(place_centre);
454
455   -- Try for OSM fallback data
456   FOR nearcountry IN select country_code from country_osm_grid where st_contains(geometry, place_centre) limit 1
457   LOOP
458     RETURN nearcountry.country_code;
459   END LOOP;
460
461 --RAISE WARNING 'natural earth: %', ST_AsText(place_centre);
462
463   -- Natural earth data (first fallback)
464   FOR nearcountry IN select country_code from country_naturalearthdata where st_contains(geometry, place_centre) limit 1
465   LOOP
466     RETURN nearcountry.country_code;
467   END LOOP;
468
469   -- Natural earth data (first fallback)
470   FOR nearcountry IN select country_code from country_naturalearthdata where st_distance(geometry, place_centre) < 0.5 limit 1
471   LOOP
472     RETURN nearcountry.country_code;
473   END LOOP;
474
475 --RAISE WARNING 'in country: %', ST_AsText(place_centre);
476
477   -- WorldBoundaries data (second fallback - think there might be something broken in this data)
478   FOR nearcountry IN select country_code from country where st_contains(geometry, place_centre) limit 1
479   LOOP
480     RETURN nearcountry.country_code;
481   END LOOP;
482
483 --RAISE WARNING 'near country: %', ST_AsText(place_centre);
484
485   -- Still not in a country - try nearest within ~12 miles of a country
486   FOR nearcountry IN select country_code from country where st_distance(geometry, place_centre) < 0.5 
487     order by st_distance(geometry, place) limit 1
488   LOOP
489     RETURN nearcountry.country_code;
490   END LOOP;
491
492   RETURN NULL;
493 END;
494 $$
495 LANGUAGE plpgsql IMMUTABLE;
496
497 CREATE OR REPLACE FUNCTION get_country_code(place geometry, in_country_code VARCHAR(2)) RETURNS TEXT
498   AS $$
499 DECLARE
500   nearcountry RECORD;
501 BEGIN
502   FOR nearcountry IN select country_code from country_name where country_code = lower(in_country_code)
503   LOOP
504     RETURN nearcountry.country_code;
505   END LOOP;
506   RETURN get_country_code(place);
507 END;
508 $$
509 LANGUAGE plpgsql IMMUTABLE;
510
511 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2)) RETURNS TEXT
512   AS $$
513 DECLARE
514   nearcountry RECORD;
515 BEGIN
516   FOR nearcountry IN select distinct country_default_language_code from country_name where country_code = search_country_code limit 1
517   LOOP
518     RETURN lower(nearcountry.country_default_language_code);
519   END LOOP;
520   RETURN NULL;
521 END;
522 $$
523 LANGUAGE plpgsql IMMUTABLE;
524
525 CREATE OR REPLACE FUNCTION get_partition(place geometry, in_country_code VARCHAR(10)) RETURNS INTEGER
526   AS $$
527 DECLARE
528   place_centre GEOMETRY;
529   nearcountry RECORD;
530 BEGIN
531   FOR nearcountry IN select partition from country_name where country_code = in_country_code
532   LOOP
533     RETURN nearcountry.partition;
534   END LOOP;
535   RETURN 0;
536 END;
537 $$
538 LANGUAGE plpgsql IMMUTABLE;
539
540 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id INTEGER) RETURNS BOOLEAN
541   AS $$
542 DECLARE
543 BEGIN
544   DELETE FROM location_area where place_id = OLD_place_id;
545 -- TODO:location_area
546   RETURN true;
547 END;
548 $$
549 LANGUAGE plpgsql;
550
551 CREATE OR REPLACE FUNCTION add_location(
552     place_id INTEGER,
553     country_code varchar(2),
554     partition INTEGER,
555     keywords INTEGER[],
556     rank_search INTEGER,
557     rank_address INTEGER,
558     geometry GEOMETRY
559   ) 
560   RETURNS BOOLEAN
561   AS $$
562 DECLARE
563   locationid INTEGER;
564   isarea BOOLEAN;
565   xmin INTEGER;
566   ymin INTEGER;
567   xmax INTEGER;
568   ymax INTEGER;
569   lon INTEGER;
570   lat INTEGER;
571   centroid GEOMETRY;
572   secgeo GEOMETRY;
573   secbox GEOMETRY;
574   diameter FLOAT;
575   x BOOLEAN;
576 BEGIN
577
578   IF rank_search > 25 THEN
579     RAISE EXCEPTION 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
580   END IF;
581
582 --  RAISE WARNING 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
583
584   x := deleteLocationArea(partition, place_id);
585
586   isarea := false;
587   IF (ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(geometry)) THEN
588
589     isArea := true;
590     centroid := ST_Centroid(geometry);
591
592     xmin := floor(st_xmin(geometry));
593     xmax := ceil(st_xmax(geometry));
594     ymin := floor(st_ymin(geometry));
595     ymax := ceil(st_ymax(geometry));
596
597     IF xmin = xmax OR ymin = ymax OR (xmax-xmin < 2 AND ymax-ymin < 2) THEN
598       x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, centroid, geometry);
599     ELSE
600 --      RAISE WARNING 'Spliting geometry: % to %, % to %', xmin, xmax, ymin, ymax;
601       FOR lon IN xmin..(xmax-1) LOOP
602         FOR lat IN ymin..(ymax-1) LOOP
603           secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(lon,lat),ST_Point(lon+1,lat+1)),4326);
604           IF st_intersects(geometry, secbox) THEN
605             secgeo := st_intersection(geometry, secbox);
606             IF NOT ST_IsEmpty(secgeo) AND ST_GeometryType(secgeo) in ('ST_Polygon','ST_MultiPolygon') THEN
607               x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, centroid, secgeo);
608             END IF;
609           END IF;
610         END LOOP;
611       END LOOP;
612     END IF;
613
614   ELSEIF rank_search < 26 THEN
615
616     diameter := 0.02;
617     IF rank_address = 0 THEN
618       diameter := 0.02;
619     ELSEIF rank_search <= 14 THEN
620       diameter := 1.2;
621     ELSEIF rank_search <= 15 THEN
622       diameter := 1;
623     ELSEIF rank_search <= 16 THEN
624       diameter := 0.5;
625     ELSEIF rank_search <= 17 THEN
626       diameter := 0.2;
627     ELSEIF rank_search <= 21 THEN
628       diameter := 0.05;
629     ELSEIF rank_search = 25 THEN
630       diameter := 0.005;
631     END IF;
632
633 --    RAISE WARNING 'adding % diameter %', place_id, diameter;
634
635     secgeo := ST_Buffer(geometry, diameter);
636     x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
637
638   ELSE
639
640     -- ~ 20meters
641     secgeo := ST_Buffer(geometry, 0.0002);
642     x := insertLocationAreaRoadNear(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
643
644     -- ~ 100meters
645     secgeo := ST_Buffer(geometry, 0.001);
646     x := insertLocationAreaRoadFar(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
647
648   END IF;
649
650   RETURN true;
651 END;
652 $$
653 LANGUAGE plpgsql;
654
655 CREATE OR REPLACE FUNCTION update_location(
656     partition INTEGER,
657     place_id INTEGER,
658     place_country_code varchar(2),
659     name hstore,
660     rank_search INTEGER,
661     rank_address INTEGER,
662     geometry GEOMETRY
663   ) 
664   RETURNS BOOLEAN
665   AS $$
666 DECLARE
667   b BOOLEAN;
668 BEGIN
669   b := deleteLocationArea(partition, place_id);
670 --  result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
671   RETURN add_location(place_id, place_country_code, name, rank_search, rank_address, geometry);
672 END;
673 $$
674 LANGUAGE plpgsql;
675
676 CREATE OR REPLACE FUNCTION search_name_add_words(parent_place_id INTEGER, to_add INTEGER[])
677   RETURNS BOOLEAN
678   AS $$
679 DECLARE
680   childplace RECORD;
681 BEGIN
682
683   IF #to_add = 0 THEN
684     RETURN true;
685   END IF;
686
687   -- this should just be an update, but it seems to do insane things to the index size (delete and insert doesn't)
688   FOR childplace IN select * from search_name,place_addressline 
689     where  address_place_id = parent_place_id
690       and search_name.place_id = place_addressline.place_id
691   LOOP
692     delete from search_name where place_id = childplace.place_id;
693     childplace.nameaddress_vector := uniq(sort_asc(childplace.nameaddress_vector + to_add));
694     IF childplace.place_id = parent_place_id THEN
695       childplace.name_vector := uniq(sort_asc(childplace.name_vector + to_add));
696     END IF;
697     insert into search_name (place_id, search_rank, address_rank, country_code, name_vector, nameaddress_vector, centroid) 
698       values (childplace.place_id, childplace.search_rank, childplace.address_rank, childplace.country_code, 
699         childplace.name_vector, childplace.nameaddress_vector, childplace.centroid);
700   END LOOP;
701
702   RETURN true;
703 END;
704 $$
705 LANGUAGE plpgsql;
706
707 CREATE OR REPLACE FUNCTION update_location_nameonly(partition INTEGER, OLD_place_id INTEGER, name hstore) RETURNS BOOLEAN
708   AS $$
709 DECLARE
710   newkeywords INTEGER[];
711   addedkeywords INTEGER[];
712   removedkeywords INTEGER[];
713 BEGIN
714
715   -- what has changed?
716   newkeywords := make_keywords(name);
717   select coalesce(newkeywords,'{}'::INTEGER[]) - coalesce(location_point.keywords,'{}'::INTEGER[]), 
718     coalesce(location_point.keywords,'{}'::INTEGER[]) - coalesce(newkeywords,'{}'::INTEGER[]) from location_point 
719     where place_id = OLD_place_id into addedkeywords, removedkeywords;
720
721 --  RAISE WARNING 'update_location_nameonly for %: new:% added:% removed:%', OLD_place_id, newkeywords, addedkeywords, removedkeywords;
722
723   IF #removedkeywords > 0 THEN
724     -- abort due to tokens removed
725     RETURN false;
726   END IF;
727   
728   IF #addedkeywords > 0 THEN
729     -- short circuit - no changes
730     RETURN true;
731   END IF;
732
733   UPDATE location_area set keywords = newkeywords where place_id = OLD_place_id;
734   RETURN search_name_add_words(OLD_place_id, addedkeywords);
735 END;
736 $$
737 LANGUAGE plpgsql;
738
739
740 CREATE OR REPLACE FUNCTION create_interpolation(wayid INTEGER, interpolationtype TEXT) RETURNS INTEGER
741   AS $$
742 DECLARE
743   
744   newpoints INTEGER;
745   waynodes integer[];
746   nodeid INTEGER;
747   prevnode RECORD;
748   nextnode RECORD;
749   startnumber INTEGER;
750   endnumber INTEGER;
751   stepsize INTEGER;
752   orginalstartnumber INTEGER;
753   originalnumberrange INTEGER;
754   housenum INTEGER;
755   linegeo GEOMETRY;
756   search_place_id INTEGER;
757   defpostalcode TEXT;
758
759   havefirstpoint BOOLEAN;
760   linestr TEXT;
761 BEGIN
762   newpoints := 0;
763   IF interpolationtype = 'odd' OR interpolationtype = 'even' OR interpolationtype = 'all' THEN
764
765     select postcode from placex where osm_type = 'W' and osm_id = wayid INTO defpostalcode;
766     select nodes from planet_osm_ways where id = wayid INTO waynodes;
767 --RAISE WARNING 'interpolation % % %',wayid,interpolationtype,waynodes;
768     IF array_upper(waynodes, 1) IS NOT NULL THEN
769
770       havefirstpoint := false;
771
772       FOR nodeidpos in 1..array_upper(waynodes, 1) LOOP
773
774         select min(place_id) from placex where osm_type = 'N' and osm_id = waynodes[nodeidpos]::INTEGER and type = 'house' INTO search_place_id;
775         IF search_place_id IS NULL THEN
776           -- null record of right type
777           select * from placex where osm_type = 'N' and osm_id = waynodes[nodeidpos]::INTEGER and type = 'house' limit 1 INTO nextnode;
778           select ST_SetSRID(ST_Point(lon::float/10000000,lat::float/10000000),4326) from planet_osm_nodes where id = waynodes[nodeidpos] INTO nextnode.geometry;
779         ELSE
780           select * from placex where place_id = search_place_id INTO nextnode;
781         END IF;
782
783 --RAISE WARNING 'interpolation node % % % ',nextnode.housenumber,ST_X(nextnode.geometry),ST_Y(nextnode.geometry);
784       
785         IF havefirstpoint THEN
786
787           -- add point to the line string
788           linestr := linestr||','||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
789           endnumber := ('0'||substring(nextnode.housenumber,'[0-9]+'))::integer;
790
791           IF startnumber IS NOT NULL and startnumber > 0 AND endnumber IS NOT NULL and endnumber > 0 THEN
792
793 --RAISE WARNING 'interpolation end % % ',nextnode.place_id,endnumber;
794
795             IF startnumber != endnumber THEN
796
797               linestr := linestr || ')';
798 --RAISE WARNING 'linestr %',linestr;
799               linegeo := ST_GeomFromText(linestr,4326);
800               linestr := 'LINESTRING('||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
801               IF (startnumber > endnumber) THEN
802                 housenum := endnumber;
803                 endnumber := startnumber;
804                 startnumber := housenum;
805                 linegeo := ST_Reverse(linegeo);
806               END IF;
807               orginalstartnumber := startnumber;
808               originalnumberrange := endnumber - startnumber;
809
810 -- Too much broken data worldwide for this test to be worth using
811 --              IF originalnumberrange > 500 THEN
812 --                RAISE WARNING 'Number block of % while processing % %', originalnumberrange, prevnode, nextnode;
813 --              END IF;
814
815               IF (interpolationtype = 'odd' AND startnumber%2 = 0) OR (interpolationtype = 'even' AND startnumber%2 = 1) THEN
816                 startnumber := startnumber + 1;
817                 stepsize := 2;
818               ELSE
819                 IF (interpolationtype = 'odd' OR interpolationtype = 'even') THEN
820                   startnumber := startnumber + 2;
821                   stepsize := 2;
822                 ELSE -- everything else assumed to be 'all'
823                   startnumber := startnumber + 1;
824                   stepsize := 1;
825                 END IF;
826               END IF;
827               endnumber := endnumber - 1;
828               delete from placex where osm_type = 'N' and osm_id = prevnode.osm_id and type = 'house' and place_id != prevnode.place_id;
829               FOR housenum IN startnumber..endnumber BY stepsize LOOP
830                 -- this should really copy postcodes but it puts a huge burdon on the system for no big benefit
831                 -- ideally postcodes should move up to the way
832                 insert into placex (osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode,
833                   country_code, parent_place_id, rank_address, rank_search, indexed_status, geometry)
834                   values ('N',prevnode.osm_id, prevnode.class, prevnode.type, prevnode.admin_level, housenum, prevnode.street, prevnode.isin, coalesce(prevnode.postcode, defpostalcode),
835                   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));
836                 newpoints := newpoints + 1;
837 --RAISE WARNING 'interpolation number % % ',prevnode.place_id,housenum;
838               END LOOP;
839             END IF;
840             havefirstpoint := false;
841           END IF;
842         END IF;
843
844         IF NOT havefirstpoint THEN
845           startnumber := ('0'||substring(nextnode.housenumber,'[0-9]+'))::integer;
846           IF startnumber IS NOT NULL AND startnumber > 0 THEN
847             havefirstpoint := true;
848             linestr := 'LINESTRING('||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
849             prevnode := nextnode;
850           END IF;
851 --RAISE WARNING 'interpolation start % % ',nextnode.place_id,startnumber;
852         END IF;
853       END LOOP;
854     END IF;
855   END IF;
856
857 --RAISE WARNING 'interpolation points % ',newpoints;
858
859   RETURN newpoints;
860 END;
861 $$
862 LANGUAGE plpgsql;
863
864 CREATE OR REPLACE FUNCTION placex_insert() RETURNS TRIGGER
865   AS $$
866 DECLARE
867   i INTEGER;
868   postcode TEXT;
869   result BOOLEAN;
870   country_code VARCHAR(2);
871   default_language VARCHAR(10);
872   diameter FLOAT;
873 BEGIN
874 --  RAISE WARNING '%',NEW.osm_id;
875
876   -- just block these
877   IF NEW.class = 'highway' and NEW.type in ('turning_circle','traffic_signals','mini_roundabout','noexit','crossing') THEN
878 --    RAISE WARNING 'bad highway %',NEW.osm_id;
879     RETURN null;
880   END IF;
881   IF NEW.class in ('landuse','natural') and NEW.name is null THEN
882 --    RAISE WARNING 'empty landuse %',NEW.osm_id;
883     RETURN null;
884   END IF;
885
886   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  
887     -- block all invalid geometary - just not worth the risk.  seg faults are causing serious problems.
888 --    RAISE WARNING 'invalid geometry %',NEW.osm_id;
889     RETURN NULL;
890
891     -- Dead code
892     IF NEW.osm_type = 'R' THEN
893       -- invalid multipolygons can crash postgis, don't even bother to try!
894       RETURN NULL;
895     END IF;
896     NEW.geometry := ST_buffer(NEW.geometry,0);
897     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  
898 --      RAISE WARNING 'Invalid geometary, rejecting: % %', NEW.osm_type, NEW.osm_id;
899       RETURN NULL;
900     END IF;
901   END IF;
902
903   NEW.place_id := nextval('seq_place');
904   NEW.indexed_status := 1; --STATUS_NEW
905
906   NEW.country_code := lower(get_country_code(NEW.geometry, NEW.country_code));
907   NEW.partition := get_partition(NEW.geometry, NEW.country_code);
908   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
909
910   -- copy 'name' to or from the default language (if there is a default language)
911   IF NEW.name is not null AND array_upper(%#NEW.name,1) > 1 THEN
912     default_language := get_country_language_code(NEW.country_code);
913     IF default_language IS NOT NULL THEN
914       IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
915         NEW.name := NEW.name || (('name:'||default_language) => (NEW.name -> 'name'));
916       ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
917         NEW.name := NEW.name || ('name' => (NEW.name -> 'name:'||default_language));
918       END IF;
919     END IF;
920   END IF;
921
922   IF NEW.admin_level > 15 THEN
923     NEW.admin_level := 15;
924   END IF;
925
926   IF NEW.housenumber IS NOT NULL THEN
927     i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
928   END IF;
929
930   IF NEW.osm_type = 'X' THEN
931     -- E'X'ternal records should already be in the right format so do nothing
932   ELSE
933     NEW.rank_search := 30;
934     NEW.rank_address := NEW.rank_search;
935
936     -- By doing in postgres we have the country available to us - currently only used for postcode
937     IF NEW.class = 'place' THEN
938       IF NEW.type in ('continent') THEN
939         NEW.rank_search := 2;
940         NEW.rank_address := NEW.rank_search;
941       ELSEIF NEW.type in ('sea') THEN
942         NEW.rank_search := 2;
943         NEW.rank_address := 0;
944       ELSEIF NEW.type in ('country') THEN
945         NEW.rank_search := 4;
946         NEW.rank_address := NEW.rank_search;
947       ELSEIF NEW.type in ('state') THEN
948         NEW.rank_search := 8;
949         NEW.rank_address := NEW.rank_search;
950       ELSEIF NEW.type in ('region') THEN
951         NEW.rank_search := 10;
952         NEW.rank_address := NEW.rank_search;
953       ELSEIF NEW.type in ('county') THEN
954         NEW.rank_search := 12;
955         NEW.rank_address := NEW.rank_search;
956       ELSEIF NEW.type in ('city') THEN
957         NEW.rank_search := 16;
958         NEW.rank_address := NEW.rank_search;
959       ELSEIF NEW.type in ('island') THEN
960         NEW.rank_search := 17;
961         NEW.rank_address := 0;
962       ELSEIF NEW.type in ('town') THEN
963         NEW.rank_search := 18;
964         NEW.rank_address := 16;
965       ELSEIF NEW.type in ('village','hamlet','municipality','district','unincorporated_area','borough') THEN
966         NEW.rank_search := 19;
967         NEW.rank_address := 16;
968       ELSEIF NEW.type in ('airport') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
969         NEW.rank_search := 18;
970         NEW.rank_address := 17;
971       ELSEIF NEW.type in ('moor') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
972         NEW.rank_search := 17;
973         NEW.rank_address := 18;
974       ELSEIF NEW.type in ('moor') THEN
975         NEW.rank_search := 17;
976         NEW.rank_address := 0;
977       ELSEIF NEW.type in ('national_park') THEN
978         NEW.rank_search := 18;
979         NEW.rank_address := 18;
980       ELSEIF NEW.type in ('suburb','croft','subdivision') THEN
981         NEW.rank_search := 20;
982         NEW.rank_address := NEW.rank_search;
983       ELSEIF NEW.type in ('farm','locality','islet') THEN
984         NEW.rank_search := 20;
985         NEW.rank_address := 0;
986       ELSEIF NEW.type in ('hall_of_residence','neighbourhood','housing_estate','nature_reserve') THEN
987         NEW.rank_search := 22;
988         NEW.rank_address := 22;
989       ELSEIF NEW.type in ('postcode') THEN
990
991         NEW.name := 'ref'=>NEW.postcode;
992
993         IF NEW.country_code = 'gb' THEN
994
995           IF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9][A-Z][A-Z])$' THEN
996             NEW.rank_search := 25;
997             NEW.rank_address := 5;
998           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9])$' THEN
999             NEW.rank_search := 23;
1000             NEW.rank_address := 5;
1001           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z])$' THEN
1002             NEW.rank_search := 21;
1003             NEW.rank_address := 5;
1004           END IF;
1005
1006         ELSEIF NEW.country_code = 'de' THEN
1007
1008           IF NEW.postcode ~ '^([0-9]{5})$' THEN
1009             NEW.rank_search := 21;
1010             NEW.rank_address := 11;
1011           END IF;
1012
1013         ELSE
1014           -- Guess at the postcode format and coverage (!)
1015           IF upper(NEW.postcode) ~ '^[A-Z0-9]{1,5}$' THEN -- Probably too short to be very local
1016             NEW.rank_search := 21;
1017             NEW.rank_address := 11;
1018           ELSE
1019             -- Does it look splitable into and area and local code?
1020             postcode := substring(upper(NEW.postcode) from '^([- :A-Z0-9]+)([- :][A-Z0-9]+)$');
1021
1022             IF postcode IS NOT NULL THEN
1023               NEW.rank_search := 25;
1024               NEW.rank_address := 11;
1025             ELSEIF NEW.postcode ~ '^[- :A-Z0-9]{6,}$' THEN
1026               NEW.rank_search := 21;
1027               NEW.rank_address := 11;
1028             END IF;
1029           END IF;
1030         END IF;
1031
1032       ELSEIF NEW.type in ('airport','street') THEN
1033         NEW.rank_search := 26;
1034         NEW.rank_address := NEW.rank_search;
1035       ELSEIF NEW.type in ('house','building') THEN
1036         NEW.rank_search := 30;
1037         NEW.rank_address := NEW.rank_search;
1038       ELSEIF NEW.type in ('houses') THEN
1039         -- can't guarantee all required nodes loaded yet due to caching in osm2pgsql
1040         -- insert new point into place for each derived building
1041         --i := create_interpolation(NEW.osm_id, NEW.housenumber);
1042         NEW.rank_search := 28;
1043         NEW.rank_address := 0;
1044       END IF;
1045
1046     ELSEIF NEW.class = 'boundary' THEN
1047       IF ST_GeometryType(NEW.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon') THEN
1048 --        RAISE WARNING 'invalid boundary %',NEW.osm_id;
1049         return NULL;
1050       END IF;
1051       NEW.rank_search := NEW.admin_level * 2;
1052       NEW.rank_address := NEW.rank_search;
1053     ELSEIF NEW.class = 'landuse' AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1054       NEW.rank_search := 22;
1055       NEW.rank_address := NEW.rank_search;
1056     -- any feature more than 5 square miles is probably worth indexing
1057     ELSEIF ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_Area(NEW.geometry) > 0.1 THEN
1058       NEW.rank_search := 22;
1059       NEW.rank_address := NEW.rank_search;
1060     ELSEIF NEW.class = 'highway' AND NEW.name is NULL AND 
1061            NEW.type in ('service','cycleway','path','footway','steps','bridleway','track','byway','motorway_link','primary_link','trunk_link','secondary_link','tertiary_link') THEN
1062 --      RAISE WARNING 'unnamed minor feature %',NEW.osm_id;
1063       RETURN NULL;
1064     ELSEIF NEW.class = 'railway' AND NEW.type in ('rail') THEN
1065       RETURN NULL;
1066     ELSEIF NEW.class = 'waterway' AND NEW.name is NULL THEN
1067       RETURN NULL;
1068     ELSEIF NEW.class = 'waterway' THEN
1069       NEW.rank_address := 17;
1070     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
1071       NEW.rank_search := 27;
1072       NEW.rank_address := NEW.rank_search;
1073     ELSEIF NEW.class = 'highway' AND NEW.osm_type != 'N' THEN
1074       NEW.rank_search := 26;
1075       NEW.rank_address := NEW.rank_search;
1076     ELSEIF NEW.class = 'natural' and NEW.type = 'sea' THEN
1077       NEW.rank_search := 4;
1078       NEW.rank_address := NEW.rank_search;
1079     ELSEIF NEW.class = 'natural' and NEW.type in ('coastline') THEN
1080       RETURN NULL;
1081     ELSEIF NEW.class = 'natural' and NEW.type in ('peak','volcano') THEN
1082       NEW.rank_search := 18;
1083       NEW.rank_address := 0;
1084     END IF;
1085
1086   END IF;
1087
1088   IF NEW.rank_search > 30 THEN
1089     NEW.rank_search := 30;
1090   END IF;
1091
1092   IF NEW.rank_address > 30 THEN
1093     NEW.rank_address := 30;
1094   END IF;
1095
1096   IF (NEW.extratags -> 'capital') = 'yes' THEN
1097     NEW.rank_search := NEW.rank_search -1;
1098   END IF;
1099
1100 -- Block import below rank 22
1101 --  IF NEW.rank_search > 22 THEN
1102 --    RETURN NULL;
1103 --  END IF;
1104
1105 --  RETURN NEW;  -- The following is not needed until doing diff updates, and slows the main index process down
1106
1107   IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
1108     -- Performance: We just can't handle re-indexing for country level changes
1109     IF st_area(NEW.geometry) < 1 THEN
1110       -- mark items within the geometry for re-indexing
1111 --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1112 -- work around bug in postgis
1113       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1114        AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) = 'ST_Point';
1115       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1116        AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) != 'ST_Point';
1117     END IF;
1118   ELSE
1119     -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
1120     diameter := 0;
1121     -- 16 = city, anything higher than city is effectively ignored (polygon required!)
1122     IF NEW.type='postcode' THEN
1123       diameter := 0.05;
1124     ELSEIF NEW.rank_search < 16 THEN
1125       diameter := 0;
1126     ELSEIF NEW.rank_search < 18 THEN
1127       diameter := 0.1;
1128     ELSEIF NEW.rank_search < 20 THEN
1129       diameter := 0.05;
1130     ELSEIF NEW.rank_search = 21 THEN
1131       diameter := 0.001;
1132     ELSEIF NEW.rank_search < 24 THEN
1133       diameter := 0.02;
1134     ELSEIF NEW.rank_search < 26 THEN
1135       diameter := 0.002; -- 100 to 200 meters
1136     ELSEIF NEW.rank_search < 28 THEN
1137       diameter := 0.001; -- 50 to 100 meters
1138     END IF;
1139     IF diameter > 0 THEN
1140 --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
1141       update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
1142     END IF;
1143
1144   END IF;
1145
1146 --  IF NEW.rank_search < 26 THEN
1147 --    RAISE WARNING 'placex insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1148 --  END IF;
1149
1150   RETURN NEW;
1151
1152 END;
1153 $$
1154 LANGUAGE plpgsql;
1155
1156 CREATE OR REPLACE FUNCTION placex_update() RETURNS 
1157 TRIGGER
1158   AS $$
1159 DECLARE
1160
1161   place_centroid GEOMETRY;
1162
1163   search_maxdistance FLOAT[];
1164   search_mindistance FLOAT[];
1165   address_havelevel BOOLEAN[];
1166 --  search_scores wordscore[];
1167 --  search_scores_pos INTEGER;
1168
1169   i INTEGER;
1170   iMax FLOAT;
1171   location RECORD;
1172   way RECORD;
1173   relation RECORD;
1174   search_diameter FLOAT;
1175   search_prevdiameter FLOAT;
1176   search_maxrank INTEGER;
1177   address_maxrank INTEGER;
1178   address_street_word_id INTEGER;
1179   parent_place_id_rank INTEGER;
1180   
1181   isin TEXT[];
1182   isin_tokens INT[];
1183
1184   location_rank_search INTEGER;
1185   location_distance FLOAT;
1186
1187   tagpairid INTEGER;
1188
1189   name_vector INTEGER[];
1190   nameaddress_vector INTEGER[];
1191
1192   result BOOLEAN;
1193 BEGIN
1194
1195 --RAISE WARNING '%',NEW.place_id;
1196 --RAISE WARNING '%', NEW;
1197
1198   IF NEW.class = 'place' AND NEW.type = 'postcodearea' THEN
1199     -- Silently do nothing
1200     RETURN NEW;
1201   END IF;
1202
1203   -- defered delete
1204   IF OLD.indexed_status = 100 THEN
1205     delete from placex where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1206     RETURN NULL;
1207   END IF;
1208
1209   IF NEW.indexed_status = 0 and OLD.indexed_status != 0 THEN
1210
1211     NEW.indexed_date = now();
1212
1213     IF NEW.class = 'place' AND NEW.type = 'houses' THEN
1214       i := create_interpolation(NEW.osm_id, NEW.housenumber);
1215       RETURN NEW;
1216     END IF;
1217
1218     result := deleteSearchName(NEW.partition, NEW.place_id);
1219     DELETE FROM place_addressline WHERE place_id = NEW.place_id;
1220     DELETE FROM place_boundingbox where place_id = NEW.place_id;
1221
1222     -- Adding ourselves to the list simplifies address calculations later
1223     INSERT INTO place_addressline VALUES (NEW.place_id, NEW.place_id, true, true, 0, NEW.rank_address); 
1224
1225     -- What level are we searching from
1226     search_maxrank := NEW.rank_search;
1227
1228     -- Speed up searches - just use the centroid of the feature
1229     -- cheaper but less acurate
1230     place_centroid := ST_Centroid(NEW.geometry);
1231
1232     -- Initialise the name vector using our name
1233     name_vector := make_keywords(NEW.name);
1234     nameaddress_vector := '{}'::int[];
1235
1236     -- some tag combinations add a special id for search
1237     tagpairid := get_tagpair(NEW.class,NEW.type);
1238     IF tagpairid IS NOT NULL THEN
1239       name_vector := name_vector + tagpairid;
1240     END IF;
1241
1242     FOR i IN 1..28 LOOP
1243       address_havelevel[i] := false;
1244     END LOOP;
1245
1246 --RAISE WARNING '% %', NEW.place_id, NEW.rank_search;
1247
1248     -- For low level elements we inherit from our parent road
1249     IF (NEW.rank_search > 27 OR (NEW.type = 'postcode' AND NEW.rank_search = 25)) THEN
1250
1251 --RAISE WARNING 'finding street for %', NEW;
1252
1253       NEW.parent_place_id := null;
1254
1255       -- to do that we have to find our parent road
1256       -- Copy data from linked items (points on ways, addr:street links, relations)
1257       -- Note that addr:street links can only be indexed once the street itself is indexed
1258       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'N' THEN
1259
1260         -- Is this node part of a relation?
1261         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id::integer] and members @> ARRAY['n'||NEW.osm_id]
1262         LOOP
1263           -- At the moment we only process one type of relation - associatedStreet
1264           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1265             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1266               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1267 --RAISE WARNING 'node in relation %',relation;
1268                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1269                   and rank_search = 26 INTO NEW.parent_place_id;
1270               END IF;
1271             END LOOP;
1272           END IF;
1273         END LOOP;      
1274
1275 --RAISE WARNING 'x1';
1276         -- Is this node part of a way?
1277         FOR way IN select id from planet_osm_ways where nodes && ARRAY[NEW.osm_id::integer] LOOP
1278 --RAISE WARNING '%', way;
1279         FOR location IN select * from placex where osm_type = 'W' and osm_id = way.id
1280         LOOP
1281 --RAISE WARNING '%', location;
1282           -- Way IS a road then we are on it - that must be our road
1283           IF location.rank_search = 26 AND NEW.parent_place_id IS NULL THEN
1284 --RAISE WARNING 'node in way that is a street %',location;
1285             NEW.parent_place_id := location.place_id;
1286           END IF;
1287
1288           -- Is the WAY part of a relation
1289           FOR relation IN select * from planet_osm_rels where parts @> ARRAY[location.osm_id::integer] and members @> ARRAY['w'||location.osm_id]
1290           LOOP
1291             -- At the moment we only process one type of relation - associatedStreet
1292             IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1293               FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1294                 IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1295 --RAISE WARNING 'node in way that is in a relation %',relation;
1296                   SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1297                     and rank_search = 26 INTO NEW.parent_place_id;
1298                 END IF;
1299               END LOOP;
1300             END IF;
1301           END LOOP;
1302           
1303           -- If the way contains an explicit name of a street copy it
1304           IF NEW.street IS NULL AND location.street IS NOT NULL THEN
1305 --RAISE WARNING 'node in way that has a streetname %',location;
1306             NEW.street := location.street;
1307           END IF;
1308
1309           -- If this way is a street interpolation line then it is probably as good as we are going to get
1310           IF NEW.parent_place_id IS NULL AND NEW.street IS NULL AND location.class = 'place' and location.type='houses' THEN
1311             -- Try and find a way that is close roughly parellel to this line
1312             FOR relation IN SELECT place_id FROM placex
1313               WHERE ST_DWithin(location.geometry, placex.geometry, 0.001) and placex.rank_search = 26
1314                 and st_geometrytype(location.geometry) in ('ST_LineString')
1315               ORDER BY (ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0))+
1316                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0.5))+
1317                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,1))) ASC limit 1
1318             LOOP
1319 --RAISE WARNING 'using nearest street to address interpolation line,0.001 %',relation;
1320               NEW.parent_place_id := relation.place_id;
1321             END LOOP;
1322           END IF;
1323
1324         END LOOP;
1325         END LOOP;
1326                 
1327       END IF;
1328
1329 --RAISE WARNING 'x2';
1330
1331       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'W' THEN
1332         -- Is this way part of a relation?
1333         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id::integer] and members @> ARRAY['w'||NEW.osm_id]
1334         LOOP
1335           -- At the moment we only process one type of relation - associatedStreet
1336           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1337             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1338               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1339 --RAISE WARNING 'way that is in a relation %',relation;
1340                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer
1341                   and rank_search = 26 INTO NEW.parent_place_id;
1342               END IF;
1343             END LOOP;
1344           END IF;
1345         END LOOP;
1346       END IF;
1347       
1348 --RAISE WARNING 'x3';
1349
1350       IF NEW.parent_place_id IS NULL AND NEW.street IS NOT NULL THEN
1351         address_street_word_id := get_name_id(make_standard_name(NEW.street));
1352         IF address_street_word_id IS NOT NULL THEN
1353           FOR location IN SELECT * from getNearestNamedRoadFeature(NEW.partition, place_centroid, address_street_word_id) LOOP
1354             NEW.parent_place_id := location.place_id;
1355           END LOOP;
1356         END IF;
1357       END IF;
1358
1359 --RAISE WARNING 'x4';
1360       -- Still nothing, just use the nearest road
1361       FOR location IN SELECT place_id FROM getNearestRoadFeature(NEW.partition, place_centroid) LOOP
1362         NEW.parent_place_id := location.place_id;
1363       END LOOP;
1364
1365 --return NEW;
1366 --RAISE WARNING 'x6 %',NEW.parent_place_id;
1367
1368       -- If we didn't find any road fallback to standard method
1369       IF NEW.parent_place_id IS NOT NULL THEN
1370
1371         -- Add the street to the address as zero distance to force to front of list
1372         INSERT INTO place_addressline VALUES (NEW.place_id, NEW.parent_place_id, true, true, 0, 26);
1373         address_havelevel[26] := true;
1374
1375         -- Import address details from parent, reclculating distance in process
1376         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
1377           from place_addressline as x join placex on (address_place_id = placex.place_id)
1378           where x.place_id = NEW.parent_place_id and x.address_place_id != NEW.parent_place_id;
1379
1380         -- Get the details of the parent road
1381         select * from search_name where place_id = NEW.parent_place_id INTO location;
1382         NEW.country_code := location.country_code;
1383
1384 --RAISE WARNING '%', NEW.name;
1385         -- If there is no name it isn't searchable, don't bother to create a search record
1386         IF NEW.name is NULL THEN
1387           return NEW;
1388         END IF;
1389
1390         -- Merge address from parent
1391         nameaddress_vector := array_merge(nameaddress_vector, location.nameaddress_vector);
1392 --return NEW;
1393         -- Performance, it would be more acurate to do all the rest of the import process but it takes too long
1394         -- Just be happy with inheriting from parent road only
1395
1396         IF NEW.rank_search <= 25 THEN
1397           result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1398         END IF;
1399
1400         result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, place_centroid);
1401
1402         return NEW;
1403       END IF;
1404
1405     END IF;
1406
1407 -- RAISE WARNING '  INDEXING: %',NEW;
1408
1409     NEW.parent_place_id = 0;
1410     parent_place_id_rank = 0;
1411
1412     -- convert isin to array of tokenids
1413     isin_tokens := '{}'::int[];
1414     IF NEW.isin IS NOT NULL THEN
1415       isin := regexp_split_to_array(NEW.isin, E'[;,]');
1416       IF array_upper(isin, 1) IS NOT NULL THEN
1417         FOR i IN 1..array_upper(isin, 1) LOOP
1418           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1419           IF address_street_word_id IS NOT NULL THEN
1420             isin_tokens := isin_tokens + address_street_word_id;
1421           END IF;
1422         END LOOP;
1423       END IF;
1424       isin_tokens := uniq(sort(isin_tokens));
1425     END IF;
1426     IF NEW.postcode IS NOT NULL THEN
1427       isin := regexp_split_to_array(NEW.postcode, E'[;,]');
1428       IF array_upper(isin, 1) IS NOT NULL THEN
1429         FOR i IN 1..array_upper(isin, 1) LOOP
1430           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1431           IF address_street_word_id IS NOT NULL THEN
1432             isin_tokens := isin_tokens + address_street_word_id;
1433           END IF;
1434         END LOOP;
1435       END IF;
1436       isin_tokens := uniq(sort(isin_tokens));
1437     END IF;
1438 --RAISE WARNING 'ISIN: %', isin_tokens;
1439
1440     -- Process area matches
1441     location_rank_search := 100;
1442     location_distance := 0;
1443 --RAISE WARNING '  getNearFeatures(%,%,%,%)',NEW.partition, place_centroid, search_maxrank, isin_tokens;
1444     FOR location IN SELECT * from getNearFeatures(NEW.partition, place_centroid, search_maxrank, isin_tokens) LOOP
1445
1446 --RAISE WARNING '  AREA: %',location;
1447
1448       IF location.rank_search < location_rank_search THEN
1449         location_rank_search := location.rank_search;
1450         location_distance := location.distance * 1.5;
1451       END IF;
1452
1453       IF location.distance < location_distance THEN
1454
1455         -- Add it to the list of search terms
1456         nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1457         INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, NOT address_havelevel[location.rank_address], location.distance, location.rank_address); 
1458         address_havelevel[location.rank_address] := true;
1459
1460         IF location.rank_address > parent_place_id_rank THEN
1461           NEW.parent_place_id = location.place_id;
1462           parent_place_id_rank = location.rank_address;
1463         END IF;
1464
1465       END IF;
1466
1467     END LOOP;
1468
1469     -- try using the isin value to find parent places
1470     IF array_upper(isin_tokens, 1) IS NOT NULL THEN
1471       FOR i IN 1..array_upper(isin_tokens, 1) LOOP
1472 --RAISE WARNING '  ISIN: % % % %',NEW.partition, place_centroid, search_maxrank, isin_tokens[i];
1473
1474         FOR location IN SELECT * from getNearestNamedFeature(NEW.partition, place_centroid, search_maxrank, isin_tokens[i]) LOOP
1475           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1476           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, false, NOT address_havelevel[location.rank_address], location.distance, location.rank_address);
1477           address_havelevel[location.rank_address] := true;
1478
1479           IF location.rank_address > parent_place_id_rank THEN
1480             NEW.parent_place_id = location.place_id;
1481             parent_place_id_rank = location.rank_address;
1482           END IF;
1483
1484         END LOOP;
1485
1486       END LOOP;
1487     END IF;
1488
1489     -- for long ways we should add search terms for the entire length
1490     IF st_length(NEW.geometry) > 0.05 THEN
1491
1492       location_rank_search := 100;
1493       location_distance := 0;
1494
1495       FOR location IN SELECT * from getNearFeatures(NEW.partition, NEW.geometry, search_maxrank, isin_tokens) LOOP
1496
1497         IF location.rank_search < location_rank_search THEN
1498           location_rank_search := location.rank_search;
1499           location_distance := location.distance * 1.5;
1500         END IF;
1501
1502         IF location.distance < location_distance THEN
1503
1504           -- Add it to the list of search terms
1505           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1506           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, false, location.distance, location.rank_address); 
1507
1508         END IF;
1509
1510       END LOOP;
1511
1512     END IF;
1513
1514     -- if we have a name add this to the name search table
1515     IF NEW.name IS NOT NULL THEN
1516
1517       IF NEW.rank_search <= 25 THEN
1518         result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1519       END IF;
1520
1521       IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1522         result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1523       END IF;
1524
1525       result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, place_centroid);
1526
1527 --      INSERT INTO search_name values (NEW.place_id, NEW.rank_search, NEW.rank_search, 0, NEW.country_code, name_vector, nameaddress_vector, place_centroid);
1528     END IF;
1529
1530   END IF;
1531
1532   RETURN NEW;
1533 END;
1534 $$
1535 LANGUAGE plpgsql;
1536
1537 CREATE OR REPLACE FUNCTION placex_delete() RETURNS TRIGGER
1538   AS $$
1539 DECLARE
1540   b BOOLEAN;
1541 BEGIN
1542
1543   IF OLD.rank_address < 30 THEN
1544
1545     -- mark everything linked to this place for re-indexing
1546     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1547       and placex.place_id = place_addressline.place_id and indexed_status = 0;
1548
1549     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1550
1551   END IF;
1552
1553   IF OLD.rank_address < 26 THEN
1554     b := deleteLocationArea(OLD.partition, OLD.place_id);
1555   END IF;
1556
1557   IF OLD.name is not null THEN
1558     b := deleteSearchName(OLD.partition, OLD.place_id);
1559   END IF;
1560
1561   DELETE FROM place_addressline where place_id = OLD.place_id;
1562
1563   RETURN OLD;
1564
1565 END;
1566 $$
1567 LANGUAGE plpgsql;
1568
1569 CREATE OR REPLACE FUNCTION place_delete() RETURNS TRIGGER
1570   AS $$
1571 DECLARE
1572   placeid INTEGER;
1573 BEGIN
1574
1575 --  RAISE WARNING 'delete: % % % %',OLD.osm_type,OLD.osm_id,OLD.class,OLD.type;
1576
1577   -- mark for delete
1578   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;
1579
1580 --  delete from placex where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1581   RETURN OLD;
1582
1583 END;
1584 $$
1585 LANGUAGE plpgsql;
1586
1587 CREATE OR REPLACE FUNCTION place_insert() RETURNS TRIGGER
1588   AS $$
1589 DECLARE
1590   i INTEGER;
1591   existing RECORD;
1592   existingplacex RECORD;
1593   existinggeometry GEOMETRY;
1594   existingplace_id INTEGER;
1595   result BOOLEAN;
1596   partition INTEGER;
1597 BEGIN
1598
1599   IF FALSE AND NEW.osm_type = 'R' THEN
1600     RAISE WARNING '-----------------------------------------------------------------------------------';
1601     RAISE WARNING 'place_insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,st_area(NEW.geometry);
1602     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;
1603     RAISE WARNING '%', existingplacex;
1604   END IF;
1605
1606   -- Just block these - lots and pointless
1607   IF NEW.class = 'highway' and NEW.type in ('turning_circle','traffic_signals','mini_roundabout','noexit','crossing') THEN
1608     RETURN null;
1609   END IF;
1610   IF NEW.class in ('landuse','natural') and NEW.name is null THEN
1611     RETURN null;
1612   END IF;
1613
1614   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  
1615 --    RAISE WARNING 'Invalid Geometry: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1616     RETURN null;
1617   END IF;
1618
1619   -- Patch in additional country names
1620   IF NEW.admin_level = 2 AND NEW.type = 'administrative' AND NEW.country_code is not null THEN
1621     select country_name.name || NEW.name from country_name where country_name.country_code = lower(NEW.country_code) INTO NEW.name;
1622   END IF;
1623     
1624   -- Have we already done this place?
1625   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;
1626
1627   -- Get the existing place_id
1628   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;
1629
1630   -- Handle a place changing type by removing the old data
1631   -- My generated 'place' types are causing havok because they overlap with real tags
1632   -- TODO: move them to their own special purpose tag to avoid collisions
1633   IF existing.osm_type IS NULL AND (NEW.type not in ('postcode','house','houses')) THEN
1634     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');
1635   END IF;
1636
1637 --  RAISE WARNING 'Existing: %',existing.place_id;
1638
1639   -- 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
1640   IF existing.osm_type IS NULL 
1641      OR existingplacex.osm_type IS NULL
1642      OR coalesce(existing.admin_level, 100) != coalesce(NEW.admin_level, 100) 
1643      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
1644      OR (existing.geometry::text != NEW.geometry::text AND ST_Distance(ST_Centroid(existing.geometry),ST_Centroid(NEW.geometry)) > 0.01 AND NOT
1645      (ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')))
1646      THEN
1647
1648 --  IF existing.osm_type IS NULL THEN
1649 --    RAISE WARNING 'no existing place';
1650 --  END IF;
1651 --  IF existingplacex.osm_type IS NULL THEN
1652 --    RAISE WARNING 'no existing placex %', existingplacex;
1653 --  END IF;
1654
1655
1656 --    RAISE WARNING 'delete and replace';
1657
1658     IF existing.osm_type IS NOT NULL THEN
1659 --      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;
1660       DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1661     END IF;   
1662
1663 --    RAISE WARNING 'delete and replace2';
1664
1665     -- No - process it as a new insertion (hopefully of low rank or it will be slow)
1666     insert into placex (osm_type, osm_id, class, type, name, admin_level, housenumber, 
1667       street, isin, postcode, country_code, extratags, geometry)
1668       values (NEW.osm_type
1669         ,NEW.osm_id
1670         ,NEW.class
1671         ,NEW.type
1672         ,NEW.name
1673         ,NEW.admin_level
1674         ,NEW.housenumber
1675         ,NEW.street
1676         ,NEW.isin
1677         ,NEW.postcode
1678         ,NEW.country_code
1679         ,NEW.extratags
1680         ,NEW.geometry
1681         );
1682
1683 --    RAISE WARNING 'insert done % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1684
1685     RETURN NEW;
1686   END IF;
1687
1688   -- Various ways to do the update
1689
1690   -- Debug, what's changed?
1691   IF FALSE THEN
1692     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') THEN
1693       RAISE WARNING 'update details, name: % % % %',NEW.osm_type,NEW.osm_id,existing.name::text,NEW.name::text;
1694     END IF;
1695     IF coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '') THEN
1696       RAISE WARNING 'update details, housenumber: % % % %',NEW.osm_type,NEW.osm_id,existing.housenumber,NEW.housenumber;
1697     END IF;
1698     IF coalesce(existing.street, '') != coalesce(NEW.street, '') THEN
1699       RAISE WARNING 'update details, street: % % % %',NEW.osm_type,NEW.osm_id,existing.street,NEW.street;
1700     END IF;
1701     IF coalesce(existing.isin, '') != coalesce(NEW.isin, '') THEN
1702       RAISE WARNING 'update details, isin: % % % %',NEW.osm_type,NEW.osm_id,existing.isin,NEW.isin;
1703     END IF;
1704     IF coalesce(existing.postcode, '') != coalesce(NEW.postcode, '') THEN
1705       RAISE WARNING 'update details, postcode: % % % %',NEW.osm_type,NEW.osm_id,existing.postcode,NEW.postcode;
1706     END IF;
1707     IF coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1708       RAISE WARNING 'update details, country_code: % % % %',NEW.osm_type,NEW.osm_id,existing.country_code,NEW.country_code;
1709     END IF;
1710   END IF;
1711
1712   -- Special case for polygon shape changes because they tend to be large and we can be a bit clever about how we handle them
1713   IF existing.geometry::text != NEW.geometry::text 
1714      AND ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon')
1715      AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') 
1716      THEN 
1717
1718     -- Get the version of the geometry actually used (in placex table)
1719     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;
1720
1721     -- Performance limit
1722     IF st_area(NEW.geometry) < 1 AND st_area(existinggeometry) < 1 THEN
1723
1724       -- 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
1725       update placex set indexed_status = 2 where indexed_status = 0 and 
1726           (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1727           AND NOT (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1728           AND rank_search > existingplacex.rank_search;
1729
1730       update placex set indexed_status = 2 where indexed_status = 0 and 
1731           (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1732           AND NOT (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1733           AND rank_search > existingplacex.rank_search;
1734
1735     END IF;
1736
1737   END IF;
1738
1739   -- Special case - if we are just adding extra words we hack them into the search_name table rather than reindexing
1740   IF FALSE AND existingplacex.rank_search < 26
1741      AND coalesce(existing.housenumber, '') = coalesce(NEW.housenumber, '')
1742      AND coalesce(existing.street, '') = coalesce(NEW.street, '')
1743      AND coalesce(existing.isin, '') = coalesce(NEW.isin, '')
1744      AND coalesce(existing.postcode, '') = coalesce(NEW.postcode, '')
1745      AND coalesce(existing.country_code, '') = coalesce(NEW.country_code, '')
1746      AND coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') 
1747      THEN
1748
1749     IF NOT update_location_nameonly(existingplacex.place_id, NEW.name) THEN
1750
1751       IF st_area(NEW.geometry) < 0.5 THEN
1752         UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
1753           and placex.place_id = place_addressline.place_id and indexed_status = 0;
1754       END IF;
1755
1756     END IF;
1757   
1758   ELSE
1759
1760     -- Anything else has changed - reindex the lot
1761     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1762         OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
1763         OR coalesce(existing.street, '') != coalesce(NEW.street, '')
1764         OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
1765         OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
1766         OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1767
1768       -- performance, can't take the load of re-indexing a whole country / huge area
1769       IF st_area(NEW.geometry) < 0.5 THEN
1770         UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
1771           and placex.place_id = place_addressline.place_id and indexed_status = 0;
1772       END IF;
1773
1774     END IF;
1775
1776   END IF;
1777
1778   IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1779      OR coalesce(existing.extratags::text, '') != coalesce(NEW.extratags::text, '')
1780      OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
1781      OR coalesce(existing.street, '') != coalesce(NEW.street, '')
1782      OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
1783      OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
1784      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
1785      OR existing.geometry::text != NEW.geometry::text
1786      THEN
1787
1788     update place set 
1789       name = NEW.name,
1790       housenumber  = NEW.housenumber,
1791       street = NEW.street,
1792       isin = NEW.isin,
1793       postcode = NEW.postcode,
1794       country_code = NEW.country_code,
1795       extratags = NEW.extratags,
1796       geometry = NEW.geometry
1797       where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1798
1799     update placex set 
1800       name = NEW.name,
1801       housenumber = NEW.housenumber,
1802       street = NEW.street,
1803       isin = NEW.isin,
1804       postcode = NEW.postcode,
1805       country_code = NEW.country_code,
1806       parent_place_id = null,
1807       extratags = NEW.extratags,
1808       indexed_status = 2,    
1809       geometry = NEW.geometry
1810       where place_id = existingplacex.place_id;
1811
1812 -- now done as part of indexing
1813 --    partition := get_partition(NEW.geometry, existingplacex.country_code);
1814 --    result := update_location(partition, existingplacex.place_id, existingplacex.country_code, NEW.name, existingplacex.rank_search, existingplacex.rank_address, NEW.geometry);
1815
1816   END IF;
1817
1818   -- Abort the add (we modified the existing place instead)
1819   RETURN NULL;
1820
1821 END; 
1822 $$ LANGUAGE plpgsql;
1823
1824 CREATE OR REPLACE FUNCTION get_name_by_language(name hstore, languagepref TEXT[]) RETURNS TEXT
1825   AS $$
1826 DECLARE
1827   search TEXT[];
1828   found BOOLEAN;
1829 BEGIN
1830
1831   IF name is null THEN
1832     RETURN null;
1833   END IF;
1834
1835   search := languagepref;
1836
1837   FOR j IN 1..array_upper(search, 1) LOOP
1838     IF name ? search[j] AND trim(name->search[j]) != '' THEN
1839       return trim(name->search[j]);
1840     END IF;
1841   END LOOP;
1842
1843   RETURN null;
1844 END;
1845 $$
1846 LANGUAGE plpgsql IMMUTABLE;
1847
1848 CREATE OR REPLACE FUNCTION get_connected_ways(way_ids INTEGER[]) RETURNS SETOF planet_osm_ways
1849   AS $$
1850 DECLARE
1851   searchnodes INTEGER[];
1852   location RECORD;
1853   j INTEGER;
1854 BEGIN
1855
1856   searchnodes := '{}';
1857   FOR j IN 1..array_upper(way_ids, 1) LOOP
1858     FOR location IN 
1859       select nodes from planet_osm_ways where id = way_ids[j] LIMIT 1
1860     LOOP
1861       searchnodes := searchnodes | location.nodes;
1862     END LOOP;
1863   END LOOP;
1864
1865   RETURN QUERY select * from planet_osm_ways where nodes && searchnodes and NOT ARRAY[id] <@ way_ids;
1866 END;
1867 $$
1868 LANGUAGE plpgsql IMMUTABLE;
1869
1870 CREATE OR REPLACE FUNCTION get_address_postcode(for_place_id INTEGER) RETURNS TEXT
1871   AS $$
1872 DECLARE
1873   result TEXT[];
1874   search TEXT[];
1875   for_postcode TEXT;
1876   found INTEGER;
1877   location RECORD;
1878 BEGIN
1879
1880   found := 1000;
1881   search := ARRAY['ref'];
1882   result := '{}';
1883
1884   select postcode from placex where place_id = for_place_id limit 1 into for_postcode;
1885
1886   FOR location IN 
1887     select rank_address,name,distance,length(name::text) as namelength 
1888       from place_addressline join placex on (address_place_id = placex.place_id) 
1889       where place_addressline.place_id = for_place_id and rank_address in (5,11)
1890       order by rank_address desc,rank_search desc,fromarea desc,distance asc,namelength desc
1891   LOOP
1892     IF array_upper(search, 1) IS NOT NULL AND array_upper(location.name, 1) IS NOT NULL THEN
1893       FOR j IN 1..array_upper(search, 1) LOOP
1894         FOR k IN 1..array_upper(location.name, 1) LOOP
1895           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
1896             result[(100 - location.rank_address)] := trim(location.name[k].value);
1897             found := location.rank_address;
1898           END IF;
1899         END LOOP;
1900       END LOOP;
1901     END IF;
1902   END LOOP;
1903
1904   RETURN array_to_string(result,', ');
1905 END;
1906 $$
1907 LANGUAGE plpgsql;
1908
1909 CREATE OR REPLACE FUNCTION get_address_by_language(for_place_id INTEGER, languagepref TEXT[]) RETURNS TEXT
1910   AS $$
1911 DECLARE
1912   result TEXT[];
1913   currresult TEXT;
1914   prevresult TEXT;
1915   location RECORD;
1916 BEGIN
1917
1918   result := '{}';
1919   prevresult := '';
1920
1921   FOR location IN select * from get_addressdata(for_place_id) where isaddress order by rank_address desc LOOP
1922     currresult := trim(get_name_by_language(location.name, languagepref));
1923     IF currresult != prevresult AND currresult IS NOT NULL THEN
1924       result[(100 - location.rank_address)] := trim(get_name_by_language(location.name, languagepref));
1925       prevresult := currresult;
1926     END IF;
1927   END LOOP;
1928
1929   RETURN array_to_string(result,', ');
1930 END;
1931 $$
1932 LANGUAGE plpgsql;
1933
1934 DROP TYPE addressline CASCADE;
1935 create type addressline as (
1936   place_id INTEGER,
1937   osm_type CHAR(1),
1938   osm_id INTEGER,
1939   name HSTORE,
1940   class TEXT,
1941   type TEXT,
1942   fromarea BOOLEAN,  
1943   isaddress BOOLEAN,  
1944   rank_address INTEGER,
1945   distance FLOAT
1946 );
1947
1948 CREATE OR REPLACE FUNCTION get_addressdata(in_place_id INTEGER) RETURNS setof addressline 
1949   AS $$
1950 DECLARE
1951   for_place_id INTEGER;
1952   result TEXT[];
1953   search TEXT[];
1954   found INTEGER;
1955   location RECORD;
1956   searchcountrycode varchar(2);
1957   searchhousenumber TEXT;
1958   searchhousename HSTORE;
1959   searchrankaddress INTEGER;
1960   searchpostcode TEXT;
1961   countryname HSTORE;
1962 BEGIN
1963
1964   select parent_place_id,'us', housenumber, 30, postcode, null from location_property_tiger 
1965     WHERE place_id = in_place_id 
1966     INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
1967
1968   IF for_place_id IS NULL THEN
1969
1970     select parent_place_id, country_code, housenumber, rank_address, postcode, name from placex 
1971       WHERE place_id = in_place_id and rank_address = 30 
1972       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
1973
1974     IF for_place_id IS NULL THEN
1975       for_place_id := in_place_id;
1976       select country_code, housenumber, rank_address, postcode, null from placex where place_id = for_place_id 
1977         INTO searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
1978     END IF;
1979
1980   END IF;
1981 --RAISE WARNING '% % % %',searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode;
1982
1983   found := 1000;
1984   FOR location IN 
1985     select placex.place_id, osm_type, osm_id, 
1986       CASE WHEN class = 'place' and type = 'postcode' THEN 'name' => postcode ELSE name END as name,
1987       class, type, fromarea, isaddress,
1988       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,
1989       distance
1990       from place_addressline join placex on (address_place_id = placex.place_id) 
1991       where place_addressline.place_id = for_place_id 
1992       and ((cached_rank_address > 0 AND cached_rank_address < searchrankaddress) OR address_place_id = for_place_id)
1993       and (placex.country_code IS NULL OR searchcountrycode IS NULL OR placex.country_code = searchcountrycode OR rank_address < 4)
1994       order by rank_address desc,isaddress desc,fromarea desc,distance asc,rank_search desc
1995   LOOP
1996 --RAISE WARNING '%',location;
1997     IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
1998       location.isaddress := FALSE;
1999     END IF;
2000     RETURN NEXT location;
2001     found := location.rank_address;
2002   END LOOP;
2003
2004   IF found > 4 THEN
2005     select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2006 --RAISE WARNING '% % %',found,searchcountrycode,countryname;
2007     IF countryname IS NOT NULL THEN
2008       location := ROW(null, null, null, countryname, 'place', 'country', true, true, 4, 0)::addressline;
2009       RETURN NEXT location;
2010     END IF;
2011   END IF;
2012
2013   IF searchcountrycode IS NOT NULL THEN
2014     location := ROW(null, null, null, 'ref'=>searchcountrycode, 'place', 'country_code', true, false, 4, 0)::addressline;
2015     RETURN NEXT location;
2016   END IF;
2017
2018   IF searchhousename IS NOT NULL THEN
2019     location := ROW(in_place_id, null, null, searchhousename, 'place', 'house_name', true, true, 29, 0)::addressline;
2020     RETURN NEXT location;
2021   END IF;
2022
2023   IF searchhousenumber IS NOT NULL THEN
2024     location := ROW(in_place_id, null, null, 'ref'=>searchhousenumber, 'place', 'house_number', true, true, 28, 0)::addressline;
2025     RETURN NEXT location;
2026   END IF;
2027
2028   IF searchpostcode IS NOT NULL THEN
2029     location := ROW(null, null, null, 'ref'=>searchpostcode, 'place', 'postcode', true, true, 5, 0)::addressline;
2030     RETURN NEXT location;
2031   END IF;
2032
2033   RETURN;
2034 END;
2035 $$
2036 LANGUAGE plpgsql;
2037
2038 CREATE OR REPLACE FUNCTION get_place_boundingbox(search_place_id INTEGER) RETURNS place_boundingbox
2039   AS $$
2040 DECLARE
2041   result place_boundingbox;
2042   numfeatures integer;
2043 BEGIN
2044   select * from place_boundingbox into result where place_id = search_place_id;
2045   IF result.place_id IS NULL THEN
2046 -- remove  isaddress = true because if there is a matching polygon it always wins
2047     select count(*) from place_addressline where address_place_id = search_place_id into numfeatures;
2048     insert into place_boundingbox select place_id,
2049              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2050              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2051              numfeatures, ST_Area(geometry),
2052              geometry as area from location_area where place_id = search_place_id;
2053     select * from place_boundingbox into result where place_id = search_place_id;
2054   END IF;
2055   IF result.place_id IS NULL THEN
2056 -- TODO 0.0001
2057     insert into place_boundingbox select address_place_id,
2058              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2059              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2060              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2061              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2062              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) 
2063              where address_place_id = search_place_id
2064 --               and (isaddress = true OR place_id = search_place_id)
2065                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2066              group by address_place_id limit 1;
2067     select * from place_boundingbox into result where place_id = search_place_id;
2068   END IF;
2069   return result;
2070 END;
2071 $$
2072 LANGUAGE plpgsql;
2073
2074 -- don't do the operation if it would be slow
2075 CREATE OR REPLACE FUNCTION get_place_boundingbox_quick(search_place_id INTEGER) RETURNS place_boundingbox
2076   AS $$
2077 DECLARE
2078   result place_boundingbox;
2079   numfeatures integer;
2080   rank integer;
2081 BEGIN
2082   select * from place_boundingbox into result where place_id = search_place_id;
2083   IF result IS NULL AND rank > 14 THEN
2084     select count(*) from place_addressline where address_place_id = search_place_id and isaddress = true into numfeatures;
2085     insert into place_boundingbox select place_id,
2086              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2087              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2088              numfeatures, ST_Area(geometry),
2089              geometry as area from location_area where place_id = search_place_id;
2090     select * from place_boundingbox into result where place_id = search_place_id;
2091   END IF;
2092   IF result IS NULL THEN
2093     select rank_search from placex where place_id = search_place_id into rank;
2094     IF rank > 20 THEN
2095 -- TODO 0.0001
2096       insert into place_boundingbox select address_place_id,
2097              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2098              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2099              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2100              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2101              from place_addressline join placex using (place_id) 
2102              where address_place_id = search_place_id 
2103                and (isaddress = true OR place_id = search_place_id)
2104                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2105              group by address_place_id limit 1;
2106       select * from place_boundingbox into result where place_id = search_place_id;
2107     END IF;
2108   END IF;
2109   return result;
2110 END;
2111 $$
2112 LANGUAGE plpgsql;
2113
2114 CREATE OR REPLACE FUNCTION update_place(search_place_id INTEGER) RETURNS BOOLEAN
2115   AS $$
2116 DECLARE
2117   result place_boundingbox;
2118   numfeatures integer;
2119 BEGIN
2120   update placex set 
2121       name = place.name,
2122       housenumber = place.housenumber,
2123       street = place.street,
2124       isin = place.isin,
2125       postcode = place.postcode,
2126       country_code = place.country_code,
2127       parent_place_id = null
2128       from place
2129       where placex.place_id = search_place_id 
2130         and place.osm_type = placex.osm_type and place.osm_id = placex.osm_id
2131         and place.class = placex.class and place.type = placex.type;
2132   update placex set indexed_status = 2 where place_id = search_place_id;
2133   update placex set indexed_status = 0 where place_id = search_place_id;
2134   return true;
2135 END;
2136 $$
2137 LANGUAGE plpgsql;
2138
2139 CREATE OR REPLACE FUNCTION get_searchrank_label(rank INTEGER) RETURNS TEXT
2140   AS $$
2141 DECLARE
2142 BEGIN
2143   IF rank < 2 THEN
2144     RETURN 'Continent';
2145   ELSEIF rank < 4 THEN
2146     RETURN 'Sea';
2147   ELSEIF rank < 8 THEN
2148     RETURN 'Country';
2149   ELSEIF rank < 12 THEN
2150     RETURN 'State';
2151   ELSEIF rank < 16 THEN
2152     RETURN 'County';
2153   ELSEIF rank = 16 THEN
2154     RETURN 'City';
2155   ELSEIF rank = 17 THEN
2156     RETURN 'Town / Island';
2157   ELSEIF rank = 18 THEN
2158     RETURN 'Village / Hamlet';
2159   ELSEIF rank = 20 THEN
2160     RETURN 'Suburb';
2161   ELSEIF rank = 21 THEN
2162     RETURN 'Postcode Area';
2163   ELSEIF rank = 22 THEN
2164     RETURN 'Croft / Farm / Locality / Islet';
2165   ELSEIF rank = 23 THEN
2166     RETURN 'Postcode Area';
2167   ELSEIF rank = 25 THEN
2168     RETURN 'Postcode Point';
2169   ELSEIF rank = 26 THEN
2170     RETURN 'Street / Major Landmark';
2171   ELSEIF rank = 27 THEN
2172     RETURN 'Minory Street / Path';
2173   ELSEIF rank = 28 THEN
2174     RETURN 'House / Building';
2175   ELSE
2176     RETURN 'Other: '||rank;
2177   END IF;
2178   
2179 END;
2180 $$
2181 LANGUAGE plpgsql;
2182
2183 CREATE OR REPLACE FUNCTION get_addressrank_label(rank INTEGER) RETURNS TEXT
2184   AS $$
2185 DECLARE
2186 BEGIN
2187   IF rank = 0 THEN
2188     RETURN 'None';
2189   ELSEIF rank < 2 THEN
2190     RETURN 'Continent';
2191   ELSEIF rank < 4 THEN
2192     RETURN 'Sea';
2193   ELSEIF rank = 5 THEN
2194     RETURN 'Postcode';
2195   ELSEIF rank < 8 THEN
2196     RETURN 'Country';
2197   ELSEIF rank < 12 THEN
2198     RETURN 'State';
2199   ELSEIF rank < 16 THEN
2200     RETURN 'County';
2201   ELSEIF rank = 16 THEN
2202     RETURN 'City';
2203   ELSEIF rank = 17 THEN
2204     RETURN 'Town / Village / Hamlet';
2205   ELSEIF rank = 20 THEN
2206     RETURN 'Suburb';
2207   ELSEIF rank = 21 THEN
2208     RETURN 'Postcode Area';
2209   ELSEIF rank = 22 THEN
2210     RETURN 'Croft / Farm / Locality / Islet';
2211   ELSEIF rank = 23 THEN
2212     RETURN 'Postcode Area';
2213   ELSEIF rank = 25 THEN
2214     RETURN 'Postcode Point';
2215   ELSEIF rank = 26 THEN
2216     RETURN 'Street / Major Landmark';
2217   ELSEIF rank = 27 THEN
2218     RETURN 'Minory Street / Path';
2219   ELSEIF rank = 28 THEN
2220     RETURN 'House / Building';
2221   ELSE
2222     RETURN 'Other: '||rank;
2223   END IF;
2224   
2225 END;
2226 $$
2227 LANGUAGE plpgsql;
2228
2229 CREATE OR REPLACE FUNCTION get_word_suggestion(srcword TEXT) RETURNS TEXT
2230   AS $$
2231 DECLARE
2232   trigramtoken TEXT;
2233   result TEXT;
2234 BEGIN
2235
2236   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2237   SELECT word FROM word WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 1 into result;
2238
2239   return result;
2240 END;
2241 $$
2242 LANGUAGE plpgsql;
2243
2244 CREATE OR REPLACE FUNCTION get_word_suggestions(srcword TEXT) RETURNS TEXT[]
2245   AS $$
2246 DECLARE
2247   trigramtoken TEXT;
2248   result TEXT[];
2249   r RECORD;
2250 BEGIN
2251
2252   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2253
2254   FOR r IN SELECT word,similarity(word_trigram, trigramtoken) as score FROM word 
2255     WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 4
2256   LOOP
2257     result[coalesce(array_upper(result,1)+1,1)] := r.word;
2258   END LOOP;
2259
2260   return result;
2261 END;
2262 $$
2263 LANGUAGE plpgsql;
2264
2265 CREATE AGGREGATE array_agg(INT[])
2266 (
2267     sfunc = array_cat,
2268     stype = INT[],
2269     initcond = '{}'
2270 );
2271
2272 CREATE OR REPLACE FUNCTION tigger_create_interpolation(linegeo GEOMETRY, in_startnumber INTEGER, 
2273   in_endnumber INTEGER, interpolationtype TEXT, 
2274   in_street TEXT, in_isin TEXT, in_postcode TEXT) RETURNS INTEGER
2275   AS $$
2276 DECLARE
2277   
2278   startnumber INTEGER;
2279   endnumber INTEGER;
2280   stepsize INTEGER;
2281   housenum INTEGER;
2282   newpoints INTEGER;
2283   numberrange INTEGER;
2284   rangestartnumber INTEGER;
2285   place_centroid GEOMETRY;
2286   partition INTEGER;
2287   parent_place_id INTEGER;
2288   location RECORD;
2289   address_street_word_id INTEGER;  
2290
2291 BEGIN
2292
2293   IF in_endnumber > in_startnumber THEN
2294     startnumber = in_startnumber;
2295     endnumber = in_endnumber;
2296   ELSE
2297     startnumber = in_endnumber;
2298     endnumber = in_startnumber;
2299   END IF;
2300
2301   numberrange := endnumber - startnumber;
2302   rangestartnumber := startnumber;
2303
2304   IF (interpolationtype = 'odd' AND startnumber%2 = 0) OR (interpolationtype = 'even' AND startnumber%2 = 1) THEN
2305     startnumber := startnumber + 1;
2306     stepsize := 2;
2307   ELSE
2308     IF (interpolationtype = 'odd' OR interpolationtype = 'even') THEN
2309       stepsize := 2;
2310     ELSE -- everything else assumed to be 'all'
2311       stepsize := 1;
2312     END IF;
2313   END IF;
2314
2315   -- Filter out really broken tiger data
2316   IF numberrange > 0 AND (numberrange::float/stepsize::float > 500) 
2317                     AND ST_length(linegeo)/(numberrange::float/stepsize::float) < 0.000001 THEN
2318     RAISE WARNING 'Road too short for number range % to % on %, % (%)',startnumber,endnumber,in_street,in_isin,
2319                   ST_length(linegeo)/(numberrange::float/stepsize::float);    
2320     RETURN 0;
2321   END IF;
2322
2323   place_centroid := ST_Centroid(linegeo);
2324   partition := get_partition(place_centroid, 'us');
2325   parent_place_id := null;
2326
2327   address_street_word_id := get_name_id(make_standard_name(in_street));
2328   IF address_street_word_id IS NOT NULL THEN
2329     FOR location IN SELECT * from getNearestNamedRoadFeature(partition, place_centroid, address_street_word_id) LOOP
2330       parent_place_id := location.place_id;
2331     END LOOP;
2332   END IF;
2333
2334   IF parent_place_id IS NULL THEN
2335     FOR location IN SELECT place_id FROM getNearestParellelRoadFeature(partition, linegeo) LOOP
2336       parent_place_id := location.place_id;
2337     END LOOP;    
2338   END IF;
2339
2340   IF parent_place_id IS NULL THEN
2341     FOR location IN SELECT place_id FROM getNearestRoadFeature(partition, place_centroid) LOOP
2342       parent_place_id := location.place_id;
2343     END LOOP;    
2344   END IF;
2345
2346   newpoints := 0;
2347   FOR housenum IN startnumber..endnumber BY stepsize LOOP
2348     insert into location_property_tiger (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2349     values (nextval('seq_place'), partition, parent_place_id, housenum, in_postcode,
2350       ST_Line_Interpolate_Point(linegeo, (housenum::float-rangestartnumber::float)/numberrange::float));
2351     newpoints := newpoints + 1;
2352   END LOOP;
2353
2354   RETURN newpoints;
2355 END;
2356 $$
2357 LANGUAGE plpgsql;