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