Created
May 24, 2017 11:17
-
-
Save curiousest/7191fbd1aa000c69bd2ee2b59b259880 to your computer and use it in GitHub Desktop.
Postgres table id prefix
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
| 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