public
Created

Fix PostgreSQL sequences

  • Download Gist
file1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/env python
 
DB_NAME = "my_db"
 
from subprocess import Popen, PIPE
import re
 
exclude = [ 'tablename', 'rows' ]
tp = re.compile( '[^a-z_]' )
ts = Popen( [ "/usr/bin/psql", DB_NAME, "-c SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg_%' AND tablename NOT LIKE 'sql_%' ORDER BY tablename" ], stdout=PIPE ).communicate()[ 0 ].split( ' ' )
 
tables = []
for t in ts:
t = tp.sub( '', t )
if len( t ) == 0 or t in exclude:
continue
tables.append( t )
 
for t in tables:
sql = "SELECT pg_catalog.setval( pg_get_serial_sequence( '%s', 'id' ), ( SELECT MAX( id ) FROM %s ) + 1 );" % ( t, t )
print Popen( [ "/usr/bin/psql", DB_NAME, "-c %s" % sql ], stdout=PIPE ).communicate()[ 0 ]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.