Skip to content

Instantly share code, notes, and snippets.

@nxmad
Created December 8, 2021 14:30
Show Gist options
  • Save nxmad/973751c49acbc18019e8f5a2df247df0 to your computer and use it in GitHub Desktop.
Save nxmad/973751c49acbc18019e8f5a2df247df0 to your computer and use it in GitHub Desktop.
Fix all tables sequences & ownership (Postgres)
CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text, sequence_name text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE 'SELECT setval( ''' || sequence_name || ''', ' || '(SELECT MAX(' || columnname ||
') FROM ' || tablename || ')' || '+1)';
EXECUTE 'ALTER SEQUENCE ' || sequence_name || ' OWNED BY ' || tablename || '.' || columnname;
END;
$body$ LANGUAGE 'plpgsql';
SELECT table_name || '_' || column_name || '_seq',
reset_sequence(table_name, column_name, table_name || '_' || column_name || '_seq')
FROM information_schema.columns where column_default like 'nextval%';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment