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