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