]> git.openstreetmap.org Git - nominatim.git/blob - lib-sql/functions/postcode_triggers.sql
Merge pull request #3373 from lonvia/restrict-man-made
[nominatim.git] / lib-sql / functions / postcode_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 location_postcode table.
9
10
11 -- Trigger for updates of location_postcode
12 --
13 -- Computes the parent object the postcode most likely refers to.
14 -- This will be the place that determines the address displayed when
15 -- searching for this postcode.
16 CREATE OR REPLACE FUNCTION postcode_update()
17   RETURNS TRIGGER
18   AS $$
19 DECLARE
20   partition SMALLINT;
21   location RECORD;
22 BEGIN
23     IF NEW.indexed_status != 0 OR OLD.indexed_status = 0 THEN
24         RETURN NEW;
25     END IF;
26
27     NEW.indexed_date = now();
28
29     partition := get_partition(NEW.country_code);
30
31     SELECT * FROM get_postcode_rank(NEW.country_code, NEW.postcode)
32       INTO NEW.rank_search, NEW.rank_address;
33
34     NEW.parent_place_id = 0;
35     FOR location IN
36       SELECT place_id
37         FROM getNearFeatures(partition, NEW.geometry, NEW.geometry, NEW.rank_search)
38         WHERE NOT isguess ORDER BY rank_address DESC, distance asc LIMIT 1
39     LOOP
40         NEW.parent_place_id = location.place_id;
41     END LOOP;
42
43     RETURN NEW;
44 END;
45 $$
46 LANGUAGE plpgsql;
47