Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 962
thesamet Avatar asked Aug 31 '13 02:08

thesamet


People also ask

Is select query a transaction?

Queries are operations to CRUD (create (insert), update (set), read (select), delete (delete)) data inside a table. The transaction is more or less the process of a single or multiple statements/queries/operations getting executed.

What does query a transaction mean?

Transaction Query means a query by the Principal or an Authorised User regarding a transaction processed to the Principal's Billing Account for which the relevant Statement of Account contains incomplete Enhanced Data; Sample 1Sample 2Sample 3.

What are transactions in SQL?

A SQL transaction is a grouping of one or more SQL statements that interact with a database. A transaction in its entirety can commit to a database as a single logical unit or rollback (become undone) as a single logical unit. In SQL, transactions are essential for maintaining database integrity.

What is transaction in SQL with example?

A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on that table.


2 Answers

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!"
like image 72
David Wolever Avatar answered Oct 19 '22 00:10

David Wolever


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
like image 30
knaperek Avatar answered Oct 19 '22 00:10

knaperek