PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/env/lib/python2.7/site-packages/django/db/transaction.py

https://github.com/m3nadav/outfitsus
Python | 541 lines | 416 code | 24 blank | 101 comment | 72 complexity | 053ed0d67979a3e349e97002ef1c1452 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause
  1. """
  2. This module implements a transaction manager that can be used to define
  3. transaction handling in a request or view function. It is used by transaction
  4. control middleware and decorators.
  5. The transaction manager can be in managed or in auto state. Auto state means the
  6. system is using a commit-on-save strategy (actually it's more like
  7. commit-on-change). As soon as the .save() or .delete() (or related) methods are
  8. called, a commit is made.
  9. Managed transactions don't do those commits, but will need some kind of manual
  10. or implicit commits or rollbacks.
  11. """
  12. import warnings
  13. from functools import wraps
  14. from django.db import (
  15. connections, DEFAULT_DB_ALIAS,
  16. DatabaseError, Error, ProgrammingError)
  17. from django.utils.decorators import available_attrs
  18. class TransactionManagementError(ProgrammingError):
  19. """
  20. This exception is thrown when transaction management is used improperly.
  21. """
  22. pass
  23. ################
  24. # Private APIs #
  25. ################
  26. def get_connection(using=None):
  27. """
  28. Get a database connection by name, or the default database connection
  29. if no name is provided.
  30. """
  31. if using is None:
  32. using = DEFAULT_DB_ALIAS
  33. return connections[using]
  34. ###########################
  35. # Deprecated private APIs #
  36. ###########################
  37. def abort(using=None):
  38. """
  39. Roll back any ongoing transactions and clean the transaction management
  40. state of the connection.
  41. This method is to be used only in cases where using balanced
  42. leave_transaction_management() calls isn't possible. For example after a
  43. request has finished, the transaction state isn't known, yet the connection
  44. must be cleaned up for the next request.
  45. """
  46. get_connection(using).abort()
  47. def enter_transaction_management(managed=True, using=None, forced=False):
  48. """
  49. Enters transaction management for a running thread. It must be balanced with
  50. the appropriate leave_transaction_management call, since the actual state is
  51. managed as a stack.
  52. The state and dirty flag are carried over from the surrounding block or
  53. from the settings, if there is no surrounding block (dirty is always false
  54. when no current block is running).
  55. """
  56. get_connection(using).enter_transaction_management(managed, forced)
  57. def leave_transaction_management(using=None):
  58. """
  59. Leaves transaction management for a running thread. A dirty flag is carried
  60. over to the surrounding block, as a commit will commit all changes, even
  61. those from outside. (Commits are on connection level.)
  62. """
  63. get_connection(using).leave_transaction_management()
  64. def is_dirty(using=None):
  65. """
  66. Returns True if the current transaction requires a commit for changes to
  67. happen.
  68. """
  69. return get_connection(using).is_dirty()
  70. def set_dirty(using=None):
  71. """
  72. Sets a dirty flag for the current thread and code streak. This can be used
  73. to decide in a managed block of code to decide whether there are open
  74. changes waiting for commit.
  75. """
  76. get_connection(using).set_dirty()
  77. def set_clean(using=None):
  78. """
  79. Resets a dirty flag for the current thread and code streak. This can be used
  80. to decide in a managed block of code to decide whether a commit or rollback
  81. should happen.
  82. """
  83. get_connection(using).set_clean()
  84. def is_managed(using=None):
  85. warnings.warn("'is_managed' is deprecated.",
  86. PendingDeprecationWarning, stacklevel=2)
  87. def managed(flag=True, using=None):
  88. warnings.warn("'managed' no longer serves a purpose.",
  89. PendingDeprecationWarning, stacklevel=2)
  90. def commit_unless_managed(using=None):
  91. warnings.warn("'commit_unless_managed' is now a no-op.",
  92. PendingDeprecationWarning, stacklevel=2)
  93. def rollback_unless_managed(using=None):
  94. warnings.warn("'rollback_unless_managed' is now a no-op.",
  95. PendingDeprecationWarning, stacklevel=2)
  96. ###############
  97. # Public APIs #
  98. ###############
  99. def get_autocommit(using=None):
  100. """
  101. Get the autocommit status of the connection.
  102. """
  103. return get_connection(using).get_autocommit()
  104. def set_autocommit(autocommit, using=None):
  105. """
  106. Set the autocommit status of the connection.
  107. """
  108. return get_connection(using).set_autocommit(autocommit)
  109. def commit(using=None):
  110. """
  111. Commits a transaction and resets the dirty flag.
  112. """
  113. get_connection(using).commit()
  114. def rollback(using=None):
  115. """
  116. Rolls back a transaction and resets the dirty flag.
  117. """
  118. get_connection(using).rollback()
  119. def savepoint(using=None):
  120. """
  121. Creates a savepoint (if supported and required by the backend) inside the
  122. current transaction. Returns an identifier for the savepoint that will be
  123. used for the subsequent rollback or commit.
  124. """
  125. return get_connection(using).savepoint()
  126. def savepoint_rollback(sid, using=None):
  127. """
  128. Rolls back the most recent savepoint (if one exists). Does nothing if
  129. savepoints are not supported.
  130. """
  131. get_connection(using).savepoint_rollback(sid)
  132. def savepoint_commit(sid, using=None):
  133. """
  134. Commits the most recent savepoint (if one exists). Does nothing if
  135. savepoints are not supported.
  136. """
  137. get_connection(using).savepoint_commit(sid)
  138. def clean_savepoints(using=None):
  139. """
  140. Resets the counter used to generate unique savepoint ids in this thread.
  141. """
  142. get_connection(using).clean_savepoints()
  143. def get_rollback(using=None):
  144. """
  145. Gets the "needs rollback" flag -- for *advanced use* only.
  146. """
  147. return get_connection(using).get_rollback()
  148. def set_rollback(rollback, using=None):
  149. """
  150. Sets or unsets the "needs rollback" flag -- for *advanced use* only.
  151. When `rollback` is `True`, it triggers a rollback when exiting the
  152. innermost enclosing atomic block that has `savepoint=True` (that's the
  153. default). Use this to force a rollback without raising an exception.
  154. When `rollback` is `False`, it prevents such a rollback. Use this only
  155. after rolling back to a known-good state! Otherwise, you break the atomic
  156. block and data corruption may occur.
  157. """
  158. return get_connection(using).set_rollback(rollback)
  159. #################################
  160. # Decorators / context managers #
  161. #################################
  162. class Atomic(object):
  163. """
  164. This class guarantees the atomic execution of a given block.
  165. An instance can be used either as a decorator or as a context manager.
  166. When it's used as a decorator, __call__ wraps the execution of the
  167. decorated function in the instance itself, used as a context manager.
  168. When it's used as a context manager, __enter__ creates a transaction or a
  169. savepoint, depending on whether a transaction is already in progress, and
  170. __exit__ commits the transaction or releases the savepoint on normal exit,
  171. and rolls back the transaction or to the savepoint on exceptions.
  172. It's possible to disable the creation of savepoints if the goal is to
  173. ensure that some code runs within a transaction without creating overhead.
  174. A stack of savepoints identifiers is maintained as an attribute of the
  175. connection. None denotes the absence of a savepoint.
  176. This allows reentrancy even if the same AtomicWrapper is reused. For
  177. example, it's possible to define `oa = @atomic('other')` and use `@oa` or
  178. `with oa:` multiple times.
  179. Since database connections are thread-local, this is thread-safe.
  180. """
  181. def __init__(self, using, savepoint):
  182. self.using = using
  183. self.savepoint = savepoint
  184. def __enter__(self):
  185. connection = get_connection(self.using)
  186. if not connection.in_atomic_block:
  187. # Reset state when entering an outermost atomic block.
  188. connection.commit_on_exit = True
  189. connection.needs_rollback = False
  190. if not connection.get_autocommit():
  191. # Some database adapters (namely sqlite3) don't handle
  192. # transactions and savepoints properly when autocommit is off.
  193. # Turning autocommit back on isn't an option; it would trigger
  194. # a premature commit. Give up if that happens.
  195. if connection.features.autocommits_when_autocommit_is_off:
  196. raise TransactionManagementError(
  197. "Your database backend doesn't behave properly when "
  198. "autocommit is off. Turn it on before using 'atomic'.")
  199. # When entering an atomic block with autocommit turned off,
  200. # Django should only use savepoints and shouldn't commit.
  201. # This requires at least a savepoint for the outermost block.
  202. if not self.savepoint:
  203. raise TransactionManagementError(
  204. "The outermost 'atomic' block cannot use "
  205. "savepoint = False when autocommit is off.")
  206. # Pretend we're already in an atomic block to bypass the code
  207. # that disables autocommit to enter a transaction, and make a
  208. # note to deal with this case in __exit__.
  209. connection.in_atomic_block = True
  210. connection.commit_on_exit = False
  211. if connection.in_atomic_block:
  212. # We're already in a transaction; create a savepoint, unless we
  213. # were told not to or we're already waiting for a rollback. The
  214. # second condition avoids creating useless savepoints and prevents
  215. # overwriting needs_rollback until the rollback is performed.
  216. if self.savepoint and not connection.needs_rollback:
  217. sid = connection.savepoint()
  218. connection.savepoint_ids.append(sid)
  219. else:
  220. connection.savepoint_ids.append(None)
  221. else:
  222. # We aren't in a transaction yet; create one.
  223. # The usual way to start a transaction is to turn autocommit off.
  224. # However, some database adapters (namely sqlite3) don't handle
  225. # transactions and savepoints properly when autocommit is off.
  226. # In such cases, start an explicit transaction instead, which has
  227. # the side-effect of disabling autocommit.
  228. if connection.features.autocommits_when_autocommit_is_off:
  229. connection._start_transaction_under_autocommit()
  230. connection.autocommit = False
  231. else:
  232. connection.set_autocommit(False)
  233. connection.in_atomic_block = True
  234. def __exit__(self, exc_type, exc_value, traceback):
  235. connection = get_connection(self.using)
  236. if connection.savepoint_ids:
  237. sid = connection.savepoint_ids.pop()
  238. else:
  239. # Prematurely unset this flag to allow using commit or rollback.
  240. connection.in_atomic_block = False
  241. try:
  242. if connection.closed_in_transaction:
  243. # The database will perform a rollback by itself.
  244. # Wait until we exit the outermost block.
  245. pass
  246. elif exc_type is None and not connection.needs_rollback:
  247. if connection.in_atomic_block:
  248. # Release savepoint if there is one
  249. if sid is not None:
  250. try:
  251. connection.savepoint_commit(sid)
  252. except DatabaseError:
  253. try:
  254. connection.savepoint_rollback(sid)
  255. except Error:
  256. # If rolling back to a savepoint fails, mark for
  257. # rollback at a higher level and avoid shadowing
  258. # the original exception.
  259. connection.needs_rollback = True
  260. raise
  261. else:
  262. # Commit transaction
  263. try:
  264. connection.commit()
  265. except DatabaseError:
  266. try:
  267. connection.rollback()
  268. except Error:
  269. # An error during rollback means that something
  270. # went wrong with the connection. Drop it.
  271. connection.close()
  272. raise
  273. else:
  274. # This flag will be set to True again if there isn't a savepoint
  275. # allowing to perform the rollback at this level.
  276. connection.needs_rollback = False
  277. if connection.in_atomic_block:
  278. # Roll back to savepoint if there is one, mark for rollback
  279. # otherwise.
  280. if sid is None:
  281. connection.needs_rollback = True
  282. else:
  283. try:
  284. connection.savepoint_rollback(sid)
  285. except Error:
  286. # If rolling back to a savepoint fails, mark for
  287. # rollback at a higher level and avoid shadowing
  288. # the original exception.
  289. connection.needs_rollback = True
  290. else:
  291. # Roll back transaction
  292. try:
  293. connection.rollback()
  294. except Error:
  295. # An error during rollback means that something
  296. # went wrong with the connection. Drop it.
  297. connection.close()
  298. finally:
  299. # Outermost block exit when autocommit was enabled.
  300. if not connection.in_atomic_block:
  301. if connection.closed_in_transaction:
  302. connection.connection = None
  303. elif connection.features.autocommits_when_autocommit_is_off:
  304. connection.autocommit = True
  305. else:
  306. connection.set_autocommit(True)
  307. # Outermost block exit when autocommit was disabled.
  308. elif not connection.savepoint_ids and not connection.commit_on_exit:
  309. if connection.closed_in_transaction:
  310. connection.connection = None
  311. else:
  312. connection.in_atomic_block = False
  313. def __call__(self, func):
  314. @wraps(func, assigned=available_attrs(func))
  315. def inner(*args, **kwargs):
  316. with self:
  317. return func(*args, **kwargs)
  318. return inner
  319. def atomic(using=None, savepoint=True):
  320. # Bare decorator: @atomic -- although the first argument is called
  321. # `using`, it's actually the function being decorated.
  322. if callable(using):
  323. return Atomic(DEFAULT_DB_ALIAS, savepoint)(using)
  324. # Decorator: @atomic(...) or context manager: with atomic(...): ...
  325. else:
  326. return Atomic(using, savepoint)
  327. def _non_atomic_requests(view, using):
  328. try:
  329. view._non_atomic_requests.add(using)
  330. except AttributeError:
  331. view._non_atomic_requests = set([using])
  332. return view
  333. def non_atomic_requests(using=None):
  334. if callable(using):
  335. return _non_atomic_requests(using, DEFAULT_DB_ALIAS)
  336. else:
  337. if using is None:
  338. using = DEFAULT_DB_ALIAS
  339. return lambda view: _non_atomic_requests(view, using)
  340. ############################################
  341. # Deprecated decorators / context managers #
  342. ############################################
  343. class Transaction(object):
  344. """
  345. Acts as either a decorator, or a context manager. If it's a decorator it
  346. takes a function and returns a wrapped function. If it's a contextmanager
  347. it's used with the ``with`` statement. In either event entering/exiting
  348. are called before and after, respectively, the function/block is executed.
  349. autocommit, commit_on_success, and commit_manually contain the
  350. implementations of entering and exiting.
  351. """
  352. def __init__(self, entering, exiting, using):
  353. self.entering = entering
  354. self.exiting = exiting
  355. self.using = using
  356. def __enter__(self):
  357. self.entering(self.using)
  358. def __exit__(self, exc_type, exc_value, traceback):
  359. self.exiting(exc_type, self.using)
  360. def __call__(self, func):
  361. @wraps(func)
  362. def inner(*args, **kwargs):
  363. with self:
  364. return func(*args, **kwargs)
  365. return inner
  366. def _transaction_func(entering, exiting, using):
  367. """
  368. Takes 3 things, an entering function (what to do to start this block of
  369. transaction management), an exiting function (what to do to end it, on both
  370. success and failure, and using which can be: None, indiciating using is
  371. DEFAULT_DB_ALIAS, a callable, indicating that using is DEFAULT_DB_ALIAS and
  372. to return the function already wrapped.
  373. Returns either a Transaction objects, which is both a decorator and a
  374. context manager, or a wrapped function, if using is a callable.
  375. """
  376. # Note that although the first argument is *called* `using`, it
  377. # may actually be a function; @autocommit and @autocommit('foo')
  378. # are both allowed forms.
  379. if using is None:
  380. using = DEFAULT_DB_ALIAS
  381. if callable(using):
  382. return Transaction(entering, exiting, DEFAULT_DB_ALIAS)(using)
  383. return Transaction(entering, exiting, using)
  384. def autocommit(using=None):
  385. """
  386. Decorator that activates commit on save. This is Django's default behavior;
  387. this decorator is useful if you globally activated transaction management in
  388. your settings file and want the default behavior in some view functions.
  389. """
  390. warnings.warn("autocommit is deprecated in favor of set_autocommit.",
  391. PendingDeprecationWarning, stacklevel=2)
  392. def entering(using):
  393. enter_transaction_management(managed=False, using=using)
  394. def exiting(exc_type, using):
  395. leave_transaction_management(using=using)
  396. return _transaction_func(entering, exiting, using)
  397. def commit_on_success(using=None):
  398. """
  399. This decorator activates commit on response. This way, if the view function
  400. runs successfully, a commit is made; if the viewfunc produces an exception,
  401. a rollback is made. This is one of the most common ways to do transaction
  402. control in Web apps.
  403. """
  404. warnings.warn("commit_on_success is deprecated in favor of atomic.",
  405. PendingDeprecationWarning, stacklevel=2)
  406. def entering(using):
  407. enter_transaction_management(using=using)
  408. def exiting(exc_type, using):
  409. try:
  410. if exc_type is not None:
  411. if is_dirty(using=using):
  412. rollback(using=using)
  413. else:
  414. if is_dirty(using=using):
  415. try:
  416. commit(using=using)
  417. except:
  418. rollback(using=using)
  419. raise
  420. finally:
  421. leave_transaction_management(using=using)
  422. return _transaction_func(entering, exiting, using)
  423. def commit_manually(using=None):
  424. """
  425. Decorator that activates manual transaction control. It just disables
  426. automatic transaction control and doesn't do any commit/rollback of its
  427. own -- it's up to the user to call the commit and rollback functions
  428. themselves.
  429. """
  430. warnings.warn("commit_manually is deprecated in favor of set_autocommit.",
  431. PendingDeprecationWarning, stacklevel=2)
  432. def entering(using):
  433. enter_transaction_management(using=using)
  434. def exiting(exc_type, using):
  435. leave_transaction_management(using=using)
  436. return _transaction_func(entering, exiting, using)
  437. def commit_on_success_unless_managed(using=None, savepoint=False):
  438. """
  439. Transitory API to preserve backwards-compatibility while refactoring.
  440. Once the legacy transaction management is fully deprecated, this should
  441. simply be replaced by atomic. Until then, it's necessary to guarantee that
  442. a commit occurs on exit, which atomic doesn't do when it's nested.
  443. Unlike atomic, savepoint defaults to False because that's closer to the
  444. legacy behavior.
  445. """
  446. connection = get_connection(using)
  447. if connection.get_autocommit() or connection.in_atomic_block:
  448. return atomic(using, savepoint)
  449. else:
  450. def entering(using):
  451. pass
  452. def exiting(exc_type, using):
  453. set_dirty(using=using)
  454. return _transaction_func(entering, exiting, using)