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