Created
May 2, 2014 14:50
-
-
Save RhubarbSin/57d389a2d10780c10d78 to your computer and use it in GitHub Desktop.
Update PostgreSQL's table sequences after importing data
This file contains 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
#!/usr/bin/env python | |
"""Update PostgreSQL's table sequences after importing data from MySQL.""" | |
import sqlobject | |
import psycopg2 | |
uri = 'postgres://username:password@localhost/dbname' | |
connection = sqlobject.connectionForURI(uri) | |
sqlobject.sqlhub.processConnection = connection | |
def qa(query): | |
print "\tRunning query: ", query | |
return connection.queryAll(query) | |
tables = qa("select * from information_schema.tables where table_schema='public' and table_type='BASE TABLE'") | |
for table in tables: | |
table = table[2] | |
print "Processing table: ", table | |
try: | |
maxid = qa("SELECT max(id) FROM %s;" % table) | |
except psycopg2.ProgrammingError: | |
print "skipping" | |
try: | |
maxid = maxid[0] | |
except TypeError: | |
continue | |
try: | |
maxid = maxid[0] | |
except TypeError: | |
continue | |
if not maxid: | |
continue | |
print "maxid is: ", maxid | |
sequence_name = "%s_id_seq" % table | |
qa("SELECT setval('%s', %i);" % (sequence_name, maxid)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment