SET search_path=public;

CREATE OR REPLACE FUNCTION for_vrevisions(in sql text) RETURNS setof text AS $$
DECLARE
    r RECORD;
BEGIN
    FOR r IN SELECT DISTINCT schemaname FROM pg_tables WHERE schemaname like 'vrevisions_%%' ORDER BY 1 LOOP
        EXECUTE 'SET search_path='||r.schemaname||',public;'||sql;
        RETURN NEXT r.schemaname;
    END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT for_vrevisions('
    DELETE FROM objects_c WHERE domain_attrs ?| ARRAY[\'cat:rd_nm\', \'cat:ad_nm\', \'cat:addr_nm\', \'cat:transport_railway_nm\', \'cat:transport_metro_nm\'];
    DELETE FROM suggest_data WHERE categories ?| ARRAY[\'cat:rd_nm\', \'cat:ad_nm\', \'cat:addr_nm\', \'cat:transport_railway_nm\', \'cat:transport_metro_nm\'];
    DELETE FROM objects_r WHERE domain_attrs->\'rel:slave\' LIKE \'%_nm\';
');

SET search_path=public;
DROP FUNCTION for_vrevisions(in sql text);

SET search_path=revision, public;

UPDATE attributes SET contents =  contents || hstore(substring(text(contents) from 'cat:(.*?)"=>"1"') || ':is_local', '1')
WHERE position('_nm:name' in array_to_string(akeys(contents),' ')) >0 AND position('is_not_local' in array_to_string(akeys(contents),' ')) =0;
UPDATE attributes SET contents =  delete(contents, substring(text(contents) from 'cat:(.*?)"=>"1"') || ':is_not_local')
WHERE position('_nm:name' in array_to_string(akeys(contents),' ')) >0 AND position('is_not_local' in array_to_string(akeys(contents),' ')) >0;

SET search_path=public;



