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