stenci
stenci

Reputation: 8481

Is it possible to nest transactions in peewee + sqlite?

Executing the code below produces unexpected results. Is it a problem with peewee, sqlite, or my understanding of transactions?

The code creates a transaction, then calls 3 times a function that creates 3 records in its own transaction. The function succeeds the 1st and 3rd time, but it fails the 2nd.

I would expect to find 6 records in the database, 3 created at the 1st call and 3 created at the 3rd, and the records created during the 2nd call would be rolled back.

Instead I find only the records created at the 3rd call.

import peewee

class DbTest(peewee.Model):
    test = peewee.CharField()
    class Meta:
        database = db

def test(txt):
    with db.transaction():
        DbTest.create(test=txt + '1')
        DbTest.create(test=txt + '2')
        if txt == 'b':
            raise
        DbTest.create(test=txt + '3')

DbTest().drop_table(True)
DbTest().create_table(True)

with db.transaction():
    for txt in ['a', 'b', 'c']:
        try:
            test(txt)
        except:
            pass

Upvotes: 0

Views: 334

Answers (1)

coleifer
coleifer

Reputation: 26245

If you want to nest transactions, you can use savepoints doc link.

with db.transaction():
    with db.savepoint():
        do_stuff()
    with db.savepoint():
        do_more_stuff()

Upvotes: 1

Related Questions