1 -- Assorted helper functions for the triggers.
 
   3 CREATE OR REPLACE FUNCTION geometry_sector(partition INTEGER, place geometry)
 
   9 --  RAISE WARNING '%',place;
 
  10   NEWgeometry := ST_PointOnSurface(place);
 
  11   RETURN (partition*1000000) + (500-ST_X(NEWgeometry)::integer)*1000 + (500-ST_Y(NEWgeometry)::integer);
 
  14 LANGUAGE plpgsql IMMUTABLE;
 
  17 CREATE OR REPLACE FUNCTION array_merge(a INTEGER[], b INTEGER[])
 
  24   IF array_upper(a, 1) IS NULL THEN
 
  27   IF array_upper(b, 1) IS NULL THEN
 
  31   FOR i IN 1..array_upper(b, 1) LOOP  
 
  32     IF NOT (ARRAY[b[i]] <@ r) THEN
 
  39 LANGUAGE plpgsql IMMUTABLE;
 
  42 CREATE OR REPLACE FUNCTION reverse_place_diameter(rank_search SMALLINT)
 
  46   IF rank_search <= 4 THEN
 
  48   ELSIF rank_search <= 8 THEN
 
  50   ELSIF rank_search <= 12 THEN
 
  52   ELSIF rank_search <= 17 THEN
 
  54   ELSIF rank_search <= 18 THEN
 
  56   ELSIF rank_search <= 19 THEN
 
  63 LANGUAGE plpgsql IMMUTABLE;
 
  66 CREATE OR REPLACE FUNCTION get_postcode_rank(country_code VARCHAR(2), postcode TEXT,
 
  67                                              OUT rank_search SMALLINT,
 
  68                                              OUT rank_address SMALLINT)
 
  75     postcode := upper(postcode);
 
  77     IF country_code = 'gb' THEN
 
  78         IF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9][A-Z][A-Z])$' THEN
 
  81         ELSEIF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z]? [0-9])$' THEN
 
  84         ELSEIF postcode ~ '^([A-Z][A-Z]?[0-9][0-9A-Z])$' THEN
 
  89     ELSEIF country_code = 'sg' THEN
 
  90         IF postcode ~ '^([0-9]{6})$' THEN
 
  95     ELSEIF country_code = 'de' THEN
 
  96         IF postcode ~ '^([0-9]{5})$' THEN
 
 102         -- Guess at the postcode format and coverage (!)
 
 103         IF postcode ~ '^[A-Z0-9]{1,5}$' THEN -- Probably too short to be very local
 
 107             -- Does it look splitable into and area and local code?
 
 108             part := substring(postcode from '^([- :A-Z0-9]+)([- :][A-Z0-9]+)$');
 
 110             IF part IS NOT NULL THEN
 
 113             ELSEIF postcode ~ '^[- :A-Z0-9]{6,}$' THEN
 
 122 LANGUAGE plpgsql IMMUTABLE;
 
 125 -- Find the nearest artificial postcode for the given geometry.
 
 126 -- TODO For areas there should not be more than two inside the geometry.
 
 127 CREATE OR REPLACE FUNCTION get_nearest_postcode(country VARCHAR(2), geom GEOMETRY)
 
 134     -- If the geometry is an area then only one postcode must be within
 
 135     -- that area, otherwise consider the area as not having a postcode.
 
 136     IF ST_GeometryType(geom) in ('ST_Polygon','ST_MultiPolygon') THEN
 
 137         SELECT min(postcode), count(*) FROM
 
 138               (SELECT postcode FROM location_postcode
 
 139                 WHERE ST_Contains(geom, location_postcode.geometry) LIMIT 2) sub
 
 149     SELECT postcode FROM location_postcode
 
 150      WHERE ST_DWithin(geom, location_postcode.geometry, 0.05)
 
 151           AND location_postcode.country_code = country
 
 152      ORDER BY ST_Distance(geom, location_postcode.geometry) LIMIT 1
 
 158 LANGUAGE plpgsql STABLE;
 
 161 CREATE OR REPLACE FUNCTION get_country_code(place geometry)
 
 165   place_centre GEOMETRY;
 
 168   place_centre := ST_PointOnSurface(place);
 
 170 -- RAISE WARNING 'get_country_code, start: %', ST_AsText(place_centre);
 
 172   -- Try for a OSM polygon
 
 174     SELECT country_code from location_area_country
 
 175     WHERE country_code is not null and st_covers(geometry, place_centre) limit 1
 
 177     RETURN nearcountry.country_code;
 
 180 -- RAISE WARNING 'osm fallback: %', ST_AsText(place_centre);
 
 182   -- Try for OSM fallback data
 
 183   -- The order is to deal with places like HongKong that are 'states' within another polygon
 
 185     SELECT country_code from country_osm_grid
 
 186     WHERE st_covers(geometry, place_centre) order by area asc limit 1
 
 188     RETURN nearcountry.country_code;
 
 191 -- RAISE WARNING 'near osm fallback: %', ST_AsText(place_centre);
 
 195     SELECT country_code from country_osm_grid
 
 196     WHERE st_dwithin(geometry, place_centre, 0.5)
 
 197     ORDER BY st_distance(geometry, place_centre) asc, area asc limit 1
 
 199     RETURN nearcountry.country_code;
 
 205 LANGUAGE plpgsql STABLE;
 
 208 CREATE OR REPLACE FUNCTION get_country_language_code(search_country_code VARCHAR(2))
 
 215     SELECT distinct country_default_language_code from country_name
 
 216     WHERE country_code = search_country_code limit 1
 
 218     RETURN lower(nearcountry.country_default_language_code);
 
 223 LANGUAGE plpgsql STABLE;
 
 226 CREATE OR REPLACE FUNCTION get_partition(in_country_code VARCHAR(10))
 
 233     SELECT partition from country_name where country_code = in_country_code
 
 235     RETURN nearcountry.partition;
 
 240 LANGUAGE plpgsql STABLE;
 
 243 -- Find the parent of an address with addr:street/addr:place tag.
 
 245 -- \param street     Value of addr:street or NULL if tag is missing.
 
 246 -- \param place      Value of addr:place or NULL if tag is missing.
 
 247 -- \param partition  Partition where to search the parent.
 
 248 -- \param centroid   Location of the address.
 
 250 -- \return Place ID of the parent if one was found, NULL otherwise.
 
 251 CREATE OR REPLACE FUNCTION find_parent_for_address(street TEXT, place TEXT,
 
 257   parent_place_id BIGINT;
 
 260   IF street is not null THEN
 
 261     -- Check for addr:street attributes
 
 262     -- Note that addr:street links can only be indexed, once the street itself is indexed
 
 263     word_ids := word_ids_from_name(street);
 
 264     IF word_ids is not null THEN
 
 265       parent_place_id := getNearestNamedRoadPlaceId(partition, centroid, word_ids);
 
 266       IF parent_place_id is not null THEN
 
 267         --DEBUG: RAISE WARNING 'Get parent form addr:street: %', parent.place_id;
 
 268         RETURN parent_place_id;
 
 273   -- Check for addr:place attributes.
 
 274   IF place is not null THEN
 
 275     word_ids := word_ids_from_name(place);
 
 276     IF word_ids is not null THEN
 
 277       parent_place_id := getNearestNamedPlacePlaceId(partition, centroid, word_ids);
 
 278       IF parent_place_id is not null THEN
 
 279         --DEBUG: RAISE WARNING 'Get parent form addr:place: %', parent.place_id;
 
 280         RETURN parent_place_id;
 
 288 LANGUAGE plpgsql STABLE;
 
 290 CREATE OR REPLACE FUNCTION delete_location(OLD_place_id BIGINT)
 
 295   DELETE FROM location_area where place_id = OLD_place_id;
 
 296 -- TODO:location_area
 
 303 CREATE OR REPLACE FUNCTION add_location(place_id BIGINT, country_code varchar(2),
 
 304                                         partition INTEGER, keywords INTEGER[],
 
 305                                         rank_search INTEGER, rank_address INTEGER,
 
 306                                         in_postcode TEXT, geometry GEOMETRY)
 
 319   IF rank_search > 25 THEN
 
 320     RAISE EXCEPTION 'Adding location with rank > 25 (% rank %)', place_id, rank_search;
 
 323   x := deleteLocationArea(partition, place_id, rank_search);
 
 325   -- add postcode only if it contains a single entry, i.e. ignore postcode lists
 
 327   IF in_postcode is not null AND in_postcode not similar to '%(,|;)%' THEN
 
 328       postcode := upper(trim (in_postcode));
 
 331   IF ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') THEN
 
 332     centroid := ST_Centroid(geometry);
 
 334     FOR secgeo IN select split_geometry(geometry) AS geom LOOP
 
 335       x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, false, postcode, centroid, secgeo);
 
 341     IF rank_address = 0 THEN
 
 343     ELSEIF rank_search <= 14 THEN
 
 345     ELSEIF rank_search <= 15 THEN
 
 347     ELSEIF rank_search <= 16 THEN
 
 349     ELSEIF rank_search <= 17 THEN
 
 351     ELSEIF rank_search <= 21 THEN
 
 353     ELSEIF rank_search = 25 THEN
 
 357 --    RAISE WARNING 'adding % diameter %', place_id, diameter;
 
 359     secgeo := ST_Buffer(geometry, diameter);
 
 360     x := insertLocationAreaLarge(partition, place_id, country_code, keywords, rank_search, rank_address, true, postcode, ST_Centroid(geometry), secgeo);
 
 370 CREATE OR REPLACE FUNCTION quad_split_geometry(geometry GEOMETRY, maxarea FLOAT,
 
 372   RETURNS SETOF GEOMETRY
 
 386   remainingdepth INTEGER;
 
 390 --  RAISE WARNING 'quad_split_geometry: maxarea=%, depth=%',maxarea,maxdepth;
 
 392   IF (ST_GeometryType(geometry) not in ('ST_Polygon','ST_MultiPolygon') OR NOT ST_IsValid(geometry)) THEN
 
 393     RETURN NEXT geometry;
 
 397   remainingdepth := maxdepth - 1;
 
 398   area := ST_AREA(geometry);
 
 399   IF remainingdepth < 1 OR area < maxarea THEN
 
 400     RETURN NEXT geometry;
 
 404   xmin := st_xmin(geometry);
 
 405   xmax := st_xmax(geometry);
 
 406   ymin := st_ymin(geometry);
 
 407   ymax := st_ymax(geometry);
 
 408   secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(ymin,xmin),ST_Point(ymax,xmax)),4326);
 
 410   -- if the geometry completely covers the box don't bother to slice any more
 
 411   IF ST_AREA(secbox) = area THEN
 
 412     RETURN NEXT geometry;
 
 416   xmid := (xmin+xmax)/2;
 
 417   ymid := (ymin+ymax)/2;
 
 423       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymin),ST_Point(xmid,ymid)),4326);
 
 426       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmin,ymid),ST_Point(xmid,ymax)),4326);
 
 429       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymin),ST_Point(xmax,ymid)),4326);
 
 432       secbox := ST_SetSRID(ST_MakeBox2D(ST_Point(xmid,ymid),ST_Point(xmax,ymax)),4326);
 
 435     IF st_intersects(geometry, secbox) THEN
 
 436       secgeo := st_intersection(geometry, secbox);
 
 437       IF NOT ST_IsEmpty(secgeo) AND ST_GeometryType(secgeo) in ('ST_Polygon','ST_MultiPolygon') THEN
 
 438         FOR geo IN select quad_split_geometry(secgeo, maxarea, remainingdepth) as geom LOOP
 
 439           IF NOT ST_IsEmpty(geo.geom) AND ST_GeometryType(geo.geom) in ('ST_Polygon','ST_MultiPolygon') THEN
 
 441             RETURN NEXT geo.geom;
 
 451 LANGUAGE plpgsql IMMUTABLE;
 
 454 CREATE OR REPLACE FUNCTION split_geometry(geometry GEOMETRY)
 
 455   RETURNS SETOF GEOMETRY
 
 460   -- 10000000000 is ~~ 1x1 degree
 
 461   FOR geo IN select quad_split_geometry(geometry, 0.25, 20) as geom LOOP
 
 462     RETURN NEXT geo.geom;
 
 467 LANGUAGE plpgsql IMMUTABLE;
 
 470 CREATE OR REPLACE FUNCTION place_force_delete(placeid BIGINT)
 
 475     osmtype character(1);
 
 479   SELECT osm_type, osm_id, class, type FROM placex WHERE place_id = placeid INTO osmtype, osmid, pclass, ptype;
 
 480   DELETE FROM import_polygon_delete where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
 
 481   DELETE FROM import_polygon_error where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
 
 482   -- force delete from place/placex by making it a very small geometry
 
 483   UPDATE place set geometry = ST_SetSRID(ST_Point(0,0), 4326) where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
 
 484   DELETE FROM place where osm_type = osmtype and osm_id = osmid and class = pclass and type = ptype;
 
 492 CREATE OR REPLACE FUNCTION place_force_update(placeid BIGINT)
 
 501   UPDATE placex SET indexed_status = 2 WHERE place_id = placeid;
 
 502   SELECT geometry, rank_search FROM placex WHERE place_id = placeid INTO placegeom, rank;
 
 503   IF placegeom IS NOT NULL AND ST_IsValid(placegeom) THEN
 
 504     IF ST_GeometryType(placegeom) in ('ST_Polygon','ST_MultiPolygon') THEN
 
 505       FOR geom IN select split_geometry(placegeom) FROM placex WHERE place_id = placeid LOOP
 
 506         update placex set indexed_status = 2 where (st_covers(geom, placex.geometry) OR ST_Intersects(geom, placex.geometry)) 
 
 507         AND rank_search > rank and indexed_status = 0 and ST_geometrytype(placex.geometry) = 'ST_Point' and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
 
 508         update placex set indexed_status = 2 where (st_covers(geom, placex.geometry) OR ST_Intersects(geom, placex.geometry)) 
 
 509         AND rank_search > rank and indexed_status = 0 and ST_geometrytype(placex.geometry) != 'ST_Point' and (rank_search < 28 or name is not null or (rank >= 16 and address ? 'place'));
 
 515         ELSEIF rank < 18 THEN
 
 517         ELSEIF rank < 20 THEN
 
 519         ELSEIF rank = 21 THEN
 
 521         ELSEIF rank < 24 THEN
 
 523         ELSEIF rank < 26 THEN
 
 524           diameter := 0.002; -- 100 to 200 meters
 
 525         ELSEIF rank < 28 THEN
 
 526           diameter := 0.001; -- 50 to 100 meters
 
 530             -- roads may cause reparenting for >27 rank places
 
 531             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter);
 
 532           ELSEIF rank >= 16 THEN
 
 533             -- up to rank 16, street-less addresses may need reparenting
 
 534             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null or address ? 'place');
 
 536             -- for all other places the search terms may change as well
 
 537             update placex set indexed_status = 2 where indexed_status = 0 and rank_search > rank and ST_DWithin(placex.geometry, placegeom, diameter) and (rank_search < 28 or name is not null);