Skip to content

Instantly share code, notes, and snippets.

@pilgrim2go
Forked from BookLaugh/set_sequence_values.py
Created October 27, 2016 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pilgrim2go/0483e7a8b5db1c21d663a06fed77842b to your computer and use it in GitHub Desktop.
Save pilgrim2go/0483e7a8b5db1c21d663a06fed77842b 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment