Skip to content

Instantly share code, notes, and snippets.

@curiousest
Created May 24, 2017 11:17
Show Gist options
  • Select an option

  • Save curiousest/7191fbd1aa000c69bd2ee2b59b259880 to your computer and use it in GitHub Desktop.

Select an option

Save curiousest/7191fbd1aa000c69bd2ee2b59b259880 to your computer and use it in GitHub Desktop.
Postgres table id prefix
def set_up_autonumbering(engine, table, prefix):
conn = engine.connect()
try:
logging.info("Creating autonumber sequence for {}".format(table))
conn.execute("CREATE SEQUENCE {}_ids".format(table))
except:
logging.info("Autonumber sequence already created".format(table))
try:
logging.info("Setting up ID format for {}".format(table))
conn.execute("""
ALTER TABLE {}
ALTER id SET DEFAULT ('{}' || nextval('{}_ids')::text)::INTEGER
;
""".format(table, prefix, table))
except:
logging.error("Failed to set up ID format for {}".format(table))
try:
logging.info("Resetting Autonumber Sequence for {}".format(table))
num = conn.execute("SELECT max(id) from {}".format(table)).first()[0]
if num:
num = int(str(num)[3:])
restart_value = num + 1
else:
restart_value = 1
conn.execute("ALTER SEQUENCE {}_ids RESTART WITH {};".format(table, restart_value))
except:
logging.error("Failed reset autonumber sequence for {}".format(table))
conn.execute("commit")
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment