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