Hi Kate,
On 06/18/2015 04:05 AM, Katarzyna Łabędź wrote:
> Maybe i didn't understand it correctly.
>
> I know Django support transactions, but isn't it do it on commit?
> I just tried to find the BEGIN statement inside them and i could not
> find it - searched through internet and what I found was a bunch of
> people asking the same question - where is the begin in the
> transactions? So i just figured i ask here.
> Why Django don't execute Begin statement ? Isn't it necessary to have a
> fully correct transaction?
You are right to be confused, because this is confusing territory.
The default behavior of all Python database adapters is "implicit
transactions", meaning the underlying database adapter library itself
(Python-MySQL, psycopg2, etc) sends a BEGIN automatically as soon as you
send your first query. (At least if the library is compliant with PEP
249 [1], the Python database adapter standard, which all adapters used
by built-in Django backends are.)
Django overrides this and places the underlying connection into
autocommit mode (no transactions) by default. But when you request a
transaction (by using an 'atomic' block), Django doesn't need to
explicitly send BEGIN, it just puts the connection back into the default
PEP 249 "implicit transactions" mode, which means the database adapter
will send BEGIN automatically as soon as you send a query. So Django
never sends a BEGIN itself, just COMMIT or ROLLBACK.
In practice, though, you can ignore this implementation detail, and just
assume that a BEGIN is sent at the start of any (outer) 'atomic' block
(and COMMIT or ROLLBACK) is sent at the end, and you'll be correct.
I wrote a blog post [2] which discusses this in more detail. It's about
PostgreSQL instead of MySQL, but the part near the beginning about PEP
249 and Django applies equally well to MySQL (I think; I'm not very
familiar with transactions on MySQL).
Carl
[1]
https://www.python.org/dev/peps/pep-0249/
[2]
http://oddbird.net/2014/06/14/sqlalchemy-postgres-autocommit/