You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
7.5KB

  1. # engine/util.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. from .. import exc
  8. from .. import util
  9. from ..util import collections_abc
  10. from ..util import immutabledict
  11. def connection_memoize(key):
  12. """Decorator, memoize a function in a connection.info stash.
  13. Only applicable to functions which take no arguments other than a
  14. connection. The memo will be stored in ``connection.info[key]``.
  15. """
  16. @util.decorator
  17. def decorated(fn, self, connection):
  18. connection = connection.connect()
  19. try:
  20. return connection.info[key]
  21. except KeyError:
  22. connection.info[key] = val = fn(self, connection)
  23. return val
  24. return decorated
  25. _no_tuple = ()
  26. _no_kw = util.immutabledict()
  27. def _distill_params(connection, multiparams, params):
  28. r"""Given arguments from the calling form \*multiparams, \**params,
  29. return a list of bind parameter structures, usually a list of
  30. dictionaries.
  31. In the case of 'raw' execution which accepts positional parameters,
  32. it may be a list of tuples or lists.
  33. """
  34. if not multiparams:
  35. if params:
  36. connection._warn_for_legacy_exec_format()
  37. return [params]
  38. else:
  39. return []
  40. elif len(multiparams) == 1:
  41. zero = multiparams[0]
  42. if isinstance(zero, (list, tuple)):
  43. if (
  44. not zero
  45. or hasattr(zero[0], "__iter__")
  46. and not hasattr(zero[0], "strip")
  47. ):
  48. # execute(stmt, [{}, {}, {}, ...])
  49. # execute(stmt, [(), (), (), ...])
  50. return zero
  51. else:
  52. # this is used by exec_driver_sql only, so a deprecation
  53. # warning would already be coming from passing a plain
  54. # textual statement with positional parameters to
  55. # execute().
  56. # execute(stmt, ("value", "value"))
  57. return [zero]
  58. elif hasattr(zero, "keys"):
  59. # execute(stmt, {"key":"value"})
  60. return [zero]
  61. else:
  62. connection._warn_for_legacy_exec_format()
  63. # execute(stmt, "value")
  64. return [[zero]]
  65. else:
  66. connection._warn_for_legacy_exec_format()
  67. if hasattr(multiparams[0], "__iter__") and not hasattr(
  68. multiparams[0], "strip"
  69. ):
  70. return multiparams
  71. else:
  72. return [multiparams]
  73. def _distill_cursor_params(connection, multiparams, params):
  74. """_distill_params without any warnings. more appropriate for
  75. "cursor" params that can include tuple arguments, lists of tuples,
  76. etc.
  77. """
  78. if not multiparams:
  79. if params:
  80. return [params]
  81. else:
  82. return []
  83. elif len(multiparams) == 1:
  84. zero = multiparams[0]
  85. if isinstance(zero, (list, tuple)):
  86. if (
  87. not zero
  88. or hasattr(zero[0], "__iter__")
  89. and not hasattr(zero[0], "strip")
  90. ):
  91. # execute(stmt, [{}, {}, {}, ...])
  92. # execute(stmt, [(), (), (), ...])
  93. return zero
  94. else:
  95. # this is used by exec_driver_sql only, so a deprecation
  96. # warning would already be coming from passing a plain
  97. # textual statement with positional parameters to
  98. # execute().
  99. # execute(stmt, ("value", "value"))
  100. return [zero]
  101. elif hasattr(zero, "keys"):
  102. # execute(stmt, {"key":"value"})
  103. return [zero]
  104. else:
  105. # execute(stmt, "value")
  106. return [[zero]]
  107. else:
  108. if hasattr(multiparams[0], "__iter__") and not hasattr(
  109. multiparams[0], "strip"
  110. ):
  111. return multiparams
  112. else:
  113. return [multiparams]
  114. def _distill_params_20(params):
  115. if params is None:
  116. return _no_tuple, _no_kw
  117. elif isinstance(params, list):
  118. # collections_abc.MutableSequence): # avoid abc.__instancecheck__
  119. if params and not isinstance(
  120. params[0], (collections_abc.Mapping, tuple)
  121. ):
  122. raise exc.ArgumentError(
  123. "List argument must consist only of tuples or dictionaries"
  124. )
  125. return (params,), _no_kw
  126. elif isinstance(
  127. params,
  128. (tuple, dict, immutabledict),
  129. # avoid abc.__instancecheck__
  130. # (collections_abc.Sequence, collections_abc.Mapping),
  131. ):
  132. return (params,), _no_kw
  133. else:
  134. raise exc.ArgumentError("mapping or sequence expected for parameters")
  135. class TransactionalContext(object):
  136. """Apply Python context manager behavior to transaction objects.
  137. Performs validation to ensure the subject of the transaction is not
  138. used if the transaction were ended prematurely.
  139. """
  140. _trans_subject = None
  141. def _transaction_is_active(self):
  142. raise NotImplementedError()
  143. def _transaction_is_closed(self):
  144. raise NotImplementedError()
  145. def _get_subject(self):
  146. raise NotImplementedError()
  147. @classmethod
  148. def _trans_ctx_check(cls, subject):
  149. trans_context = subject._trans_context_manager
  150. if trans_context:
  151. if not trans_context._transaction_is_active():
  152. raise exc.InvalidRequestError(
  153. "Can't operate on closed transaction inside context "
  154. "manager. Please complete the context manager "
  155. "before emitting further commands."
  156. )
  157. def __enter__(self):
  158. subject = self._get_subject()
  159. # none for outer transaction, may be non-None for nested
  160. # savepoint, legacy nesting cases
  161. trans_context = subject._trans_context_manager
  162. self._outer_trans_ctx = trans_context
  163. self._trans_subject = subject
  164. subject._trans_context_manager = self
  165. return self
  166. def __exit__(self, type_, value, traceback):
  167. subject = self._trans_subject
  168. # simplistically we could assume that
  169. # "subject._trans_context_manager is self". However, any calling
  170. # code that is manipulating __exit__ directly would break this
  171. # assumption. alembic context manager
  172. # is an example of partial use that just calls __exit__ and
  173. # not __enter__ at the moment. it's safe to assume this is being done
  174. # in the wild also
  175. out_of_band_exit = (
  176. subject is None or subject._trans_context_manager is not self
  177. )
  178. if type_ is None and self._transaction_is_active():
  179. try:
  180. self.commit()
  181. except:
  182. with util.safe_reraise():
  183. self.rollback()
  184. finally:
  185. if not out_of_band_exit:
  186. subject._trans_context_manager = self._outer_trans_ctx
  187. self._trans_subject = self._outer_trans_ctx = None
  188. else:
  189. try:
  190. if not self._transaction_is_active():
  191. if not self._transaction_is_closed():
  192. self.close()
  193. else:
  194. self.rollback()
  195. finally:
  196. if not out_of_band_exit:
  197. subject._trans_context_manager = self._outer_trans_ctx
  198. self._trans_subject = self._outer_trans_ctx = None