with transaction.atomic() not working for Azure SQL Database

329 views Asked by At

I use django-pyodbc-azure 2.1.0.0 for the connection with an Azure SQL database which works fine.

When I understand the documentation of django-pyodbc-azure correctly, transactions should be supported.

However, this code immediately updates the row. I would expect, that the row is updated after 20 seconds.

from django.db import transaction
from myapp.models import MyModel
import time

with transaction.atomic():
    MyModel.objects.filter(id=1).update(my_field='Test')
    time.sleep(20)

Am I doing something wrong? Do I need to specifiy certain settings on the Azure SQL database?


When I set AUTOCOMMIT = False in my database settings, then the following code will not update the row at all.

MyModel.objects.filter(id=1).update(my_field='Test')
time.sleep(20)
transaction.commit()

My current settings.py

'azure_reporting': {
    'ENGINE': 'sql_server.pyodbc',
    'NAME': 'reporting_db',
    'HOST': 'xxxxxx.database.windows.net',
    'PORT': '',
    'USER': '[email protected]',
    'PASSWORD': 'xxxxxx',

    'OPTIONS': {
        'driver': 'ODBC Driver 17 for SQL Server'
    }
}
1

There are 1 answers

2
Leon Yue On

Please make sure you have set the AUTOCOMMIT=true on database settings:

DATABASES = {
    'default': {
        'ENGINE': 'sql_server.pyodbc',
        'HOST': 'yourserver.com',
        'PORT': '1433',
        'NAME': 'your_db',
        'USER': 'your_user',
        'PASSWORD': 'your_pw',
        'AUTOCOMMIT': True,

        'OPTIONS': {
            'driver': 'ODBC Driver 13 for SQL Server',

        },
    },
}

No error happened, the only things what we can do is recheck the configuration of django-pyodbc-azure.

As you said: When I set AUTOCOMMIT = False in my database settings, then the following code will not update the row at all.

I think the transactions should works well.

Hope this helps.