Question

For testing purposes, I clear (delete) every table before executing code.

for table in reversed(db.metadata.sorted_tables):
    engine.execute(table.delete())

do_stuff()

However, the new data's id values start from where the previous id's left off:

First iteration:

 id  | value   
-----+---------
 1   | hi      
 2   | there   

Second iteration (delete table, insert new data):

 id  | value   
-----+---------
 3   | good    
 4   | day     

Is there any way to reset the id count when I delete the table?


EDIT: seems I broke it, table is not cleared at all now

config.py

SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:myPassword@localhost/myDatabase'


app.py

app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)


models.py

from app import app, db

def clear():
    for table in reversed(db.metadata.sorted_tables):
        db.engine.execute('TRUNCATE TABLE ' + table.name + ' RESTART IDENTITY CASCADE')

The table is still being added to (using db.session.add_all() and db.session.commit()). However, clear() does nothing. When I log in as the postgres user in terminal and directly execute TRUNCATE TABLE myTable RESTART IDENTITY CASCADE, it works.

table.name gives the correct names. That leads me to believe there is something wrong with db.engine.execute(), but that does not make much sense since db.session.add_all() works

Was it helpful?

Solution

Call TRUNCATE TABLE MyTable RESTART IDENTITY; for every table in the loop instead of calling table.delete() - this should reset the auto increment sequence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top