]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions.sql
add support for Irish townlands
[nominatim.git] / sql / functions.sql
1 --DROP TRIGGER IF EXISTS place_before_insert on placex;
2 --DROP TRIGGER IF EXISTS place_before_update on placex;
3 --CREATE TYPE addresscalculationtype AS (
4 --  word text,
5 --  score integer
6 --);
7
8
9 CREATE OR REPLACE FUNCTION getclasstypekey(c text, t text) RETURNS TEXT
10   AS $$
11 DECLARE
12 BEGIN
13   RETURN c||'|'||t;
14 END;
15 $$
16 LANGUAGE plpgsql IMMUTABLE;
17
18 CREATE OR REPLACE FUNCTION isbrokengeometry(place geometry) RETURNS BOOLEAN
19   AS $$
20 DECLARE
21   NEWgeometry geometry;
22 BEGIN
23   NEWgeometry := place;
24   IF ST_IsEmpty(NEWgeometry) OR NOT ST_IsValid(NEWgeometry) OR ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
25     RETURN true;
26   END IF;
27   RETURN false;
28 END;
29 $$
30 LANGUAGE plpgsql IMMUTABLE;
31
32 CREATE OR REPLACE FUNCTION clean_geometry(place geometry) RETURNS geometry
33   AS $$
34 DECLARE
35   NEWgeometry geometry;
36 BEGIN
37   NEWgeometry := place;
38   IF ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
39     NEWgeometry := ST_buffer(NEWgeometry,0);
40     IF ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
41       RETURN ST_SetSRID(ST_Point(0,0),4326);
42     END IF;
43   END IF;
44   RETURN NEWgeometry;
45 END;
46 $$
47 LANGUAGE plpgsql IMMUTABLE;
48
49 CREATE OR REPLACE FUNCTION geometry_sector(partition INTEGER, place geometry) RETURNS INTEGER
50   AS $$
51 DECLARE
52   NEWgeometry geometry;
53 BEGIN
54 --  RAISE WARNING '%',place;
55   NEWgeometry := place;
56   IF ST_IsEmpty(NEWgeometry) OR NOT ST_IsValid(NEWgeometry) OR ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
57     NEWgeometry := ST_buffer(NEWgeometry,0);
58     IF ST_IsEmpty(NEWgeometry) OR NOT ST_IsValid(NEWgeometry) OR ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
59       RETURN 0;
60     END IF;
61   END IF;
62   RETURN (partition*1000000) + (500-ST_X(ST_Centroid(NEWgeometry))::integer)*1000 + (500-ST_Y(ST_Centroid(NEWgeometry))::integer);
63 END;
64 $$
65 LANGUAGE plpgsql IMMUTABLE;
66
67 CREATE OR REPLACE FUNCTION debug_geometry_sector(osmid integer, place geometry) RETURNS INTEGER
68   AS $$
69 DECLARE
70   NEWgeometry geometry;
71 BEGIN
72 --  RAISE WARNING '%',osmid;
73   IF osmid = 61315 THEN
74     return null;
75   END IF;
76   NEWgeometry := place;
77   IF ST_IsEmpty(NEWgeometry) OR NOT ST_IsValid(NEWgeometry) OR ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
78     NEWgeometry := ST_buffer(NEWgeometry,0);
79     IF ST_IsEmpty(NEWgeometry) OR NOT ST_IsValid(NEWgeometry) OR ST_X(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEWgeometry))::text in ('NaN','Infinity','-Infinity') THEN  
80       RETURN NULL;
81     END IF;
82   END IF;
83   RETURN (500-ST_X(ST_Centroid(NEWgeometry))::integer)*1000 + (500-ST_Y(ST_Centroid(NEWgeometry))::integer);
84 END;
85 $$
86 LANGUAGE plpgsql IMMUTABLE;
87
88 CREATE OR REPLACE FUNCTION transliteration(text) RETURNS text
89   AS '{modulepath}/nominatim.so', 'transliteration'
90 LANGUAGE c IMMUTABLE STRICT;
91
92 CREATE OR REPLACE FUNCTION gettokenstring(text) RETURNS text
93   AS '{modulepath}/nominatim.so', 'gettokenstring'
94 LANGUAGE c IMMUTABLE STRICT;
95
96 CREATE OR REPLACE FUNCTION make_standard_name(name TEXT) RETURNS TEXT
97   AS $$
98 DECLARE
99   o TEXT;
100 BEGIN
101   o := gettokenstring(transliteration(name));
102   RETURN trim(substr(o,1,length(o)));
103 END;
104 $$
105 LANGUAGE 'plpgsql' IMMUTABLE;
106
107 CREATE OR REPLACE FUNCTION getorcreate_word_id(lookup_word TEXT) 
108   RETURNS INTEGER
109   AS $$
110 DECLARE
111   lookup_token TEXT;
112   return_word_id INTEGER;
113 BEGIN
114   lookup_token := trim(lookup_word);
115   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class is null and type is null into return_word_id;
116   IF return_word_id IS NULL THEN
117     return_word_id := nextval('seq_word');
118     INSERT INTO word VALUES (return_word_id, lookup_token, regexp_replace(lookup_token,E'([^0-9])\\1+',E'\\1','g'), null, null, null, null, 0, null);
119   END IF;
120   RETURN return_word_id;
121 END;
122 $$
123 LANGUAGE plpgsql;
124
125 CREATE OR REPLACE FUNCTION getorcreate_housenumber_id(lookup_word TEXT)
126   RETURNS INTEGER
127   AS $$
128 DECLARE
129   lookup_token TEXT;
130   return_word_id INTEGER;
131 BEGIN
132   lookup_token := ' '||trim(lookup_word);
133   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class='place' and type='house' into return_word_id;
134   IF return_word_id IS NULL THEN
135     return_word_id := nextval('seq_word');
136     INSERT INTO word VALUES (return_word_id, lookup_token, null, null, 'place', 'house', null, 0, null);
137   END IF;
138   RETURN return_word_id;
139 END;
140 $$
141 LANGUAGE plpgsql;
142
143 CREATE OR REPLACE FUNCTION getorcreate_country(lookup_word TEXT, lookup_country_code varchar(2))
144   RETURNS INTEGER
145   AS $$
146 DECLARE
147   lookup_token TEXT;
148   return_word_id INTEGER;
149 BEGIN
150   lookup_token := ' '||trim(lookup_word);
151   SELECT min(word_id) FROM word WHERE word_token = lookup_token and country_code=lookup_country_code into return_word_id;
152   IF return_word_id IS NULL THEN
153     return_word_id := nextval('seq_word');
154     INSERT INTO word VALUES (return_word_id, lookup_token, null, null, null, null, lookup_country_code, 0, null);
155   END IF;
156   RETURN return_word_id;
157 END;
158 $$
159 LANGUAGE plpgsql;
160
161 CREATE OR REPLACE FUNCTION getorcreate_amenity(lookup_word TEXT, lookup_class text, lookup_type text)
162   RETURNS INTEGER
163   AS $$
164 DECLARE
165   lookup_token TEXT;
166   return_word_id INTEGER;
167 BEGIN
168   lookup_token := ' '||trim(lookup_word);
169   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class=lookup_class and type = lookup_type into return_word_id;
170   IF return_word_id IS NULL THEN
171     return_word_id := nextval('seq_word');
172     INSERT INTO word VALUES (return_word_id, lookup_token, null, null, lookup_class, lookup_type, null, 0, null);
173   END IF;
174   RETURN return_word_id;
175 END;
176 $$
177 LANGUAGE plpgsql;
178
179 CREATE OR REPLACE FUNCTION getorcreate_tagpair(lookup_class text, lookup_type text)
180   RETURNS INTEGER
181   AS $$
182 DECLARE
183   lookup_token TEXT;
184   return_word_id INTEGER;
185 BEGIN
186   lookup_token := lookup_class||'='||lookup_type;
187   SELECT min(word_id) FROM word WHERE word_token = lookup_token into return_word_id;
188   IF return_word_id IS NULL THEN
189     return_word_id := nextval('seq_word');
190     INSERT INTO word VALUES (return_word_id, lookup_token, null, null, null, null, null, 0, null);
191   END IF;
192   RETURN return_word_id;
193 END;
194 $$
195 LANGUAGE plpgsql;
196
197 CREATE OR REPLACE FUNCTION get_tagpair(lookup_class text, lookup_type text)
198   RETURNS INTEGER
199   AS $$
200 DECLARE
201   lookup_token TEXT;
202   return_word_id INTEGER;
203 BEGIN
204   lookup_token := lookup_class||'='||lookup_type;
205   SELECT min(word_id) FROM word WHERE word_token = lookup_token into return_word_id;
206   RETURN return_word_id;
207 END;
208 $$
209 LANGUAGE plpgsql;
210
211 CREATE OR REPLACE FUNCTION getorcreate_amenityoperator(lookup_word TEXT, lookup_class text, lookup_type text, op text)
212   RETURNS INTEGER
213   AS $$
214 DECLARE
215   lookup_token TEXT;
216   return_word_id INTEGER;
217 BEGIN
218   lookup_token := ' '||trim(lookup_word);
219   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class=lookup_class and type = lookup_type and operator = op into return_word_id;
220   IF return_word_id IS NULL THEN
221     return_word_id := nextval('seq_word');
222     INSERT INTO word VALUES (return_word_id, lookup_token, null, null, lookup_class, lookup_type, null, 0, op, null);
223   END IF;
224   RETURN return_word_id;
225 END;
226 $$
227 LANGUAGE plpgsql;
228
229 CREATE OR REPLACE FUNCTION getorcreate_name_id(lookup_word TEXT, src_word TEXT) 
230   RETURNS INTEGER
231   AS $$
232 DECLARE
233   lookup_token TEXT;
234   nospace_lookup_token TEXT;
235   return_word_id INTEGER;
236 BEGIN
237   lookup_token := ' '||trim(lookup_word);
238   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class is null and type is null into return_word_id;
239   IF return_word_id IS NULL THEN
240     return_word_id := nextval('seq_word');
241     INSERT INTO word VALUES (return_word_id, lookup_token, regexp_replace(lookup_token,E'([^0-9])\\1+',E'\\1','g'), src_word, null, null, null, 0, null);
242 --    nospace_lookup_token := replace(replace(lookup_token, '-',''), ' ','');
243 --    IF ' '||nospace_lookup_token != lookup_token THEN
244 --      INSERT INTO word VALUES (return_word_id, '-'||nospace_lookup_token, null, src_word, null, null, null, 0, null);
245 --    END IF;
246   END IF;
247   RETURN return_word_id;
248 END;
249 $$
250 LANGUAGE plpgsql;
251
252 CREATE OR REPLACE FUNCTION getorcreate_name_id(lookup_word TEXT) 
253   RETURNS INTEGER
254   AS $$
255 DECLARE
256 BEGIN
257   RETURN getorcreate_name_id(lookup_word, '');
258 END;
259 $$
260 LANGUAGE plpgsql;
261
262 CREATE OR REPLACE FUNCTION get_word_id(lookup_word TEXT) 
263   RETURNS INTEGER
264   AS $$
265 DECLARE
266   lookup_token TEXT;
267   return_word_id INTEGER;
268 BEGIN
269   lookup_token := trim(lookup_word);
270   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class is null and type is null into return_word_id;
271   RETURN return_word_id;
272 END;
273 $$
274 LANGUAGE plpgsql IMMUTABLE;
275
276 CREATE OR REPLACE FUNCTION get_name_id(lookup_word TEXT) 
277   RETURNS INTEGER
278   AS $$
279 DECLARE
280   lookup_token TEXT;
281   return_word_id INTEGER;
282 BEGIN
283   lookup_token := ' '||trim(lookup_word);
284   SELECT min(word_id) FROM word WHERE word_token = lookup_token and class is null and type is null into return_word_id;
285   RETURN return_word_id;
286 END;
287 $$
288 LANGUAGE plpgsql IMMUTABLE;
289
290 CREATE OR REPLACE FUNCTION array_merge(a INTEGER[], b INTEGER[])
291   RETURNS INTEGER[]
292   AS $$
293 DECLARE
294   i INTEGER;
295   r INTEGER[];
296 BEGIN
297   IF array_upper(a, 1) IS NULL THEN
298     RETURN b;
299   END IF;
300   IF array_upper(b, 1) IS NULL THEN
301     RETURN a;
302   END IF;
303   r := a;
304   FOR i IN 1..array_upper(b, 1) LOOP  
305     IF NOT (ARRAY[b[i]] <@ r) THEN
306       r := r || b[i];
307     END IF;
308   END LOOP;
309   RETURN r;
310 END;
311 $$
312 LANGUAGE plpgsql IMMUTABLE;
313
314 CREATE OR REPLACE FUNCTION make_keywords(src HSTORE) RETURNS INTEGER[]
315   AS $$
316 DECLARE
317   result INTEGER[];
318   s TEXT;
319   w INTEGER;
320   words TEXT[];
321   item RECORD;
322   j INTEGER;
323 BEGIN
324   result := '{}'::INTEGER[];
325
326   FOR item IN SELECT (each(src)).* LOOP
327
328     s := make_standard_name(item.value);
329
330     w := getorcreate_name_id(s, item.value);
331
332     IF not(ARRAY[w] <@ result) THEN
333       result := result || w;
334     END IF;
335
336     words := string_to_array(s, ' ');
337     IF array_upper(words, 1) IS NOT NULL THEN
338       FOR j IN 1..array_upper(words, 1) LOOP
339         IF (words[j] != '') THEN
340           w = getorcreate_word_id(words[j]);
341           IF NOT (ARRAY[w] <@ result) THEN
342             result := result || w;
343           END IF;
344         END IF;
345       END LOOP;
346     END IF;
347
348     words := regexp_split_to_array(item.value, E'[,;()]');
349     IF array_upper(words, 1) != 1 THEN
350       FOR j IN 1..array_upper(words, 1) LOOP
351         s := make_standard_name(words[j]);
352         IF s != '' THEN
353           w := getorcreate_word_id(s);
354           IF NOT (ARRAY[w] <@ result) THEN
355             result := result || w;
356           END IF;
357         END IF;
358       END LOOP;
359     END IF;
360
361     s := regexp_replace(item.value, '市$', '');
362     IF s != item.value THEN
363       s := make_standard_name(s);
364       IF s != '' THEN
365         w := getorcreate_name_id(s, item.value);
366         IF NOT (ARRAY[w] <@ result) THEN
367           result := result || w;
368         END IF;
369       END IF;
370     END IF;
371
372   END LOOP;
373
374   RETURN result;
375 END;
376 $$
377 LANGUAGE plpgsql IMMUTABLE;
378
379 CREATE OR REPLACE FUNCTION make_keywords(src TEXT) RETURNS INTEGER[]
380   AS $$
381 DECLARE
382   result INTEGER[];
383   s TEXT;
384   w INTEGER;
385   words TEXT[];
386   i INTEGER;
387   j INTEGER;
388 BEGIN
389   result := '{}'::INTEGER[];
390
391   s := make_standard_name(src);
392   w := getorcreate_name_id(s);
393
394   IF NOT (ARRAY[w] <@ result) THEN
395     result := result || w;
396   END IF;
397
398   words := string_to_array(s, ' ');
399   IF array_upper(words, 1) IS NOT NULL THEN
400     FOR j IN 1..array_upper(words, 1) LOOP
401       IF (words[j] != '') THEN
402         w = getorcreate_word_id(words[j]);
403         IF NOT (ARRAY[w] <@ result) THEN
404           result := result || w;
405         END IF;
406       END IF;
407     END LOOP;
408   END IF;
409
410   RETURN result;
411 END;
412 $$
413 LANGUAGE plpgsql IMMUTABLE;
414
415 CREATE OR REPLACE FUNCTION get_word_score(wordscores wordscore[], words text[]) RETURNS integer
416   AS $$
417 DECLARE
418   idxword integer;
419   idxscores integer;
420   result integer;
421 BEGIN
422   IF (wordscores is null OR words is null) THEN
423     RETURN 0;
424   END IF;
425
426   result := 0;
427   FOR idxword in 1 .. array_upper(words, 1) LOOP
428     FOR idxscores in 1 .. array_upper(wordscores, 1) LOOP
429       IF wordscores[idxscores].word = words[idxword] THEN
430         result := result + wordscores[idxscores].score;
431       END IF;
432     END LOOP;
433   END LOOP;
434
435   RETURN result;
436 END;
437 $$
438 LANGUAGE plpgsql IMMUTABLE;
439
440 CREATE OR REPLACE FUNCTION get_country_code(place geometry) RETURNS TEXT
441   AS $$
442 DECLARE
443   place_centre GEOMETRY;
444   nearcountry RECORD;
445 BEGIN
446   place_centre := ST_Centroid(place);
447
448 --RAISE WARNING 'start: %', ST_AsText(place_centre);
449
450   -- Try for a OSM polygon first
451   FOR nearcountry IN select country_code from location_area_country where country_code is not null and not isguess and st_contains(geometry, place_centre) limit 1
452   LOOP
453     RETURN nearcountry.country_code;
454   END LOOP;
455
456 --RAISE WARNING 'osm fallback: %', ST_AsText(place_centre);
457
458   -- Try for OSM fallback data
459   FOR nearcountry IN select country_code from country_osm_grid where st_contains(geometry, place_centre) limit 1
460   LOOP
461     RETURN nearcountry.country_code;
462   END LOOP;
463
464 --RAISE WARNING 'natural earth: %', ST_AsText(place_centre);
465
466   -- Natural earth data (first fallback)
467   FOR nearcountry IN select country_code from country_naturalearthdata where st_contains(geometry, place_centre) limit 1
468   LOOP
469     RETURN nearcountry.country_code;
470   END LOOP;
471
472   -- Natural earth data (first fallback)
473   FOR nearcountry IN select country_code from country_naturalearthdata where st_distance(geometry, place_centre) < 0.5 limit 1
474   LOOP
475     RETURN nearcountry.country_code;
476   END LOOP;
477
478 --RAISE WARNING 'in country: %', ST_AsText(place_centre);
479
480   -- WorldBoundaries data (second fallback - think there might be something broken in this data)
481   FOR nearcountry IN select country_code from country where st_contains(geometry, place_centre) limit 1
482   LOOP
483     RETURN nearcountry.country_code;
484   END LOOP;
485
486 --RAISE WARNING 'near country: %', ST_AsText(place_centre);
487
488   -- Still not in a country - try nearest within ~12 miles of a country
489   FOR nearcountry IN select country_code from country where st_distance(geometry, place_centre) < 0.5 
490     order by st_distance(geometry, place) limit 1
491   LOOP
492     RETURN nearcountry.country_code;
493   END LOOP;
494
495   RETURN NULL;
496 END;
497 $$
498 LANGUAGE plpgsql IMMUTABLE;
499
500 CREATE OR REPLACE FUNCTION get_country_code(place geometry, in_country_code VARCHAR(2)) RETURNS TEXT
501   AS $$
502 DECLARE
503   nearcountry RECORD;
504 BEGIN
505   FOR nearcountry IN select country_code from country_name where country_code = lower(in_country_code)
506   LOOP
507     RETURN nearcountry.country_code;
508   END LOOP;
509   RETURN get_country_code(place);
510 END;
511 $$
512 LANGUAGE plpgsql IMMUTABLE;
513
514 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2)) RETURNS TEXT
515   AS $$
516 DECLARE
517   nearcountry RECORD;
518 BEGIN
519   FOR nearcountry IN select distinct country_default_language_code from country_name where country_code = search_country_code limit 1
520   LOOP
521     RETURN lower(nearcountry.country_default_language_code);
522   END LOOP;
523   RETURN NULL;
524 END;
525 $$
526 LANGUAGE plpgsql IMMUTABLE;
527
528 CREATE OR REPLACE FUNCTION get_partition(place geometry, in_country_code VARCHAR(10)) RETURNS INTEGER
529   AS $$
530 DECLARE
531   place_centre GEOMETRY;
532   nearcountry RECORD;
533 BEGIN
534   FOR nearcountry IN select partition from country_name where country_code = in_country_code
535   LOOP
536     RETURN nearcountry.partition;
537   END LOOP;
538   RETURN 0;
539 END;
540 $$
541 LANGUAGE plpgsql IMMUTABLE;
542
543 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT) RETURNS BOOLEAN
544   AS $$
545 DECLARE
546 BEGIN
547   DELETE FROM location_area where place_id = OLD_place_id;
548 -- TODO:location_area
549   RETURN true;
550 END;
551 $$
552 LANGUAGE plpgsql;
553
554 CREATE OR REPLACE FUNCTION add_location(
555     place_id BIGINT,
556     country_code varchar(2),
557     partition INTEGER,
558     keywords INTEGER[],
559     rank_search INTEGER,
560     rank_address INTEGER,
561     geometry GEOMETRY
562   ) 
563   RETURNS BOOLEAN
564   AS $$
565 DECLARE
566   locationid INTEGER;
567   isarea BOOLEAN;
568   xmin INTEGER;
569   ymin INTEGER;
570   xmax INTEGER;
571   ymax INTEGER;
572   lon INTEGER;
573   lat INTEGER;
574   centroid GEOMETRY;
575   secgeo GEOMETRY;
576   secbox GEOMETRY;
577   diameter FLOAT;
578   x BOOLEAN;
579 BEGIN
580
581   IF rank_search > 25 THEN
582     RAISE EXCEPTION 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
583   END IF;
584
585 --  RAISE WARNING 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
586
587   x := deleteLocationArea(partition, place_id);
588
589   isarea := false;
590   IF (ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(geometry)) THEN
591
592     isArea := true;
593     centroid := ST_Centroid(geometry);
594
595     xmin := floor(st_xmin(geometry));
596     xmax := ceil(st_xmax(geometry));
597     ymin := floor(st_ymin(geometry));
598     ymax := ceil(st_ymax(geometry));
599
600     IF xmin = xmax OR ymin = ymax OR (xmax-xmin < 2 AND ymax-ymin < 2) THEN
601       x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, centroid, geometry);
602     ELSE
603 --      RAISE WARNING 'Spliting geometry: % to %, % to %', xmin, xmax, ymin, ymax;
604       FOR lon IN xmin..(xmax-1) LOOP
605         FOR lat IN ymin..(ymax-1) LOOP
606           secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(lon,lat),ST_Point(lon+1,lat+1)),4326);
607           IF st_intersects(geometry, secbox) THEN
608             secgeo := st_intersection(geometry, secbox);
609             IF NOT ST_IsEmpty(secgeo) AND ST_GeometryType(secgeo) in ('ST_Polygon','ST_MultiPolygon') THEN
610               x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, centroid, secgeo);
611             END IF;
612           END IF;
613         END LOOP;
614       END LOOP;
615     END IF;
616
617   ELSEIF rank_search < 26 THEN
618
619     diameter := 0.02;
620     IF rank_address = 0 THEN
621       diameter := 0.02;
622     ELSEIF rank_search <= 14 THEN
623       diameter := 1.2;
624     ELSEIF rank_search <= 15 THEN
625       diameter := 1;
626     ELSEIF rank_search <= 16 THEN
627       diameter := 0.5;
628     ELSEIF rank_search <= 17 THEN
629       diameter := 0.2;
630     ELSEIF rank_search <= 21 THEN
631       diameter := 0.05;
632     ELSEIF rank_search = 25 THEN
633       diameter := 0.005;
634     END IF;
635
636 --    RAISE WARNING 'adding % diameter %', place_id, diameter;
637
638     secgeo := ST_Buffer(geometry, diameter);
639     x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
640
641   ELSE
642
643     -- ~ 20meters
644     secgeo := ST_Buffer(geometry, 0.0002);
645     x := insertLocationAreaRoadNear(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
646
647     -- ~ 100meters
648     secgeo := ST_Buffer(geometry, 0.001);
649     x := insertLocationAreaRoadFar(partition, place_id, country_code, keywords, rank_search, rank_address, true, ST_Centroid(geometry), secgeo);
650
651   END IF;
652
653   RETURN true;
654 END;
655 $$
656 LANGUAGE plpgsql;
657
658 CREATE OR REPLACE FUNCTION update_location(
659     partition INTEGER,
660     place_id BIGINT,
661     place_country_code varchar(2),
662     name hstore,
663     rank_search INTEGER,
664     rank_address INTEGER,
665     geometry GEOMETRY
666   ) 
667   RETURNS BOOLEAN
668   AS $$
669 DECLARE
670   b BOOLEAN;
671 BEGIN
672   b := deleteLocationArea(partition, place_id);
673 --  result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
674   RETURN add_location(place_id, place_country_code, name, rank_search, rank_address, geometry);
675 END;
676 $$
677 LANGUAGE plpgsql;
678
679 CREATE OR REPLACE FUNCTION search_name_add_words(parent_place_id BIGINT, to_add INTEGER[])
680   RETURNS BOOLEAN
681   AS $$
682 DECLARE
683   childplace RECORD;
684 BEGIN
685
686   IF #to_add = 0 THEN
687     RETURN true;
688   END IF;
689
690   -- this should just be an update, but it seems to do insane things to the index size (delete and insert doesn't)
691   FOR childplace IN select * from search_name,place_addressline 
692     where  address_place_id = parent_place_id
693       and search_name.place_id = place_addressline.place_id
694   LOOP
695     delete from search_name where place_id = childplace.place_id;
696     IF not (ARRAY[to_add] <@ childplace.nameaddress_vector) THEN
697       childplace.nameaddress_vector := childplace.nameaddress_vector || to_add;
698     END IF;
699     IF childplace.place_id = parent_place_id and not (ARRAY[to_add] <@ childplace.name_vector) THEN
700       childplace.name_vector := childplace.name_vector || to_add;
701     END IF;
702     insert into search_name (place_id, search_rank, address_rank, country_code, name_vector, nameaddress_vector, centroid) 
703       values (childplace.place_id, childplace.search_rank, childplace.address_rank, childplace.country_code, 
704         childplace.name_vector, childplace.nameaddress_vector, childplace.centroid);
705   END LOOP;
706
707   RETURN true;
708 END;
709 $$
710 LANGUAGE plpgsql;
711
712 CREATE OR REPLACE FUNCTION update_location_nameonly(partition INTEGER, OLD_place_id BIGINT, name hstore) RETURNS BOOLEAN
713   AS $$
714 DECLARE
715   newkeywords INTEGER[];
716   addedkeywords INTEGER[];
717   removedkeywords INTEGER[];
718 BEGIN
719
720   -- what has changed?
721   newkeywords := make_keywords(name);
722   select coalesce(newkeywords,'{}'::INTEGER[]) - coalesce(location_point.keywords,'{}'::INTEGER[]), 
723     coalesce(location_point.keywords,'{}'::INTEGER[]) - coalesce(newkeywords,'{}'::INTEGER[]) from location_point 
724     where place_id = OLD_place_id into addedkeywords, removedkeywords;
725
726 --  RAISE WARNING 'update_location_nameonly for %: new:% added:% removed:%', OLD_place_id, newkeywords, addedkeywords, removedkeywords;
727
728   IF #removedkeywords > 0 THEN
729     -- abort due to tokens removed
730     RETURN false;
731   END IF;
732   
733   IF #addedkeywords > 0 THEN
734     -- short circuit - no changes
735     RETURN true;
736   END IF;
737
738   UPDATE location_area set keywords = newkeywords where place_id = OLD_place_id;
739   RETURN search_name_add_words(OLD_place_id, addedkeywords);
740 END;
741 $$
742 LANGUAGE plpgsql;
743
744
745 CREATE OR REPLACE FUNCTION create_interpolation(wayid INTEGER, interpolationtype TEXT) RETURNS INTEGER
746   AS $$
747 DECLARE
748   
749   newpoints INTEGER;
750   waynodes integer[];
751   nodeid INTEGER;
752   prevnode RECORD;
753   nextnode RECORD;
754   startnumber INTEGER;
755   endnumber INTEGER;
756   stepsize INTEGER;
757   orginalstartnumber INTEGER;
758   originalnumberrange INTEGER;
759   housenum INTEGER;
760   linegeo GEOMETRY;
761   search_place_id BIGINT;
762   defpostalcode TEXT;
763
764   havefirstpoint BOOLEAN;
765   linestr TEXT;
766 BEGIN
767   newpoints := 0;
768   IF interpolationtype = 'odd' OR interpolationtype = 'even' OR interpolationtype = 'all' THEN
769
770     select postcode from placex where osm_type = 'W' and osm_id = wayid INTO defpostalcode;
771     select nodes from planet_osm_ways where id = wayid INTO waynodes;
772 --RAISE WARNING 'interpolation % % %',wayid,interpolationtype,waynodes;
773     IF array_upper(waynodes, 1) IS NOT NULL THEN
774
775       havefirstpoint := false;
776
777       FOR nodeidpos in 1..array_upper(waynodes, 1) LOOP
778
779         select min(place_id) from placex where osm_type = 'N' and osm_id = waynodes[nodeidpos]::INTEGER and type = 'house' INTO search_place_id;
780         IF search_place_id IS NULL THEN
781           -- null record of right type
782           select * from placex where osm_type = 'N' and osm_id = waynodes[nodeidpos]::INTEGER and type = 'house' limit 1 INTO nextnode;
783           select ST_SetSRID(ST_Point(lon::float/10000000,lat::float/10000000),4326) from planet_osm_nodes where id = waynodes[nodeidpos] INTO nextnode.geometry;
784         ELSE
785           select * from placex where place_id = search_place_id INTO nextnode;
786         END IF;
787
788 --RAISE WARNING 'interpolation node % % % ',nextnode.housenumber,ST_X(nextnode.geometry),ST_Y(nextnode.geometry);
789       
790         IF havefirstpoint THEN
791
792           -- add point to the line string
793           linestr := linestr||','||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
794           endnumber := ('0'||substring(nextnode.housenumber,'[0-9]+'))::integer;
795
796           IF startnumber IS NOT NULL and startnumber > 0 AND endnumber IS NOT NULL and endnumber > 0 AND @(startnumber - endnumber) < 1000 THEN
797
798 --RAISE WARNING 'interpolation end % % ',nextnode.place_id,endnumber;
799
800             IF startnumber != endnumber THEN
801
802               linestr := linestr || ')';
803 --RAISE WARNING 'linestr %',linestr;
804               linegeo := ST_GeomFromText(linestr,4326);
805               linestr := 'LINESTRING('||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
806               IF (startnumber > endnumber) THEN
807                 housenum := endnumber;
808                 endnumber := startnumber;
809                 startnumber := housenum;
810                 linegeo := ST_Reverse(linegeo);
811               END IF;
812               orginalstartnumber := startnumber;
813               originalnumberrange := endnumber - startnumber;
814
815 -- Too much broken data worldwide for this test to be worth using
816 --              IF originalnumberrange > 500 THEN
817 --                RAISE WARNING 'Number block of % while processing % %', originalnumberrange, prevnode, nextnode;
818 --              END IF;
819
820               IF (interpolationtype = 'odd' AND startnumber%2 = 0) OR (interpolationtype = 'even' AND startnumber%2 = 1) THEN
821                 startnumber := startnumber + 1;
822                 stepsize := 2;
823               ELSE
824                 IF (interpolationtype = 'odd' OR interpolationtype = 'even') THEN
825                   startnumber := startnumber + 2;
826                   stepsize := 2;
827                 ELSE -- everything else assumed to be 'all'
828                   startnumber := startnumber + 1;
829                   stepsize := 1;
830                 END IF;
831               END IF;
832               endnumber := endnumber - 1;
833               delete from placex where osm_type = 'N' and osm_id = prevnode.osm_id and type = 'house' and place_id != prevnode.place_id;
834               FOR housenum IN startnumber..endnumber BY stepsize LOOP
835                 -- this should really copy postcodes but it puts a huge burdon on the system for no big benefit
836                 -- ideally postcodes should move up to the way
837                 insert into placex (osm_type, osm_id, class, type, admin_level, housenumber, street, isin, postcode,
838                   country_code, parent_place_id, rank_address, rank_search, indexed_status, geometry)
839                   values ('N',prevnode.osm_id, prevnode.class, prevnode.type, prevnode.admin_level, housenum, prevnode.street, prevnode.isin, coalesce(prevnode.postcode, defpostalcode),
840                   prevnode.country_code, prevnode.parent_place_id, prevnode.rank_address, prevnode.rank_search, 1, ST_Line_Interpolate_Point(linegeo, (housenum::float-orginalstartnumber::float)/originalnumberrange::float));
841                 newpoints := newpoints + 1;
842 --RAISE WARNING 'interpolation number % % ',prevnode.place_id,housenum;
843               END LOOP;
844             END IF;
845             havefirstpoint := false;
846           END IF;
847         END IF;
848
849         IF NOT havefirstpoint THEN
850           startnumber := ('0'||substring(nextnode.housenumber,'[0-9]+'))::integer;
851           IF startnumber IS NOT NULL AND startnumber > 0 THEN
852             havefirstpoint := true;
853             linestr := 'LINESTRING('||ST_X(nextnode.geometry)||' '||ST_Y(nextnode.geometry);
854             prevnode := nextnode;
855           END IF;
856 --RAISE WARNING 'interpolation start % % ',nextnode.place_id,startnumber;
857         END IF;
858       END LOOP;
859     END IF;
860   END IF;
861
862 --RAISE WARNING 'interpolation points % ',newpoints;
863
864   RETURN newpoints;
865 END;
866 $$
867 LANGUAGE plpgsql;
868
869 CREATE OR REPLACE FUNCTION placex_insert() RETURNS TRIGGER
870   AS $$
871 DECLARE
872   i INTEGER;
873   postcode TEXT;
874   result BOOLEAN;
875   country_code VARCHAR(2);
876   default_language VARCHAR(10);
877   diameter FLOAT;
878   classtable TEXT;
879 BEGIN
880 --  RAISE WARNING '%',NEW.osm_id;
881
882   -- just block these
883   IF NEW.class = 'highway' and NEW.type in ('turning_circle','traffic_signals','mini_roundabout','noexit','crossing') THEN
884 --    RAISE WARNING 'bad highway %',NEW.osm_id;
885     RETURN null;
886   END IF;
887   IF NEW.class in ('landuse','natural') and NEW.name is null THEN
888 --    RAISE WARNING 'empty landuse %',NEW.osm_id;
889     RETURN null;
890   END IF;
891
892   IF ST_IsEmpty(NEW.geometry) OR NOT ST_IsValid(NEW.geometry) OR ST_X(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') THEN  
893     -- block all invalid geometary - just not worth the risk.  seg faults are causing serious problems.
894 --    RAISE WARNING 'invalid geometry %',NEW.osm_id;
895     RETURN NULL;
896
897     -- Dead code
898     IF NEW.osm_type = 'R' THEN
899       -- invalid multipolygons can crash postgis, don't even bother to try!
900       RETURN NULL;
901     END IF;
902     NEW.geometry := ST_buffer(NEW.geometry,0);
903     IF ST_IsEmpty(NEW.geometry) OR NOT ST_IsValid(NEW.geometry) OR ST_X(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') OR ST_Y(ST_Centroid(NEW.geometry))::text in ('NaN','Infinity','-Infinity') THEN  
904 --      RAISE WARNING 'Invalid geometary, rejecting: % %', NEW.osm_type, NEW.osm_id;
905       RETURN NULL;
906     END IF;
907   END IF;
908
909   NEW.place_id := nextval('seq_place');
910   NEW.indexed_status := 1; --STATUS_NEW
911
912   NEW.country_code := lower(get_country_code(NEW.geometry, NEW.country_code));
913   NEW.partition := get_partition(NEW.geometry, NEW.country_code);
914   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
915
916   -- copy 'name' to or from the default language (if there is a default language)
917   IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
918     default_language := get_country_language_code(NEW.country_code);
919     IF default_language IS NOT NULL THEN
920       IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
921         NEW.name := NEW.name || (('name:'||default_language) => (NEW.name -> 'name'));
922       ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
923         NEW.name := NEW.name || ('name' => (NEW.name -> ('name:'||default_language)));
924       END IF;
925     END IF;
926   END IF;
927
928   IF NEW.admin_level > 15 THEN
929     NEW.admin_level := 15;
930   END IF;
931
932   IF NEW.housenumber IS NOT NULL THEN
933     i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
934   END IF;
935
936   IF NEW.osm_type = 'X' THEN
937     -- E'X'ternal records should already be in the right format so do nothing
938   ELSE
939     NEW.rank_search := 30;
940     NEW.rank_address := NEW.rank_search;
941
942     -- By doing in postgres we have the country available to us - currently only used for postcode
943     IF NEW.class in ('place','boundary') AND NEW.type in ('postcode','postal_code') THEN
944
945         IF NEW.postcode IS NULL THEN
946             -- most likely just a part of a multipolygon postcode boundary, throw it away
947             RETURN NULL;
948         END IF;
949
950         NEW.name := 'ref'=>NEW.postcode;
951
952         IF NEW.country_code = 'gb' THEN
953
954           IF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9][A-Z][A-Z])$' THEN
955             NEW.rank_search := 25;
956             NEW.rank_address := 5;
957           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9])$' THEN
958             NEW.rank_search := 23;
959             NEW.rank_address := 5;
960           ELSEIF NEW.postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z])$' THEN
961             NEW.rank_search := 21;
962             NEW.rank_address := 5;
963           END IF;
964
965         ELSEIF NEW.country_code = 'de' THEN
966
967           IF NEW.postcode ~ '^([0-9]{5})$' THEN
968             NEW.rank_search := 21;
969             NEW.rank_address := 11;
970           END IF;
971
972         ELSE
973           -- Guess at the postcode format and coverage (!)
974           IF upper(NEW.postcode) ~ '^[A-Z0-9]{1,5}$' THEN -- Probably too short to be very local
975             NEW.rank_search := 21;
976             NEW.rank_address := 11;
977           ELSE
978             -- Does it look splitable into and area and local code?
979             postcode := substring(upper(NEW.postcode) from '^([- :A-Z0-9]+)([- :][A-Z0-9]+)$');
980
981             IF postcode IS NOT NULL THEN
982               NEW.rank_search := 25;
983               NEW.rank_address := 11;
984             ELSEIF NEW.postcode ~ '^[- :A-Z0-9]{6,}$' THEN
985               NEW.rank_search := 21;
986               NEW.rank_address := 11;
987             END IF;
988           END IF;
989         END IF;
990
991     ELSEIF NEW.class = 'place' THEN
992       IF NEW.type in ('continent') THEN
993         NEW.rank_search := 2;
994         NEW.rank_address := NEW.rank_search;
995       ELSEIF NEW.type in ('sea') THEN
996         NEW.rank_search := 2;
997         NEW.rank_address := 0;
998       ELSEIF NEW.type in ('country') THEN
999         NEW.rank_search := 4;
1000         NEW.rank_address := NEW.rank_search;
1001       ELSEIF NEW.type in ('state') THEN
1002         NEW.rank_search := 8;
1003         NEW.rank_address := NEW.rank_search;
1004       ELSEIF NEW.type in ('region') THEN
1005         NEW.rank_search := 10;
1006         NEW.rank_address := NEW.rank_search;
1007       ELSEIF NEW.type in ('county') THEN
1008         NEW.rank_search := 12;
1009         NEW.rank_address := NEW.rank_search;
1010       ELSEIF NEW.type in ('city') THEN
1011         NEW.rank_search := 16;
1012         NEW.rank_address := NEW.rank_search;
1013       ELSEIF NEW.type in ('island') THEN
1014         NEW.rank_search := 17;
1015         NEW.rank_address := 0;
1016       ELSEIF NEW.type in ('town') THEN
1017         NEW.rank_search := 18;
1018         NEW.rank_address := 16;
1019       ELSEIF NEW.type in ('village','hamlet','municipality','district','unincorporated_area','borough') THEN
1020         NEW.rank_search := 19;
1021         NEW.rank_address := 16;
1022       ELSEIF NEW.type in ('airport') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1023         NEW.rank_search := 18;
1024         NEW.rank_address := 17;
1025       ELSEIF NEW.type in ('moor') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1026         NEW.rank_search := 17;
1027         NEW.rank_address := 18;
1028       ELSEIF NEW.type in ('moor') THEN
1029         NEW.rank_search := 17;
1030         NEW.rank_address := 0;
1031       ELSEIF NEW.type in ('national_park') THEN
1032         NEW.rank_search := 18;
1033         NEW.rank_address := 18;
1034       ELSEIF NEW.type in ('suburb','croft','subdivision') THEN
1035         NEW.rank_search := 20;
1036         NEW.rank_address := NEW.rank_search;
1037       ELSEIF NEW.type in ('farm','locality','islet','isolated_dwelling','mountain_pass') THEN
1038         NEW.rank_search := 20;
1039         NEW.rank_address := 0;
1040         -- Irish townlands, tagged as place=locality and locality=townland
1041         IF (NEW.extratags -> 'locality') = 'townland' THEN
1042           NEW.rank_address := 20;
1043         END IF;
1044       ELSEIF NEW.type in ('hall_of_residence','neighbourhood','housing_estate','nature_reserve') THEN
1045         NEW.rank_search := 22;
1046         NEW.rank_address := 22;
1047       ELSEIF NEW.type in ('airport','street') THEN
1048         NEW.rank_search := 26;
1049         NEW.rank_address := NEW.rank_search;
1050       ELSEIF NEW.type in ('house','building') THEN
1051         NEW.rank_search := 30;
1052         NEW.rank_address := NEW.rank_search;
1053       ELSEIF NEW.type in ('houses') THEN
1054         -- can't guarantee all required nodes loaded yet due to caching in osm2pgsql
1055         -- insert new point into place for each derived building
1056         --i := create_interpolation(NEW.osm_id, NEW.housenumber);
1057         NEW.rank_search := 28;
1058         NEW.rank_address := 0;
1059       END IF;
1060
1061     ELSEIF NEW.class = 'boundary' THEN
1062       IF ST_GeometryType(NEW.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon') THEN
1063 --        RAISE WARNING 'invalid boundary %',NEW.osm_id;
1064         return NULL;
1065       END IF;
1066       NEW.rank_search := NEW.admin_level * 2;
1067       NEW.rank_address := NEW.rank_search;
1068     ELSEIF NEW.class = 'landuse' AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
1069       NEW.rank_search := 22;
1070       NEW.rank_address := NEW.rank_search;
1071     -- any feature more than 5 square miles is probably worth indexing
1072     ELSEIF ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_Area(NEW.geometry) > 0.1 THEN
1073       NEW.rank_search := 22;
1074       NEW.rank_address := NEW.rank_search;
1075     ELSEIF NEW.class = 'highway' AND NEW.name is NULL AND 
1076            NEW.type in ('service','cycleway','path','footway','steps','bridleway','track','byway','motorway_link','primary_link','trunk_link','secondary_link','tertiary_link') THEN
1077 --      RAISE WARNING 'unnamed minor feature %',NEW.osm_id;
1078       RETURN NULL;
1079     ELSEIF NEW.class = 'railway' AND NEW.type in ('rail') THEN
1080       RETURN NULL;
1081     ELSEIF NEW.class = 'waterway' AND NEW.name is NULL THEN
1082       RETURN NULL;
1083     ELSEIF NEW.class = 'waterway' THEN
1084       NEW.rank_address := 17;
1085     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
1086       NEW.rank_search := 27;
1087       NEW.rank_address := NEW.rank_search;
1088     ELSEIF NEW.class = 'highway' AND NEW.osm_type != 'N' THEN
1089       NEW.rank_search := 26;
1090       NEW.rank_address := NEW.rank_search;
1091     ELSEIF NEW.class = 'natural' and NEW.type = 'sea' THEN
1092       NEW.rank_search := 4;
1093       NEW.rank_address := NEW.rank_search;
1094     ELSEIF NEW.class = 'natural' and NEW.type in ('coastline') THEN
1095       RETURN NULL;
1096     ELSEIF NEW.class = 'natural' and NEW.type in ('peak','volcano') THEN
1097       NEW.rank_search := 18;
1098       NEW.rank_address := 0;
1099     END IF;
1100
1101   END IF;
1102
1103   IF NEW.rank_search > 30 THEN
1104     NEW.rank_search := 30;
1105   END IF;
1106
1107   IF NEW.rank_address > 30 THEN
1108     NEW.rank_address := 30;
1109   END IF;
1110
1111   IF (NEW.extratags -> 'capital') = 'yes' THEN
1112     NEW.rank_search := NEW.rank_search -1;
1113   END IF;
1114
1115 -- Block import below rank 22
1116 --  IF NEW.rank_search > 22 THEN
1117 --    RETURN NULL;
1118 --  END IF;
1119
1120   RETURN NEW;  -- The following is not needed until doing diff updates, and slows the main index process down
1121
1122   IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
1123     -- Performance: We just can't handle re-indexing for country level changes
1124     IF st_area(NEW.geometry) < 1 THEN
1125       -- mark items within the geometry for re-indexing
1126 --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1127
1128       -- work around bug in postgis, this may have been fixed in 2.0.0 (see http://trac.osgeo.org/postgis/ticket/547)
1129       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1130        AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) = 'ST_Point' and (rank_search < 28 or name is not null);
1131       update placex set indexed_status = 2 where (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
1132        AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) != 'ST_Point' and (rank_search < 28 or name is not null);
1133     END IF;
1134   ELSE
1135     -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
1136     diameter := 0;
1137     -- 16 = city, anything higher than city is effectively ignored (polygon required!)
1138     IF NEW.type='postcode' THEN
1139       diameter := 0.05;
1140     ELSEIF NEW.rank_search < 16 THEN
1141       diameter := 0;
1142     ELSEIF NEW.rank_search < 18 THEN
1143       diameter := 0.1;
1144     ELSEIF NEW.rank_search < 20 THEN
1145       diameter := 0.05;
1146     ELSEIF NEW.rank_search = 21 THEN
1147       diameter := 0.001;
1148     ELSEIF NEW.rank_search < 24 THEN
1149       diameter := 0.02;
1150     ELSEIF NEW.rank_search < 26 THEN
1151       diameter := 0.002; -- 100 to 200 meters
1152     ELSEIF NEW.rank_search < 28 THEN
1153       diameter := 0.001; -- 50 to 100 meters
1154     END IF;
1155     IF diameter > 0 THEN
1156 --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
1157       update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter) and (rank_search < 28 or name is not null);
1158     END IF;
1159
1160   END IF;
1161
1162    -- add to tables for special search
1163    -- Note: won't work on initial import because the classtype tables
1164    -- do not yet exist. It won't hurt either.
1165   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
1166   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable INTO result;
1167   IF result THEN
1168     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
1169     USING NEW.place_id, ST_Centroid(NEW.geometry);
1170   END IF;
1171
1172
1173 --  IF NEW.rank_search < 26 THEN
1174 --    RAISE WARNING 'placex insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1175 --  END IF;
1176
1177   RETURN NEW;
1178
1179 END;
1180 $$
1181 LANGUAGE plpgsql;
1182
1183 CREATE OR REPLACE FUNCTION placex_update() RETURNS 
1184 TRIGGER
1185   AS $$
1186 DECLARE
1187
1188   place_centroid GEOMETRY;
1189
1190   search_maxdistance FLOAT[];
1191   search_mindistance FLOAT[];
1192   address_havelevel BOOLEAN[];
1193 --  search_scores wordscore[];
1194 --  search_scores_pos INTEGER;
1195
1196   i INTEGER;
1197   iMax FLOAT;
1198   location RECORD;
1199   way RECORD;
1200   relation RECORD;
1201   relation_members TEXT[];
1202   relMember RECORD;
1203   linkedplacex RECORD;
1204   search_diameter FLOAT;
1205   search_prevdiameter FLOAT;
1206   search_maxrank INTEGER;
1207   address_maxrank INTEGER;
1208   address_street_word_id INTEGER;
1209   parent_place_id_rank BIGINT;
1210   
1211   isin TEXT[];
1212   isin_tokens INT[];
1213
1214   location_rank_search INTEGER;
1215   location_distance FLOAT;
1216
1217   tagpairid INTEGER;
1218
1219   default_language TEXT;
1220   name_vector INTEGER[];
1221   nameaddress_vector INTEGER[];
1222
1223   result BOOLEAN;
1224 BEGIN
1225
1226 --RAISE WARNING '%',NEW.place_id;
1227 --RAISE WARNING '%', NEW;
1228
1229   IF NEW.class = 'place' AND NEW.type = 'postcodearea' THEN
1230     -- Silently do nothing
1231     RETURN NEW;
1232   END IF;
1233
1234   -- deferred delete
1235   IF OLD.indexed_status = 100 THEN
1236     delete from placex where place_id = OLD.place_id;
1237     RETURN NULL;
1238   END IF;
1239
1240   IF NEW.indexed_status = 0 and OLD.indexed_status != 0 THEN
1241
1242     NEW.indexed_date = now();
1243
1244     IF NEW.class = 'place' AND NEW.type = 'houses' THEN
1245       i := create_interpolation(NEW.osm_id, NEW.housenumber);
1246       RETURN NEW;
1247     END IF;
1248
1249     IF OLD.indexed_status > 1 THEN
1250       result := deleteSearchName(NEW.partition, NEW.place_id);
1251       DELETE FROM place_addressline WHERE place_id = NEW.place_id;
1252       DELETE FROM place_boundingbox where place_id = NEW.place_id;
1253       result := deleteRoad(NEW.partition, NEW.place_id);
1254       result := deleteLocationArea(NEW.partition, NEW.place_id);
1255       UPDATE placex set linked_place_id = null where linked_place_id = NEW.place_id;
1256     END IF;
1257
1258     -- reclaculate country and partition (should probably have a country_code and calculated_country_code as seperate fields)
1259     SELECT country_code from place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type INTO NEW.country_code;
1260     NEW.country_code := lower(get_country_code(NEW.geometry, NEW.country_code));
1261     NEW.partition := get_partition(NEW.geometry, NEW.country_code);
1262     NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
1263
1264     -- Adding ourselves to the list simplifies address calculations later
1265     INSERT INTO place_addressline VALUES (NEW.place_id, NEW.place_id, true, true, 0, NEW.rank_address); 
1266
1267     -- What level are we searching from
1268     search_maxrank := NEW.rank_search;
1269
1270     -- Speed up searches - just use the centroid of the feature
1271     -- cheaper but less acurate
1272     place_centroid := ST_Centroid(NEW.geometry);
1273     NEW.centroid := null;
1274
1275     -- Thought this wasn't needed but when we add new languages to the country_name table
1276     -- we need to update the existing names
1277     IF NEW.name is not null AND array_upper(akeys(NEW.name),1) > 1 THEN
1278       default_language := get_country_language_code(NEW.country_code);
1279       IF default_language IS NOT NULL THEN
1280         IF NEW.name ? 'name' AND NOT NEW.name ? ('name:'||default_language) THEN
1281           NEW.name := NEW.name || (('name:'||default_language) => (NEW.name -> 'name'));
1282         ELSEIF NEW.name ? ('name:'||default_language) AND NOT NEW.name ? 'name' THEN
1283           NEW.name := NEW.name || ('name' => (NEW.name -> ('name:'||default_language)));
1284         END IF;
1285       END IF;
1286     END IF;
1287
1288     -- Initialise the name vector using our name
1289     name_vector := make_keywords(NEW.name);
1290     nameaddress_vector := '{}'::int[];
1291
1292     -- some tag combinations add a special id for search
1293     tagpairid := get_tagpair(NEW.class,NEW.type);
1294     IF tagpairid IS NOT NULL THEN
1295       name_vector := name_vector + tagpairid;
1296     END IF;
1297
1298     FOR i IN 1..28 LOOP
1299       address_havelevel[i] := false;
1300     END LOOP;
1301
1302 --RAISE WARNING '% %', NEW.place_id, NEW.rank_search;
1303
1304     -- For low level elements we inherit from our parent road
1305     IF (NEW.rank_search > 27 OR (NEW.type = 'postcode' AND NEW.rank_search = 25)) THEN
1306
1307 --RAISE WARNING 'finding street for %', NEW;
1308
1309       NEW.parent_place_id := null;
1310
1311       -- to do that we have to find our parent road
1312       -- Copy data from linked items (points on ways, addr:street links, relations)
1313       -- Note that addr:street links can only be indexed once the street itself is indexed
1314       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'N' THEN
1315
1316         -- Is this node part of a relation?
1317         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id::integer] and members @> ARRAY['n'||NEW.osm_id]
1318         LOOP
1319           -- At the moment we only process one type of relation - associatedStreet
1320           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1321             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1322               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1323 --RAISE WARNING 'node in relation %',relation;
1324                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1325                   and rank_search = 26 INTO NEW.parent_place_id;
1326               END IF;
1327             END LOOP;
1328           END IF;
1329         END LOOP;      
1330
1331 --RAISE WARNING 'x1';
1332         -- Is this node part of a way?
1333         FOR way IN select id from planet_osm_ways where nodes @> ARRAY[NEW.osm_id::integer] LOOP
1334 --RAISE WARNING '%', way;
1335         FOR location IN select * from placex where osm_type = 'W' and osm_id = way.id
1336         LOOP
1337 --RAISE WARNING '%', location;
1338           -- Way IS a road then we are on it - that must be our road
1339           IF location.rank_search = 26 AND NEW.parent_place_id IS NULL THEN
1340 --RAISE WARNING 'node in way that is a street %',location;
1341             NEW.parent_place_id := location.place_id;
1342           END IF;
1343
1344           -- Is the WAY part of a relation
1345           IF NEW.parent_place_id IS NULL THEN
1346               FOR relation IN select * from planet_osm_rels where parts @> ARRAY[location.osm_id::integer] and members @> ARRAY['w'||location.osm_id]
1347               LOOP
1348                 -- At the moment we only process one type of relation - associatedStreet
1349                 IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1350                   FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1351                     IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1352     --RAISE WARNING 'node in way that is in a relation %',relation;
1353                       SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer 
1354                         and rank_search = 26 INTO NEW.parent_place_id;
1355                     END IF;
1356                   END LOOP;
1357                 END IF;
1358               END LOOP;
1359           END IF;    
1360           
1361           -- If the way contains an explicit name of a street copy it
1362           IF NEW.street IS NULL AND location.street IS NOT NULL THEN
1363 --RAISE WARNING 'node in way that has a streetname %',location;
1364             NEW.street := location.street;
1365           END IF;
1366
1367           -- If this way is a street interpolation line then it is probably as good as we are going to get
1368           IF NEW.parent_place_id IS NULL AND NEW.street IS NULL AND location.class = 'place' and location.type='houses' THEN
1369             -- Try and find a way that is close roughly parellel to this line
1370             FOR relation IN SELECT place_id FROM placex
1371               WHERE ST_DWithin(location.geometry, placex.geometry, 0.001) and placex.rank_search = 26
1372                 and st_geometrytype(location.geometry) in ('ST_LineString')
1373               ORDER BY (ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0))+
1374                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,0.5))+
1375                         ST_distance(placex.geometry, ST_Line_Interpolate_Point(location.geometry,1))) ASC limit 1
1376             LOOP
1377 --RAISE WARNING 'using nearest street to address interpolation line,0.001 %',relation;
1378               NEW.parent_place_id := relation.place_id;
1379             END LOOP;
1380           END IF;
1381
1382         END LOOP;
1383         END LOOP;
1384                 
1385       END IF;
1386
1387 --RAISE WARNING 'x2';
1388
1389       IF NEW.parent_place_id IS NULL AND NEW.osm_type = 'W' THEN
1390         -- Is this way part of a relation?
1391         FOR relation IN select * from planet_osm_rels where parts @> ARRAY[NEW.osm_id::integer] and members @> ARRAY['w'||NEW.osm_id]
1392         LOOP
1393           -- At the moment we only process one type of relation - associatedStreet
1394           IF relation.tags @> ARRAY['associatedStreet'] AND array_upper(relation.members, 1) IS NOT NULL THEN
1395             FOR i IN 1..array_upper(relation.members, 1) BY 2 LOOP
1396               IF NEW.parent_place_id IS NULL AND relation.members[i+1] = 'street' THEN
1397 --RAISE WARNING 'way that is in a relation %',relation;
1398                 SELECT place_id from placex where osm_type='W' and osm_id = substring(relation.members[i],2,200)::integer
1399                   and rank_search = 26 INTO NEW.parent_place_id;
1400               END IF;
1401             END LOOP;
1402           END IF;
1403         END LOOP;
1404       END IF;
1405       
1406 --RAISE WARNING 'x3 %',NEW.parent_place_id;
1407
1408       IF NEW.parent_place_id IS NULL AND NEW.street IS NOT NULL THEN
1409         address_street_word_id := get_name_id(make_standard_name(NEW.street));
1410         IF address_street_word_id IS NOT NULL THEN
1411           FOR location IN SELECT * from getNearestNamedRoadFeature(NEW.partition, place_centroid, address_street_word_id) LOOP
1412             NEW.parent_place_id := location.place_id;
1413           END LOOP;
1414         END IF;
1415       END IF;
1416
1417 --RAISE WARNING 'x4 %',NEW.parent_place_id;
1418       -- Still nothing, just use the nearest road
1419       IF NEW.parent_place_id IS NULL THEN
1420         FOR location IN SELECT place_id FROM getNearestRoadFeature(NEW.partition, place_centroid) LOOP
1421           NEW.parent_place_id := location.place_id;
1422         END LOOP;
1423       END IF;
1424
1425 --return NEW;
1426 --RAISE WARNING 'x6 %',NEW.parent_place_id;
1427
1428       -- If we didn't find any road fallback to standard method
1429       IF NEW.parent_place_id IS NOT NULL THEN
1430
1431         -- Add the street to the address as zero distance to force to front of list
1432 --        INSERT INTO place_addressline VALUES (NEW.place_id, NEW.parent_place_id, true, true, 0, 26);
1433         address_havelevel[26] := true;
1434
1435         -- Import address details from parent, reclculating distance in process
1436 --        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
1437 --          from place_addressline as x join placex on (address_place_id = placex.place_id)
1438 --          where x.place_id = NEW.parent_place_id and x.address_place_id != NEW.parent_place_id;
1439
1440         -- Get the details of the parent road
1441         select * from search_name where place_id = NEW.parent_place_id INTO location;
1442         NEW.country_code := location.country_code;
1443
1444 --RAISE WARNING '%', NEW.name;
1445         -- If there is no name it isn't searchable, don't bother to create a search record
1446         IF NEW.name is NULL THEN
1447           return NEW;
1448         END IF;
1449
1450         -- Merge address from parent
1451         nameaddress_vector := array_merge(nameaddress_vector, location.nameaddress_vector);
1452 --return NEW;
1453         -- Performance, it would be more acurate to do all the rest of the import process but it takes too long
1454         -- Just be happy with inheriting from parent road only
1455
1456         IF NEW.rank_search <= 25 THEN
1457           result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1458         END IF;
1459
1460         result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, NEW.importance, place_centroid);
1461
1462         return NEW;
1463       END IF;
1464
1465     END IF;
1466
1467 -- RAISE WARNING '  INDEXING: %',NEW;
1468
1469     IF NEW.osm_type = 'R' AND NEW.rank_search < 26 THEN
1470
1471       -- see if we have any special relation members
1472       select members from planet_osm_rels where id = NEW.osm_id INTO relation_members;
1473
1474       FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['label']) as member LOOP
1475
1476         select * from placex where osm_type = upper(substring(relMember.member,1,1)) 
1477           and osm_id = substring(relMember.member,2,10000)::integer order by rank_search desc limit 1 into linkedPlacex;
1478
1479         -- If we don't already have one use this as the centre point of the geometry
1480         IF NEW.centroid IS NULL THEN
1481           NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1482         END IF;
1483
1484         -- merge in the label name, re-init word vector
1485         NEW.name := linkedPlacex.name || NEW.name;
1486         name_vector := make_keywords(NEW.name);
1487
1488         -- merge in extra tags
1489         NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1490
1491         -- mark the linked place (excludes from search results)
1492         UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1493
1494       END LOOP;
1495
1496       IF NEW.centroid IS NULL THEN
1497
1498         FOR relMember IN select get_osm_rel_members(relation_members,ARRAY['admin_center','admin_centre']) as member LOOP
1499
1500           select * from placex where osm_type = upper(substring(relMember.member,1,1)) 
1501             and osm_id = substring(relMember.member,2,10000)::integer order by rank_search desc limit 1 into linkedPlacex;
1502
1503           IF NEW.name->'name' = linkedPlacex.name->'name' AND NEW.rank_search = linkedPlacex.rank_search THEN
1504             -- If we don't already have one use this as the centre point of the geometry
1505             IF NEW.centroid IS NULL THEN
1506               NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1507             END IF;
1508
1509             -- merge in the name, re-init word vector
1510             NEW.name := linkedPlacex.name || NEW.name;
1511             name_vector := make_keywords(NEW.name);
1512
1513             -- merge in extra tags
1514             NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1515
1516             -- mark the linked place (excludes from search results)
1517             UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1518           END IF;
1519
1520         END LOOP;
1521
1522       END IF;
1523
1524       -- not found one yet? how about doing a name search
1525       IF NEW.centroid IS NULL THEN
1526         FOR linkedPlacex IN select placex.* from search_name join placex using (place_id) WHERE
1527           search_name.name_vector @> ARRAY[getorcreate_name_id(make_standard_name(NEW.name->'name'))] 
1528           AND search_name.search_rank = NEW.rank_search
1529           AND search_name.place_id != NEW.place_id
1530           AND osm_type = 'N'
1531           AND NEW.name->'name' = placex.name->'name'
1532           AND st_contains(NEW.geometry, placex.geometry)
1533         LOOP
1534           -- If we don't already have one use this as the centre point of the geometry
1535           IF NEW.centroid IS NULL THEN
1536             NEW.centroid := coalesce(linkedPlacex.centroid,st_centroid(linkedPlacex.geometry));
1537           END IF;
1538
1539           -- merge in the name, re-init word vector
1540           NEW.name := linkedPlacex.name || NEW.name;
1541           name_vector := make_keywords(NEW.name);
1542
1543           -- merge in extra tags
1544           NEW.extratags := linkedPlacex.extratags || NEW.extratags;
1545
1546           -- mark the linked place (excludes from search results)
1547           UPDATE placex set linked_place_id = NEW.place_id where place_id = linkedPlacex.place_id;
1548
1549         END LOOP;
1550       END IF;
1551
1552       IF NEW.centroid IS NOT NULL THEN
1553         place_centroid := NEW.centroid;
1554       END IF;
1555
1556     END IF;
1557
1558     NEW.parent_place_id = 0;
1559     parent_place_id_rank = 0;
1560
1561     -- convert isin to array of tokenids
1562     isin_tokens := '{}'::int[];
1563     IF NEW.isin IS NOT NULL THEN
1564       isin := regexp_split_to_array(NEW.isin, E'[;,]');
1565       IF array_upper(isin, 1) IS NOT NULL THEN
1566         FOR i IN 1..array_upper(isin, 1) LOOP
1567           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1568           IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1569             isin_tokens := isin_tokens || address_street_word_id;
1570           END IF;
1571         END LOOP;
1572       END IF;
1573     END IF;
1574     IF NEW.postcode IS NOT NULL THEN
1575       isin := regexp_split_to_array(NEW.postcode, E'[;,]');
1576       IF array_upper(isin, 1) IS NOT NULL THEN
1577         FOR i IN 1..array_upper(isin, 1) LOOP
1578           address_street_word_id := get_name_id(make_standard_name(isin[i]));
1579           IF address_street_word_id IS NOT NULL AND NOT(ARRAY[address_street_word_id] <@ isin_tokens) THEN
1580             isin_tokens := isin_tokens || address_street_word_id;
1581           END IF;
1582         END LOOP;
1583       END IF;
1584     END IF;
1585 --RAISE WARNING 'ISIN: %', isin_tokens;
1586
1587     -- Process area matches
1588     location_rank_search := 100;
1589     location_distance := 0;
1590 --RAISE WARNING '  getNearFeatures(%,''%'',%,''%'')',NEW.partition, place_centroid, search_maxrank, isin_tokens;
1591     FOR location IN SELECT * from getNearFeatures(NEW.partition, place_centroid, search_maxrank, isin_tokens) LOOP
1592
1593 --RAISE WARNING '  AREA: %',location;
1594
1595       IF location.rank_search < location_rank_search THEN
1596         location_rank_search := location.rank_search;
1597         location_distance := location.distance * 1.5;
1598       END IF;
1599
1600       IF location.distance < location_distance OR NOT location.isguess THEN
1601
1602         -- Add it to the list of search terms
1603         nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1604         INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, NOT address_havelevel[location.rank_address], location.distance, location.rank_address); 
1605         address_havelevel[location.rank_address] := true;
1606
1607 --RAISE WARNING '  Terms: (%) %',location, nameaddress_vector;
1608
1609         IF location.rank_address > parent_place_id_rank THEN
1610           NEW.parent_place_id = location.place_id;
1611           parent_place_id_rank = location.rank_address;
1612         END IF;
1613
1614       END IF;
1615
1616     END LOOP;
1617
1618     -- try using the isin value to find parent places
1619     IF array_upper(isin_tokens, 1) IS NOT NULL THEN
1620       FOR i IN 1..array_upper(isin_tokens, 1) LOOP
1621 --RAISE WARNING '  getNearestNamedFeature: % % % %',NEW.partition, place_centroid, search_maxrank, isin_tokens[i];
1622
1623         FOR location IN SELECT * from getNearestNamedFeature(NEW.partition, place_centroid, search_maxrank, isin_tokens[i]) LOOP
1624
1625 --RAISE WARNING '  ISIN: %',location;
1626
1627           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1628           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, false, NOT address_havelevel[location.rank_address], location.distance, location.rank_address);
1629           address_havelevel[location.rank_address] := true;
1630
1631           IF location.rank_address > parent_place_id_rank THEN
1632             NEW.parent_place_id = location.place_id;
1633             parent_place_id_rank = location.rank_address;
1634           END IF;
1635
1636         END LOOP;
1637
1638       END LOOP;
1639     END IF;
1640
1641     -- for long ways we should add search terms for the entire length
1642     IF st_length(NEW.geometry) > 0.05 THEN
1643
1644       location_rank_search := 100;
1645       location_distance := 0;
1646
1647       FOR location IN SELECT * from getNearFeatures(NEW.partition, NEW.geometry, search_maxrank, isin_tokens) LOOP
1648
1649         IF location.rank_search < location_rank_search THEN
1650           location_rank_search := location.rank_search;
1651           location_distance := location.distance * 1.5;
1652         END IF;
1653
1654         IF location.distance < location_distance THEN
1655
1656           -- Add it to the list of search terms
1657           nameaddress_vector := array_merge(nameaddress_vector, location.keywords::integer[]);
1658           INSERT INTO place_addressline VALUES (NEW.place_id, location.place_id, true, false, location.distance, location.rank_address); 
1659
1660         END IF;
1661
1662       END LOOP;
1663
1664     END IF;
1665
1666     -- if we have a name add this to the name search table
1667     IF NEW.name IS NOT NULL THEN
1668
1669       IF NEW.rank_search <= 25 THEN
1670         result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, NEW.geometry);
1671       END IF;
1672
1673       IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1674         result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1675       END IF;
1676
1677       result := insertSearchName(NEW.partition, NEW.place_id, NEW.country_code, name_vector, nameaddress_vector, NEW.rank_search, NEW.rank_address, NEW.importance, place_centroid);
1678
1679 --      INSERT INTO search_name values (NEW.place_id, NEW.rank_search, NEW.rank_search, 0, NEW.country_code, name_vector, nameaddress_vector, place_centroid);
1680     END IF;
1681
1682     -- If we've not managed to pick up a better one - default centroid
1683     IF NEW.centroid IS NULL THEN
1684       NEW.centroid := place_centroid;
1685     END IF;
1686
1687   END IF;
1688
1689   RETURN NEW;
1690 END;
1691 $$
1692 LANGUAGE plpgsql;
1693
1694 CREATE OR REPLACE FUNCTION placex_delete() RETURNS TRIGGER
1695   AS $$
1696 DECLARE
1697   b BOOLEAN;
1698   classtable TEXT;
1699 BEGIN
1700
1701   update placex set linked_place_id = null where linked_place_id = OLD.place_id;
1702   update placex set indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
1703
1704   IF OLD.rank_address < 30 THEN
1705
1706     -- mark everything linked to this place for re-indexing
1707     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1708       and placex.place_id = place_addressline.place_id and indexed_status = 0;
1709
1710     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1711
1712     b := deleteRoad(OLD.partition, OLD.place_id);
1713
1714     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1715
1716   END IF;
1717
1718   IF OLD.rank_address < 26 THEN
1719     b := deleteLocationArea(OLD.partition, OLD.place_id);
1720   END IF;
1721
1722   IF OLD.name is not null THEN
1723     b := deleteSearchName(OLD.partition, OLD.place_id);
1724   END IF;
1725
1726   DELETE FROM place_addressline where place_id = OLD.place_id;
1727
1728   -- remove from tables for special search
1729   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1730   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable INTO b;
1731   IF b THEN
1732     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1733   END IF;
1734
1735   RETURN OLD;
1736
1737 END;
1738 $$
1739 LANGUAGE plpgsql;
1740
1741 CREATE OR REPLACE FUNCTION place_delete() RETURNS TRIGGER
1742   AS $$
1743 DECLARE
1744   placeid BIGINT;
1745 BEGIN
1746
1747 --  RAISE WARNING 'delete: % % % %',OLD.osm_type,OLD.osm_id,OLD.class,OLD.type;
1748
1749   -- deleting large polygons can have a massive effect ont he system - require manual intervention to let them through
1750   IF st_area(OLD.geometry) > 2 THEN
1751     insert into import_polygon_delete values (OLD.osm_type,OLD.osm_id,OLD.class,OLD.type);
1752     RETURN NULL;
1753   END IF;
1754
1755   -- mark for delete
1756   UPDATE placex set indexed_status = 100 where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1757
1758 --  delete from placex where osm_type = OLD.osm_type and osm_id = OLD.osm_id and class = OLD.class and type = OLD.type;
1759   RETURN OLD;
1760
1761 END;
1762 $$
1763 LANGUAGE plpgsql;
1764
1765 CREATE OR REPLACE FUNCTION place_insert() RETURNS TRIGGER
1766   AS $$
1767 DECLARE
1768   i INTEGER;
1769   existing RECORD;
1770   existingplacex RECORD;
1771   existinggeometry GEOMETRY;
1772   existingplace_id BIGINT;
1773   result BOOLEAN;
1774   partition INTEGER;
1775 BEGIN
1776
1777   IF FALSE and NEW.osm_type = 'R' THEN
1778     RAISE WARNING '-----------------------------------------------------------------------------------';
1779     RAISE WARNING 'place_insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,st_area(NEW.geometry);
1780     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;
1781     RAISE WARNING '%', existingplacex;
1782   END IF;
1783
1784   -- Just block these - lots and pointless
1785   IF NEW.class = 'highway' and NEW.type in ('turning_circle','traffic_signals','mini_roundabout','noexit','crossing') THEN
1786     RETURN null;
1787   END IF;
1788   IF NEW.class in ('landuse','natural') and NEW.name is null THEN
1789     RETURN null;
1790   END IF;
1791
1792   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  
1793     INSERT INTO import_polygon_error values (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.country_code, 
1794       now(), ST_IsValidReason(NEW.geometry), null, NEW.geometry);
1795 --    RAISE WARNING 'Invalid Geometry: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1796     RETURN null;
1797   END IF;
1798
1799   -- Patch in additional country names
1800   IF NEW.admin_level = 2 AND NEW.type = 'administrative' AND NEW.country_code is not null THEN
1801     select country_name.name || NEW.name from country_name where country_name.country_code = lower(NEW.country_code) INTO NEW.name;
1802   END IF;
1803     
1804   -- Have we already done this place?
1805   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;
1806
1807   -- Get the existing place_id
1808   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;
1809
1810   -- Handle a place changing type by removing the old data
1811   -- My generated 'place' types are causing havok because they overlap with real keys
1812   -- TODO: move them to their own special purpose key/class to avoid collisions
1813   IF existing.osm_type IS NULL AND (NEW.type not in ('postcode','house','houses')) THEN
1814     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');
1815   END IF;
1816
1817 --  RAISE WARNING 'Existing: %',existing.place_id;
1818
1819   -- Log and discard 
1820   IF existing.geometry is not null AND st_isvalid(existing.geometry) 
1821     AND st_area(existing.geometry) > 0.02
1822     AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')
1823     AND st_area(NEW.geometry) < st_area(existing.geometry)*0.5
1824     THEN
1825     INSERT INTO import_polygon_error values (NEW.osm_type, NEW.osm_id, NEW.class, NEW.type, NEW.name, NEW.country_code, now(), 
1826       'Area reduced from '||st_area(existing.geometry)||' to '||st_area(NEW.geometry), existing.geometry, NEW.geometry);
1827     RETURN null;
1828   END IF;
1829
1830   DELETE from import_polygon_error where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1831   DELETE from import_polygon_delete where osm_type = NEW.osm_type and osm_id = NEW.osm_id;
1832
1833   -- 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
1834   IF existing.osm_type IS NULL 
1835      OR existingplacex.osm_type IS NULL
1836      OR coalesce(existing.admin_level, 100) != coalesce(NEW.admin_level, 100) 
1837      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
1838      OR (existing.geometry::text != NEW.geometry::text AND ST_Distance(ST_Centroid(existing.geometry),ST_Centroid(NEW.geometry)) > 0.01 AND NOT
1839      (ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon')))
1840      THEN
1841
1842 --  IF existing.osm_type IS NULL THEN
1843 --    RAISE WARNING 'no existing place';
1844 --  END IF;
1845 --  IF existingplacex.osm_type IS NULL THEN
1846 --    RAISE WARNING 'no existing placex %', existingplacex;
1847 --  END IF;
1848
1849 --    RAISE WARNING 'delete and replace';
1850
1851     IF existing.osm_type IS NOT NULL THEN
1852 --      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;
1853       DELETE FROM place where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1854     END IF;   
1855
1856 --    RAISE WARNING 'delete and replace2';
1857
1858     -- No - process it as a new insertion (hopefully of low rank or it will be slow)
1859     insert into placex (osm_type, osm_id, class, type, name, admin_level, housenumber, 
1860       street, isin, postcode, country_code, extratags, geometry)
1861       values (NEW.osm_type
1862         ,NEW.osm_id
1863         ,NEW.class
1864         ,NEW.type
1865         ,NEW.name
1866         ,NEW.admin_level
1867         ,NEW.housenumber
1868         ,NEW.street
1869         ,NEW.isin
1870         ,NEW.postcode
1871         ,NEW.country_code
1872         ,NEW.extratags
1873         ,NEW.geometry
1874         );
1875
1876 --    RAISE WARNING 'insert done % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
1877
1878     RETURN NEW;
1879   END IF;
1880
1881   -- Various ways to do the update
1882
1883   -- Debug, what's changed?
1884   IF FALSE THEN
1885     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') THEN
1886       RAISE WARNING 'update details, name: % % % %',NEW.osm_type,NEW.osm_id,existing.name::text,NEW.name::text;
1887     END IF;
1888     IF coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '') THEN
1889       RAISE WARNING 'update details, housenumber: % % % %',NEW.osm_type,NEW.osm_id,existing.housenumber,NEW.housenumber;
1890     END IF;
1891     IF coalesce(existing.street, '') != coalesce(NEW.street, '') THEN
1892       RAISE WARNING 'update details, street: % % % %',NEW.osm_type,NEW.osm_id,existing.street,NEW.street;
1893     END IF;
1894     IF coalesce(existing.isin, '') != coalesce(NEW.isin, '') THEN
1895       RAISE WARNING 'update details, isin: % % % %',NEW.osm_type,NEW.osm_id,existing.isin,NEW.isin;
1896     END IF;
1897     IF coalesce(existing.postcode, '') != coalesce(NEW.postcode, '') THEN
1898       RAISE WARNING 'update details, postcode: % % % %',NEW.osm_type,NEW.osm_id,existing.postcode,NEW.postcode;
1899     END IF;
1900     IF coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1901       RAISE WARNING 'update details, country_code: % % % %',NEW.osm_type,NEW.osm_id,existing.country_code,NEW.country_code;
1902     END IF;
1903   END IF;
1904
1905   -- Special case for polygon shape changes because they tend to be large and we can be a bit clever about how we handle them
1906   IF existing.geometry::text != NEW.geometry::text 
1907      AND ST_GeometryType(existing.geometry) in ('ST_Polygon','ST_MultiPolygon')
1908      AND ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') 
1909      THEN 
1910
1911     -- Get the version of the geometry actually used (in placex table)
1912     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;
1913
1914     -- Performance limit
1915     IF st_area(NEW.geometry) < 0.000000001 AND st_area(existinggeometry) < 1 THEN
1916
1917       -- 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
1918       update placex set indexed_status = 2 where indexed_status = 0 and 
1919           (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1920           AND NOT (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1921           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1922
1923       update placex set indexed_status = 2 where indexed_status = 0 and 
1924           (ST_Contains(existinggeometry, placex.geometry) OR ST_Intersects(existinggeometry, placex.geometry))
1925           AND NOT (ST_Contains(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry))
1926           AND rank_search > existingplacex.rank_search AND (rank_search < 28 or name is not null);
1927
1928     END IF;
1929
1930   END IF;
1931
1932   -- Special case - if we are just adding extra words we hack them into the search_name table rather than reindexing
1933   IF FALSE AND existingplacex.rank_search < 26
1934      AND coalesce(existing.housenumber, '') = coalesce(NEW.housenumber, '')
1935      AND coalesce(existing.street, '') = coalesce(NEW.street, '')
1936      AND coalesce(existing.isin, '') = coalesce(NEW.isin, '')
1937      AND coalesce(existing.postcode, '') = coalesce(NEW.postcode, '')
1938      AND coalesce(existing.country_code, '') = coalesce(NEW.country_code, '')
1939      AND coalesce(existing.name::text, '') != coalesce(NEW.name::text, '') 
1940      THEN
1941
1942     IF NOT update_location_nameonly(existingplacex.place_id, NEW.name) THEN
1943
1944       IF st_area(NEW.geometry) < 0.5 THEN
1945         UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
1946           and placex.place_id = place_addressline.place_id and indexed_status = 0
1947           and (rank_search < 28 or name is not null);
1948       END IF;
1949
1950     END IF;
1951   
1952   ELSE
1953
1954     -- Anything else has changed - reindex the lot
1955     IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1956         OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
1957         OR coalesce(existing.street, '') != coalesce(NEW.street, '')
1958         OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
1959         OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
1960         OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '') THEN
1961
1962       -- performance, can't take the load of re-indexing a whole country / huge area
1963       IF st_area(NEW.geometry) < 0.5 THEN
1964 --        UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = existingplacex.place_id 
1965 --          and placex.place_id = place_addressline.place_id and indexed_status = 0;
1966       END IF;
1967
1968     END IF;
1969
1970   END IF;
1971
1972   IF coalesce(existing.name::text, '') != coalesce(NEW.name::text, '')
1973      OR coalesce(existing.extratags::text, '') != coalesce(NEW.extratags::text, '')
1974      OR coalesce(existing.housenumber, '') != coalesce(NEW.housenumber, '')
1975      OR coalesce(existing.street, '') != coalesce(NEW.street, '')
1976      OR coalesce(existing.isin, '') != coalesce(NEW.isin, '')
1977      OR coalesce(existing.postcode, '') != coalesce(NEW.postcode, '')
1978      OR coalesce(existing.country_code, '') != coalesce(NEW.country_code, '')
1979      OR existing.geometry::text != NEW.geometry::text
1980      THEN
1981
1982     update place set 
1983       name = NEW.name,
1984       housenumber  = NEW.housenumber,
1985       street = NEW.street,
1986       isin = NEW.isin,
1987       postcode = NEW.postcode,
1988       country_code = NEW.country_code,
1989       extratags = NEW.extratags,
1990       geometry = NEW.geometry
1991       where osm_type = NEW.osm_type and osm_id = NEW.osm_id and class = NEW.class and type = NEW.type;
1992
1993     update placex set 
1994       name = NEW.name,
1995       housenumber = NEW.housenumber,
1996       street = NEW.street,
1997       isin = NEW.isin,
1998       postcode = NEW.postcode,
1999       country_code = NEW.country_code,
2000       parent_place_id = null,
2001       extratags = NEW.extratags,
2002       indexed_status = 2,    
2003       geometry = NEW.geometry
2004       where place_id = existingplacex.place_id;
2005
2006 -- now done as part of insert
2007 --    partition := get_partition(NEW.geometry, existingplacex.country_code);
2008 --    result := update_location(partition, existingplacex.place_id, existingplacex.country_code, NEW.name, existingplacex.rank_search, existingplacex.rank_address, NEW.geometry);
2009
2010   END IF;
2011
2012   -- Abort the add (we modified the existing place instead)
2013   RETURN NULL;
2014
2015 END; 
2016 $$ LANGUAGE plpgsql;
2017
2018 CREATE OR REPLACE FUNCTION get_name_by_language(name hstore, languagepref TEXT[]) RETURNS TEXT
2019   AS $$
2020 DECLARE
2021   search TEXT[];
2022   found BOOLEAN;
2023 BEGIN
2024
2025   IF name is null THEN
2026     RETURN null;
2027   END IF;
2028
2029   search := languagepref;
2030
2031   FOR j IN 1..array_upper(search, 1) LOOP
2032     IF name ? search[j] AND trim(name->search[j]) != '' THEN
2033       return trim(name->search[j]);
2034     END IF;
2035   END LOOP;
2036
2037   RETURN null;
2038 END;
2039 $$
2040 LANGUAGE plpgsql IMMUTABLE;
2041
2042 CREATE OR REPLACE FUNCTION get_connected_ways(way_ids INTEGER[]) RETURNS SETOF planet_osm_ways
2043   AS $$
2044 DECLARE
2045   searchnodes INTEGER[];
2046   location RECORD;
2047   j INTEGER;
2048 BEGIN
2049
2050   searchnodes := '{}';
2051   FOR j IN 1..array_upper(way_ids, 1) LOOP
2052     FOR location IN 
2053       select nodes from planet_osm_ways where id = way_ids[j] LIMIT 1
2054     LOOP
2055       IF not (ARRAY[location.nodes] <@ searchnodes) THEN
2056         searchnodes := searchnodes || location.nodes;
2057       END IF;
2058     END LOOP;
2059   END LOOP;
2060
2061   RETURN QUERY select * from planet_osm_ways where nodes && searchnodes and NOT ARRAY[id] <@ way_ids;
2062 END;
2063 $$
2064 LANGUAGE plpgsql IMMUTABLE;
2065
2066 CREATE OR REPLACE FUNCTION get_address_postcode(for_place_id BIGINT) RETURNS TEXT
2067   AS $$
2068 DECLARE
2069   result TEXT[];
2070   search TEXT[];
2071   for_postcode TEXT;
2072   found INTEGER;
2073   location RECORD;
2074 BEGIN
2075
2076   found := 1000;
2077   search := ARRAY['ref'];
2078   result := '{}';
2079
2080   select postcode from placex where place_id = for_place_id limit 1 into for_postcode;
2081
2082   FOR location IN 
2083     select rank_address,name,distance,length(name::text) as namelength 
2084       from place_addressline join placex on (address_place_id = placex.place_id) 
2085       where place_addressline.place_id = for_place_id and rank_address in (5,11)
2086       order by rank_address desc,rank_search desc,fromarea desc,distance asc,namelength desc
2087   LOOP
2088     IF array_upper(search, 1) IS NOT NULL AND array_upper(location.name, 1) IS NOT NULL THEN
2089       FOR j IN 1..array_upper(search, 1) LOOP
2090         FOR k IN 1..array_upper(location.name, 1) LOOP
2091           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
2092             result[(100 - location.rank_address)] := trim(location.name[k].value);
2093             found := location.rank_address;
2094           END IF;
2095         END LOOP;
2096       END LOOP;
2097     END IF;
2098   END LOOP;
2099
2100   RETURN array_to_string(result,', ');
2101 END;
2102 $$
2103 LANGUAGE plpgsql;
2104
2105 CREATE OR REPLACE FUNCTION get_address_by_language(for_place_id BIGINT, languagepref TEXT[]) RETURNS TEXT
2106   AS $$
2107 DECLARE
2108   result TEXT[];
2109   currresult TEXT;
2110   prevresult TEXT;
2111   location RECORD;
2112 BEGIN
2113
2114   result := '{}';
2115   prevresult := '';
2116
2117   FOR location IN select * from get_addressdata(for_place_id) where isaddress order by rank_address desc LOOP
2118     currresult := trim(get_name_by_language(location.name, languagepref));
2119     IF currresult != prevresult AND currresult IS NOT NULL THEN
2120       result[(100 - location.rank_address)] := trim(get_name_by_language(location.name, languagepref));
2121       prevresult := currresult;
2122     END IF;
2123   END LOOP;
2124
2125   RETURN array_to_string(result,', ');
2126 END;
2127 $$
2128 LANGUAGE plpgsql;
2129
2130 DROP TYPE addressline CASCADE;
2131 create type addressline as (
2132   place_id BIGINT,
2133   osm_type CHAR(1),
2134   osm_id INTEGER,
2135   name HSTORE,
2136   class TEXT,
2137   type TEXT,
2138   admin_level INTEGER,
2139   fromarea BOOLEAN,  
2140   isaddress BOOLEAN,  
2141   rank_address INTEGER,
2142   distance FLOAT
2143 );
2144
2145 CREATE OR REPLACE FUNCTION get_addressdata(in_place_id BIGINT) RETURNS setof addressline 
2146   AS $$
2147 DECLARE
2148   for_place_id BIGINT;
2149   result TEXT[];
2150   search TEXT[];
2151   found INTEGER;
2152   location RECORD;
2153   countrylocation RECORD;
2154   searchcountrycode varchar(2);
2155   searchhousenumber TEXT;
2156   searchhousename HSTORE;
2157   searchrankaddress INTEGER;
2158   searchpostcode TEXT;
2159   searchclass TEXT;
2160   searchtype TEXT;
2161   countryname HSTORE;
2162   hadcountry BOOLEAN;
2163 BEGIN
2164
2165   select parent_place_id,'us', housenumber, 30, postcode, null, 'place', 'house' from location_property_tiger 
2166     WHERE place_id = in_place_id 
2167     INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2168
2169   IF for_place_id IS NULL THEN
2170     select parent_place_id,'us', housenumber, 30, postcode, null, 'place', 'house' from location_property_aux
2171       WHERE place_id = in_place_id 
2172       INTO for_place_id,searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2173   END IF;
2174
2175   IF for_place_id IS NULL THEN
2176     select parent_place_id, country_code, housenumber, rank_address, postcode, name, class, type from placex 
2177       WHERE place_id = in_place_id and rank_address = 30 
2178       INTO for_place_id, searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename, searchclass, searchtype;
2179   END IF;
2180
2181   IF for_place_id IS NULL THEN
2182     for_place_id := in_place_id;
2183     select country_code, housenumber, rank_address, postcode, null from placex where place_id = for_place_id 
2184       INTO searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode, searchhousename;
2185   END IF;
2186
2187 --RAISE WARNING '% % % %',searchcountrycode, searchhousenumber, searchrankaddress, searchpostcode;
2188
2189   found := 1000;
2190   hadcountry := false;
2191   FOR location IN 
2192     select placex.place_id, osm_type, osm_id,
2193       CASE WHEN class = 'place' and type = 'postcode' THEN 'name' => postcode ELSE name END as name,
2194       class, type, admin_level, true as fromarea, true as isaddress,
2195       CASE WHEN rank_address = 0 THEN 100 WHEN rank_address = 11 THEN 5 ELSE rank_address END as rank_address,
2196       0 as distance, country_code
2197       from placex
2198       where place_id = for_place_id 
2199   LOOP
2200 --RAISE WARNING '%',location;
2201     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2202       searchcountrycode := location.country_code;
2203     END IF;
2204     IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
2205       location.isaddress := FALSE;
2206     END IF;
2207     IF location.rank_address = 4 AND location.isaddress THEN
2208       hadcountry := true;
2209     END IF;
2210     IF location.rank_address < 4 AND NOT hadcountry THEN
2211       select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2212       IF countryname IS NOT NULL THEN
2213         countrylocation := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2214         RETURN NEXT countrylocation;
2215       END IF;
2216     END IF;
2217     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id, location.name, location.class, 
2218                            location.type, location.admin_level, location.fromarea, location.isaddress, location.rank_address, 
2219                            location.distance)::addressline;
2220     RETURN NEXT countrylocation;
2221     found := location.rank_address;
2222   END LOOP;
2223
2224   FOR location IN 
2225     select placex.place_id, osm_type, osm_id,
2226       CASE WHEN class = 'place' and type = 'postcode' THEN 'name' => postcode ELSE name END as name,
2227       class, type, admin_level, fromarea, isaddress,
2228       CASE WHEN address_place_id = for_place_id AND rank_address = 0 THEN 100 WHEN rank_address = 11 THEN 5 ELSE rank_address END as rank_address,
2229       distance,country_code
2230       from place_addressline join placex on (address_place_id = placex.place_id) 
2231       where place_addressline.place_id = for_place_id 
2232       and (cached_rank_address > 0 AND cached_rank_address < searchrankaddress)
2233       and address_place_id != for_place_id
2234       and (placex.country_code IS NULL OR searchcountrycode IS NULL OR placex.country_code = searchcountrycode OR rank_address < 4)
2235       order by rank_address desc,isaddress desc,fromarea desc,distance asc,rank_search desc
2236   LOOP
2237 --RAISE WARNING '%',location;
2238     IF searchcountrycode IS NULL AND location.country_code IS NOT NULL THEN
2239       searchcountrycode := location.country_code;
2240     END IF;
2241     IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
2242       location.isaddress := FALSE;
2243     END IF;
2244     IF location.rank_address = 4 AND location.isaddress THEN
2245       hadcountry := true;
2246     END IF;
2247     IF location.rank_address < 4 AND NOT hadcountry THEN
2248       select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2249       IF countryname IS NOT NULL THEN
2250         countrylocation := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2251         RETURN NEXT countrylocation;
2252       END IF;
2253     END IF;
2254     countrylocation := ROW(location.place_id, location.osm_type, location.osm_id, location.name, location.class, 
2255                            location.type, location.admin_level, location.fromarea, location.isaddress, location.rank_address, 
2256                            location.distance)::addressline;
2257     RETURN NEXT countrylocation;
2258     found := location.rank_address;
2259   END LOOP;
2260
2261   IF found > 4 THEN
2262     select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
2263 --RAISE WARNING '% % %',found,searchcountrycode,countryname;
2264     IF countryname IS NOT NULL THEN
2265       location := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
2266       RETURN NEXT location;
2267     END IF;
2268   END IF;
2269
2270   IF searchcountrycode IS NOT NULL THEN
2271     location := ROW(null, null, null, 'ref'=>searchcountrycode, 'place', 'country_code', null, true, false, 4, 0)::addressline;
2272     RETURN NEXT location;
2273   END IF;
2274
2275   IF searchhousename IS NOT NULL THEN
2276     location := ROW(in_place_id, null, null, searchhousename, searchclass, searchtype, null, true, true, 29, 0)::addressline;
2277 --    location := ROW(in_place_id, null, null, searchhousename, 'place', 'house_name', null, true, true, 29, 0)::addressline;
2278     RETURN NEXT location;
2279   END IF;
2280
2281   IF searchhousenumber IS NOT NULL THEN
2282     location := ROW(in_place_id, null, null, 'ref'=>searchhousenumber, 'place', 'house_number', null, true, true, 28, 0)::addressline;
2283     RETURN NEXT location;
2284   END IF;
2285
2286   IF searchpostcode IS NOT NULL THEN
2287     location := ROW(null, null, null, 'ref'=>searchpostcode, 'place', 'postcode', null, true, true, 5, 0)::addressline;
2288     RETURN NEXT location;
2289   END IF;
2290
2291   RETURN;
2292 END;
2293 $$
2294 LANGUAGE plpgsql;
2295
2296 CREATE OR REPLACE FUNCTION get_place_boundingbox(search_place_id BIGINT) RETURNS place_boundingbox
2297   AS $$
2298 DECLARE
2299   result place_boundingbox;
2300   numfeatures integer;
2301 BEGIN
2302   select * from place_boundingbox into result where place_id = search_place_id;
2303   IF result.place_id IS NULL THEN
2304 -- remove  isaddress = true because if there is a matching polygon it always wins
2305     select count(*) from place_addressline where address_place_id = search_place_id into numfeatures;
2306     insert into place_boundingbox select place_id,
2307              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2308              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2309              numfeatures, ST_Area(geometry),
2310              geometry as area from location_area where place_id = search_place_id;
2311     select * from place_boundingbox into result where place_id = search_place_id;
2312   END IF;
2313   IF result.place_id IS NULL THEN
2314 -- TODO 0.0001
2315     insert into place_boundingbox select address_place_id,
2316              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2317              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2318              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2319              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2320              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) 
2321              where address_place_id = search_place_id
2322 --               and (isaddress = true OR place_id = search_place_id)
2323                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2324              group by address_place_id limit 1;
2325     select * from place_boundingbox into result where place_id = search_place_id;
2326   END IF;
2327   return result;
2328 END;
2329 $$
2330 LANGUAGE plpgsql;
2331
2332 -- don't do the operation if it would be slow
2333 CREATE OR REPLACE FUNCTION get_place_boundingbox_quick(search_place_id BIGINT) RETURNS place_boundingbox
2334   AS $$
2335 DECLARE
2336   result place_boundingbox;
2337   numfeatures integer;
2338   rank integer;
2339 BEGIN
2340   select * from place_boundingbox into result where place_id = search_place_id;
2341   IF result IS NULL AND rank > 14 THEN
2342     select count(*) from place_addressline where address_place_id = search_place_id and isaddress = true into numfeatures;
2343     insert into place_boundingbox select place_id,
2344              ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)),ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)),
2345              ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)),ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)),
2346              numfeatures, ST_Area(geometry),
2347              geometry as area from location_area where place_id = search_place_id;
2348     select * from place_boundingbox into result where place_id = search_place_id;
2349   END IF;
2350   IF result IS NULL THEN
2351     select rank_search from placex where place_id = search_place_id into rank;
2352     IF rank > 20 THEN
2353 -- TODO 0.0001
2354       insert into place_boundingbox select address_place_id,
2355              min(ST_Y(ST_Centroid(geometry))) as minlon,max(ST_Y(ST_Centroid(geometry))) as maxlon,
2356              min(ST_X(ST_Centroid(geometry))) as minlat,max(ST_X(ST_Centroid(geometry))) as maxlat,
2357              count(*), ST_Area(ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001)) as area,
2358              ST_Buffer(ST_Convexhull(ST_Collect(geometry)),0.0001) as boundary 
2359              from place_addressline join placex using (place_id) 
2360              where address_place_id = search_place_id 
2361                and (isaddress = true OR place_id = search_place_id)
2362                and (st_length(geometry) < 0.01 or place_id = search_place_id)
2363              group by address_place_id limit 1;
2364       select * from place_boundingbox into result where place_id = search_place_id;
2365     END IF;
2366   END IF;
2367   return result;
2368 END;
2369 $$
2370 LANGUAGE plpgsql;
2371
2372 CREATE OR REPLACE FUNCTION update_place(search_place_id BIGINT) RETURNS BOOLEAN
2373   AS $$
2374 DECLARE
2375   result place_boundingbox;
2376   numfeatures integer;
2377 BEGIN
2378   update placex set 
2379       name = place.name,
2380       housenumber = place.housenumber,
2381       street = place.street,
2382       isin = place.isin,
2383       postcode = place.postcode,
2384       country_code = place.country_code,
2385       parent_place_id = null
2386       from place
2387       where placex.place_id = search_place_id 
2388         and place.osm_type = placex.osm_type and place.osm_id = placex.osm_id
2389         and place.class = placex.class and place.type = placex.type;
2390   update placex set indexed_status = 2 where place_id = search_place_id;
2391   update placex set indexed_status = 0 where place_id = search_place_id;
2392   return true;
2393 END;
2394 $$
2395 LANGUAGE plpgsql;
2396
2397 CREATE OR REPLACE FUNCTION get_searchrank_label(rank INTEGER) RETURNS TEXT
2398   AS $$
2399 DECLARE
2400 BEGIN
2401   IF rank < 2 THEN
2402     RETURN 'Continent';
2403   ELSEIF rank < 4 THEN
2404     RETURN 'Sea';
2405   ELSEIF rank < 8 THEN
2406     RETURN 'Country';
2407   ELSEIF rank < 12 THEN
2408     RETURN 'State';
2409   ELSEIF rank < 16 THEN
2410     RETURN 'County';
2411   ELSEIF rank = 16 THEN
2412     RETURN 'City';
2413   ELSEIF rank = 17 THEN
2414     RETURN 'Town / Island';
2415   ELSEIF rank = 18 THEN
2416     RETURN 'Village / Hamlet';
2417   ELSEIF rank = 20 THEN
2418     RETURN 'Suburb';
2419   ELSEIF rank = 21 THEN
2420     RETURN 'Postcode Area';
2421   ELSEIF rank = 22 THEN
2422     RETURN 'Croft / Farm / Locality / Islet';
2423   ELSEIF rank = 23 THEN
2424     RETURN 'Postcode Area';
2425   ELSEIF rank = 25 THEN
2426     RETURN 'Postcode Point';
2427   ELSEIF rank = 26 THEN
2428     RETURN 'Street / Major Landmark';
2429   ELSEIF rank = 27 THEN
2430     RETURN 'Minory Street / Path';
2431   ELSEIF rank = 28 THEN
2432     RETURN 'House / Building';
2433   ELSE
2434     RETURN 'Other: '||rank;
2435   END IF;
2436   
2437 END;
2438 $$
2439 LANGUAGE plpgsql;
2440
2441 CREATE OR REPLACE FUNCTION get_addressrank_label(rank INTEGER) RETURNS TEXT
2442   AS $$
2443 DECLARE
2444 BEGIN
2445   IF rank = 0 THEN
2446     RETURN 'None';
2447   ELSEIF rank < 2 THEN
2448     RETURN 'Continent';
2449   ELSEIF rank < 4 THEN
2450     RETURN 'Sea';
2451   ELSEIF rank = 5 THEN
2452     RETURN 'Postcode';
2453   ELSEIF rank < 8 THEN
2454     RETURN 'Country';
2455   ELSEIF rank < 12 THEN
2456     RETURN 'State';
2457   ELSEIF rank < 16 THEN
2458     RETURN 'County';
2459   ELSEIF rank = 16 THEN
2460     RETURN 'City';
2461   ELSEIF rank = 17 THEN
2462     RETURN 'Town / Village / Hamlet';
2463   ELSEIF rank = 20 THEN
2464     RETURN 'Suburb';
2465   ELSEIF rank = 21 THEN
2466     RETURN 'Postcode Area';
2467   ELSEIF rank = 22 THEN
2468     RETURN 'Croft / Farm / Locality / Islet';
2469   ELSEIF rank = 23 THEN
2470     RETURN 'Postcode Area';
2471   ELSEIF rank = 25 THEN
2472     RETURN 'Postcode Point';
2473   ELSEIF rank = 26 THEN
2474     RETURN 'Street / Major Landmark';
2475   ELSEIF rank = 27 THEN
2476     RETURN 'Minory Street / Path';
2477   ELSEIF rank = 28 THEN
2478     RETURN 'House / Building';
2479   ELSE
2480     RETURN 'Other: '||rank;
2481   END IF;
2482   
2483 END;
2484 $$
2485 LANGUAGE plpgsql;
2486
2487 CREATE OR REPLACE FUNCTION get_word_suggestion(srcword TEXT) RETURNS TEXT
2488   AS $$
2489 DECLARE
2490   trigramtoken TEXT;
2491   result TEXT;
2492 BEGIN
2493
2494   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2495   SELECT word FROM word WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 1 into result;
2496
2497   return result;
2498 END;
2499 $$
2500 LANGUAGE plpgsql;
2501
2502 CREATE OR REPLACE FUNCTION get_word_suggestions(srcword TEXT) RETURNS TEXT[]
2503   AS $$
2504 DECLARE
2505   trigramtoken TEXT;
2506   result TEXT[];
2507   r RECORD;
2508 BEGIN
2509
2510   trigramtoken := regexp_replace(make_standard_name(srcword),E'([^0-9])\\1+',E'\\1','g');
2511
2512   FOR r IN SELECT word,similarity(word_trigram, trigramtoken) as score FROM word 
2513     WHERE word_trigram like ' %' and word_trigram % trigramtoken ORDER BY similarity(word_trigram, trigramtoken) DESC, word limit 4
2514   LOOP
2515     result[coalesce(array_upper(result,1)+1,1)] := r.word;
2516   END LOOP;
2517
2518   return result;
2519 END;
2520 $$
2521 LANGUAGE plpgsql;
2522
2523 CREATE OR REPLACE FUNCTION tigger_create_interpolation(linegeo GEOMETRY, in_startnumber INTEGER, 
2524   in_endnumber INTEGER, interpolationtype TEXT, 
2525   in_street TEXT, in_isin TEXT, in_postcode TEXT) RETURNS INTEGER
2526   AS $$
2527 DECLARE
2528   
2529   startnumber INTEGER;
2530   endnumber INTEGER;
2531   stepsize INTEGER;
2532   housenum INTEGER;
2533   newpoints INTEGER;
2534   numberrange INTEGER;
2535   rangestartnumber INTEGER;
2536   place_centroid GEOMETRY;
2537   out_partition INTEGER;
2538   out_parent_place_id BIGINT;
2539   location RECORD;
2540   address_street_word_id INTEGER;  
2541
2542 BEGIN
2543
2544   IF in_endnumber > in_startnumber THEN
2545     startnumber = in_startnumber;
2546     endnumber = in_endnumber;
2547   ELSE
2548     startnumber = in_endnumber;
2549     endnumber = in_startnumber;
2550   END IF;
2551
2552   numberrange := endnumber - startnumber;
2553   rangestartnumber := startnumber;
2554
2555   IF (interpolationtype = 'odd' AND startnumber%2 = 0) OR (interpolationtype = 'even' AND startnumber%2 = 1) THEN
2556     startnumber := startnumber + 1;
2557     stepsize := 2;
2558   ELSE
2559     IF (interpolationtype = 'odd' OR interpolationtype = 'even') THEN
2560       stepsize := 2;
2561     ELSE -- everything else assumed to be 'all'
2562       stepsize := 1;
2563     END IF;
2564   END IF;
2565
2566   -- Filter out really broken tiger data
2567   IF numberrange > 0 AND (numberrange::float/stepsize::float > 500) 
2568                     AND ST_length(linegeo)/(numberrange::float/stepsize::float) < 0.000001 THEN
2569     RAISE WARNING 'Road too short for number range % to % on %, % (%)',startnumber,endnumber,in_street,in_isin,
2570                   ST_length(linegeo)/(numberrange::float/stepsize::float);    
2571     RETURN 0;
2572   END IF;
2573
2574   place_centroid := ST_Centroid(linegeo);
2575   out_partition := get_partition(place_centroid, 'us');
2576   out_parent_place_id := null;
2577
2578   address_street_word_id := get_name_id(make_standard_name(in_street));
2579   IF address_street_word_id IS NOT NULL THEN
2580     FOR location IN SELECT * from getNearestNamedRoadFeature(out_partition, place_centroid, address_street_word_id) LOOP
2581       out_parent_place_id := location.place_id;
2582     END LOOP;
2583   END IF;
2584
2585   IF out_parent_place_id IS NULL THEN
2586     FOR location IN SELECT place_id FROM getNearestParellelRoadFeature(out_partition, linegeo) LOOP
2587       out_parent_place_id := location.place_id;
2588     END LOOP;    
2589   END IF;
2590
2591   IF out_parent_place_id IS NULL THEN
2592     FOR location IN SELECT place_id FROM getNearestRoadFeature(out_partition, place_centroid) LOOP
2593       out_parent_place_id := location.place_id;
2594     END LOOP;    
2595   END IF;
2596
2597   newpoints := 0;
2598   FOR housenum IN startnumber..endnumber BY stepsize LOOP
2599     insert into location_property_tiger (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2600     values (nextval('seq_place'), out_partition, out_parent_place_id, housenum, in_postcode,
2601       ST_Line_Interpolate_Point(linegeo, (housenum::float-rangestartnumber::float)/numberrange::float));
2602     newpoints := newpoints + 1;
2603   END LOOP;
2604
2605   RETURN newpoints;
2606 END;
2607 $$
2608 LANGUAGE plpgsql;
2609
2610 CREATE OR REPLACE FUNCTION aux_create_property(pointgeo GEOMETRY, in_housenumber TEXT, 
2611   in_street TEXT, in_isin TEXT, in_postcode TEXT, in_countrycode char(2)) RETURNS INTEGER
2612   AS $$
2613 DECLARE
2614
2615   newpoints INTEGER;
2616   place_centroid GEOMETRY;
2617   out_partition INTEGER;
2618   out_parent_place_id BIGINT;
2619   location RECORD;
2620   address_street_word_id INTEGER;  
2621   out_postcode TEXT;
2622
2623 BEGIN
2624
2625   place_centroid := ST_Centroid(pointgeo);
2626   out_partition := get_partition(place_centroid, in_countrycode);
2627   out_parent_place_id := null;
2628
2629   address_street_word_id := get_name_id(make_standard_name(in_street));
2630   IF address_street_word_id IS NOT NULL THEN
2631     FOR location IN SELECT * from getNearestNamedRoadFeature(out_partition, place_centroid, address_street_word_id) LOOP
2632       out_parent_place_id := location.place_id;
2633     END LOOP;
2634   END IF;
2635
2636   IF out_parent_place_id IS NULL THEN
2637     FOR location IN SELECT place_id FROM getNearestRoadFeature(out_partition, place_centroid) LOOP
2638       out_parent_place_id := location.place_id;
2639     END LOOP;    
2640   END IF;
2641
2642   out_postcode := in_postcode;
2643   IF out_postcode IS NULL THEN
2644     SELECT postcode from placex where place_id = out_parent_place_id INTO out_postcode;
2645   END IF;
2646   IF out_postcode IS NULL THEN
2647     out_postcode := getNearestPostcode(out_partition, place_centroid);
2648   END IF;
2649
2650   newpoints := 0;
2651   insert into location_property_aux (place_id, partition, parent_place_id, housenumber, postcode, centroid)
2652     values (nextval('seq_place'), out_partition, out_parent_place_id, in_housenumber, out_postcode, place_centroid);
2653   newpoints := newpoints + 1;
2654
2655   RETURN newpoints;
2656 END;
2657 $$
2658 LANGUAGE plpgsql;
2659
2660 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], member TEXT) RETURNS TEXT[]
2661   AS $$
2662 DECLARE
2663   result TEXT[];
2664   i INTEGER;
2665 BEGIN
2666
2667   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2668     IF members[i+1] = member THEN
2669       result := result || members[i];
2670     END IF;
2671   END LOOP;
2672
2673   return result;
2674 END;
2675 $$
2676 LANGUAGE plpgsql;
2677
2678 CREATE OR REPLACE FUNCTION get_osm_rel_members(members TEXT[], memberLabels TEXT[]) RETURNS SETOF TEXT
2679   AS $$
2680 DECLARE
2681   i INTEGER;
2682 BEGIN
2683
2684   FOR i IN 1..ARRAY_UPPER(members,1) BY 2 LOOP
2685     IF members[i+1] = ANY(memberLabels) THEN
2686       RETURN NEXT members[i];
2687     END IF;
2688   END LOOP;
2689
2690   RETURN;
2691 END;
2692 $$
2693 LANGUAGE plpgsql;
2694
2695