Created
March 3, 2016 05:21
-
-
Save ninjadq/9b5036e6028e1bf4dc73 to your computer and use it in GitHub Desktop.
django transactions with raw sql and multiple databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
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
looks like
atomic
doesn't work with cursor.execute(raw_sql)no transaction rollback happens in case of exceptions