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