Skip to content

Instantly share code, notes, and snippets.

@RhubarbSin
Created May 2, 2014 14:50
Show Gist options
  • Save RhubarbSin/57d389a2d10780c10d78 to your computer and use it in GitHub Desktop.
Save RhubarbSin/57d389a2d10780c10d78 to your computer and use it in GitHub Desktop.
Update PostgreSQL's table sequences after importing data
#!/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)
print
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))
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment