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