engine.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. from .. import util
  2. from ..engine import Connection as _LegacyConnection
  3. from ..engine import create_engine as _create_engine
  4. from ..engine import Engine as _LegacyEngine
  5. from ..engine.base import OptionEngineMixin
  6. NO_OPTIONS = util.immutabledict()
  7. def create_engine(*arg, **kw):
  8. """Create a new :class:`_future.Engine` instance.
  9. Arguments passed to :func:`_future.create_engine` are mostly identical
  10. to those passed to the 1.x :func:`_sa.create_engine` function.
  11. The difference is that the object returned is the :class:`._future.Engine`
  12. which has the 2.0 version of the API.
  13. """
  14. kw["_future_engine_class"] = Engine
  15. return _create_engine(*arg, **kw)
  16. class Connection(_LegacyConnection):
  17. """Provides high-level functionality for a wrapped DB-API connection.
  18. The :class:`_future.Connection` object is procured by calling
  19. the :meth:`_future.Engine.connect` method of the :class:`_future.Engine`
  20. object, and provides services for execution of SQL statements as well
  21. as transaction control.
  22. **This is the SQLAlchemy 2.0 version** of the :class:`_engine.Connection`
  23. class. The API and behavior of this object is largely the same, with the
  24. following differences in behavior:
  25. * The result object returned for results is the
  26. :class:`_engine.CursorResult`
  27. object, which is a subclass of the :class:`_engine.Result`.
  28. This object has a slightly different API and behavior than the
  29. :class:`_engine.LegacyCursorResult` returned for 1.x style usage.
  30. * The object has :meth:`_future.Connection.commit` and
  31. :meth:`_future.Connection.rollback` methods which commit or roll back
  32. the current transaction in progress, if any.
  33. * The object features "autobegin" behavior, such that any call to
  34. :meth:`_future.Connection.execute` will
  35. unconditionally start a
  36. transaction which can be controlled using the above mentioned
  37. :meth:`_future.Connection.commit` and
  38. :meth:`_future.Connection.rollback` methods.
  39. * The object does not have any "autocommit" functionality. Any SQL
  40. statement or DDL statement will not be followed by any COMMIT until
  41. the transaction is explicitly committed, either via the
  42. :meth:`_future.Connection.commit` method, or if the connection is
  43. being used in a context manager that commits such as the one
  44. returned by :meth:`_future.Engine.begin`.
  45. * The SAVEPOINT method :meth:`_future.Connection.begin_nested` returns
  46. a :class:`_engine.NestedTransaction` as was always the case, and the
  47. savepoint can be controlled by invoking
  48. :meth:`_engine.NestedTransaction.commit` or
  49. :meth:`_engine.NestedTransaction.rollback` as was the case before.
  50. However, this savepoint "transaction" is not associated with the
  51. transaction that is controlled by the connection itself; the overall
  52. transaction can be committed or rolled back directly which will not emit
  53. any special instructions for the SAVEPOINT (this will typically have the
  54. effect that one desires).
  55. * The :class:`_future.Connection` object does not support "branching",
  56. which was a pattern by which a sub "connection" would be used that
  57. refers to this connection as a parent.
  58. """
  59. _is_future = True
  60. def _branch(self):
  61. raise NotImplementedError(
  62. "sqlalchemy.future.Connection does not support "
  63. "'branching' of new connections."
  64. )
  65. def begin(self):
  66. """Begin a transaction prior to autobegin occurring.
  67. The returned object is an instance of :class:`_engine.RootTransaction`.
  68. This object represents the "scope" of the transaction,
  69. which completes when either the :meth:`_engine.Transaction.rollback`
  70. or :meth:`_engine.Transaction.commit` method is called.
  71. The :meth:`_future.Connection.begin` method in SQLAlchemy 2.0 begins a
  72. transaction that normally will be begun in any case when the connection
  73. is first used to execute a statement. The reason this method might be
  74. used would be to invoke the :meth:`_events.ConnectionEvents.begin`
  75. event at a specific time, or to organize code within the scope of a
  76. connection checkout in terms of context managed blocks, such as::
  77. with engine.connect() as conn:
  78. with conn.begin():
  79. conn.execute(...)
  80. conn.execute(...)
  81. with conn.begin():
  82. conn.execute(...)
  83. conn.execute(...)
  84. The above code is not fundamentally any different in its behavior than
  85. the following code which does not use
  86. :meth:`_future.Connection.begin`; the below style is referred towards
  87. as "commit as you go" style::
  88. with engine.connect() as conn:
  89. conn.execute(...)
  90. conn.execute(...)
  91. conn.commit()
  92. conn.execute(...)
  93. conn.execute(...)
  94. conn.commit()
  95. From a database point of view, the :meth:`_future.Connection.begin`
  96. method does not emit any SQL or change the state of the underlying
  97. DBAPI connection in any way; the Python DBAPI does not have any
  98. concept of explicit transaction begin.
  99. .. seealso::
  100. :ref:`tutorial_working_with_transactions` - in the
  101. :ref:`unified_tutorial`
  102. :meth:`_future.Connection.begin_nested` - use a SAVEPOINT
  103. :meth:`_engine.Connection.begin_twophase` -
  104. use a two phase /XID transaction
  105. :meth:`_future.Engine.begin` - context manager available from
  106. :class:`_future.Engine`
  107. """
  108. return super(Connection, self).begin()
  109. def begin_nested(self):
  110. """Begin a nested transaction (i.e. SAVEPOINT) and return a transaction
  111. handle.
  112. The returned object is an instance of
  113. :class:`_engine.NestedTransaction`.
  114. Nested transactions require SAVEPOINT support in the
  115. underlying database. Any transaction in the hierarchy may
  116. ``commit`` and ``rollback``, however the outermost transaction
  117. still controls the overall ``commit`` or ``rollback`` of the
  118. transaction of a whole.
  119. If an outer :class:`.RootTransaction` is not present on this
  120. :class:`_future.Connection`, a new one is created using "autobegin".
  121. This outer transaction may be completed using "commit-as-you-go" style
  122. usage, by calling upon :meth:`_future.Connection.commit` or
  123. :meth:`_future.Connection.rollback`.
  124. .. tip::
  125. The "autobegin" behavior of :meth:`_future.Connection.begin_nested`
  126. is specific to :term:`2.0 style` use; for legacy behaviors, see
  127. :meth:`_engine.Connection.begin_nested`.
  128. The :class:`_engine.NestedTransaction` remains independent of the
  129. :class:`_future.Connection` object itself. Calling the
  130. :meth:`_future.Connection.commit` or
  131. :meth:`_future.Connection.rollback` will always affect the actual
  132. containing database transaction itself, and not the SAVEPOINT itself.
  133. When a database transaction is committed, any SAVEPOINTs that have been
  134. established are cleared and the data changes within their scope is also
  135. committed.
  136. .. seealso::
  137. :meth:`_future.Connection.begin`
  138. """
  139. return super(Connection, self).begin_nested()
  140. def commit(self):
  141. """Commit the transaction that is currently in progress.
  142. This method commits the current transaction if one has been started.
  143. If no transaction was started, the method has no effect, assuming
  144. the connection is in a non-invalidated state.
  145. A transaction is begun on a :class:`_future.Connection` automatically
  146. whenever a statement is first executed, or when the
  147. :meth:`_future.Connection.begin` method is called.
  148. .. note:: The :meth:`_future.Connection.commit` method only acts upon
  149. the primary database transaction that is linked to the
  150. :class:`_future.Connection` object. It does not operate upon a
  151. SAVEPOINT that would have been invoked from the
  152. :meth:`_future.Connection.begin_nested` method; for control of a
  153. SAVEPOINT, call :meth:`_engine.NestedTransaction.commit` on the
  154. :class:`_engine.NestedTransaction` that is returned by the
  155. :meth:`_future.Connection.begin_nested` method itself.
  156. """
  157. if self._transaction:
  158. self._transaction.commit()
  159. def rollback(self):
  160. """Roll back the transaction that is currently in progress.
  161. This method rolls back the current transaction if one has been started.
  162. If no transaction was started, the method has no effect. If a
  163. transaction was started and the connection is in an invalidated state,
  164. the transaction is cleared using this method.
  165. A transaction is begun on a :class:`_future.Connection` automatically
  166. whenever a statement is first executed, or when the
  167. :meth:`_future.Connection.begin` method is called.
  168. .. note:: The :meth:`_future.Connection.rollback` method only acts
  169. upon the primary database transaction that is linked to the
  170. :class:`_future.Connection` object. It does not operate upon a
  171. SAVEPOINT that would have been invoked from the
  172. :meth:`_future.Connection.begin_nested` method; for control of a
  173. SAVEPOINT, call :meth:`_engine.NestedTransaction.rollback` on the
  174. :class:`_engine.NestedTransaction` that is returned by the
  175. :meth:`_future.Connection.begin_nested` method itself.
  176. """
  177. if self._transaction:
  178. self._transaction.rollback()
  179. def close(self):
  180. """Close this :class:`_future.Connection`.
  181. This has the effect of also calling :meth:`_future.Connection.rollback`
  182. if any transaction is in place.
  183. """
  184. super(Connection, self).close()
  185. def execute(self, statement, parameters=None, execution_options=None):
  186. r"""Executes a SQL statement construct and returns a
  187. :class:`_engine.Result`.
  188. :param statement: The statement to be executed. This is always
  189. an object that is in both the :class:`_expression.ClauseElement` and
  190. :class:`_expression.Executable` hierarchies, including:
  191. * :class:`_expression.Select`
  192. * :class:`_expression.Insert`, :class:`_expression.Update`,
  193. :class:`_expression.Delete`
  194. * :class:`_expression.TextClause` and
  195. :class:`_expression.TextualSelect`
  196. * :class:`_schema.DDL` and objects which inherit from
  197. :class:`_schema.DDLElement`
  198. :param parameters: parameters which will be bound into the statement.
  199. This may be either a dictionary of parameter names to values,
  200. or a mutable sequence (e.g. a list) of dictionaries. When a
  201. list of dictionaries is passed, the underlying statement execution
  202. will make use of the DBAPI ``cursor.executemany()`` method.
  203. When a single dictionary is passed, the DBAPI ``cursor.execute()``
  204. method will be used.
  205. :param execution_options: optional dictionary of execution options,
  206. which will be associated with the statement execution. This
  207. dictionary can provide a subset of the options that are accepted
  208. by :meth:`_future.Connection.execution_options`.
  209. :return: a :class:`_engine.Result` object.
  210. """
  211. return self._execute_20(
  212. statement, parameters, execution_options or NO_OPTIONS
  213. )
  214. def scalar(self, statement, parameters=None, execution_options=None):
  215. r"""Executes a SQL statement construct and returns a scalar object.
  216. This method is shorthand for invoking the
  217. :meth:`_engine.Result.scalar` method after invoking the
  218. :meth:`_future.Connection.execute` method. Parameters are equivalent.
  219. :return: a scalar Python value representing the first column of the
  220. first row returned.
  221. """
  222. return self.execute(statement, parameters, execution_options).scalar()
  223. class Engine(_LegacyEngine):
  224. """Connects a :class:`_pool.Pool` and
  225. :class:`_engine.Dialect` together to provide a
  226. source of database connectivity and behavior.
  227. **This is the SQLAlchemy 2.0 version** of the :class:`~.engine.Engine`.
  228. An :class:`.future.Engine` object is instantiated publicly using the
  229. :func:`~sqlalchemy.future.create_engine` function.
  230. .. seealso::
  231. :doc:`/core/engines`
  232. :ref:`connections_toplevel`
  233. """
  234. _connection_cls = Connection
  235. _is_future = True
  236. def _not_implemented(self, *arg, **kw):
  237. raise NotImplementedError(
  238. "This method is not implemented for SQLAlchemy 2.0."
  239. )
  240. transaction = (
  241. run_callable
  242. ) = (
  243. execute
  244. ) = (
  245. scalar
  246. ) = (
  247. _execute_clauseelement
  248. ) = _execute_compiled = table_names = has_table = _not_implemented
  249. def _run_ddl_visitor(self, visitorcallable, element, **kwargs):
  250. # TODO: this is for create_all support etc. not clear if we
  251. # want to provide this in 2.0, that is, a way to execute SQL where
  252. # they aren't calling "engine.begin()" explicitly, however, DDL
  253. # may be a special case for which we want to continue doing it this
  254. # way. A big win here is that the full DDL sequence is inside of a
  255. # single transaction rather than COMMIT for each statement.
  256. with self.begin() as conn:
  257. conn._run_ddl_visitor(visitorcallable, element, **kwargs)
  258. @classmethod
  259. def _future_facade(self, legacy_engine):
  260. return Engine(
  261. legacy_engine.pool,
  262. legacy_engine.dialect,
  263. legacy_engine.url,
  264. logging_name=legacy_engine.logging_name,
  265. echo=legacy_engine.echo,
  266. hide_parameters=legacy_engine.hide_parameters,
  267. execution_options=legacy_engine._execution_options,
  268. )
  269. @util.contextmanager
  270. def begin(self):
  271. """Return a :class:`_future.Connection` object with a transaction
  272. begun.
  273. Use of this method is similar to that of
  274. :meth:`_future.Engine.connect`, typically as a context manager, which
  275. will automatically maintain the state of the transaction when the block
  276. ends, either by calling :meth:`_future.Connection.commit` when the
  277. block succeeds normally, or :meth:`_future.Connection.rollback` when an
  278. exception is raised, before propagating the exception outwards::
  279. with engine.begin() as connection:
  280. connection.execute(text("insert into table values ('foo')"))
  281. .. seealso::
  282. :meth:`_future.Engine.connect`
  283. :meth:`_future.Connection.begin`
  284. """
  285. with self.connect() as conn:
  286. with conn.begin():
  287. yield conn
  288. def connect(self):
  289. """Return a new :class:`_future.Connection` object.
  290. The :class:`_future.Connection` acts as a Python context manager, so
  291. the typical use of this method looks like::
  292. with engine.connect() as connection:
  293. connection.execute(text("insert into table values ('foo')"))
  294. connection.commit()
  295. Where above, after the block is completed, the connection is "closed"
  296. and its underlying DBAPI resources are returned to the connection pool.
  297. This also has the effect of rolling back any transaction that
  298. was explicitly begun or was begun via autobegin, and will
  299. emit the :meth:`_events.ConnectionEvents.rollback` event if one was
  300. started and is still in progress.
  301. .. seealso::
  302. :meth:`_future.Engine.begin`
  303. """
  304. return super(Engine, self).connect()
  305. class OptionEngine(OptionEngineMixin, Engine):
  306. pass
  307. Engine._option_cls = OptionEngine