]> git.openstreetmap.org Git - nominatim.git/blob - sql/functions/placex_triggers.sql
Merge pull request #1972 from lonvia/exclude-unnamed-highway-areas
[nominatim.git] / sql / functions / placex_triggers.sql
1 -- Trigger functions for the placex table.
2
3 -- Find the parent road of a POI.
4 --
5 -- \returns Place ID of parent object or NULL if none
6 --
7 -- Copy data from linked items (POIs on ways, addr:street links, relations).
8 --
9 CREATE OR REPLACE FUNCTION find_parent_for_poi(poi_osm_type CHAR(1),
10                                                poi_osm_id BIGINT,
11                                                poi_partition SMALLINT,
12                                                bbox GEOMETRY,
13                                                addr_street TEXT,
14                                                addr_place TEXT,
15                                                fallback BOOL = true)
16   RETURNS BIGINT
17   AS $$
18 DECLARE
19   parent_place_id BIGINT DEFAULT NULL;
20   location RECORD;
21   parent RECORD;
22 BEGIN
23     --DEBUG: RAISE WARNING 'finding street for % %', poi_osm_type, poi_osm_id;
24
25     -- Is this object part of an associatedStreet relation?
26     FOR location IN
27       SELECT members FROM planet_osm_rels
28       WHERE parts @> ARRAY[poi_osm_id]
29         and members @> ARRAY[lower(poi_osm_type) || poi_osm_id]
30         and tags @> ARRAY['associatedStreet']
31     LOOP
32       FOR i IN 1..array_upper(location.members, 1) BY 2 LOOP
33         IF location.members[i+1] = 'street' THEN
34           FOR parent IN
35             SELECT place_id from placex
36              WHERE osm_type = 'W' and osm_id = substring(location.members[i],2)::bigint
37                and name is not null
38                and rank_search between 26 and 27
39           LOOP
40             RETURN parent.place_id;
41           END LOOP;
42         END IF;
43       END LOOP;
44     END LOOP;
45
46     parent_place_id := find_parent_for_address(addr_street, addr_place,
47                                                poi_partition, bbox);
48     IF parent_place_id is not null THEN
49       RETURN parent_place_id;
50     END IF;
51
52     IF poi_osm_type = 'N' THEN
53       -- Is this node part of an interpolation?
54       FOR parent IN
55         SELECT q.parent_place_id
56           FROM location_property_osmline q, planet_osm_ways x
57          WHERE q.linegeo && bbox and x.id = q.osm_id
58                and poi_osm_id = any(x.nodes)
59          LIMIT 1
60       LOOP
61         --DEBUG: RAISE WARNING 'Get parent from interpolation: %', parent.parent_place_id;
62         RETURN parent.parent_place_id;
63       END LOOP;
64
65       -- Is this node part of any other way?
66       FOR location IN
67         SELECT p.place_id, p.osm_id, p.rank_search, p.address,
68                coalesce(p.centroid, ST_Centroid(p.geometry)) as centroid
69           FROM placex p, planet_osm_ways w
70          WHERE p.osm_type = 'W' and p.rank_search >= 26
71                and p.geometry && bbox
72                and w.id = p.osm_id and poi_osm_id = any(w.nodes)
73       LOOP
74         --DEBUG: RAISE WARNING 'Node is part of way % ', location.osm_id;
75
76         -- Way IS a road then we are on it - that must be our road
77         IF location.rank_search < 28 THEN
78           --DEBUG: RAISE WARNING 'node in way that is a street %',location;
79           return location.place_id;
80         END IF;
81
82         SELECT find_parent_for_poi('W', location.osm_id, poi_partition,
83                                    location.centroid,
84                                    location.address->'street',
85                                    location.address->'place',
86                                    false)
87           INTO parent_place_id;
88         IF parent_place_id is not null THEN
89           RETURN parent_place_id;
90         END IF;
91       END LOOP;
92     END IF;
93
94     IF fallback THEN
95       IF addr_street is null and addr_place is not null THEN
96         -- The address is attached to a place we don't know. Find the
97         -- nearest place instead.
98         FOR location IN
99           SELECT place_id FROM getNearFeatures(poi_partition, bbox, 26, '{}'::INTEGER[])
100             ORDER BY rank_address DESC, isguess asc, distance LIMIT 1
101         LOOP
102           parent_place_id := location.place_id;
103         END LOOP;
104       ELSEIF ST_Area(bbox) < 0.005 THEN
105         -- for smaller features get the nearest road
106         SELECT getNearestRoadPlaceId(poi_partition, bbox) INTO parent_place_id;
107         --DEBUG: RAISE WARNING 'Checked for nearest way (%)', parent_place_id;
108       ELSE
109         -- for larger features simply find the area with the largest rank that
110         -- contains the bbox, only use addressable features
111         FOR location IN
112           SELECT place_id FROM placex
113             WHERE bbox @ geometry AND _ST_Covers(geometry, ST_Centroid(bbox))
114                   AND rank_address between 5 and 25
115             ORDER BY rank_address desc
116         LOOP
117             RETURN location.place_id;
118         END LOOP;
119       END IF;
120     END IF;
121
122     RETURN parent_place_id;
123 END;
124 $$
125 LANGUAGE plpgsql STABLE;
126
127 -- Try to find a linked place for the given object.
128 CREATE OR REPLACE FUNCTION find_linked_place(bnd placex)
129   RETURNS placex
130   AS $$
131 DECLARE
132   relation_members TEXT[];
133   rel_member RECORD;
134   linked_placex placex%ROWTYPE;
135   bnd_name TEXT;
136 BEGIN
137   IF bnd.rank_search >= 26 or bnd.rank_address = 0
138      or ST_GeometryType(bnd.geometry) NOT IN ('ST_Polygon','ST_MultiPolygon')
139   THEN
140     RETURN NULL;
141   END IF;
142
143   IF bnd.osm_type = 'R' THEN
144     -- see if we have any special relation members
145     SELECT members FROM planet_osm_rels WHERE id = bnd.osm_id INTO relation_members;
146     --DEBUG: RAISE WARNING 'Got relation members';
147
148     -- Search for relation members with role 'lable'.
149     IF relation_members IS NOT NULL THEN
150       FOR rel_member IN
151         SELECT get_rel_node_members(relation_members, ARRAY['label']) as member
152       LOOP
153         --DEBUG: RAISE WARNING 'Found label member %', rel_member.member;
154
155         FOR linked_placex IN
156           SELECT * from placex
157           WHERE osm_type = 'N' and osm_id = rel_member.member
158             and class = 'place'
159         LOOP
160           --DEBUG: RAISE WARNING 'Linked label member';
161           RETURN linked_placex;
162         END LOOP;
163
164       END LOOP;
165     END IF;
166   END IF;
167
168   IF bnd.name ? 'name' THEN
169     bnd_name := make_standard_name(bnd.name->'name');
170     IF bnd_name = '' THEN
171       bnd_name := NULL;
172     END IF;
173   END IF;
174
175   -- If extratags has a place tag, look for linked nodes by their place type.
176   -- Area and node still have to have the same name.
177   IF bnd.extratags ? 'place' and bnd_name is not null THEN
178     FOR linked_placex IN
179       SELECT * FROM placex
180       WHERE make_standard_name(name->'name') = bnd_name
181         AND placex.class = 'place' AND placex.type = bnd.extratags->'place'
182         AND placex.osm_type = 'N'
183         AND placex.rank_search < 26 -- needed to select the right index
184         AND _st_covers(bnd.geometry, placex.geometry)
185     LOOP
186       --DEBUG: RAISE WARNING 'Found type-matching place node %', linked_placex.osm_id;
187       RETURN linked_placex;
188     END LOOP;
189   END IF;
190
191   IF bnd.extratags ? 'wikidata' THEN
192     FOR linked_placex IN
193       SELECT * FROM placex
194       WHERE placex.class = 'place' AND placex.osm_type = 'N'
195         AND placex.extratags ? 'wikidata' -- needed to select right index
196         AND placex.extratags->'wikidata' = bnd.extratags->'wikidata'
197         AND placex.rank_search < 26
198         AND _st_covers(bnd.geometry, placex.geometry)
199       ORDER BY make_standard_name(name->'name') = bnd_name desc
200     LOOP
201       --DEBUG: RAISE WARNING 'Found wikidata-matching place node %', linked_placex.osm_id;
202       RETURN linked_placex;
203     END LOOP;
204   END IF;
205
206   -- Name searches can be done for ways as well as relations
207   IF bnd_name is not null THEN
208     --DEBUG: RAISE WARNING 'Looking for nodes with matching names';
209     FOR linked_placex IN
210       SELECT placex.* from placex
211       WHERE make_standard_name(name->'name') = bnd_name
212         AND ((bnd.rank_address > 0 and placex.rank_address = bnd.rank_address)
213              OR (bnd.rank_address = 0 and placex.rank_search = bnd.rank_search))
214         AND placex.osm_type = 'N'
215         AND placex.rank_search < 26 -- needed to select the right index
216         AND _st_covers(bnd.geometry, placex.geometry)
217     LOOP
218       --DEBUG: RAISE WARNING 'Found matching place node %', linked_placex.osm_id;
219       RETURN linked_placex;
220     END LOOP;
221   END IF;
222
223   RETURN NULL;
224 END;
225 $$
226 LANGUAGE plpgsql STABLE;
227
228
229 -- Insert address of a place into the place_addressline table.
230 --
231 -- \param obj_place_id  Place_id of the place to compute the address for.
232 -- \param partition     Partition number where the place is in.
233 -- \param maxrank       Rank of the place. All address features must have
234 --                      a search rank lower than the given rank.
235 -- \param address       Address terms for the place.
236 -- \param geometry      Geometry to which the address objects should be close.
237 --
238 -- \retval parent_place_id  Place_id of the address object that is the direct
239 --                          ancestor.
240 -- \retval postcode         Postcode computed from the address. This is the
241 --                          addr:postcode of one of the address objects. If
242 --                          more than one of has a postcode, the highest ranking
243 --                          one is used. May be NULL.
244 -- \retval nameaddress_vector  Search terms for the address. This is the sum
245 --                             of name terms of all address objects.
246 CREATE OR REPLACE FUNCTION insert_addresslines(obj_place_id BIGINT,
247                                                partition SMALLINT,
248                                                maxrank SMALLINT,
249                                                address HSTORE,
250                                                geometry GEOMETRY,
251                                                OUT parent_place_id BIGINT,
252                                                OUT postcode TEXT,
253                                                OUT nameaddress_vector INT[])
254   AS $$
255 DECLARE
256   current_rank_address INTEGER := 0;
257   location_distance FLOAT := 0;
258   location_parent GEOMETRY := NULL;
259   parent_place_id_rank SMALLINT := 0;
260
261   location_isaddress BOOLEAN;
262
263   address_havelevel BOOLEAN[];
264   location_keywords INT[];
265
266   location RECORD;
267   addr_item RECORD;
268
269   isin_tokens INT[];
270   isin TEXT[];
271 BEGIN
272   parent_place_id := 0;
273   nameaddress_vector := '{}'::int[];
274   isin_tokens := '{}'::int[];
275
276   ---- convert address store to array of tokenids
277   IF address IS NOT NULL THEN
278     FOR addr_item IN SELECT * FROM each(address)
279     LOOP
280       IF addr_item.key IN ('city', 'tiger:county', 'state', 'suburb', 'province',
281                            'district', 'region', 'county', 'municipality',
282                            'hamlet', 'village', 'subdistrict', 'town',
283                            'neighbourhood', 'quarter', 'parish')
284       THEN
285         isin_tokens := array_merge(isin_tokens,
286                                    word_ids_from_name(addr_item.value));
287         IF NOT %REVERSE-ONLY% THEN
288           nameaddress_vector := array_merge(nameaddress_vector,
289                                             addr_ids_from_name(addr_item.value));
290         END IF;
291       END IF;
292     END LOOP;
293
294     IF address ? 'is_in' THEN
295       -- is_in items need splitting
296       isin := regexp_split_to_array(address->'is_in', E'[;,]');
297       IF array_upper(isin, 1) IS NOT NULL THEN
298         FOR i IN 1..array_upper(isin, 1) LOOP
299           isin_tokens := array_merge(isin_tokens,
300                                      word_ids_from_name(isin[i]));
301
302           -- merge word into address vector
303           IF NOT %REVERSE-ONLY% THEN
304             nameaddress_vector := array_merge(nameaddress_vector,
305                                               addr_ids_from_name(isin[i]));
306           END IF;
307         END LOOP;
308       END IF;
309     END IF;
310   END IF;
311   IF NOT %REVERSE-ONLY% THEN
312     nameaddress_vector := array_merge(nameaddress_vector, isin_tokens);
313   END IF;
314
315   ---- now compute the address terms
316   FOR i IN 1..28 LOOP
317     address_havelevel[i] := false;
318   END LOOP;
319
320   FOR location IN
321     SELECT * FROM getNearFeatures(partition, geometry, maxrank, isin_tokens)
322   LOOP
323     IF location.rank_address != current_rank_address THEN
324       current_rank_address := location.rank_address;
325       IF location.isguess THEN
326         location_distance := location.distance * 1.5;
327       ELSE
328         IF location.rank_address <= 12 THEN
329           -- for county and above, if we have an area consider that exact
330           -- (It would be nice to relax the constraint for places close to
331           --  the boundary but we'd need the exact geometry for that. Too
332           --  expensive.)
333           location_distance = 0;
334         ELSE
335           -- Below county level remain slightly fuzzy.
336           location_distance := location.distance * 0.5;
337         END IF;
338       END IF;
339     ELSE
340       CONTINUE WHEN location.keywords <@ location_keywords;
341     END IF;
342
343     IF location.distance < location_distance OR NOT location.isguess THEN
344       location_keywords := location.keywords;
345
346       location_isaddress := NOT address_havelevel[location.rank_address];
347       --DEBUG: RAISE WARNING 'should be address: %, is guess: %, rank: %', location_isaddress, location.isguess, location.rank_address;
348       IF location_isaddress AND location.isguess AND location_parent IS NOT NULL THEN
349           location_isaddress := ST_Contains(location_parent, location.centroid);
350       END IF;
351
352       --DEBUG: RAISE WARNING '% isaddress: %', location.place_id, location_isaddress;
353       -- Add it to the list of search terms
354       IF NOT %REVERSE-ONLY% THEN
355           nameaddress_vector := array_merge(nameaddress_vector,
356                                             location.keywords::integer[]);
357       END IF;
358
359       INSERT INTO place_addressline (place_id, address_place_id, fromarea,
360                                      isaddress, distance, cached_rank_address)
361         VALUES (obj_place_id, location.place_id, true,
362                 location_isaddress, location.distance, location.rank_address);
363
364       IF location_isaddress THEN
365         -- add postcode if we have one
366         -- (If multiple postcodes are available, we end up with the highest ranking one.)
367         IF location.postcode is not null THEN
368             postcode = location.postcode;
369         END IF;
370
371         address_havelevel[location.rank_address] := true;
372         -- add a hack against postcode ranks
373         IF NOT location.isguess
374            AND location.rank_address != 11 AND location.rank_address != 5
375         THEN
376           SELECT p.geometry FROM placex p
377             WHERE p.place_id = location.place_id INTO location_parent;
378         END IF;
379
380         IF location.rank_address > parent_place_id_rank THEN
381           parent_place_id = location.place_id;
382           parent_place_id_rank = location.rank_address;
383         END IF;
384       END IF;
385     END IF;
386
387   END LOOP;
388 END;
389 $$
390 LANGUAGE plpgsql;
391
392
393 CREATE OR REPLACE FUNCTION placex_insert()
394   RETURNS TRIGGER
395   AS $$
396 DECLARE
397   postcode TEXT;
398   result BOOLEAN;
399   is_area BOOLEAN;
400   country_code VARCHAR(2);
401   diameter FLOAT;
402   classtable TEXT;
403 BEGIN
404   --DEBUG: RAISE WARNING '% % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
405
406   NEW.place_id := nextval('seq_place');
407   NEW.indexed_status := 1; --STATUS_NEW
408
409   NEW.country_code := lower(get_country_code(NEW.geometry));
410
411   NEW.partition := get_partition(NEW.country_code);
412   NEW.geometry_sector := geometry_sector(NEW.partition, NEW.geometry);
413
414   IF NEW.osm_type = 'X' THEN
415     -- E'X'ternal records should already be in the right format so do nothing
416   ELSE
417     is_area := ST_GeometryType(NEW.geometry) IN ('ST_Polygon','ST_MultiPolygon');
418
419     IF NEW.class in ('place','boundary')
420        AND NEW.type in ('postcode','postal_code')
421     THEN
422       IF NEW.address IS NULL OR NOT NEW.address ? 'postcode' THEN
423           -- most likely just a part of a multipolygon postcode boundary, throw it away
424           RETURN NULL;
425       END IF;
426
427       NEW.name := hstore('ref', NEW.address->'postcode');
428
429     ELSEIF NEW.class = 'highway' AND is_area AND NEW.name is null
430            AND NEW.extratags ? 'area' AND NEW.extratags->'area' = 'yes'
431     THEN
432         RETURN NULL;
433     ELSEIF NEW.class = 'boundary' AND NOT is_area
434     THEN
435         RETURN NULL;
436     ELSEIF NEW.class = 'boundary' AND NEW.type = 'administrative'
437            AND NEW.admin_level <= 4 AND NEW.osm_type = 'W'
438     THEN
439         RETURN NULL;
440     END IF;
441
442     SELECT * INTO NEW.rank_search, NEW.rank_address
443       FROM compute_place_rank(NEW.country_code,
444                               CASE WHEN is_area THEN 'A' ELSE NEW.osm_type END,
445                               NEW.class, NEW.type, NEW.admin_level,
446                               (NEW.extratags->'capital') = 'yes',
447                               NEW.address->'postcode');
448
449     -- a country code make no sense below rank 4 (country)
450     IF NEW.rank_search < 4 THEN
451       NEW.country_code := NULL;
452     END IF;
453
454   END IF;
455
456   --DEBUG: RAISE WARNING 'placex_insert:END: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
457
458   RETURN NEW; -- %DIFFUPDATES% The following is not needed until doing diff updates, and slows the main index process down
459
460   IF NEW.osm_type = 'N' and NEW.rank_search > 28 THEN
461       -- might be part of an interpolation
462       result := osmline_reinsert(NEW.osm_id, NEW.geometry);
463   ELSEIF NEW.rank_address > 0 THEN
464     IF (ST_GeometryType(NEW.geometry) in ('ST_Polygon','ST_MultiPolygon') AND ST_IsValid(NEW.geometry)) THEN
465       -- Performance: We just can't handle re-indexing for country level changes
466       IF st_area(NEW.geometry) < 1 THEN
467         -- mark items within the geometry for re-indexing
468   --    RAISE WARNING 'placex poly insert: % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type;
469
470         -- work around bug in postgis, this may have been fixed in 2.0.0 (see http://trac.osgeo.org/postgis/ticket/547)
471         update placex set indexed_status = 2 where (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
472          AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) = 'ST_Point' and (rank_search < 28 or name is not null or (NEW.rank_search >= 16 and address ? 'place'));
473         update placex set indexed_status = 2 where (st_covers(NEW.geometry, placex.geometry) OR ST_Intersects(NEW.geometry, placex.geometry)) 
474          AND rank_search > NEW.rank_search and indexed_status = 0 and ST_geometrytype(placex.geometry) != 'ST_Point' and (rank_search < 28 or name is not null or (NEW.rank_search >= 16 and address ? 'place'));
475       END IF;
476     ELSE
477       -- mark nearby items for re-indexing, where 'nearby' depends on the features rank_search and is a complete guess :(
478       diameter := update_place_diameter(NEW.rank_search);
479       IF diameter > 0 THEN
480   --      RAISE WARNING 'placex point insert: % % % % %',NEW.osm_type,NEW.osm_id,NEW.class,NEW.type,diameter;
481         IF NEW.rank_search >= 26 THEN
482           -- roads may cause reparenting for >27 rank places
483           update placex set indexed_status = 2 where indexed_status = 0 and rank_search > NEW.rank_search and ST_DWithin(placex.geometry, NEW.geometry, diameter);
484           -- reparenting also for OSM Interpolation Lines (and for Tiger?)
485           update location_property_osmline set indexed_status = 2 where indexed_status = 0 and ST_DWithin(location_property_osmline.linegeo, NEW.geometry, diameter);
486         ELSEIF NEW.rank_search >= 16 THEN
487           -- up to rank 16, street-less addresses may need reparenting
488           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');
489         ELSE
490           -- for all other places the search terms may change as well
491           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);
492         END IF;
493       END IF;
494     END IF;
495   END IF;
496
497
498    -- add to tables for special search
499    -- Note: won't work on initial import because the classtype tables
500    -- do not yet exist. It won't hurt either.
501   classtable := 'place_classtype_' || NEW.class || '_' || NEW.type;
502   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO result;
503   IF result THEN
504     EXECUTE 'INSERT INTO ' || classtable::regclass || ' (place_id, centroid) VALUES ($1,$2)' 
505     USING NEW.place_id, ST_Centroid(NEW.geometry);
506   END IF;
507
508   RETURN NEW;
509
510 END;
511 $$
512 LANGUAGE plpgsql;
513
514 CREATE OR REPLACE FUNCTION get_parent_address_level(geom GEOMETRY, in_level SMALLINT)
515   RETURNS SMALLINT
516   AS $$
517 DECLARE
518   address_rank SMALLINT;
519 BEGIN
520   IF in_level <= 3 or in_level > 15 THEN
521     address_rank := 3;
522   ELSE
523     SELECT rank_address INTO address_rank
524       FROM placex
525       WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
526             and admin_level < in_level
527             and geometry && geom and ST_Covers(geometry, geom)
528       ORDER BY admin_level desc LIMIT 1;
529   END IF;
530
531   IF address_rank is NULL or address_rank <= 3 THEN
532     RETURN 3;
533   END IF;
534
535   RETURN address_rank;
536 END;
537 $$
538 LANGUAGE plpgsql;
539
540
541 CREATE OR REPLACE FUNCTION placex_update()
542   RETURNS TRIGGER
543   AS $$
544 DECLARE
545   i INTEGER;
546   location RECORD;
547   relation_members TEXT[];
548
549   centroid GEOMETRY;
550   parent_address_level SMALLINT;
551   place_address_level SMALLINT;
552
553   addr_street TEXT;
554   addr_place TEXT;
555
556   name_vector INTEGER[];
557   nameaddress_vector INTEGER[];
558   addr_nameaddress_vector INTEGER[];
559
560   inherited_address HSTORE;
561
562   linked_node_id BIGINT;
563   linked_importance FLOAT;
564   linked_wikipedia TEXT;
565
566   result BOOLEAN;
567 BEGIN
568   -- deferred delete
569   IF OLD.indexed_status = 100 THEN
570     --DEBUG: RAISE WARNING 'placex_update delete % %',NEW.osm_type,NEW.osm_id;
571     delete from placex where place_id = OLD.place_id;
572     RETURN NULL;
573   END IF;
574
575   IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
576     RETURN NEW;
577   END IF;
578
579   --DEBUG: RAISE WARNING 'placex_update % % (%)',NEW.osm_type,NEW.osm_id,NEW.place_id;
580
581   NEW.indexed_date = now();
582
583   IF NOT %REVERSE-ONLY% THEN
584     DELETE from search_name WHERE place_id = NEW.place_id;
585   END IF;
586   result := deleteSearchName(NEW.partition, NEW.place_id);
587   DELETE FROM place_addressline WHERE place_id = NEW.place_id;
588   result := deleteRoad(NEW.partition, NEW.place_id);
589   result := deleteLocationArea(NEW.partition, NEW.place_id, NEW.rank_search);
590   UPDATE placex set linked_place_id = null, indexed_status = 2
591          where linked_place_id = NEW.place_id;
592   -- update not necessary for osmline, cause linked_place_id does not exist
593
594   NEW.extratags := NEW.extratags - 'linked_place'::TEXT;
595
596   IF NEW.linked_place_id is not null THEN
597     --DEBUG: RAISE WARNING 'place already linked to %', NEW.linked_place_id;
598     RETURN NEW;
599   END IF;
600
601   -- Postcodes are just here to compute the centroids. They are not searchable
602   -- unless they are a boundary=postal_code.
603   -- There was an error in the style so that boundary=postal_code used to be
604   -- imported as place=postcode. That's why relations are allowed to pass here.
605   -- This can go away in a couple of versions.
606   IF NEW.class = 'place'  and NEW.type = 'postcode' and NEW.osm_type != 'R' THEN
607     RETURN NEW;
608   END IF;
609
610   -- Speed up searches - just use the centroid of the feature
611   -- cheaper but less acurate
612   NEW.centroid := ST_PointOnSurface(NEW.geometry);
613   --DEBUG: RAISE WARNING 'Computing preliminary centroid at %',ST_AsText(NEW.centroid);
614
615   -- recompute the ranks, they might change when linking changes
616   SELECT * INTO NEW.rank_search, NEW.rank_address
617     FROM compute_place_rank(NEW.country_code,
618                             CASE WHEN ST_GeometryType(NEW.geometry)
619                                         IN ('ST_Polygon','ST_MultiPolygon')
620                             THEN 'A' ELSE NEW.osm_type END,
621                             NEW.class, NEW.type, NEW.admin_level,
622                             (NEW.extratags->'capital') = 'yes',
623                             NEW.address->'postcode');
624   -- We must always increase the address level relative to the admin boundary.
625   IF NEW.class = 'boundary' and NEW.type = 'administrative'
626      and NEW.osm_type = 'R' and NEW.rank_address > 0
627   THEN
628     parent_address_level := get_parent_address_level(NEW.centroid, NEW.admin_level);
629     IF parent_address_level >= NEW.rank_address THEN
630       IF parent_address_level >= 24 THEN
631         NEW.rank_address := 25;
632       ELSE
633         NEW.rank_address := parent_address_level + 2;
634       END IF;
635     END IF;
636   ELSE
637     parent_address_level := 3;
638   END IF;
639
640   --DEBUG: RAISE WARNING 'Copy over address tags';
641   -- housenumber is a computed field, so start with an empty value
642   NEW.housenumber := NULL;
643   IF NEW.address is not NULL THEN
644       IF NEW.address ? 'conscriptionnumber' THEN
645         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'conscriptionnumber'));
646         IF NEW.address ? 'streetnumber' THEN
647             i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
648             NEW.housenumber := (NEW.address->'conscriptionnumber') || '/' || (NEW.address->'streetnumber');
649         ELSE
650             NEW.housenumber := NEW.address->'conscriptionnumber';
651         END IF;
652       ELSEIF NEW.address ? 'streetnumber' THEN
653         NEW.housenumber := NEW.address->'streetnumber';
654         i := getorcreate_housenumber_id(make_standard_name(NEW.address->'streetnumber'));
655       ELSEIF NEW.address ? 'housenumber' THEN
656         NEW.housenumber := NEW.address->'housenumber';
657         i := getorcreate_housenumber_id(make_standard_name(NEW.housenumber));
658       END IF;
659
660       addr_street := NEW.address->'street';
661       addr_place := NEW.address->'place';
662
663       IF NEW.address ? 'postcode' and NEW.address->'postcode' not similar to '%(:|,|;)%' THEN
664         i := getorcreate_postcode_id(NEW.address->'postcode');
665       END IF;
666   END IF;
667
668   NEW.postcode := null;
669
670   -- recalculate country and partition
671   IF NEW.rank_search = 4 AND NEW.address is not NULL AND NEW.address ? 'country' THEN
672     -- for countries, believe the mapped country code,
673     -- so that we remain in the right partition if the boundaries
674     -- suddenly expand.
675     NEW.country_code := lower(NEW.address->'country');
676     NEW.partition := get_partition(lower(NEW.country_code));
677     IF NEW.partition = 0 THEN
678       NEW.country_code := lower(get_country_code(NEW.centroid));
679       NEW.partition := get_partition(NEW.country_code);
680     END IF;
681   ELSE
682     IF NEW.rank_search >= 4 THEN
683       NEW.country_code := lower(get_country_code(NEW.centroid));
684     ELSE
685       NEW.country_code := NULL;
686     END IF;
687     NEW.partition := get_partition(NEW.country_code);
688   END IF;
689   --DEBUG: RAISE WARNING 'Country updated: "%"', NEW.country_code;
690
691   -- waterway ways are linked when they are part of a relation and have the same class/type
692   IF NEW.osm_type = 'R' and NEW.class = 'waterway' THEN
693       FOR relation_members IN select members from planet_osm_rels r where r.id = NEW.osm_id and r.parts != array[]::bigint[]
694       LOOP
695           FOR i IN 1..array_upper(relation_members, 1) BY 2 LOOP
696               IF relation_members[i+1] in ('', 'main_stream', 'side_stream') AND substring(relation_members[i],1,1) = 'w' THEN
697                 --DEBUG: RAISE WARNING 'waterway parent %, child %/%', NEW.osm_id, i, relation_members[i];
698                 FOR linked_node_id IN SELECT place_id FROM placex
699                   WHERE osm_type = 'W' and osm_id = substring(relation_members[i],2,200)::bigint
700                   and class = NEW.class and type in ('river', 'stream', 'canal', 'drain', 'ditch')
701                   and ( relation_members[i+1] != 'side_stream' or NEW.name->'name' = name->'name')
702                 LOOP
703                   UPDATE placex SET linked_place_id = NEW.place_id WHERE place_id = linked_node_id;
704                   IF NOT %REVERSE-ONLY% THEN
705                     DELETE FROM search_name WHERE place_id = linked_node_id;
706                   END IF;
707                 END LOOP;
708               END IF;
709           END LOOP;
710       END LOOP;
711       --DEBUG: RAISE WARNING 'Waterway processed';
712   END IF;
713
714   NEW.importance := null;
715   SELECT wikipedia, importance
716     FROM compute_importance(NEW.extratags, NEW.country_code, NEW.osm_type, NEW.osm_id)
717     INTO NEW.wikipedia,NEW.importance;
718
719 --DEBUG: RAISE WARNING 'Importance computed from wikipedia: %', NEW.importance;
720
721   -- ---------------------------------------------------------------------------
722   -- For low level elements we inherit from our parent road
723   IF NEW.rank_search > 27 THEN
724
725     --DEBUG: RAISE WARNING 'finding street for % %', NEW.osm_type, NEW.osm_id;
726     NEW.parent_place_id := null;
727
728     -- if we have a POI and there is no address information,
729     -- see if we can get it from a surrounding building
730     inherited_address := ''::HSTORE;
731     IF NEW.osm_type = 'N' AND addr_street IS NULL AND addr_place IS NULL
732        AND NEW.housenumber IS NULL THEN
733       FOR location IN
734         -- The additional && condition works around the misguided query
735         -- planner of postgis 3.0.
736         SELECT address from placex where ST_Covers(geometry, NEW.centroid)
737             and geometry && NEW.centroid
738             and (address ? 'housenumber' or address ? 'street' or address ? 'place')
739             and rank_search > 28 AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')
740             limit 1
741       LOOP
742         NEW.housenumber := location.address->'housenumber';
743         addr_street := location.address->'street';
744         addr_place := location.address->'place';
745         inherited_address := location.address;
746       END LOOP;
747     END IF;
748
749     -- We have to find our parent road.
750     NEW.parent_place_id := find_parent_for_poi(NEW.osm_type, NEW.osm_id,
751                                                NEW.partition,
752                                                ST_Envelope(NEW.geometry),
753                                                addr_street, addr_place);
754
755     -- If we found the road take a shortcut here.
756     -- Otherwise fall back to the full address getting method below.
757     IF NEW.parent_place_id is not null THEN
758
759       -- Get the details of the parent road
760       SELECT p.country_code, p.postcode FROM placex p
761        WHERE p.place_id = NEW.parent_place_id INTO location;
762
763       NEW.country_code := location.country_code;
764       --DEBUG: RAISE WARNING 'Got parent details from search name';
765
766       -- determine postcode
767       IF NEW.address is not null AND NEW.address ? 'postcode' THEN
768           NEW.postcode = upper(trim(NEW.address->'postcode'));
769       ELSE
770          NEW.postcode := location.postcode;
771       END IF;
772       IF NEW.postcode is null THEN
773         NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
774       END IF;
775
776       IF NEW.name is not NULL THEN
777           NEW.name := add_default_place_name(NEW.country_code, NEW.name);
778           name_vector := make_keywords(NEW.name);
779
780           IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
781             result := add_location(NEW.place_id, NEW.country_code, NEW.partition,
782                                    name_vector, NEW.rank_search, NEW.rank_address,
783                                    upper(trim(NEW.address->'postcode')), NEW.geometry);
784             --DEBUG: RAISE WARNING 'Place added to location table';
785           END IF;
786
787       END IF;
788
789       IF NOT %REVERSE-ONLY% THEN
790         SELECT * INTO name_vector, nameaddress_vector
791           FROM create_poi_search_terms(NEW.parent_place_id,
792                                        inherited_address || NEW.address,
793                                        NEW.housenumber, name_vector);
794
795         IF array_length(name_vector, 1) is not NULL THEN
796           INSERT INTO search_name (place_id, search_rank, address_rank,
797                                    importance, country_code, name_vector,
798                                    nameaddress_vector, centroid)
799                  VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
800                          NEW.importance, NEW.country_code, name_vector,
801                          nameaddress_vector, NEW.centroid);
802           --DEBUG: RAISE WARNING 'Place added to search table';
803         END IF;
804       END IF;
805
806       RETURN NEW;
807     END IF;
808
809   END IF;
810
811   -- ---------------------------------------------------------------------------
812   -- Full indexing
813   --DEBUG: RAISE WARNING 'Using full index mode for % %', NEW.osm_type, NEW.osm_id;
814   SELECT * INTO location FROM find_linked_place(NEW);
815   IF location.place_id is not null THEN
816     --DEBUG: RAISE WARNING 'Linked %', location;
817
818     -- Use the linked point as the centre point of the geometry,
819     -- but only if it is within the area of the boundary.
820     centroid := coalesce(location.centroid, ST_Centroid(location.geometry));
821     IF centroid is not NULL AND ST_Within(centroid, NEW.geometry) THEN
822         NEW.centroid := centroid;
823     END IF;
824
825     --DEBUG: RAISE WARNING 'parent address: % rank address: %', parent_address_level, location.rank_address;
826     IF location.rank_address > parent_address_level
827        and location.rank_address < 26
828     THEN
829       NEW.rank_address := location.rank_address;
830     END IF;
831
832     -- merge in the label name
833     IF NOT location.name IS NULL THEN
834       NEW.name := location.name || NEW.name;
835     END IF;
836
837     -- merge in extra tags
838     NEW.extratags := hstore('linked_' || location.class, location.type)
839                      || coalesce(location.extratags, ''::hstore)
840                      || coalesce(NEW.extratags, ''::hstore);
841
842     -- mark the linked place (excludes from search results)
843     UPDATE placex set linked_place_id = NEW.place_id
844       WHERE place_id = location.place_id;
845     -- ensure that those places are not found anymore
846     IF NOT %REVERSE-ONLY% THEN
847       DELETE FROM search_name WHERE place_id = location.place_id;
848     END IF;
849     PERFORM deleteLocationArea(NEW.partition, location.place_id, NEW.rank_search);
850
851     SELECT wikipedia, importance
852       FROM compute_importance(location.extratags, NEW.country_code,
853                               'N', location.osm_id)
854       INTO linked_wikipedia,linked_importance;
855
856     -- Use the maximum importance if one could be computed from the linked object.
857     IF linked_importance is not null AND
858        (NEW.importance is null or NEW.importance < linked_importance)
859     THEN
860       NEW.importance = linked_importance;
861     END IF;
862   ELSE
863     -- No linked place? As a last resort check if the boundary is tagged with
864     -- a place type and adapt the rank address.
865     IF NEW.rank_address > 0 and NEW.extratags ? 'place' THEN
866       SELECT address_rank INTO place_address_level
867         FROM compute_place_rank(NEW.country_code, 'A', 'place',
868                                 NEW.extratags->'place', 0::SMALLINT, False, null);
869       IF place_address_level > parent_address_level and
870          place_address_level < 26 THEN
871         NEW.rank_address := place_address_level;
872       END IF;
873     END IF;
874   END IF;
875
876   -- Initialise the name vector using our name
877   NEW.name := add_default_place_name(NEW.country_code, NEW.name);
878   name_vector := make_keywords(NEW.name);
879
880   -- make sure all names are in the word table
881   IF NEW.admin_level = 2
882      AND NEW.class = 'boundary' AND NEW.type = 'administrative'
883      AND NEW.country_code IS NOT NULL AND NEW.osm_type = 'R'
884   THEN
885     PERFORM create_country(NEW.name, lower(NEW.country_code));
886     --DEBUG: RAISE WARNING 'Country names updated';
887   END IF;
888
889   SELECT * FROM insert_addresslines(NEW.place_id, NEW.partition,
890                                     CASE WHEN NEW.rank_address = 0
891                                       THEN NEW.rank_search ELSE NEW.rank_address END,
892                                     NEW.address,
893                                     CASE WHEN NEW.rank_search >= 26
894                                              AND NEW.rank_search < 30
895                                       THEN NEW.geometry ELSE NEW.centroid END)
896     INTO NEW.parent_place_id, NEW.postcode, nameaddress_vector;
897
898   --DEBUG: RAISE WARNING 'RETURN insert_addresslines: %, %, %', NEW.parent_place_id, NEW.postcode, nameaddress_vector;
899
900   IF NEW.address is not null AND NEW.address ? 'postcode' 
901      AND NEW.address->'postcode' not similar to '%(,|;)%' THEN
902     NEW.postcode := upper(trim(NEW.address->'postcode'));
903   END IF;
904
905   IF NEW.postcode is null AND NEW.rank_search > 8 THEN
906     NEW.postcode := get_nearest_postcode(NEW.country_code, NEW.geometry);
907   END IF;
908
909   -- if we have a name add this to the name search table
910   IF NEW.name IS NOT NULL THEN
911
912     IF NEW.rank_search <= 25 and NEW.rank_address > 0 THEN
913       result := add_location(NEW.place_id, NEW.country_code, NEW.partition, name_vector, NEW.rank_search, NEW.rank_address, upper(trim(NEW.address->'postcode')), NEW.geometry);
914       --DEBUG: RAISE WARNING 'added to location (full)';
915     END IF;
916
917     IF NEW.rank_search between 26 and 27 and NEW.class = 'highway' THEN
918       result := insertLocationRoad(NEW.partition, NEW.place_id, NEW.country_code, NEW.geometry);
919       --DEBUG: RAISE WARNING 'insert into road location table (full)';
920     END IF;
921
922     result := insertSearchName(NEW.partition, NEW.place_id, name_vector,
923                                NEW.rank_search, NEW.rank_address, NEW.geometry);
924     --DEBUG: RAISE WARNING 'added to search name (full)';
925
926     IF NOT %REVERSE-ONLY% THEN
927         INSERT INTO search_name (place_id, search_rank, address_rank,
928                                  importance, country_code, name_vector,
929                                  nameaddress_vector, centroid)
930                VALUES (NEW.place_id, NEW.rank_search, NEW.rank_address,
931                        NEW.importance, NEW.country_code, name_vector,
932                        nameaddress_vector, NEW.centroid);
933     END IF;
934
935   END IF;
936
937   --DEBUG: RAISE WARNING 'place update % % finsihed.', NEW.osm_type, NEW.osm_id;
938
939   RETURN NEW;
940 END;
941 $$
942 LANGUAGE plpgsql;
943
944
945 CREATE OR REPLACE FUNCTION placex_delete()
946   RETURNS TRIGGER
947   AS $$
948 DECLARE
949   b BOOLEAN;
950   classtable TEXT;
951 BEGIN
952   -- RAISE WARNING 'placex_delete % %',OLD.osm_type,OLD.osm_id;
953
954   IF OLD.linked_place_id is null THEN
955     update placex set linked_place_id = null, indexed_status = 2 where linked_place_id = OLD.place_id and indexed_status = 0;
956     --DEBUG: RAISE WARNING 'placex_delete:01 % %',OLD.osm_type,OLD.osm_id;
957     update placex set linked_place_id = null where linked_place_id = OLD.place_id;
958     --DEBUG: RAISE WARNING 'placex_delete:02 % %',OLD.osm_type,OLD.osm_id;
959   ELSE
960     update placex set indexed_status = 2 where place_id = OLD.linked_place_id and indexed_status = 0;
961   END IF;
962
963   IF OLD.rank_address < 30 THEN
964
965     -- mark everything linked to this place for re-indexing
966     --DEBUG: RAISE WARNING 'placex_delete:03 % %',OLD.osm_type,OLD.osm_id;
967     UPDATE placex set indexed_status = 2 from place_addressline where address_place_id = OLD.place_id 
968       and placex.place_id = place_addressline.place_id and indexed_status = 0 and place_addressline.isaddress;
969
970     --DEBUG: RAISE WARNING 'placex_delete:04 % %',OLD.osm_type,OLD.osm_id;
971     DELETE FROM place_addressline where address_place_id = OLD.place_id;
972
973     --DEBUG: RAISE WARNING 'placex_delete:05 % %',OLD.osm_type,OLD.osm_id;
974     b := deleteRoad(OLD.partition, OLD.place_id);
975
976     --DEBUG: RAISE WARNING 'placex_delete:06 % %',OLD.osm_type,OLD.osm_id;
977     update placex set indexed_status = 2 where parent_place_id = OLD.place_id and indexed_status = 0;
978     --DEBUG: RAISE WARNING 'placex_delete:07 % %',OLD.osm_type,OLD.osm_id;
979     -- reparenting also for OSM Interpolation Lines (and for Tiger?)
980     update location_property_osmline set indexed_status = 2 where indexed_status = 0 and parent_place_id = OLD.place_id;
981
982   END IF;
983
984   --DEBUG: RAISE WARNING 'placex_delete:08 % %',OLD.osm_type,OLD.osm_id;
985
986   IF OLD.rank_address < 26 THEN
987     b := deleteLocationArea(OLD.partition, OLD.place_id, OLD.rank_search);
988   END IF;
989
990   --DEBUG: RAISE WARNING 'placex_delete:09 % %',OLD.osm_type,OLD.osm_id;
991
992   IF OLD.name is not null THEN
993     IF NOT %REVERSE-ONLY% THEN
994       DELETE from search_name WHERE place_id = OLD.place_id;
995     END IF;
996     b := deleteSearchName(OLD.partition, OLD.place_id);
997   END IF;
998
999   --DEBUG: RAISE WARNING 'placex_delete:10 % %',OLD.osm_type,OLD.osm_id;
1000
1001   DELETE FROM place_addressline where place_id = OLD.place_id;
1002
1003   --DEBUG: RAISE WARNING 'placex_delete:11 % %',OLD.osm_type,OLD.osm_id;
1004
1005   -- remove from tables for special search
1006   classtable := 'place_classtype_' || OLD.class || '_' || OLD.type;
1007   SELECT count(*)>0 FROM pg_tables WHERE tablename = classtable and schemaname = current_schema() INTO b;
1008   IF b THEN
1009     EXECUTE 'DELETE FROM ' || classtable::regclass || ' WHERE place_id = $1' USING OLD.place_id;
1010   END IF;
1011
1012   --DEBUG: RAISE WARNING 'placex_delete:12 % %',OLD.osm_type,OLD.osm_id;
1013
1014   RETURN OLD;
1015
1016 END;
1017 $$
1018 LANGUAGE plpgsql;