[Python] Is it possible to nest transactions in peewee + sqlite?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página