+ FOR location IN
+ select placex.place_id, osm_type, osm_id,
+ CASE WHEN class = 'place' and type = 'postcode' THEN hstore('name', postcode) ELSE name END as name,
+ CASE WHEN extratags ? 'place' THEN 'place' ELSE class END as class,
+ CASE WHEN extratags ? 'place' THEN extratags->'place' ELSE type END as type,
+ admin_level, fromarea, isaddress,
+ CASE WHEN address_place_id = for_place_id AND rank_address = 0 THEN 100 WHEN rank_address = 11 THEN 5 ELSE rank_address END as rank_address,
+ distance,calculated_country_code,postcode
+ from place_addressline join placex on (address_place_id = placex.place_id)
+ where place_addressline.place_id = for_place_id
+ and (cached_rank_address > 0 AND cached_rank_address < searchrankaddress)
+ and address_place_id != for_place_id
+ and (placex.calculated_country_code IS NULL OR searchcountrycode IS NULL OR placex.calculated_country_code = searchcountrycode)
+ order by rank_address desc,isaddress desc,fromarea desc,distance asc,rank_search desc
+ LOOP
+--RAISE WARNING '%',location;
+ IF searchcountrycode IS NULL AND location.calculated_country_code IS NOT NULL THEN
+ searchcountrycode := location.calculated_country_code;
+ END IF;
+ IF searchpostcode IS NOT NULL and location.type = 'postcode' THEN
+ location.isaddress := FALSE;
+ END IF;
+ IF searchpostcode IS NULL and location.isaddress and location.type != 'postcode' and location.postcode IS NOT NULL THEN
+ searchpostcode := location.postcode;
+ END IF;
+ IF location.rank_address = 4 AND location.isaddress THEN
+ hadcountry := true;
+ END IF;
+ IF location.rank_address < 4 AND NOT hadcountry THEN
+ select name from country_name where country_code = searchcountrycode limit 1 INTO countryname;
+ IF countryname IS NOT NULL THEN
+ countrylocation := ROW(null, null, null, countryname, 'place', 'country', null, true, true, 4, 0)::addressline;
+ RETURN NEXT countrylocation;
+ END IF;
+ END IF;
+ countrylocation := ROW(location.place_id, location.osm_type, location.osm_id, location.name, location.class,
+ location.type, location.admin_level, location.fromarea, location.isaddress, location.rank_address,
+ location.distance)::addressline;
+ RETURN NEXT countrylocation;
+ found := location.rank_address;
+ END LOOP;