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