关于 peewee 事务提交

About peewee transaction commit

我使用的是mysql8.0,使用的是innodb引擎,使用的是peewee 3.14版本,我使用的是peewee事务提交,没有执行commit,看到数据已经写入数据库,但是我没有执行db.commit(),我手动执行MySQL中的命令。如果我不执行commit,我就写不下去了。但是使用peewee事务提交时会出现不一致的情况。我的代码有什么问题?

db =db = MySQLDatabase("address", host="127.0.0.1", port=3306, user="root", passwd="xxx",autocommit=False,autorollback=True)
with db.manual_commit():
    db.begin()
    Spead.create(dis="test",number="test",value=333)

您还在 peewee 问题跟踪器上打开了一个问题,我在其中回复了以下评论:

I saw the data has been written into the database

假设您的意思是您正在使用一个单独的连接并且在 peewee 连接提交之前看到了数据?你可能会检查你的阅读 isolation settings.

当我运行以下脚本时,我得到了预期的输出——第二个连接在我调用提交之前看不到未提交的行:

from peewee import *

db = MySQLDatabase('peewee_test')
db2 = MySQLDatabase('peewee_test')  # 2nd connection

class Reg(Model):
    key = TextField()
    class Meta:
        database = db

class Reg2(Reg):  # model class for accessing table using 2nd conn
    class Meta:
        database = db2
        table_name = 'reg'


db.create_tables([Reg])

with db.manual_commit() as tx:
    db.begin()
    Reg.create(key='k1')  # create a row using first conn

    db2.connect()  # query table using 2nd conn
    print('is "k1" visible to conn2 BEFORE commit?')
    print('rows in "reg" table: %s' % Reg2.select().count())

    db.commit()
    print('is "k1" visible to conn2 AFTER commit?')
    print('rows in "reg" table: %s' % Reg2.select().count())

    db2.close()

db.drop_tables([Reg])

输出:

is "k1" visible to conn2 BEFORE commit?                                                                              
rows in "reg" table: 0                                                                                               
is "k1" visible to conn2 AFTER commit?                                                                               
rows in "reg" table: 1