+ IF NEW.class = 'boundary' and NEW.type = 'administrative'
+ and NEW.osm_type = 'R' and NEW.rank_address > 0
+ THEN
+ -- First, check that admin boundaries do not overtake each other rank-wise.
+ parent_address_level := 3;
+ FOR location IN
+ SELECT rank_address,
+ (CASE WHEN extratags ? 'wikidata' and NEW.extratags ? 'wikidata'
+ and extratags->'wikidata' = NEW.extratags->'wikidata'
+ THEN ST_Equals(geometry, NEW.geometry)
+ ELSE false END) as is_same
+ FROM placex
+ WHERE osm_type = 'R' and class = 'boundary' and type = 'administrative'
+ and admin_level < NEW.admin_level and admin_level > 3
+ and rank_address > 0
+ and geometry && NEW.centroid and _ST_Covers(geometry, NEW.centroid)
+ ORDER BY admin_level desc LIMIT 1
+ LOOP
+ IF location.is_same THEN
+ -- Looks like the same boundary is replicated on multiple admin_levels.
+ -- Usual tagging in Poland. Remove our boundary from addresses.
+ NEW.rank_address := 0;
+ ELSE
+ parent_address_level := location.rank_address;
+ IF location.rank_address >= NEW.rank_address THEN
+ IF location.rank_address >= 24 THEN
+ NEW.rank_address := 25;
+ ELSE
+ NEW.rank_address := location.rank_address + 2;
+ END IF;
+ END IF;
+ END IF;
+ END LOOP;
+
+ IF NEW.rank_address > 9 THEN
+ -- Second check that the boundary is not completely contained in a
+ -- place area with a higher address rank
+ FOR location IN
+ SELECT rank_address FROM placex
+ WHERE class = 'place' and rank_address < 24
+ and rank_address > NEW.rank_address
+ and geometry && NEW.geometry
+ and geometry ~ NEW.geometry -- needed because ST_Relate does not do bbox cover test
+ and ST_Relate(geometry, NEW.geometry, 'T*T***FF*') -- contains but not equal
+ ORDER BY rank_address desc LIMIT 1
+ LOOP
+ NEW.rank_address := location.rank_address + 2;
+ END LOOP;