How to tell if your select query is within a transaction or not?

∥☆過路亽.° 提交于 2019-12-23 15:44:13

问题


In Django 1.5.x, I have a long running management command where select queries are returning stale data. I suspect this is due to the fact that they are running within a transaction that are started earlier on the db connnection. Is there a way a tell if a query runs within a transaction or it is in autocommit mode?

(this is somewhat more focused version of an earlier question I posted at https://stackoverflow.com/questions/18540099/orm-does-not-return-recent-database-changes)


回答1:


You can check if you are in a transaction by checking is_managed

if transaction.is_managed():
    print "tutsi frutsi!"



回答2:


Since Django 1.7, Connection.in_atomic_block will tell you if a connection is inside a transaction or not. It doesn't seem like this is documented, but it Works On My Machine:

from django.db import transaction
cxn = transaction.get_connection()
if cxn.in_atomic_block:
    print "We're inside a transaction!"



回答3:


Since Django 1.6 you can tell if you're in autocommit mode via transaction.get_autocommit API.

from django.db import transaction

if transaction.get_autocommit():
    pass  # We are in autocommit


来源:https://stackoverflow.com/questions/18544033/how-to-tell-if-your-select-query-is-within-a-transaction-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!