Last active
May 23, 2017 03:04
-
-
Save sylvainv/da8031b6ea7f3530ea33c38ee0bd1a9c to your computer and use it in GitHub Desktop.
Update all PostgreSQL sequences to the max id.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DO $$ | |
DECLARE r pg_catalog.pg_class%rowtype; | |
DECLARE _max_id int; | |
DECLARE _table_name text; | |
DECLARE _column_name text; | |
DECLARE _result int; | |
BEGIN | |
FOR r IN | |
select * from pg_catalog.pg_class where relkind = 'S' | |
LOOP | |
SELECT pg_catalog.quote_ident(nspname) || '.' || | |
pg_catalog.quote_ident(relname), | |
pg_catalog.quote_ident(attname) | |
INTO _table_name, _column_name | |
FROM pg_catalog.pg_class c | |
INNER JOIN pg_catalog.pg_depend d ON c.oid=d.refobjid | |
INNER JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace | |
INNER JOIN pg_catalog.pg_attribute a ON ( | |
a.attrelid=c.oid AND | |
a.attnum=d.refobjsubid) | |
WHERE d.classid='pg_catalog.pg_class'::pg_catalog.regclass | |
AND d.refclassid='pg_catalog.pg_class'::pg_catalog.regclass | |
AND d.objid=r.relname::regclass::oid | |
AND d.deptype='a'; | |
EXECUTE format('SELECT max(%s) FROM %I', _column_name, _table_name::regclass::text) INTO _max_id; | |
EXECUTE 'SELECT setval($1, $2)' INTO _result USING r.relname::regclass, _max_id; | |
RAISE NOTICE 'Set current % sequence value to %', r.relname::regclass, _result; | |
END LOOP; | |
END; | |
$$ LANGUAGE 'plpgsql'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment