]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/placex_triggers.sql
Merge pull request #4073 from lonvia/area-updates
[nominatim.git] / lib-sql / functions / placex_triggers.sql
1 -- SPDX-License-Identifier: GPL-2.0-only
2 --
3 -- This file is part of Nominatim. (https://nominatim.org)
4 --
5 -- Copyright (C) 2026 by the Nominatim developer community.
6 -- For a full list of authors see the git log.
7
8 -- Trigger functions for the placex table.
9
10 -- Information returned by update preparation.
11 DROP TYPE IF EXISTS prepare_update_info CASCADE;
12 CREATE TYPE prepare_update_info AS (
13   name HSTORE,
14   address HSTORE,
15   rank_address SMALLINT,
16   country_code TEXT,
17   class TEXT,
18   type TEXT,
19   linked_place_id BIGINT,
20   centroid_x float,
21   centroid_y float
22 );
23
24 -- Retrieve the data needed by the indexer for updating the place.
25 CREATE OR REPLACE FUNCTION placex_indexing_prepare(p placex)
26   RETURNS prepare_update_info
27   AS $$
28 DECLARE
29   location RECORD;
30   result prepare_update_info;
31   extra_names HSTORE;
32   default_language VARCHAR(10);
33 BEGIN
34   IF not p.address ? '_inherited' THEN
35     result.address := p.address;
36   END IF;
37
38   -- For POI nodes, check if the address should be derived from a surrounding
39   -- building.
40   IF p.rank_search = 30 AND p.osm_type = 'N' THEN
41     IF p.address is null THEN
42         -- The additional && condition works around the misguided query
43         -- planner of postgis 3.0.
44         SELECT placex.address || hstore('_inherited', '') INTO result.address
45           FROM placex
46          WHERE ST_Covers(geometry, p.centroid)
47                and geometry && p.centroid
48                and placex.address is not null
49                and (placex.address ? 'housenumber' or placex.address ? 'street' or placex.address ? 'place')
50                and rank_search = 30 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
51          LIMIT 1;
52     ELSE
53       -- See if we can inherit additional address tags from an interpolation.
54       -- These will become permanent.
55       FOR location IN
56         SELECT address FROM place_interpolation
57           WHERE ARRAY[p.osm_id] && place_interpolation.nodes AND address is not NULL
58       LOOP
59         result.address := location.address || result.address;
60       END LOOP;
61     END IF;
62   END IF;
63
64   -- remove internal and derived names
65   result.address := result.address - '_unlisted_place'::TEXT;
66   SELECT hstore(array_agg(key), array_agg(value)) INTO result.name
67     FROM each(p.name) WHERE key not like '\_%';
68
69   result.class := p.class;
70   result.type := p.type;
71   result.country_code := p.country_code;
72   result.rank_address := p.rank_address;
73   result.centroid_x := ST_X(p.centroid);
74   result.centroid_y := ST_Y(p.centroid);
75
76   -- Names of linked places need to be merged in, so search for a linkable
77   -- place already here.
78   SELECT * INTO location FROM find_linked_place(p);
79
80   IF location.place_id is not NULL THEN
81     result.linked_place_id := location.place_id;
82
83     IF location.name is not NULL THEN
84       {% if debug %}RAISE WARNING 'Names original: %, location: %', result.name, location.name;{% endif %}
85
86       -- Add the linked-place (e.g. city) name as a searchable placename in the default language (if any)
87       default_language := get_country_language_code(location.country_code);
88       IF default_language is not NULL AND location.name ? 'name' AND NOT location.name ? ('name:' || default_language) THEN
89         location.name := location.name || hstore('name:' || default_language, location.name->'name');
90       END IF;
91
92       -- Add all names from the place nodes that deviate from the name
93       -- in the relation with the prefix '_place_'. Deviation means that
94       -- either the value is different or a given key is missing completely
95       IF result.name is null THEN
96         SELECT hstore(array_agg('_place_' || key), array_agg(value))
97           INTO result.name
98           FROM each(location.name);
99       ELSE
100         SELECT hstore(array_agg('_place_' || key), array_agg(value)) INTO extra_names
101           FROM each(location.name - result.name);
102         {% if debug %}RAISE WARNING 'Extra names: %', extra_names;{% endif %}
103
104         IF extra_names is not null THEN
105             result.name := result.name || extra_names;
106         END IF;
107       END IF;
108
109       {% if debug %}RAISE WARNING 'Final names: %', result.name;{% endif %}
110     END IF;
111   END IF;
112
113   RETURN result;
114 END;
115 $$
116 LANGUAGE plpgsql STABLE PARALLEL SAFE;
117
118
119 CREATE OR REPLACE FUNCTION find_associated_street(poi_osm_type CHAR(1),
120                                                   poi_osm_id BIGINT,
121                                                   bbox GEOMETRY)
122   RETURNS BIGINT
123   AS $$
124 DECLARE
125   parent RECORD;
126   result BIGINT;
127   distance FLOAT;
128   new_distance FLOAT;
129   waygeom GEOMETRY;
130 BEGIN
131   -- Use UNION of two queries (one for Ways, one for Relations) to allow
132   -- PostgreSQL to use partial indexes on placex.osm_type.
133   FOR parent IN
134     SELECT p.place_id, p.geometry
135       FROM place_associated_street h
136       JOIN place_associated_street s
137            ON h.relation_id = s.relation_id AND s.member_role = 'street'
138       JOIN placex p
139            ON p.osm_type = 'W'
140               AND p.osm_id = s.member_id
141               AND p.name IS NOT NULL
142               AND p.rank_search BETWEEN 26 AND 27
143      WHERE h.member_type = poi_osm_type
144        AND h.member_id = poi_osm_id
145        AND h.member_role = 'house'
146        AND s.member_type = 'W'
147     UNION ALL
148     SELECT p.place_id, p.geometry
149       FROM place_associated_street h
150       JOIN place_associated_street s
151            ON h.relation_id = s.relation_id AND s.member_role = 'street'
152       JOIN placex p
153            ON p.osm_type = 'R'
154               AND p.osm_id = s.member_id
155               AND p.name IS NOT NULL
156               AND p.rank_search BETWEEN 26 AND 27
157      WHERE h.member_type = poi_osm_type
158        AND h.member_id = poi_osm_id
159        AND h.member_role = 'house'
160        AND s.member_type = 'R'
161   LOOP
162     -- Find the closest 'street' member.
163     -- Avoid distance computation for the frequent case where there is
164     -- only one street member.
165     IF waygeom IS NULL THEN
166       result := parent.place_id;
167       waygeom := parent.geometry;
168     ELSE
169       distance := coalesce(distance, ST_Distance(waygeom, bbox));
170       new_distance := ST_Distance(parent.geometry, bbox);
171       IF new_distance < distance THEN
172         distance := new_distance;
173         result := parent.place_id;
174         waygeom := parent.geometry;
175       END IF;
176     END IF;
177   END LOOP;
178
179   RETURN result;
180 END;
181 $$
182 LANGUAGE plpgsql STABLE PARALLEL SAFE;
183
184
185 -- Find the parent road of a POI.
186 --
187 -- \returns Place ID of parent object or NULL if none
188 --
189 -- Copy data from linked items (POIs on ways, addr:street links, relations).
190 --
191 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
192                                                poi_osm_id BIGINT,
193                                                poi_partition SMALLINT,
194                                                bbox GEOMETRY,
195                                                token_info JSONB,
196                                                is_place_addr BOOLEAN)
197   RETURNS BIGINT
198   AS $$
199 DECLARE
200   parent_place_id BIGINT DEFAULT NULL;
201   location RECORD;
202 BEGIN
203   {% if debug %}RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;{% endif %}
204
205   -- Is this object part of an associatedStreet relation?
206   parent_place_id := find_associated_street(poi_osm_type, poi_osm_id, bbox);
207
208   IF parent_place_id is null THEN
209     parent_place_id := find_parent_for_address(token_info, poi_partition, bbox);
210   END IF;
211
212   IF parent_place_id is null and poi_osm_type = 'N' THEN
213     FOR location IN
214       SELECT p.place_id, p.osm_id, p.rank_search, p.address,
215              coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
216         FROM placex p, planet_osm_ways w
217        WHERE p.osm_type = 'W' and p.rank_search >= 26
218              and p.geometry && bbox
219              and w.id = p.osm_id and poi_osm_id = any(w.nodes)
220     LOOP
221       {% if debug %}RAISE WARNING 'Node is part of way % ', location.osm_id;{% endif %}
222
223       -- Way IS a road then we are on it - that must be our road
224       IF location.rank_search < 28 THEN
225         {% if debug %}RAISE WARNING 'node in way that is a street %',location;{% endif %}
226         RETURN location.place_id;
227       END IF;
228
229       parent_place_id := find_associated_street('W', location.osm_id, bbox);
230     END LOOP;
231   END IF;
232
233   IF parent_place_id is NULL THEN
234     IF is_place_addr THEN
235       -- The address is attached to a place we don't know.
236       -- Instead simply use the containing area with the largest rank.
237       FOR location IN
238         SELECT place_id FROM placex
239          WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
240                AND rank_address between 5 and 25
241                AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
242          ORDER BY rank_address desc
243       LOOP
244         RETURN location.place_id;
245       END LOOP;
246     ELSEIF ST_Area(bbox) < 0.005 THEN
247       -- for smaller features get the nearest road
248       SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
249       {% if debug %}RAISE WARNING 'Checked for nearest way (%)', parent_place_id;{% endif %}
250     ELSE
251       -- for larger features simply find the area with the largest rank that
252       -- contains the bbox, only use addressable features
253       FOR location IN
254         SELECT place_id FROM placex
255          WHERE bbox && geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
256                AND rank_address between 5 and 25
257                AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
258         ORDER BY rank_address desc
259       LOOP
260         RETURN location.place_id;
261       END LOOP;
262     END IF;
263   END IF;
264
265   RETURN parent_place_id;
266 END;
267 $$
268 LANGUAGE plpgsql STABLE PARALLEL SAFE;
269
270 -- Try to find a linked place for the given object.
271 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
272   RETURNS placex
273   AS $$
274 DECLARE
275 {% if db.middle_db_format == '1' %}
276   relation_members TEXT[];
277 {% else %}
278   relation_members JSONB;
279 {% endif %}
280   rel_member RECORD;
281   linked_placex placex%ROWTYPE;
282   bnd_name TEXT;
283 BEGIN
284   IF bnd.rank_search >= 26 or bnd.rank_address = 0
285      or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
286   THEN
287     RETURN NULL;
288   END IF;
289
290   IF bnd.osm_type = 'R' THEN
291     -- see if we have any special relation members
292     SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
293     {% if debug %}RAISE WARNING 'Got relation members';{% endif %}
294
295     -- Search for relation members with role 'lable'.
296     IF relation_members IS NOT NULL THEN
297       FOR rel_member IN
298         SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
299       LOOP
300         {% if debug %}RAISE WARNING 'Found label member %', rel_member.member;{% endif %}
301
302         FOR linked_placex IN
303           SELECT * from placex
304           WHERE osm_type = 'N' and osm_id = rel_member.member
305             and class = 'place'
306         LOOP
307           {% if debug %}RAISE WARNING 'Linked label member';{% endif %}
308           RETURN linked_placex;
309         END LOOP;
310
311       END LOOP;
312     END IF;
313   END IF;
314
315   IF bnd.name ? 'name' THEN
316     bnd_name := lower(bnd.name->'name');
317     IF bnd_name = '' THEN
318       bnd_name := NULL;
319     END IF;
320   END IF;
321
322   IF bnd.extratags ? 'wikidata' THEN
323     FOR linked_placex IN
324       SELECT * FROM placex
325       WHERE placex.class = 'place' AND placex.osm_type = 'N'
326         AND placex.extratags ? 'wikidata' -- needed to select right index
327         AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
328         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
329         AND placex.rank_search < 26
330         AND _st_covers(bnd.geometry, placex.geometry)
331       ORDER BY lower(name->'name') = bnd_name desc
332     LOOP
333       {% if debug %}RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;{% endif %}
334       RETURN linked_placex;
335     END LOOP;
336   END IF;
337
338   -- If extratags has a place tag, look for linked nodes by their place type.
339   -- Area and node still have to have the same name.
340   IF bnd.extratags ? 'place' and bnd_name is not null
341   THEN
342     FOR linked_placex IN
343       SELECT * FROM placex
344       WHERE (position(lower(name->'name') in bnd_name) > 0
345              OR position(bnd_name in lower(name->'name')) > 0)
346         AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
347         AND placex.osm_type = 'N'
348         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
349         AND placex.rank_search < 26 -- needed to select the right index
350         AND (NOT placex.extratags ? 'wikidata' OR NOT bnd.extratags ? 'wikidata'
351              OR placex.extratags->'wikidata' = bnd.extratags->'wikidata')
352         AND ST_Covers(bnd.geometry, placex.geometry)
353     LOOP
354       {% if debug %}RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;{% endif %}
355       RETURN linked_placex;
356     END LOOP;
357   END IF;
358
359   -- Name searches can be done for ways as well as relations
360   IF bnd_name is not null THEN
361     {% if debug %}RAISE WARNING 'Looking for nodes with matching names';{% endif %}
362     FOR linked_placex IN
363       SELECT placex.* from placex
364       WHERE lower(name->'name') = bnd_name
365         AND ((bnd.rank_address > 0
366               and bnd.rank_address = (compute_place_rank(placex.country_code,
367                                                          'N', placex.class,
368                                                          placex.type, 15::SMALLINT,
369                                                          false, placex.postcode)).address_rank)
370              OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
371         AND placex.osm_type = 'N'
372         AND placex.class = 'place'
373         AND (placex.linked_place_id is null or placex.linked_place_id = bnd.place_id)
374         AND placex.rank_search < 26 -- needed to select the right index
375         AND (placex.extratags->'wikidata' is null OR bnd.extratags->'wikidata' is null
376              OR placex.extratags->'wikidata' = bnd.extratags->'wikidata')
377         AND ST_Covers(bnd.geometry, placex.geometry)
378     LOOP
379       {% if debug %}RAISE WARNING 'Found matching place node %', linked_placex.osm_id;{% endif %}
380       RETURN linked_placex;
381     END LOOP;
382   END IF;
383
384   RETURN NULL;
385 END;
386 $$
387 LANGUAGE plpgsql STABLE PARALLEL SAFE;
388
389
390 CREATE OR REPLACE FUNCTION create_poi_search_terms(obj_place_id BIGINT,
391                                                    in_partition SMALLINT,
392                                                    parent_place_id BIGINT,
393                                                    is_place_addr BOOLEAN,
394                                                    country TEXT,
395                                                    token_info JSONB,
396                                                    geometry GEOMETRY,
397                                                    OUT name_vector INTEGER[],
398                                                    OUT nameaddress_vector INTEGER[])
399   AS $$
400 DECLARE
401   parent_name_vector INTEGER[];
402   parent_address_vector INTEGER[];
403   addr_place_ids INTEGER[];
404   hnr_vector INTEGER[];
405
406   addr_item RECORD;
407   addr_place RECORD;
408   parent_address_place_ids BIGINT[];
409 BEGIN
410   nameaddress_vector := '{}'::INTEGER[];
411
412   SELECT s.name_vector, s.nameaddress_vector
413     INTO parent_name_vector, parent_address_vector
414     FROM search_name s
415     WHERE s.place_id = parent_place_id;
416
417   FOR addr_item IN
418     SELECT ranks.*, key,
419            token_get_address_search_tokens(token_info, key) as search_tokens
420       FROM token_get_address_keys(token_info) as key,
421            LATERAL get_addr_tag_rank(key, country) as ranks
422       WHERE not token_get_address_search_tokens(token_info, key) <@ parent_address_vector
423   LOOP
424     addr_place := get_address_place(in_partition, geometry,
425                                     addr_item.from_rank, addr_item.to_rank,
426                                     addr_item.extent, token_info, addr_item.key);
427
428     IF addr_place is null THEN
429       -- No place found in OSM that matches. Make it at least searchable.
430       nameaddress_vector := array_merge(nameaddress_vector, addr_item.search_tokens);
431     ELSE
432       IF parent_address_place_ids is null THEN
433         SELECT array_agg(parent_place_id) INTO parent_address_place_ids
434           FROM place_addressline
435           WHERE place_id = parent_place_id;
436       END IF;
437
438       -- If the parent already lists the place in place_address line, then we
439       -- are done. Otherwise, add its own place_address line.
440       IF not parent_address_place_ids @> ARRAY[addr_place.place_id] THEN
441         nameaddress_vector := array_merge(nameaddress_vector, addr_place.keywords);
442
443         INSERT INTO place_addressline (place_id, address_place_id, fromarea,
444                                        isaddress, distance, cached_rank_address)
445           VALUES (obj_place_id, addr_place.place_id, not addr_place.isguess,
446                     true, addr_place.distance, addr_place.rank_address);
447       END IF;
448     END IF;
449   END LOOP;
450
451   name_vector := COALESCE(token_get_name_search_tokens(token_info), '{}'::INTEGER[]);
452
453   -- Check if the parent covers all address terms.
454   -- If not, create a search name entry with the house number as the name.
455   -- This is unusual for the search_name table but prevents that the place
456   -- is returned when we only search for the street/place.
457
458   hnr_vector := token_get_housenumber_search_tokens(token_info);
459
460   IF hnr_vector is not null and not nameaddress_vector <@ parent_address_vector THEN
461     name_vector := array_merge(name_vector, hnr_vector);
462   END IF;
463
464   -- Cheating here by not recomputing all terms but simply using the ones
465   -- from the parent object.
466   nameaddress_vector := array_merge(nameaddress_vector, parent_name_vector);
467   nameaddress_vector := array_merge(nameaddress_vector, parent_address_vector);
468
469   -- make sure addr:place terms are always searchable
470   IF is_place_addr THEN
471     addr_place_ids := token_addr_place_search_tokens(token_info);
472     IF hnr_vector is not null AND not addr_place_ids <@ parent_name_vector
473     THEN
474       name_vector := array_merge(name_vector, hnr_vector);
475     END IF;
476     nameaddress_vector := array_merge(nameaddress_vector, addr_place_ids);
477   END IF;
478 END;
479 $$
480 LANGUAGE plpgsql;
481
482
483 -- Insert address of a place into the place_addressline table.
484 --
485 -- \param obj_place_id  Place_id of the place to compute the address for.
486 -- \param partition     Partition number where the place is in.
487 -- \param maxrank       Rank of the place. All address features must have
488 --                      a search rank lower than the given rank.
489 -- \param address       Address terms for the place.
490 -- \param geometry      Geometry to which the address objects should be close.
491 --
492 -- \retval parent_place_id  Place_id of the address object that is the direct
493 --                          ancestor.
494 -- \retval postcode         Postcode computed from the address. This is the
495 --                          addr:postcode of one of the address objects. If
496 --                          more than one of has a postcode, the highest ranking
497 --                          one is used. May be NULL.
498 -- \retval nameaddress_vector  Search terms for the address. This is the sum
499 --                             of name terms of all address objects.
500 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
501                                                partition SMALLINT,
502                                                maxrank SMALLINT,
503                                                token_info JSONB,
504                                                geometry GEOMETRY,
505                                                centroid GEOMETRY,
506                                                country TEXT,
507                                                OUT parent_place_id BIGINT,
508                                                OUT postcode TEXT,
509                                                OUT nameaddress_vector INT[])
510   AS $$
511 DECLARE
512   address_havelevel BOOLEAN[];
513   place_min_distance FLOAT[];
514
515   location_isaddress BOOLEAN;
516   current_boundary GEOMETRY := NULL;
517   current_node_area GEOMETRY := NULL;
518
519   parent_place_rank INT := 0;
520   addr_place_ids BIGINT[] := '{}'::int[];
521   new_address_vector INT[];
522
523   location RECORD;
524 BEGIN
525   parent_place_id := 0;
526   nameaddress_vector := '{}'::int[];
527
528   address_havelevel := array_fill(false, ARRAY[maxrank]);
529   place_min_distance := array_fill(1.0, ARRAY[maxrank]);
530
531   FOR location IN
532     SELECT apl.*, key
533       FROM (SELECT extra.*, key
534               FROM token_get_address_keys(token_info) as key,
535                    LATERAL get_addr_tag_rank(key, country) as extra) x,
536            LATERAL get_address_place(partition, geometry, from_rank, to_rank,
537                               extent, token_info, key) as apl
538       ORDER BY rank_address, distance, isguess desc
539   LOOP
540     IF location.place_id is null THEN
541       {% if not db.reverse_only %}
542       nameaddress_vector := array_merge(nameaddress_vector,
543                                         token_get_address_search_tokens(token_info,
544                                                                         location.key));
545       {% endif %}
546     ELSE
547       {% if not db.reverse_only %}
548       nameaddress_vector := array_merge(nameaddress_vector, location.keywords::INTEGER[]);
549       {% endif %}
550
551       location_isaddress := not address_havelevel[location.rank_address];
552       IF not address_havelevel[location.rank_address] THEN
553         address_havelevel[location.rank_address] := true;
554         IF parent_place_rank < location.rank_address THEN
555           parent_place_id := location.place_id;
556           parent_place_rank := location.rank_address;
557         END IF;
558       END IF;
559
560       IF location.isguess and location.distance < place_min_distance[location.rank_address] THEN
561         place_min_distance[location.rank_address] := location.distance;
562       END IF;
563
564       INSERT INTO place_addressline (place_id, address_place_id, fromarea,
565                                      isaddress, distance, cached_rank_address)
566         VALUES (obj_place_id, location.place_id, not location.isguess,
567                 true, location.distance, location.rank_address);
568
569       addr_place_ids := addr_place_ids || location.place_id;
570     END IF;
571   END LOOP;
572
573   FOR location IN
574     SELECT * FROM getNearFeatures(partition, geometry, centroid, maxrank)
575     WHERE not addr_place_ids @> ARRAY[place_id]
576     ORDER BY rank_address, isguess asc,
577              distance *
578                CASE WHEN rank_address = 16 AND rank_search = 15 THEN 0.2
579                     WHEN rank_address = 16 AND rank_search = 16 THEN 0.25
580                     WHEN rank_address = 16 AND rank_search = 18 THEN 0.5
581                     ELSE 1 END ASC
582   LOOP
583     -- Ignore all place nodes that do not fit in a lower level boundary.
584     CONTINUE WHEN location.isguess
585                   and current_boundary is not NULL
586                   and not ST_Contains(current_boundary, location.centroid);
587
588     -- If this is the first item in the rank, then assume it is the address.
589     location_isaddress := not address_havelevel[location.rank_address];
590
591     -- Ignore guessed places when they are too far away compared to similar closer ones.
592     IF location.isguess THEN
593       CONTINUE WHEN not location_isaddress
594                     AND location.distance > 2 * place_min_distance[location.rank_address];
595
596       IF location.distance < place_min_distance[location.rank_address] THEN
597         place_min_distance[location.rank_address] := location.distance;
598       END IF;
599     END IF;
600
601     -- Further sanity checks to ensure that the address forms a sane hierarchy.
602     IF location_isaddress THEN
603       IF location.isguess and current_node_area is not NULL THEN
604         location_isaddress := ST_Contains(current_node_area, location.centroid);
605       END IF;
606       IF not location.isguess and current_boundary is not NULL
607          and location.rank_address != 11 AND location.rank_address != 5 THEN
608         location_isaddress := ST_Contains(current_boundary, location.centroid);
609       END IF;
610     END IF;
611
612     IF location_isaddress THEN
613       address_havelevel[location.rank_address] := true;
614       parent_place_id := location.place_id;
615
616       -- Set postcode if we have one.
617       -- (Returned will be the highest ranking one.)
618       IF location.postcode is not NULL THEN
619         postcode = location.postcode;
620       END IF;
621
622       -- Recompute the areas we need for hierarchy sanity checks.
623       IF location.rank_address != 11 AND location.rank_address != 5 THEN
624         IF location.isguess THEN
625           current_node_area := place_node_fuzzy_area(location.centroid,
626                                                      location.rank_search);
627         ELSE
628           current_node_area := NULL;
629           SELECT p.geometry FROM placex p
630               WHERE p.place_id = location.place_id INTO current_boundary;
631         END IF;
632       END IF;
633     END IF;
634
635     -- Add it to the list of search terms
636     {% if not db.reverse_only %}
637       IF location.rank_address != 11 AND location.rank_address != 5 THEN
638           nameaddress_vector := array_merge(nameaddress_vector,
639                                             location.keywords::integer[]);
640       END IF;
641     {% endif %}
642
643     INSERT INTO place_addressline (place_id, address_place_id, fromarea,
644                                      isaddress, distance, cached_rank_address)
645         VALUES (obj_place_id, location.place_id, not location.isguess,
646                 location_isaddress, location.distance, location.rank_address);
647   END LOOP;
648 END;
649 $$
650 LANGUAGE plpgsql;
651
652
653 CREATE OR REPLACE FUNCTION placex_insert()
654   RETURNS TRIGGER
655   AS $$
656 DECLARE
657   postcode TEXT;
658   result INT;
659   is_area BOOLEAN;
660   country_code VARCHAR(2);
661   diameter FLOAT;
662   classtable TEXT;
663 BEGIN
664   {% if debug %}RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
665
666   NEW.place_id := nextval('seq_place');
667   NEW.indexed_status := 1; --STATUS_NEW
668
669   NEW.centroid := get_center_point(NEW.geometry);
670   NEW.country_code := lower(get_country_code(NEW.centroid));
671
672   NEW.partition := get_partition(NEW.country_code);
673   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.centroid);
674
675   IF NEW.osm_type = 'X' THEN
676     -- E'X'ternal records should already be in the right format so do nothing
677   ELSE
678     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
679
680     IF NOT is_rankable_place(NEW.osm_type, NEW.class, NEW.admin_level,
681                              NEW.name, NEW.extratags, is_area)
682     THEN
683         RETURN NULL;
684     END IF;
685
686     SELECT * INTO NEW.rank_search, NEW.rank_address
687       FROM compute_place_rank(NEW.country_code,
688                               CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
689                               NEW.class, NEW.type, NEW.admin_level,
690                               (NEW.extratags->'capital') = 'yes',
691                               NEW.address->'postcode');
692
693     -- a country code make no sense below rank 4 (country)
694     IF NEW.rank_search < 4 THEN
695       NEW.country_code := NULL;
696     END IF;
697
698     -- Simplify polygons with a very large memory footprint when they
699     -- do not take part in address computation.
700     IF NEW.rank_address = 0 THEN
701       NEW.geometry := simplify_large_polygons(NEW.geometry);
702     END IF;
703
704   END IF;
705
706   IF NEW.importance IS NULL THEN
707     NEW.importance := 0.40001 - (NEW.rank_search::float / 75);
708   END IF;
709
710   {% if debug %}RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;{% endif %}
711
712 {% if not disable_diff_updates %}
713   -- The following is not needed until doing diff updates, and slows the main index process down
714
715    -- add to tables for special search
716   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
717   SELECT count(*) INTO result
718     FROM pg_tables
719     WHERE classtable NOT SIMILAR TO '%\W%'
720           AND tablename = classtable and schemaname = current_schema();
721   IF result > 0 THEN
722     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
723     USING NEW.place_id, NEW.centroid;
724   END IF;
725
726 {% endif %} -- not disable_diff_updates
727
728   RETURN NEW;
729
730 END;
731 $$
732 LANGUAGE plpgsql;
733
734 CREATE OR REPLACE FUNCTION placex_update()
735   RETURNS TRIGGER
736   AS $$
737 DECLARE
738   i INTEGER;
739   location RECORD;
740 {% if db.middle_db_format == '1' %}
741   relation_members TEXT[];
742 {% else %}
743   relation_member JSONB;
744 {% endif %}
745
746   geom GEOMETRY;
747   parent_address_level SMALLINT;
748   place_address_level SMALLINT;
749
750   max_rank SMALLINT;
751
752   name_vector INTEGER[];
753   nameaddress_vector INTEGER[];
754   addr_nameaddress_vector INTEGER[];
755
756   linked_place BIGINT;
757
758   linked_node_id BIGINT;
759   linked_importance FLOAT;
760   linked_wikipedia TEXT;
761
762   is_place_address BOOLEAN;
763   result BOOLEAN;
764 BEGIN
765   -- deferred delete
766   IF OLD.indexed_status = 100 THEN
767     {% if debug %}RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;{% endif %}
768     delete from placex where place_id = OLD.place_id;
769     RETURN NULL;
770   END IF;
771
772   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
773     RETURN NEW;
774   END IF;
775
776   {% if debug %}RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;{% endif %}
777
778   NEW.indexed_date = now();
779
780   IF OLD.indexed_status > 1 THEN
781     {% if 'search_name' in db.tables %}
782       DELETE from search_name WHERE place_id = NEW.place_id;
783     {% endif %}
784     result := deleteSearchName(NEW.partition, NEW.place_id);
785     DELETE FROM place_addressline WHERE place_id = NEW.place_id;
786     result := deleteRoad(NEW.partition, NEW.place_id);
787     result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
788   END IF;
789
790   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
791   IF NEW.extratags = ''::hstore THEN
792     NEW.extratags := NULL;
793   END IF;
794
795   -- NEW.linked_place_id contains the precomputed linkee. Save this and restore
796   -- the previous link status.
797   linked_place := NEW.linked_place_id;
798   NEW.linked_place_id := OLD.linked_place_id;
799
800   -- Remove linkage, if we have computed a different new linkee.
801   IF OLD.indexed_status > 1 THEN
802     UPDATE placex
803       SET linked_place_id = null,
804           indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
805       WHERE linked_place_id = NEW.place_id
806             and (linked_place is null or place_id != linked_place);
807   END IF;
808
809   -- Compute a preliminary centroid.
810   NEW.centroid := get_center_point(NEW.geometry);
811
812   -- Record the entrance node locations
813   IF NEW.osm_type = 'W' and (NEW.rank_search > 27 or NEW.class IN ('landuse', 'leisure')) THEN
814     PERFORM place_update_entrances(NEW.place_id, NEW.osm_id);
815   END IF;
816
817     -- recalculate country and partition
818   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
819     -- for countries, believe the mapped country code,
820     -- so that we remain in the right partition if the boundaries
821     -- suddenly expand.
822     NEW.country_code := lower(NEW.address->'country');
823     NEW.partition := get_partition(lower(NEW.country_code));
824     IF NEW.partition = 0 THEN
825       NEW.country_code := lower(get_country_code(NEW.centroid));
826       NEW.partition := get_partition(NEW.country_code);
827     END IF;
828   ELSE
829     IF NEW.rank_search >= 4 THEN
830       NEW.country_code := lower(get_country_code(NEW.centroid));
831     ELSE
832       NEW.country_code := NULL;
833     END IF;
834     NEW.partition := get_partition(NEW.country_code);
835   END IF;
836   {% if debug %}RAISE WARNING 'Country updated: "%"', NEW.country_code;{% endif %}
837
838
839   -- recompute the ranks, they might change when linking changes
840   SELECT * INTO NEW.rank_search, NEW.rank_address
841     FROM compute_place_rank(NEW.country_code,
842                             CASE WHEN ST_GeometryType(NEW.geometry)
843                                         IN ('ST_Polygon','ST_MultiPolygon')
844                             THEN 'A' ELSE NEW.osm_type END,
845                             NEW.class, NEW.type, NEW.admin_level,
846                             (NEW.extratags->'capital') = 'yes',
847                             NEW.address->'postcode');
848
849   -- Short-cut out for linked places. Note that this must happen after the
850   -- address rank has been recomputed. The linking might nullify a shift in
851   -- address rank.
852   IF NEW.linked_place_id is not null THEN
853     NEW.token_info := null;
854     {% if debug %}RAISE WARNING 'place already linked to %', OLD.linked_place_id;{% endif %}
855     RETURN NEW;
856   END IF;
857
858   -- We must always increase the address level relative to the admin boundary.
859   IF NEW.class = 'boundary' and NEW.type = 'administrative'
860      and NEW.osm_type = 'R' and NEW.rank_address > 0
861   THEN
862     -- First, check that admin boundaries do not overtake each other rank-wise.
863     parent_address_level := 3;
864     FOR location IN
865       SELECT rank_address,
866              (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
867                         and extratags->'wikidata' = NEW.extratags->'wikidata'
868                    THEN ST_Equals(geometry, NEW.geometry)
869                    ELSE false END) as is_same
870       FROM placex
871       WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
872             and admin_level < NEW.admin_level and admin_level > 3
873             and rank_address between 1 and 25 -- for index selection
874             and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- for index selection
875             and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
876       ORDER BY admin_level desc LIMIT 1
877     LOOP
878       IF location.is_same THEN
879         -- Looks like the same boundary is replicated on multiple admin_levels.
880         -- Usual tagging in Poland. Remove our boundary from addresses.
881         NEW.rank_address := 0;
882       ELSE
883         parent_address_level := location.rank_address;
884         IF location.rank_address >= NEW.rank_address THEN
885           IF location.rank_address >= 24 THEN
886             NEW.rank_address := 25;
887           ELSE
888             NEW.rank_address := location.rank_address + 2;
889           END IF;
890         END IF;
891       END IF;
892     END LOOP;
893
894     IF NEW.rank_address > 9 THEN
895         -- Second check that the boundary is not completely contained in a
896         -- place area with a equal or higher address rank.
897         FOR location IN
898           SELECT rank_address
899           FROM placex,
900                LATERAL compute_place_rank(country_code, 'A', class, type,
901                                           admin_level, False, null) prank
902           WHERE class = 'place' and rank_address between 1 and 23
903                 and prank.address_rank >= NEW.rank_address
904                 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
905                 and ST_Contains(geometry, NEW.geometry)
906                 and not ST_Equals(geometry, NEW.geometry)
907           ORDER BY prank.address_rank desc LIMIT 1
908         LOOP
909           NEW.rank_address := location.rank_address + 2;
910         END LOOP;
911     END IF;
912   ELSEIF NEW.class = 'place'
913          and ST_GeometryType(NEW.geometry) in ('ST_Polygon', 'ST_MultiPolygon')
914          and NEW.rank_address between 16 and 23
915   THEN
916     -- For place areas make sure they are not completely contained in an area
917     -- with a equal or higher address rank.
918     FOR location IN
919           SELECT rank_address
920           FROM placex,
921                LATERAL compute_place_rank(country_code, 'A', class, type,
922                                           admin_level, False, null) prank
923           WHERE prank.address_rank < 24
924                 and rank_address between 1 and 25 -- select right index
925                 and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
926                 and prank.address_rank >= NEW.rank_address
927                 and ST_Contains(geometry, NEW.geometry)
928                 and not ST_Equals(geometry, NEW.geometry)
929           ORDER BY prank.address_rank desc LIMIT 1
930         LOOP
931           NEW.rank_address := location.rank_address + 2;
932         END LOOP;
933   ELSEIF NEW.class = 'place' and NEW.osm_type = 'N'
934          and NEW.rank_address between 16 and 23
935   THEN
936     -- If a place node is contained in an admin or place boundary with the same
937     -- address level and has not been linked, then make the node a subpart
938     -- by increasing the address rank (city level and above).
939     FOR location IN
940         SELECT rank_address
941         FROM placex,
942              LATERAL compute_place_rank(country_code, 'A', class, type,
943                                         admin_level, False, null) prank
944         WHERE osm_type = 'R'
945               and rank_address between 1 and 25 -- select right index
946               and ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon') -- select right index
947               and ((class = 'place' and prank.address_rank = NEW.rank_address)
948                    or (class = 'boundary' and rank_address = NEW.rank_address))
949               and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
950         LIMIT 1
951     LOOP
952       NEW.rank_address = NEW.rank_address + 2;
953     END LOOP;
954   ELSE
955     parent_address_level := 3;
956   END IF;
957
958   NEW.housenumber := token_normalized_housenumber(NEW.token_info);
959
960   NEW.postcode := null;
961
962   -- waterway ways are linked when they are part of a relation and have the same class/type
963   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
964 {% if db.middle_db_format == '1' %}
965       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
966       LOOP
967           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
968               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
969                 {% if debug %}RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];{% endif %}
970                 FOR linked_node_id IN SELECT place_id FROM placex
971                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
972                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
973                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
974                 LOOP
975                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
976                   {% if 'search_name' in db.tables %}
977                     IF OLD.indexed_status > 1 THEN
978                       DELETE FROM search_name WHERE place_id = linked_node_id;
979                     END IF;
980                   {% endif %}
981                 END LOOP;
982               END IF;
983           END LOOP;
984       END LOOP;
985 {% else %}
986     FOR relation_member IN
987       SELECT value FROM planet_osm_rels r, LATERAL jsonb_array_elements(r.members)
988       WHERE r.id = NEW.osm_id
989     LOOP
990       IF relation_member->>'role' IN ('', 'main_stream', 'side_stream')
991          and relation_member->>'type' = 'W'
992       THEN
993         {% if debug %}RAISE WARNING 'waterway parent %, child %', NEW.osm_id, relation_member;{% endif %}
994         FOR linked_node_id IN
995           SELECT place_id FROM placex
996           WHERE osm_type = 'W' and osm_id = (relation_member->>'ref')::bigint
997                 and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
998                 and (relation_member->>'role' != 'side_stream' or NEW.name->'name' = name->'name')
999         LOOP
1000           UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
1001           {% if 'search_name' in db.tables %}
1002             DELETE FROM search_name WHERE place_id = linked_node_id;
1003           {% endif %}
1004         END LOOP;
1005       END IF;
1006     END LOOP;
1007 {% endif %}
1008       {% if debug %}RAISE WARNING 'Waterway processed';{% endif %}
1009   END IF;
1010
1011   SELECT wikipedia, importance INTO NEW.wikipedia, NEW.importance
1012     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.rank_search, NEW.centroid);
1013
1014 {% if debug %}RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;{% endif %}
1015
1016   -- ---------------------------------------------------------------------------
1017   -- For low level elements we inherit from our parent road
1018   IF NEW.rank_search > 27 THEN
1019
1020     {% if debug %}RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1021     NEW.parent_place_id := null;
1022     is_place_address := not token_is_street_address(NEW.token_info);
1023
1024     -- We have to find our parent road.
1025     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
1026                                                NEW.partition,
1027                                                ST_Envelope(NEW.geometry),
1028                                                NEW.token_info,
1029                                                is_place_address);
1030
1031     -- If we found the road take a shortcut here.
1032     -- Otherwise fall back to the full address getting method below.
1033     IF NEW.parent_place_id is not null THEN
1034
1035       -- Get the details of the parent road
1036       SELECT p.country_code, p.postcode, p.name FROM placex p
1037        WHERE p.place_id = NEW.parent_place_id INTO location;
1038
1039       IF is_place_address and NEW.address ? 'place' THEN
1040         -- Check if the addr:place tag is part of the parent name
1041         SELECT count(*) INTO i
1042           FROM svals(location.name) AS pname WHERE pname = NEW.address->'place';
1043         IF i = 0 THEN
1044           NEW.address = NEW.address || hstore('_unlisted_place', NEW.address->'place');
1045         END IF;
1046       END IF;
1047
1048       NEW.country_code := location.country_code;
1049       {% if debug %}RAISE WARNING 'Got parent details from search name';{% endif %}
1050
1051       -- determine postcode
1052       NEW.postcode := coalesce(token_get_postcode(NEW.token_info),
1053                                location.postcode,
1054                                get_nearest_postcode(NEW.country_code, NEW.centroid));
1055
1056       IF NEW.name is not NULL THEN
1057           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1058       END IF;
1059
1060       {% if not db.reverse_only %}
1061       IF NEW.name is not NULL OR NEW.address is not NULL THEN
1062         SELECT * INTO name_vector, nameaddress_vector
1063           FROM create_poi_search_terms(NEW.place_id,
1064                                        NEW.partition, NEW.parent_place_id,
1065                                        is_place_address, NEW.country_code,
1066                                        NEW.token_info, NEW.centroid);
1067
1068         IF array_length(name_vector, 1) is not NULL THEN
1069           INSERT INTO search_name (place_id, address_rank,
1070                                    importance, country_code, name_vector,
1071                                    nameaddress_vector, centroid)
1072                  VALUES (NEW.place_id, NEW.rank_address,
1073                          NEW.importance, NEW.country_code, name_vector,
1074                          nameaddress_vector, NEW.centroid);
1075           {% if debug %}RAISE WARNING 'Place added to search table';{% endif %}
1076         END IF;
1077       END IF;
1078       {% endif %}
1079
1080       NEW.token_info := token_strip_info(NEW.token_info);
1081
1082       RETURN NEW;
1083     END IF;
1084
1085   END IF;
1086
1087   -- ---------------------------------------------------------------------------
1088   -- Full indexing
1089   {% if debug %}RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;{% endif %}
1090   IF linked_place is not null THEN
1091     -- Recompute the ranks here as the ones from the linked place might
1092     -- have been shifted to accommodate surrounding boundaries.
1093     SELECT place_id, osm_id, class, type, extratags, rank_search,
1094            centroid, geometry,
1095            (compute_place_rank(country_code, osm_type, class, type, admin_level,
1096                               (extratags->'capital') = 'yes', null)).*
1097       INTO location
1098       FROM placex WHERE place_id = linked_place;
1099
1100     {% if debug %}RAISE WARNING 'Linked %', location;{% endif %}
1101
1102     -- Use the linked point as the centre point of the geometry,
1103     -- but only if it is within the area of the boundary.
1104     geom := coalesce(location.centroid, ST_Centroid(location.geometry));
1105     IF geom is not NULL AND ST_Within(geom, NEW.geometry) THEN
1106         NEW.centroid := geom;
1107     END IF;
1108
1109     {% if debug %}RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.address_rank;{% endif %}
1110     IF location.address_rank > parent_address_level
1111        and location.address_rank < 26
1112     THEN
1113       NEW.rank_address := location.address_rank;
1114     END IF;
1115
1116     -- merge in extra tags
1117     NEW.extratags := hstore('linked_' || location.class, location.type)
1118                      || coalesce(location.extratags, ''::hstore)
1119                      || coalesce(NEW.extratags, ''::hstore);
1120
1121     -- mark the linked place (excludes from search results)
1122     -- Force reindexing to remove any traces from the search indexes and
1123     -- reset the address rank if necessary.
1124     UPDATE placex set linked_place_id = NEW.place_id, indexed_status = 2
1125       WHERE place_id = location.place_id;
1126
1127     SELECT wikipedia, importance
1128       FROM compute_importance(location.extratags, NEW.country_code,
1129                               location.rank_search, NEW.centroid)
1130       INTO linked_wikipedia,linked_importance;
1131
1132     -- Use the maximum importance if one could be computed from the linked object.
1133     IF linked_importance is not null AND
1134        (NEW.importance is null or NEW.importance < linked_importance)
1135     THEN
1136       NEW.importance := linked_importance;
1137     END IF;
1138   ELSE
1139     -- No linked place? As a last resort check if the boundary is tagged with
1140     -- a place type and adapt the rank address.
1141     IF NEW.rank_address between 4 and 25 and NEW.extratags ? 'place' THEN
1142       SELECT address_rank INTO place_address_level
1143         FROM compute_place_rank(NEW.country_code, 'A', 'place',
1144                                 NEW.extratags->'place', 0::SMALLINT, False, null);
1145       IF place_address_level > parent_address_level and
1146          place_address_level < 26 THEN
1147         NEW.rank_address := place_address_level;
1148       END IF;
1149     END IF;
1150   END IF;
1151
1152   {% if not disable_diff_updates %}
1153   IF OLD.rank_address != NEW.rank_address THEN
1154     -- After a rank shift all addresses containing us must be updated.
1155     UPDATE placex p SET indexed_status = 2 FROM place_addressline pa
1156       WHERE pa.address_place_id = NEW.place_id and p.place_id = pa.place_id
1157             and p.indexed_status = 0 and p.rank_address between 4 and 25;
1158   END IF;
1159   {% endif %}
1160
1161   IF NEW.admin_level = 2
1162      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
1163      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
1164   THEN
1165     -- Update the list of country names.
1166     -- Only take the name from the largest area for the given country code
1167     -- in the hope that this is the authoritative one.
1168     -- Also replace any old names so that all mapping mistakes can
1169     -- be fixed through regular OSM updates.
1170     FOR location IN
1171       SELECT osm_id FROM placex
1172        WHERE rank_search = 4 and osm_type = 'R'
1173              and country_code = NEW.country_code
1174        ORDER BY ST_Area(geometry) desc
1175        LIMIT 1
1176     LOOP
1177       IF location.osm_id = NEW.osm_id THEN
1178         {% if debug %}RAISE WARNING 'Updating names for country ''%'' with: %', NEW.country_code, NEW.name;{% endif %}
1179         UPDATE country_name SET derived_name = NEW.name WHERE country_code = NEW.country_code;
1180       END IF;
1181     END LOOP;
1182   END IF;
1183
1184   -- For linear features we need the full geometry for determining the address
1185   -- because they may go through several administrative entities. Otherwise use
1186   -- the centroid for performance reasons.
1187   IF ST_GeometryType(NEW.geometry) in ('ST_LineString', 'ST_MultiLineString') THEN
1188     geom := NEW.geometry;
1189   ELSE
1190     geom := NEW.centroid;
1191   END IF;
1192
1193   IF NEW.rank_address = 0 THEN
1194     max_rank := geometry_to_rank(NEW.rank_search, NEW.geometry, NEW.country_code);
1195     -- Rank 0 features may also span multiple administrative areas (e.g. lakes)
1196     -- so use the geometry here too. Just make sure the areas don't become too
1197     -- large.
1198     IF NEW.class = 'natural' or max_rank > 10 THEN
1199       geom := NEW.geometry;
1200     END IF;
1201   ELSEIF NEW.rank_address > 25 THEN
1202     max_rank := 25;
1203   ELSE
1204     max_rank := NEW.rank_address;
1205   END IF;
1206
1207   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition, max_rank,
1208                                     NEW.token_info, geom, NEW.centroid,
1209                                     NEW.country_code)
1210     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
1211
1212   {% if debug %}RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;{% endif %}
1213
1214   NEW.postcode := coalesce(token_get_postcode(NEW.token_info), NEW.postcode);
1215
1216   -- if we have a name add this to the name search table
1217   name_vector := token_get_name_search_tokens(NEW.token_info);
1218   IF array_length(name_vector, 1) is not NULL THEN
1219     -- Initialise the name vector using our name
1220     NEW.name := add_default_place_name(NEW.country_code, NEW.name);
1221
1222     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
1223       result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
1224                              name_vector, NEW.rank_search, NEW.rank_address,
1225                              NEW.postcode, NEW.geometry, NEW.centroid);
1226       {% if debug %}RAISE WARNING 'added to location (full)';{% endif %}
1227     END IF;
1228
1229     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
1230       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
1231       {% if debug %}RAISE WARNING 'insert into road location table (full)';{% endif %}
1232     END IF;
1233
1234     IF NEW.rank_address between 16 and 27 THEN
1235       result := insertSearchName(NEW.partition, NEW.place_id,
1236                                  token_get_name_match_tokens(NEW.token_info),
1237                                  NEW.rank_search, NEW.rank_address, NEW.geometry);
1238     END IF;
1239     {% if debug %}RAISE WARNING 'added to search name (full)';{% endif %}
1240
1241     {% if not db.reverse_only %}
1242         INSERT INTO search_name (place_id, address_rank,
1243                                  importance, country_code, name_vector,
1244                                  nameaddress_vector, centroid)
1245                VALUES (NEW.place_id, NEW.rank_address,
1246                        NEW.importance, NEW.country_code, name_vector,
1247                        nameaddress_vector, NEW.centroid);
1248     {% endif %}
1249   END IF;
1250
1251   IF NEW.postcode is null AND NEW.rank_search > 8
1252      AND (NEW.rank_address > 0
1253           OR ST_GeometryType(NEW.geometry) not in ('ST_LineString','ST_MultiLineString')
1254           OR ST_Length(NEW.geometry) < 0.02)
1255   THEN
1256     NEW.postcode := get_nearest_postcode(NEW.country_code,
1257                                          CASE WHEN NEW.rank_address > 25
1258                                               THEN NEW.centroid ELSE NEW.geometry END);
1259   END IF;
1260
1261   {% if debug %}RAISE WARNING 'place update % % finished.', NEW.osm_type, NEW.osm_id;{% endif %}
1262
1263   NEW.token_info := token_strip_info(NEW.token_info);
1264   RETURN NEW;
1265 END;
1266 $$
1267 LANGUAGE plpgsql;
1268
1269
1270 CREATE OR REPLACE FUNCTION placex_delete()
1271   RETURNS TRIGGER
1272   AS $$
1273 DECLARE
1274   b BOOLEAN;
1275   result INT;
1276   classtable TEXT;
1277 BEGIN
1278   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
1279
1280   IF OLD.linked_place_id is null THEN
1281     UPDATE placex
1282       SET linked_place_id = NULL,
1283           indexed_status = CASE WHEN indexed_status = 0 THEN 2 ELSE indexed_status END
1284       WHERE linked_place_id = OLD.place_id;
1285   ELSE
1286     update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
1287   END IF;
1288
1289   IF OLD.rank_address < 30 THEN
1290
1291     -- mark everything linked to this place for re-indexing
1292     {% if debug %}RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1293     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
1294       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
1295
1296     {% if debug %}RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1297     DELETE FROM place_addressline where address_place_id = OLD.place_id;
1298
1299     {% if debug %}RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1300     b := deleteRoad(OLD.partition, OLD.place_id);
1301
1302     {% if debug %}RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1303     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
1304     {% if debug %}RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1305     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
1306     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
1307
1308     UPDATE location_postcodes SET indexed_status = 2 WHERE parent_place_id = OLD.place_id;
1309   END IF;
1310
1311   {% if debug %}RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1312
1313   IF OLD.rank_address < 26 THEN
1314     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
1315   END IF;
1316
1317   {% if debug %}RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1318
1319   IF OLD.name is not null THEN
1320     {% if 'search_name' in db.tables %}
1321       DELETE from search_name WHERE place_id = OLD.place_id;
1322     {% endif %}
1323     b := deleteSearchName(OLD.partition, OLD.place_id);
1324   END IF;
1325
1326   {% if debug %}RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1327
1328   DELETE FROM place_addressline where place_id = OLD.place_id;
1329
1330   {% if debug %}RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1331
1332   -- remove from tables for special search
1333   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1334   SELECT count(*) INTO result
1335     FROM pg_tables
1336     WHERE classtable NOT SIMILAR TO '%\W%'
1337           AND tablename = classtable and schemaname = current_schema();
1338
1339   IF result > 0 THEN
1340     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1341   END IF;
1342
1343   {% if debug %}RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;{% endif %}
1344   RETURN OLD;
1345
1346 END;
1347 $$
1348 LANGUAGE plpgsql;