Skip to content

Instantly share code, notes, and snippets.

@ninjadq
Created March 3, 2016 05:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninjadq/9b5036e6028e1bf4dc73 to your computer and use it in GitHub Desktop.
Save ninjadq/9b5036e6028e1bf4dc73 to your computer and use it in GitHub Desktop.
django transactions with raw sql and multiple databases
def test_transaction(*args):
create_sql = "INSERT INTO user (name) VALUES (%s)"
transaction.set_autocommit(False, using='uic')
try:
cursor = connections['uic'].cursor()
for u in args:
cursor.execute(create_sql,[u])
except IntegrityError as e:
transaction.rollback(using='uic')
else:
transaction.commit(using='uic')
finally:
transaction.set_autocommit(True, using='uic')
def test_transaction_2(username1, username2, tpl1, tpl2):
create_sql = "INSERT INTO user (name) VALUES (%s)"
with transaction.atomic(using='uic'):
cursor = connections['uic'].cursor()
cursor.execute(create_sql,[username1])
cursor.execute(create_sql, [username2])
with transaction.atomic(using='portal'):
create_sql = '''INSERT INTO tpl (tpl_name, parent_id, action_id, create_user) VALUES (%s, 0, 0, 'root')'''
with connections['portal'].cursor() as c:
c.execute(create_sql, [tpl1])
c.execute(create_sql, [tpl2])
with transaction.atomic():
p1 = Project(name='p1111111', tag='testtttttt')
p1.save()
@hexvolt
Copy link

hexvolt commented Jun 1, 2016

looks like atomic doesn't work with cursor.execute(raw_sql)
no transaction rollback happens in case of exceptions

@Genarito
Copy link

Genarito commented Nov 6, 2020

Neither work with raw sql for me in Django 3.1.2 :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment