Skip to content

Instantly share code, notes, and snippets.

@BookLaugh
Last active October 27, 2016 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BookLaugh/a129a11487857107f1f7 to your computer and use it in GitHub Desktop.
Save BookLaugh/a129a11487857107f1f7 to your computer and use it in GitHub Desktop.
PostgreSQL procedure for updating all sequences used as default values for table columns. Once called, it will update values of sequences to max value present in column plus 5 (why 5? So you can find out which sequences were altered). Function returns list of names of updated sequences.
CREATE OR REPLACE FUNCTION set_seq_vals(schema_name TEXT)
RETURNS TEXT[]
AS $$
schemaname = schema_name if schema_name else 'public'
plpy.execute("SET SEARCH_PATH=%s,public" % schemaname)
tables = plpy.execute("SELECT tablename FROM pg_tables WHERE schemaname = '%s'" % schemaname);
altered_seqs = []
for t in tables:
cols = plpy.execute("SELECT column_name, column_default, data_type, is_nullable FROM information_schema.columns WHERE table_name = '%s' AND data_type in ('integer', 'bigint') AND column_default IS NOT NULL" % t["tablename"])
for c in cols:
if not c["column_default"].lstrip().lower().startswith("nextval"):
continue
seqname = plpy.execute("""SELECT pg_get_serial_sequence('%s', '%s') AS "seq_name" """ % (t["tablename"], c["column_name"]))
if seqname and seqname[0]["seq_name"] is not None:
sname = seqname[0]["seq_name"]
max_val = plpy.execute("""SELECT coalesce(max(%s), 1) as "mv" FROM "%s" """ % (c["column_name"], t["tablename"]))[0]
seq_last = plpy.execute("""SELECT coalesce(last_value, 2) as "sl" FROM %s """ % (sname))[0]
if max_val["mv"] > seq_last["sl"]:
plpy.execute("SELECT setval('%s', %d, true)" % (sname, max_val["mv"] + 5))
altered_seqs.append(sname)
return altered_seqs
$$ LANGUAGE plpython2u;
@BookLaugh
Copy link
Author

Language PLPython is described here: http://www.postgresql.org/docs/current/interactive/plpython.html

To make it available on your database server you need to do the following:

  1. Add PLPython to your PostgreSQL installation, if not present. Ubuntu users, please do: sudo apt-get install postgresql-plpython-K.N where K.N is your PostgreSQL version (like 9.4 or 9.5)
  2. In your database console (e.g. psql) run following statements: CREATE EXTENSION plpythonu; CREATE LANGUAGE plpython2u;

And you're done 👍 Good luck and have fun coding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment