简体   繁体   English

是否可以在peewee + sqlite中嵌套交易?

[英]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? 小矮人,sqlite或我对交易的理解是否有问题?

The code creates a transaction, then calls 3 times a function that creates 3 records in its own transaction. 该代码创建一个事务,然后调用3次函数,该函数在其自己的事务中创建3条记录。 The function succeeds the 1st and 3rd time, but it fails the 2nd. 该函数在第1次和第3次成功,但在第2次失败。

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. 我希望在数据库中找到6条记录,在第一次调用时创建3条记录,在第三次调用时创建3条记录,在第二次调用期间创建的记录将被回滚。

Instead I find only the records created at the 3rd call. 相反,我只找到在第3次调用中创建的记录。

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

If you want to nest transactions, you can use savepoints doc link . 如果要嵌套事务,可以使用savepoints doc link

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM