[英]reason for sqlalchemy to roll back
I am using sqlalchemy to store data into a postgresql database. 我正在使用sqlalchemy将数据存储到postgresql数据库中。 I am a little bit confused that sqlalchemy rolls back on execution without throwing an exception. 我有点困惑sqlalchemy在执行时回滚而不抛出异常。 I found an article in the documentary and tried to prevent rollbacks by setting pool_reset_on_return='commit'
我在纪录片中找到了一篇文章,并试图通过设置pool_reset_on_return='commit'
来防止回滚
This actually leads sqlalchemy to do nothing. 这实际上导致sqlalchemy不执行任何操作。 Hence, I inserted a line that explicitly calls trans.commit()
that leads to the following output: 因此,我插入了一行明确调用trans.commit()
的行,该行导致以下输出:
2014-03-03 18:03:33,390,p:32764 Thread-3, sqlalchemy.engine.base.Engine(_execute_context) [INFO]: INSERT INTO _fd (**)
2014-03-03 18:03:33,391,p:32764 Thread-3, sqlalchemy.engine.base.Engine(_execute_context) [INFO]: {****}
2014-03-03 18:03:33,392,p:32764 Thread-3, sqlalchemy.engine.base.Engine(__init__) [DEBUG]: Col ('fid',)
2014-03-03 18:03:33,393,p:32764 Thread-3, sqlalchemy.engine.base.Engine(process_rows) [DEBUG]: Row (*,)
2014-03-03 18:03:33,393,p:32764 Thread-3, sqlalchemy.engine.base.Engine(_rollback_impl) [INFO]: ROLLBACK
The code is quit simple so far: 到目前为止,该代码非常简单:
1837 with conn.begin() as trans:
1838 statement = meta.tables[_table_name].insert().values(
...
1847 )
1848 res = conn.execute(statement)
1849 trans.commit()
Does anyone have an idea, what could be the cause for the rollbacks? 有谁知道,回滚的原因是什么?
Not 100% sure about the reason but looking at the source , we can see that when you do trans.commit()
within your with....
construct, it sets the transaction to inactive. 不是100%知道原因,而是查看源代码 ,我们可以看到,当您在with....
构造中执行trans.commit()
,它将事务设置为非活动状态。 Now when the Context Manager
for the transaction tries to run the __exit__()
method at the end of the with
statement, it triggers a rollback()
because the is_active
flag has been set to False. 现在,当事务的Context Manager
尝试在with
语句的末尾运行__exit__()
方法时,由于is_active
标志已设置为False,它将触发rollback()
。 (I don't know what happens when you commit a transaction and then roll it back). (我不知道在提交事务然后回滚时会发生什么)。
Anyways the "problem" is that with
construct handles the commit and rollback part implicitly. 无论如何,“问题”是with
结构隐式处理了提交和回滚部分。 Per the docs , all you need to do is 根据文档 ,您所需要做的就是
with conn.begin() as trans:
statement = meta.tables[_table_name].insert().values(
...
)
res = conn.execute(statement)
好的,我没有这个习惯的原因,但是在语句末尾放置conn.execute("commit")
可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.