是否可以在peewee + sqlite中嵌套事务?

时间:2014-06-03 14:51:20

标签: python sqlite transactions peewee

执行以下代码会产生意外结果。这是peewee,sqlite或我对交易的理解的问题吗?

代码创建一个事务,然后调用一次在其自己的事务中创建3条记录的函数。该功能在第1次和第3次成功,但第2次失败。

我希望在数据库中找到6条记录,3条在第一次调用时创建,3条在第3次调用时创建,第二次调用期间创建的记录将被回滚。

相反,我只找到第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

1 个答案:

答案 0 :(得分:1)

如果要嵌套交易,可以使用保存点doc link

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