nested transactions context manager and decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from django.db.transaction import managed, enter_transaction_management, is_dirty, rollback, commit, leave_transaction_management, _transaction_func

import threading

# storage of nested count
_tl = threading.local()

def nested_commit_on_success(using=None):

   def entering(using):
     lev = getattr(_tl,"level",0)
     lev += 1
     _tl.level = lev
     if lev >= 2: # is it nested ?
       return # yes it's nested, do nothing
     else:
       # first time, enter transaction
       enter_transaction_management(using=using)
       managed(True, using=using)

   def exiting(exc_value, using):
     lev = _tl.level
     _tl.level -= 1
     if lev >= 2: # is it nested ?
       return # yes, do nothing
     # last time, must do correct transaction ending
     try:
         if exc_value is not None:
             if is_dirty(using=using):
                 rollback(using=using)
         else:
             if is_dirty(using=using):
                 try:
                     commit(using=using)
                 except:
                     rollback(using=using)
                     raise
     finally:
         leave_transaction_management(using=using)

   return _transaction_func(entering, exiting, using)

More like this

  1. Nested commit_on_success by rfk 5 years, 1 month ago
  2. Commit on success unless managed decorator by Kronuz 4 years, 7 months ago
  3. Recursive template tag for Django with arguments by hyperair 1 year, 3 months ago
  4. Cache Any Function by jeffwheeler 7 years, 1 month ago
  5. Deep package test runner by eternicode 3 years, 1 month ago

Comments

(Forgotten your password?)