Last active
January 10, 2018 12:04
-
-
Save igorescobar/4a84f1f47454f162981d406651514b09 to your computer and use it in GitHub Desktop.
Syncing Postgres Sequences for All Tables
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
-- https://wiki.postgresql.org/wiki/Fixing_Sequences | |
SELECT 'SELECT SETVAL(' || | |
quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || | |
', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || | |
quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';' | |
FROM pg_class AS S, | |
pg_depend AS D, | |
pg_class AS T, | |
pg_attribute AS C, | |
pg_tables AS PGT | |
WHERE S.relkind = 'S' | |
AND S.oid = D.objid | |
AND D.refobjid = T.oid | |
AND D.refobjid = C.attrelid | |
AND D.refobjsubid = C.attnum | |
AND T.relname = PGT.tablename | |
ORDER BY S.relname; |
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
# this script will generate a bunch of SQL queries to fix your sequences on each table | |
psql -Atq -h $database_host -U $database_user -d $database_name -p 5432 -f sequence_reset.sql -o temp | |
# this will consume the temp file generated by the previous command | |
psql -h $database_host -U $database_user -d $database_name -p 5432 -f temp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment