U a@sXddlmZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z d d l m Z d d l m Z d d l mZd d l mZd dlmZd d lmZeZGdddeZGdddeZGddde ZGdddeZGdddeZGdddeZGdddeZGdddeejZGdd d eZGd!d"d"eeZee_ dS)#)with_statementN) Connectable)ExceptionContext)_distill_params)_distill_params_20)TransactionalContext)exc) inspection)log)util)compilerc@seZdZdZdZdZdZdddZej dd Z d d Z d d Z e ddZddZddZddZddZddZddZddZe ddZe d d!Ze d"d#Zd$d%Ze d&d'Zd(d)Zd*d+Ze d,d-Ze d.d/Zed0dd1d2Z dd3d4Z!d5d6Z"d7d8Z#d9d:Z$d;d<Z%dd=d>Z&d?d@Z'ddAdBZ(ddCdDZ)dEdFZ*dGdHZ+dIdJZ,dKdLZ-dMdNZ.dOdPZ/dQdRZ0ddSdTZ1ddUdVZ2dWdXZ3dYdZZ4d[d\Z5d]d^Z6d_d`Z7dadbZ8dcddZ9dedfZ:dgdhZ;didjZe?fdodpZ@dqdrZAdsdtZBdudvZCe?fdwdxZDdydzZEde?fd{d|ZFdd}d~ZGddZHdddZIddZJdZKdZLddZMeNddZOddZPeQddddZReQddddZSdS) ConnectionaProvides high-level functionality for a wrapped DB-API connection. **This is the SQLAlchemy 1.x.x version** of the :class:`_engine.Connection` class. For the :term:`2.0 style` version, which features some API differences, see :class:`_future.Connection`. The :class:`_engine.Connection` object is procured by calling the :meth:`_engine.Engine.connect` method of the :class:`_engine.Engine` object, and provides services for execution of SQL statements as well as transaction control. The Connection object is **not** thread-safe. While a Connection can be shared among threads using properly synchronized access, it is still possible that the underlying DBAPI connection may not support shared access between threads. Check the DBAPI documentation for details. The Connection object represents a single DBAPI connection checked out from the connection pool. In this state, the connection pool has no affect upon the connection, including its expiration or timeout state. For the connection pool to properly manage connections, connections should be returned to the connection pool (i.e. ``connection.close()``) whenever the connection is not in use. .. index:: single: thread safety; Connection Fzsqlalchemy.engine.ConnectionNTc Cs||_|j|_||_|rP|jdks&t||_||_|j|_d|_||_|j |_ n|dk r\|n| |_d|_ |_ d|_ d|_||_||_|j|_|dkr|j|j|_|p|dko|j |_ |rt|j|_|j s|jj r|j||dk dS)zConstruct a new Connection.NFr)enginedialect_Connection__branch_fromAssertionError_dbapi_connection_execution_options_echoshould_close_with_resultdispatch _has_eventsraw_connection _transaction_nested_transaction_Connection__savepoint_seq_Connection__in_begin_Connection__can_reconnect_should_log_info_joinZengine_connect) selfr connectionclose_with_result _branch_fromr _dispatchrZ_allow_revalidater'WC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\engine\base.py__init__Cs<     zConnection.__init__cs(d|jkr |jdfddSdSdS)NZ logging_tokencs d|fS)Nz[%s] %sr')msgtokenr'r(~z/Connection._message_formatter..rr"r'r+r(_message_formatterzs   zConnection._message_formattercOs,|j}|r||}|jjj|f||dSN)r1rloggerinfor"messageargkwfmtr'r'r( _log_infoszConnection._log_infocOs,|j}|r||}|jjj|f||dSr2)r1rr3debugr5r'r'r( _log_debugszConnection._log_debugcCs|jddS)Nschema_translate_maprgetr0r'r'r(_schema_translate_mapsz Connection._schema_translate_mapcCs6|j}|jdd}|r.||kr.|jr.||S|SdS)ztReturn the schema name for the given schema item taking into account current schema translate map. r=N)schemarr?Z_use_schema_map)r"objnamer=r'r'r(schema_for_objectszConnection.schema_for_objectcCs.|jj|j|j|jr|jn||j|j|jdS)azReturn a new Connection which references this Connection's engine and connection; but does not have close_with_result enabled, and also whose close() method does nothing. .. deprecated:: 1.4 the "branching" concept will be removed in SQLAlchemy 2.0 as well as the "Connection.connect()" method which is the only consumer for this. The Core uses this very sparingly, only in the case of custom SQL default functions that are to be INSERTed as the primary key of a row where we need to get the value back, so we have to invoke it distinctly - this is a very uncommon case. Userland code accesses _branch() when the connect() method is called. The branched connection acts as much as possible like the parent, except that it stays connected when a close() event occurs. )r%rrr&)r_connection_clsrrrrrr0r'r'r(_branchszConnection._branchcCs,|jr |S|j|j}|j|_|SdS)z@define connection method chaining behavior for execution_optionsN) _is_future __class____new____dict__copy)r"cr'r'r(_generate_for_optionss  z Connection._generate_for_optionscCs|Sr2r'r0r'r'r( __enter__szConnection.__enter__cCs |dSr2)closer"type_value tracebackr'r'r(__exit__szConnection.__exit__cKsD|}|j||_|js$|jjr2|j|||j|||S)ac Set non-SQL options for the connection which take effect during execution. For a "future" style connection, this method returns this same :class:`_future.Connection` object with the new options added. For a legacy connection, this method returns a copy of this :class:`_engine.Connection` which references the same underlying DBAPI connection, but also defines the given execution options which will take effect for a call to :meth:`execute`. As the new :class:`_engine.Connection` references the same underlying resource, it's usually a good idea to ensure that the copies will be discarded immediately, which is implicit if used as in:: result = connection.execution_options(stream_results=True).\ execute(stmt) Note that any key/value can be passed to :meth:`_engine.Connection.execution_options`, and it will be stored in the ``_execution_options`` dictionary of the :class:`_engine.Connection`. It is suitable for usage by end-user schemes to communicate with event listeners, for example. The keywords that are currently recognized by SQLAlchemy itself include all those listed under :meth:`.Executable.execution_options`, as well as others that are specific to :class:`_engine.Connection`. :param autocommit: Available on: Connection, statement. When True, a COMMIT will be invoked after execution when executed in 'autocommit' mode, i.e. when an explicit transaction is not begun on the connection. Note that this is **library level, not DBAPI level autocommit**. The DBAPI connection will remain in a real transaction unless the "AUTOCOMMIT" isolation level is used. .. deprecated:: 1.4 The "autocommit" execution option is deprecated and will be removed in SQLAlchemy 2.0. See :ref:`migration_20_autocommit` for discussion. :param compiled_cache: Available on: Connection. A dictionary where :class:`.Compiled` objects will be cached when the :class:`_engine.Connection` compiles a clause expression into a :class:`.Compiled` object. This dictionary will supersede the statement cache that may be configured on the :class:`_engine.Engine` itself. If set to None, caching is disabled, even if the engine has a configured cache size. Note that the ORM makes use of its own "compiled" caches for some operations, including flush operations. The caching used by the ORM internally supersedes a cache dictionary specified here. :param logging_token: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. Adds the specified string token surrounded by brackets in log messages logged by the connection, i.e. the logging that's enabled either via the :paramref:`_sa.create_engine.echo` flag or via the ``logging.getLogger("sqlalchemy.engine")`` logger. This allows a per-connection or per-sub-engine token to be available which is useful for debugging concurrent connection scenarios. .. versionadded:: 1.4.0b2 .. seealso:: :ref:`dbengine_logging_tokens` - usage example :paramref:`_sa.create_engine.logging_name` - adds a name to the name used by the Python logger object itself. :param isolation_level: Available on: :class:`_engine.Connection`. Set the transaction isolation level for the lifespan of this :class:`_engine.Connection` object. Valid values include those string values accepted by the :paramref:`_sa.create_engine.isolation_level` parameter passed to :func:`_sa.create_engine`. These levels are semi-database specific; see individual dialect documentation for valid levels. The isolation level option applies the isolation level by emitting statements on the DBAPI connection, and **necessarily affects the original Connection object overall**, not just the copy that is returned by the call to :meth:`_engine.Connection.execution_options` method. The isolation level will remain at the given setting until the DBAPI connection itself is returned to the connection pool, i.e. the :meth:`_engine.Connection.close` method on the original :class:`_engine.Connection` is called, where an event handler will emit additional statements on the DBAPI connection in order to revert the isolation level change. .. warning:: The ``isolation_level`` execution option should **not** be used when a transaction is already established, that is, the :meth:`_engine.Connection.begin` method or similar has been called. A database cannot change the isolation level on a transaction in progress, and different DBAPIs and/or SQLAlchemy dialects may implicitly roll back or commit the transaction, or not affect the connection at all. .. note:: The ``isolation_level`` execution option is implicitly reset if the :class:`_engine.Connection` is invalidated, e.g. via the :meth:`_engine.Connection.invalidate` method, or if a disconnection error occurs. The new connection produced after the invalidation will not have the isolation level re-applied to it automatically. .. seealso:: :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :meth:`_engine.Connection.get_isolation_level` - view current level :ref:`SQLite Transaction Isolation ` :ref:`PostgreSQL Transaction Isolation ` :ref:`MySQL Transaction Isolation ` :ref:`SQL Server Transaction Isolation ` :ref:`session_transaction_isolation` - for the ORM :param no_parameters: When ``True``, if the final parameter list or dictionary is totally empty, will invoke the statement on the cursor as ``cursor.execute(statement)``, not passing the parameter collection at all. Some DBAPIs such as psycopg2 and mysql-python consider percent signs as significant only when parameters are present; this option allows code to generate SQL containing percent signs (and possibly other characters) that is neutral regarding whether it's executed by the DBAPI or piped into a script that's later invoked by command line tools. :param stream_results: Available on: Connection, statement. Indicate to the dialect that results should be "streamed" and not pre-buffered, if possible. This is a limitation of many DBAPIs. The flag is currently understood within a subset of dialects within the PostgreSQL and MySQL categories, and may be supported by other third party dialects as well. .. seealso:: :ref:`engine_stream_results` :param schema_translate_map: Available on: Connection, Engine. A dictionary mapping schema names to schema names, that will be applied to the :paramref:`_schema.Table.schema` element of each :class:`_schema.Table` encountered when SQL or DDL expression elements are compiled into strings; the resulting schema name will be converted based on presence in the map of the original name. .. versionadded:: 1.1 .. seealso:: :ref:`schema_translating` .. seealso:: :meth:`_engine.Engine.execution_options` :meth:`.Executable.execution_options` :meth:`_engine.Connection.get_execution_options` )rMrunionrrrZ set_connection_execution_optionsr)r"optrLr'r'r(execution_optionss4zConnection.execution_optionscCs|jS)zGet the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`_engine.Connection.execution_options` r/r0r'r'r(get_execution_optionss z Connection.get_execution_optionscCs|jdko|j S)z)Return True if this connection is closed.N)rrr0r'r'r(closedszConnection.closedcCs |jr|jjS|jdko|j S)z/Return True if this connection was invalidated.N)r invalidatedrrYr0r'r'r(rZs zConnection.invalidatedc Csr|jdkrhz |WStjtjfk r2Yqntk rd}z||ddddW5d}~XYqnXn|jSdS)zThe underlying DB-API connection managed by this Connection. .. seealso:: :ref:`dbapi_connections` N)r_revalidate_connectionr PendingRollbackErrorResourceClosedError BaseException_handle_dbapi_exceptionr"er'r'r(r#s  &zConnection.connectionc CsJz|j|jWStk rD}z||ddddW5d}~XYnXdS)aReturn the current isolation level assigned to this :class:`_engine.Connection`. This will typically be the default isolation level as determined by the dialect, unless if the :paramref:`.Connection.execution_options.isolation_level` feature has been used to alter the isolation level on a per-:class:`_engine.Connection` basis. This attribute will typically perform a live SQL operation in order to procure the current isolation level, so the value returned is the actual level on the underlying DBAPI connection regardless of how this state was set. Compare to the :attr:`_engine.Connection.default_isolation_level` accessor which returns the dialect-level setting without performing a SQL query. .. versionadded:: 0.9.9 .. seealso:: :attr:`_engine.Connection.default_isolation_level` - view default level :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`_engine.Connection` isolation level N)rget_isolation_levelr#r^r_r`r'r'r(rbs zConnection.get_isolation_levelcCs|jjS)aCThe default isolation level assigned to this :class:`_engine.Connection`. This is the isolation level setting that the :class:`_engine.Connection` has when first procured via the :meth:`_engine.Engine.connect` method. This level stays in place until the :paramref:`.Connection.execution_options.isolation_level` is used to change the setting on a per-:class:`_engine.Connection` basis. Unlike :meth:`_engine.Connection.get_isolation_level`, this attribute is set ahead of time from the first connection procured by the dialect, so SQL query is not invoked when this accessor is called. .. versionadded:: 0.9.9 .. seealso:: :meth:`_engine.Connection.get_isolation_level` - view current level :paramref:`_sa.create_engine.isolation_level` - set per :class:`_engine.Engine` isolation level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`_engine.Connection` isolation level )rdefault_isolation_levelr0r'r'r(rcsz"Connection.default_isolation_levelcCsV|jr(tjd|jdk rdndddn*|jr2ttjd|jdk rFdnddddS)Nz;Can't reconnect until invalid %stransaction is rolled back.z savepoint Z8s2b)codez\This connection is on an inactive %stransaction. Please rollback() fully before proceeding.Z8s2a)rZr r\rrGrr0r'r'r(_invalid_transactions$ zConnection._invalid_transactioncCsR|jr|jS|jrD|jrD|jdk r.||jj|d|_|jSt ddS)N) _connectionThis Connection is closed) rr[rrZrrfrrrr r]r0r'r'r(r[+s   z!Connection._revalidate_connectioncCs|jdk ot|jddS)Nis_validF)rgetattrr0r'r'r()_still_open_and_dbapi_connection_is_valid7s  z4Connection._still_open_and_dbapi_connection_is_validcCs|jjS)aInfo dictionary associated with the underlying DBAPI connection referred to by this :class:`_engine.Connection`, allowing user-defined data to be associated with the connection. The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of :class:`_engine.Connection`. )r#r4r0r'r'r(r4=s zConnection.infoz:meth:`.Connection.connect`cCs|S)aReturns a branched version of this :class:`_engine.Connection`. The :meth:`_engine.Connection.close` method on the returned :class:`_engine.Connection` can be called and this :class:`_engine.Connection` will remain open. This method provides usage symmetry with :meth:`_engine.Engine.connect`, including for usage with context managers. )rFr"r$r'r'r(connectKszConnection.connectcCsJ|jr|jj|dS|jrdS|jr.td|jr@|j|d|_dS)aInvalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. An attempt will be made to close the underlying DBAPI connection immediately; however if this operation fails, the error is logged but not raised. The connection is then discarded whether or not close() succeeded. Upon the next use (where "use" typically means using the :meth:`_engine.Connection.execute` method or similar), this :class:`_engine.Connection` will attempt to procure a new DBAPI connection using the services of the :class:`_pool.Pool` as a source of connectivity (e.g. a "reconnection"). If a transaction was in progress (e.g. the :meth:`_engine.Connection.begin` method has been called) when :meth:`_engine.Connection.invalidate` method is called, at the DBAPI level all state associated with this transaction is lost, as the DBAPI connection is closed. The :class:`_engine.Connection` will not allow a reconnection to proceed until the :class:`.Transaction` object is ended, by calling the :meth:`.Transaction.rollback` method; until that point, any attempt at continuing to use the :class:`_engine.Connection` will raise an :class:`~sqlalchemy.exc.InvalidRequestError`. This is to prevent applications from accidentally continuing an ongoing transactional operations despite the fact that the transaction has been lost due to an invalidation. The :meth:`_engine.Connection.invalidate` method, just like auto-invalidation, will at the connection pool level invoke the :meth:`_events.PoolEvents.invalidate` event. :param exception: an optional ``Exception`` instance that's the reason for the invalidation. is passed along to event handlers and logging functions. .. seealso:: :ref:`pool_connection_invalidation` ) exceptionNrh)r invalidaterZrYr r]rkr)r"rnr'r'r(ro[s.  zConnection.invalidatecCs|jdS)a2Detach the underlying DB-API connection from its connection pool. E.g.:: with engine.connect() as conn: conn.detach() conn.execute(text("SET search_path TO schema1, schema2")) # work with connection # connection is fully closed (since we used "with:", can # also call .close()) This :class:`_engine.Connection` instance will remain usable. When closed (or exited from a context manager context as above), the DB-API connection will be literally closed and not returned to its originating pool. This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar). N)rdetachr0r'r'r(rpszConnection.detachcCs |dSr2)beginr0r'r'r( _autobeginszConnection._autobegincCsd|jr|jr"tn|jr"|jS|jr,dS|jdkrFt||_|jS|jrXtdnt |SdS)aBegin a transaction and return a transaction handle. The returned object is an instance of :class:`.Transaction`. This object represents the "scope" of the transaction, which completes when either the :meth:`.Transaction.rollback` or :meth:`.Transaction.commit` method is called. .. tip:: The :meth:`_engine.Connection.begin` method is invoked when using the :meth:`_engine.Engine.begin` context manager method as well. All documentation that refers to behaviors specific to the :meth:`_engine.Connection.begin` method also apply to use of the :meth:`_engine.Engine.begin` method. Legacy use: nested calls to :meth:`.begin` on the same :class:`_engine.Connection` will return new :class:`.Transaction` objects that represent an emulated transaction within the scope of the enclosing transaction, that is:: trans = conn.begin() # outermost transaction trans2 = conn.begin() # "nested" trans2.commit() # does nothing trans.commit() # actually commits Calls to :meth:`.Transaction.commit` only have an effect when invoked via the outermost :class:`.Transaction` object, though the :meth:`.Transaction.rollback` method of any of the :class:`.Transaction` objects will roll back the transaction. .. tip:: The above "nesting" behavior is a legacy behavior specific to :term:`1.x style` use and will be removed in SQLAlchemy 2.0. For notes on :term:`2.0 style` use, see :meth:`_future.Connection.begin`. .. seealso:: :meth:`_engine.Connection.begin_nested` - use a SAVEPOINT :meth:`_engine.Connection.begin_twophase` - use a two phase /XID transaction :meth:`_engine.Engine.begin` - context manager available from :class:`_engine.Engine` Nz2a transaction is already begun for this connection) rGrrrqrrRootTransactionr InvalidRequestErrorMarkerTransactionr0r'r'r(rqs3    zConnection.begincCsT|jr|jr"tn|jr"|jS|jdkrL|jsDtd|S|t |S)aBegin a nested transaction (i.e. SAVEPOINT) and return a transaction handle, assuming an outer transaction is already established. Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may ``commit`` and ``rollback``, however the outermost transaction still controls the overall ``commit`` or ``rollback`` of the transaction of a whole. The legacy form of :meth:`_engine.Connection.begin_nested` method has alternate behaviors based on whether or not the :meth:`_engine.Connection.begin` method was called previously. If :meth:`_engine.Connection.begin` was not called, then this method will behave the same as the :meth:`_engine.Connection.begin` method and return a :class:`.RootTransaction` object that begins and commits a real transaction - **no savepoint is invoked**. If :meth:`_engine.Connection.begin` **has** been called, and a :class:`.RootTransaction` is already established, then this method returns an instance of :class:`.NestedTransaction` which will invoke and manage the scope of a SAVEPOINT. .. tip:: The above mentioned behavior of :meth:`_engine.Connection.begin_nested` is a legacy behavior specific to :term:`1.x style` use. In :term:`2.0 style` use, the :meth:`_future.Connection.begin_nested` method instead autobegins the outer transaction that can be committed using "commit-as-you-go" style; see :meth:`_future.Connection.begin_nested` for migration details. .. versionchanged:: 1.4.13 The behavior of :meth:`_engine.Connection.begin_nested` as returning a :class:`.RootTransaction` if :meth:`_engine.Connection.begin` were not called has been restored as was the case in 1.3.x versions; in previous 1.4.x versions, an outer transaction would be "autobegun" but would not be committed. .. seealso:: :meth:`_engine.Connection.begin` :meth:`_engine.Connection.begin_twophase` Na(Calling Connection.begin_nested() in 2.0 style use will return a NestedTransaction (SAVEPOINT) in all cases, that will not commit the outer transaction. For code that is cross-compatible between 1.x and 2.0 style use, ensure Connection.begin() is called before calling Connection.begin_nested().) rGrr begin_nestedrr warn_deprecated_20rqrrNestedTransactionr0r'r'r(rvs0   zConnection.begin_nestedcCsF|jr|jj|dS|jdk r(td|dkr<|jj}t||S)a'Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of :class:`.TwoPhaseTransaction`, which in addition to the methods provided by :class:`.Transaction`, also provides a :meth:`~.TwoPhaseTransaction.prepare` method. :param xid: the two phase transaction id. If not supplied, a random id will be generated. .. seealso:: :meth:`_engine.Connection.begin` :meth:`_engine.Connection.begin_twophase` )xidNzOCannot start a two phase transaction when a transaction is already in progress.) rbegin_twophaserr rtrrZ create_xidTwoPhaseTransaction)r"ryr'r'r(rzDs  zConnection.begin_twophasecCs|jj|Sr2)rrZdo_recover_twophaser0r'r'r(recover_twophasedszConnection.recover_twophasecCs|jjj|||ddSN)recover)rrdo_rollback_twophaser"ryr~r'r'r(rollback_preparedgszConnection.rollback_preparedcCs|jjj|||ddSr})rrdo_commit_twophaserr'r'r(commit_preparedjszConnection.commit_preparedcCs&|jdk r|jS|jdk o$|jjSz,Return True if a transaction is in progress.N)rin_transactionr is_activer0r'r'r(rms  zConnection.in_transactioncCs&|jdk r|jS|jdk o$|jjSr)rin_nested_transactionrrr0r'r'r(rts    z Connection.in_nested_transactioncCs|jdddkS)NZisolation_levelZ AUTOCOMMITr>r0r'r'r(_is_autocommit~s zConnection._is_autocommitcCs|jdk r|jS|jS)zaReturn the current root transaction in progress, if any. .. versionadded:: 1.4 N)rget_transactionrr0r'r'r(rs  zConnection.get_transactioncCs|jdk r|jS|jS)zcReturn the current nested transaction in progress, if any. .. versionadded:: 1.4 N)rget_nested_transactionrr0r'r'r(rs  z!Connection.get_nested_transactionc Cs|jr t|jr|dd|_|js.|jjr:|j|zNz|jj |j Wn4t k r}z| |ddddW5d}~XYnXW5d|_XdS)NzBEGIN (implicit)TF)rrrr:rrrrrqrZdo_beginr#r^r_r" transactionrar'r'r( _begin_impls   (zConnection._begin_implc Cs|jr t|js|jjr$|j||jr|jrN|rD| dn | dz|jj |j Wn4t k r}z||ddddW5d}~XYnXdS)NzVROLLBACK using DBAPI connection.rollback(), DBAPI should ignore due to autocommit modeZROLLBACK)rrrrrrollbackrkrrr:rZ do_rollbackr#r^r_r`r'r'r(_rollback_impls   zConnection._rollback_implc Cs|jr t|r |s td|js.|jjr:|j||j r^|rT| dn | dz|jj |j Wn4tk r}z||ddddW5d}~XYnXdS)NzThe current statement is being autocommitted using implicit autocommit, which will be removed in SQLAlchemy 2.0. Use the .begin() method of Engine or Connection in order to use an explicit transaction for DML and DDL statements.zRCOMMIT using DBAPI connection.commit(), DBAPI should ignore due to autocommit modeZCOMMIT)rrrr rwrrrcommitrr:rZ do_commitr#r^r_)r" autocommitrar'r'r( _commit_impls"    zConnection._commit_implcCsd|jr t|js|jjr&|j|||dkrF|jd7_d|j}|jr`|jj |||SdS)Nrzsa_savepoint_%s) rrrrrZ savepointrrkrZ do_savepointr"rCr'r'r(_savepoint_impls  zConnection._savepoint_implcCsB|jr t|js|jjr(|j||d|jr>|jj||dSr2) rrrrrZrollback_savepointrkrZdo_rollback_to_savepointrr'r'r(_rollback_to_savepoint_impls  z&Connection._rollback_to_savepoint_implcCsB|jr t|js|jjr(|j||d|jr>|jj||dSr2) rrrrrZrelease_savepointrkrZdo_release_savepointrr'r'r(_release_savepoint_impls  z"Connection._release_savepoint_implc Cs|jr t|jr|d|js(|jjr8|j||j|j rd|_ zPz|jj ||jWn4t k r}z||ddddW5d}~XYnXW5d|_ XdS)NzBEGIN TWOPHASE (implicit)TF)rrrr:rrrrzryrkrrZdo_begin_twophaser^r_rr'r'r(_begin_twophase_impls  (zConnection._begin_twophase_implc Cs|jr t|js|jjr&|j|||jrt|jt stz|jj |||Wn4t k r}z| |ddddW5d}~XYnXdSr2)rrrrrZrollback_twophaserkrrr{rrr^r_r"ryZ is_preparedrar'r'r(_rollback_twophase_impls z"Connection._rollback_twophase_implc Cs|jr t|js|jjr(|j||||jrt|jt s>tz|jj |||Wn4t k r}z| |ddddW5d}~XYnXdSr2)rrrrrZcommit_twophaserkrrr{rrr^r_rr'r'r(_commit_twophase_impl.s z Connection._commit_twophase_implcCs$|jr|j|s |dSr2)r _autorollbackrrr0r'r'r(r;s zConnection._autorollbackcCstddS)Na The connection.execute() method in SQLAlchemy 2.0 will accept parameters as a single dictionary or a single sequence of dictionaries only. Parameters passed as keyword arguments, tuples or positionally oriented dictionaries and/or tuples will no longer be accepted.)r rwr0r'r'r(_warn_for_legacy_exec_formatBsz'Connection._warn_for_legacy_exec_formatcCsz|jr*|jrttdd|_d|_dS|jr@|jd}nd}|jdk rp|j}|rb| n|d|_d|_dS)afClose this :class:`_engine.Connection`. This results in a release of the underlying database resources, that is, the DBAPI connection referenced internally. The DBAPI connection is typically restored back to the connection-holding :class:`_pool.Pool` referenced by the :class:`_engine.Engine` that produced this :class:`_engine.Connection`. Any transactional state present on the DBAPI connection is also unconditionally released via the DBAPI connection's ``rollback()`` method, regardless of any :class:`.Transaction` object that may be outstanding with regards to this :class:`_engine.Connection`. After :meth:`_engine.Connection.close` is called, the :class:`_engine.Connection` is permanently in a closed state, and will allow no further operations. zThe .close() method on a so-called 'branched' connection is deprecated as of 1.4, as are 'branched' connections overall, and will be removed in a future release. If this is a default-handling function, don't close the connection.NFT) rrGrr rwrrrrOZ_close_no_reset)r"Z skip_resetconnr'r'r(rOMs&    zConnection.closecOs|j|f||SzExecutes and returns the first column of the first row. The underlying result/cursor is closed after execution. executescalar)r"Zobject_ multiparamsparamsr'r'r(rszConnection.scalarc Os~t|tjr*td|j|||tddSz |j}Wn6tk rj}ztjt ||dW5d}~XYnX||||tSdS)aY Executes a SQL statement construct and returns a :class:`_engine.CursorResult`. :param statement: The statement to be executed. May be one of: * a plain string (deprecated) * any :class:`_expression.ClauseElement` construct that is also a subclass of :class:`.Executable`, such as a :func:`_expression.select` construct * a :class:`.FunctionElement`, such as that generated by :data:`.func`, will be automatically wrapped in a SELECT statement, which is then executed. * a :class:`.DDLElement` object * a :class:`.DefaultGenerator` object * a :class:`.Compiled` object .. deprecated:: 2.0 passing a string to :meth:`_engine.Connection.execute` is deprecated and will be removed in version 2.0. Use the :func:`_expression.text` construct with :meth:`_engine.Connection.execute`, or the :meth:`_engine.Connection.exec_driver_sql` method to invoke a driver-level SQL string. :param \*multiparams/\**params: represent bound parameter values to be used in the execution. Typically, the format is either a collection of one or more dictionaries passed to \*multiparams:: conn.execute( table.insert(), {"id":1, "value":"v1"}, {"id":2, "value":"v2"} ) ...or individual key/values interpreted by \**params:: conn.execute( table.insert(), id=1, value="v1" ) In the case that a plain SQL string is passed, and the underlying DBAPI accepts positional bind parameters, a collection of tuples or individual values in \*multiparams may be passed:: conn.execute( "INSERT INTO table (id, value) VALUES (?, ?)", (1, "v1"), (2, "v2") ) conn.execute( "INSERT INTO table (id, value) VALUES (?, ?)", 1, "v1" ) Note above, the usage of a question mark "?" or other symbol is contingent upon the "paramstyle" accepted by the DBAPI in use, which may be any of "qmark", "named", "pyformat", "format", "numeric". See `pep-249 `_ for details on paramstyle. To execute a textual SQL statement which uses bound parameters in a DBAPI-agnostic way, use the :func:`_expression.text` construct. .. deprecated:: 2.0 use of tuple or scalar positional parameters is deprecated. All params should be dicts or sequences of dicts. Use :meth:`.exec_driver_sql` to execute a plain string with tuple or scalar positional parameters. zPassing a string to Connection.execute() is deprecated and will be removed in version 2.0. Use the text() construct, or the Connection.exec_driver_sql() method to invoke a driver-level SQL string.FfutureZreplace_contextN) rr string_typesrw_exec_driver_sql_EMPTY_EXECUTION_OPTS_execute_on_connectionAttributeErrorraise_r ObjectNotExecutableError)r" statementrrmetherrr'r'r(rs&K  zConnection.executecCs|||||S)z%Execute a sql.FunctionElement object.)_execute_clauseelementselect)r"funcrrrWr'r'r(_execute_functions zConnection._execute_functionc Cs|j|}t|||}|js&|jjr:||||\}}}z2|j} | dkrR|} |j} | j | || |} WnPt j t j fk rYn4tk r} z|| ddddW5d} ~ XYnX| d|d} |jr||js|jjr|j|||||| | S)z&Execute a schema.ColumnDefault object.N)r merge_withrrr_invoke_before_exec_eventrr[rexecution_ctx_clsZ _init_defaultr r\r]r^r_Z _exec_defaultrrOr after_execute)r"defaultrrrWdistilled_parametersdistilled_paramsevent_multiparams event_paramsrrctxraretr'r'r(_execute_defaultsT  $ zConnection._execute_defaultcCs|j|j|}t|||}|js*|jjr>||||\}}}|j|} | dd} |j} |j| | d} | | | j j | d|| } |js|jjr|j |||||| | S)zExecute a schema.DDL object.r=N)rr=)rrrrrrr?rcompile_execute_contextrZ _init_ddlrr)r"ZddlrrrWrrrrZ exec_optsr=rcompiledrr'r'r( _execute_ddl/sP   zConnection._execute_ddlcCst|dkrg|d}}n |i}}|jjD]}||||||\}}}q.|rft|}|rvtdn|rr|g}ng}|||fS)NrrzLEvent handler can't return non-empty multiparams and params at the same time)lenrZbefore_executelistr rt)r"elemrrWrrfnr'r'r(r\s*    z$Connection._invoke_before_exec_eventc Cs|j|j|}t|||}|jp(|jj}|rB||||\}}}|r`t|d} t|dk} ng} d} |j} | dd} | d|jj } |j | | | | | |jj t jBd\}}}|j| | jj||||||||d }|r|j|||||||S) z#Execute a sql.ClauseElement object.rrFr=Ncompiled_cache)rrZ column_keysfor_executemanyr=Zlinting) cache_hit)rrrrrrsortedrrr?_compiled_cacheZ_compile_w_cacheZcompiler_lintingrZ WARN_LINTINGrr_init_compiledrr)r"rrrrWrZ has_eventsrrkeysrrr=rZ compiled_sqlZextracted_paramsrrr'r'r(r|sx    z!Connection._execute_clauseelementc Cs|j|j|}t|||}|js*|jjr>||||\}}}|j} || | j j |||||dd } |jsp|jjr|j |||||| | S)ziExecute a sql.Compiled object. TODO: why do we have this? likely deprecate or remove N) rWrrrrrrrrrrrr) r"rrrrWrrrrrrr'r'r(_execute_compiledsJ   zConnection._execute_compiledc Cs|j|}t|||}|s>|js*|jjr>||||\}}} |j} || | jj |||||} |s|jsp|jjr|j |||| || | Sr2) rrrrrrrrrZ_init_statementrr) r"rrrrWrrrrrrrr'r'r(rsH  zConnection._exec_driver_sqlc Cs`t|\}}z |j}Wn6tk rL}ztjt||dW5d}~XYnX|||||SdS)Nr)rrrr rr r)r"r parametersrW args_10stylekwargs_10stylerrr'r'r( _execute_20!s  zConnection._execute_20cCs t|\}}|j||||ddS)aExecutes a SQL statement construct and returns a :class:`_engine.CursorResult`. :param statement: The statement str to be executed. Bound parameters must use the underlying DBAPI's paramstyle, such as "qmark", "pyformat", "format", etc. :param parameters: represent bound parameter values to be used in the execution. The format is one of: a dictionary of named parameters, a tuple of positional parameters, or a list containing either dictionaries or tuples for multiple-execute support. E.g. multiple dictionaries:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", [{"id":1, "value":"v1"}, {"id":2, "value":"v2"}] ) Single dictionary:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)", dict(id=1, value="v1") ) Single tuple:: conn.exec_driver_sql( "INSERT INTO table (id, value) VALUES (?, ?)", (1, 'v1') ) .. note:: The :meth:`_engine.Connection.exec_driver_sql` method does not participate in the :meth:`_events.ConnectionEvents.before_execute` and :meth:`_events.ConnectionEvents.after_execute` events. To intercept calls to :meth:`_engine.Connection.exec_driver_sql`, use :meth:`_events.ConnectionEvents.before_cursor_execute` and :meth:`_events.ConnectionEvents.after_cursor_execute`. .. seealso:: :pep:`249` Tr)rr)r"rrrWrrr'r'r(exec_driver_sql1s3 zConnection.exec_driver_sqlc Os|}|jr|j}z0|j} | dkr(|} |||| |f||} WnVtjtjfk r^Yn:tk r} z|| t ||ddW5d} ~ XYnX|j r|j j r|j r|j j s| n|jrt||jr|j dkr|| |jr| | j| j| j} }}| js"|d}|js4|jjr\|jjD]} | || ||| | j\}}q<|jr||| }|jj!s|d|t"j#|d| jdn|d|fd}z| jr|j$jr|j$jj%D] } | | ||| rd}qq|s|j$%| ||| n|sh| j&rh|j$jrP|j$jj'D]} | | || r0d}qPq0|s|j$'| || nN|j$jr|j$jj(D] } | | ||| r|d}qq||s|j$(| ||| |js|jjr|j)|| ||| | j| *| +}|jsT|j,}|j-s|rd|_.|j dkr2| j/r2|j0dd |rT| j-rT|jrLt1|2Wn6tk r} z|| ||| | W5d} ~ XYnX|S) zdCreate an :class:`.ExecutionContext` and execute, returning a :class:`_engine.CursorResult`.Nrz[%s] %r )Zbatchesismultiz8[%s] [SQL parameters hidden due to hide_parameters=True]FT)r)3rrr[r r\r]r^r_r text_typerrrrf_trans_context_managerr_trans_ctx_checkrGrrZpre_execZuse_setinputsizesZ_set_input_sizescursorrr executemanyrrrbefore_cursor_executerr:Z_get_cache_statshide_parameterssql_utilZ _repr_paramsrZdo_executemanyZ no_parametersZdo_execute_no_params do_executeafter_cursor_executeZ post_execZ_setup_result_proxyrZ _soft_closedZ_autoclose_connectionZshould_autocommitrrrO)r"r constructorrrrWargsr8ZbranchedrcontextrarrstatsZ evt_handledresultrr'r'r(rns(                  zConnection._execute_contextc Cs|js|jjr2|jjD]}||||||d\}}q|jrN|||d|zD|jjs\dn|jjjD]}|||||rfqqf|j||||Wn4tk r}z| |||||W5d}~XYnX|js|jjr|j |||||ddS)a_Execute a statement + params on the given cursor. Adds appropriate logging and exception handling. This method is used by DefaultDialect for special-case executions, such as for sequences and column defaults. The path of statement execution in the majority of cases terminates at _execute_context(). Fz [raw sql] %rr'N) rrrrrr:rrr^r_r)r"rrrrrrar'r'r(_cursor_executesL     zConnection._cursor_executecCs:z |Wn(tk r4|jjjjdddYnXdS)z\Close the given cursor, catching exceptions and turning into log warnings. zError closing cursorT)exc_infoN)rO Exceptionrpoolr3error)r"rr'r'r(_safe_close_cursorDs  zConnection._safe_close_cursorc Cst}t|}|jsZt||jjjrL|j rL|j ||j sD|j nd|pV|oV|j |_| }|j rtjtjj||||jjj|jj|j|dk r|jndd|d|dd|_ zt||jjjp|dk o|dko| } | rtjj||||jjj|jj|j|j|dk r|jndd} nd} d} |js6|jjr|jddst|| |j||||||j| } |j j!D]\}z || }|dk r|| _"} Wn4t#k r}z|} WY qW5d}~XYnXql|j| j kr| j |_| r| j | _$| j%}| r |r |&||jsB|r"|'|tj(dd|)W5QRX| r^tj| |d|dn2| rztj| |d|dntj|d |dd W5|` |jr|`|j s|j } |r|jj| ||||jr|jrt|XdS) N)rrrr with_tracebackfrom_T)rconnection_invalidatedrrZskip_user_error_eventsF)Z warn_onlyrr)*sysrr is_exit_exception_is_disconnectrrdbapiErrorrY is_disconnectrZr_reentrant_errorrr DBAPIErrorinstancerrrrZ _invalidaterorrGrrOrrr?ExceptionContextImplr handle_errorchained_exceptionrrinvalidate_pool_on_disconnectZhandle_dbapi_exceptionr safe_reraiser)r"rarrrrrrrZdbapi_conn_wrapper should_wrapsqlalchemy_exceptionnewraiserrper_fn_raisedr'r'r(r_Ts        "     z"Connection._handle_dbapi_exceptionc Cs:t}||dd}t||jj}|rHtjjdd||jj|j |d}nd}d}|j rt |||ddddd|d } |j j D]T} z| | } | dk r| | _}Wqxtk r} z| }WYqW5d} ~ XYqxXqx|r|| jkr| j|_}|rtj||d|dn2|r tj||d|dntj|d|dddS)N)rrTr rrr)rrrrrrr rrrrrrrrrrr r) clsrarrrrrrrrrrrr'r'r($_handle_dbapi_exception_noconnections`  z/Connection._handle_dbapi_exception_noconnectioncKs||j|f||dS)zrun a DDL visitor. This method is only here so that the MockConnection can change the options given to the visitor so that "checkfirst" is skipped. N)rZtraverse_single)r"visitorcallableelementkwargsr'r'r(_run_ddl_visitorszConnection._run_ddl_visitor1.4zThe :meth:`_engine.Connection.transaction` method is deprecated and will be removed in a future release. Use the :meth:`_engine.Engine.begin` context manager instead.c Os^d|d<|}z |j|f||}||WSt|W5QRXYnXdS)atExecute the given function within a transaction boundary. The function is passed this :class:`_engine.Connection` as the first argument, followed by the given \*args and \**kwargs, e.g.:: def do_something(conn, x, y): conn.execute(text("some statement"), {'x':x, 'y':y}) conn.transaction(do_something, 5, 10) The operations inside the function are all invoked within the context of a single :class:`.Transaction`. Upon success, the transaction is committed. If an exception is raised, the transaction is rolled back before propagating the exception. .. note:: The :meth:`.transaction` method is superseded by the usage of the Python ``with:`` statement, which can be used with :meth:`_engine.Connection.begin`:: with conn.begin(): conn.execute(text("some statement"), {'x':5, 'y':10}) As well as with :meth:`_engine.Engine.begin`:: with engine.begin() as conn: conn.execute(text("some statement"), {'x':5, 'y':10}) .. seealso:: :meth:`_engine.Engine.begin` - engine-level transactional context :meth:`_engine.Engine.transaction` - engine-level version of :meth:`_engine.Connection.transaction` T_sa_skip_warningN)rq run_callablerr rr)r" callable_rr transrr'r'r(r$s1 zConnection.transactionzThe :meth:`_engine.Connection.run_callable` method is deprecated and will be removed in a future release. Invoke the callable function directly, passing the Connection.cOs||f||S)aGiven a callable object or function, execute it, passing a :class:`_engine.Connection` as the first argument. The given \*args and \**kwargs are passed subsequent to the :class:`_engine.Connection` argument. This function, along with :meth:`_engine.Engine.run_callable`, allows a function to be run with a :class:`_engine.Connection` or :class:`_engine.Engine` object without the need to know which one is being dealt with. r')r"rrr r'r'r(r_szConnection.run_callable)NFNNNNT)F)N)N)F)F)F)N)NN)N)T__name__ __module__ __qualname____doc__rG_sqla_logger_namespacerr)r Zmemoized_propertyr1r:r<propertyr@rDrFrMrNrTrWrXrYrZr#rbrcrfr[rkr4 deprecated_20rmrorprrrqrvrzr|rrrrrrrrrrrrrrrrrrrrOrrrrrrrrrrrrrrrrrr_ classmethodrr  deprecatedrrr'r'r'r(r s 7   ;    %      ;JE            7e  7- L 3.  =/ (   <  4rc@seZdZdZddZdS)rz3Implement the :class:`.ExceptionContext` interface.c Cs:||_||_||_||_||_||_||_| |_| |_dSr2) rr#rZoriginal_exceptionZexecution_contextrrrr) r"rnrrr#rrrrrrr'r'r(r)ys zExceptionContextImpl.__init__N)rrrrr)r'r'r'r(rvsrc@seZdZdZdZdZddZddZedd Z d d Z d d Z ddZ eddZ ddZddZddZddZddZddZdS) TransactionatRepresent a database transaction in progress. The :class:`.Transaction` object is procured by calling the :meth:`_engine.Connection.begin` method of :class:`_engine.Connection`:: from sqlalchemy import create_engine engine = create_engine("postgresql://scott:tiger@localhost/test") connection = engine.connect() trans = connection.begin() connection.execute(text("insert into x (a, b) values (1, 2)")) trans.commit() The object provides :meth:`.rollback` and :meth:`.commit` methods in order to control transaction boundaries. It also implements a context manager interface so that the Python ``with`` statement can be used with the :meth:`_engine.Connection.begin` method:: with connection.begin(): connection.execute(text("insert into x (a, b) values (1, 2)")) The Transaction object is **not** threadsafe. .. seealso:: :meth:`_engine.Connection.begin` :meth:`_engine.Connection.begin_twophase` :meth:`_engine.Connection.begin_nested` .. index:: single: thread safety; Transaction r'FcCs tdSr2NotImplementedErrorr"r#r'r'r(r)szTransaction.__init__cCs tdS)ado whatever steps are necessary to set this transaction as "deactive", however leave this transaction object in place as far as the connection's state. for a "real" transaction this should roll back the transaction and ensure this transaction is no longer a reset agent. this is used for nesting of marker transactions where the marker can set the "real" transaction as rolled back, however it stays in place. for 2.0 we hope to remove this nesting feature. Nrr0r'r'r(_do_deactivateszTransaction._do_deactivatecCs tdS)zTrue if this transaction is totally deactivated from the connection and therefore can no longer affect its state. Nrr0r'r'r(_deactivated_from_connectionsz(Transaction._deactivated_from_connectioncCs tdSr2rr0r'r'r( _do_closeszTransaction._do_closecCs tdSr2rr0r'r'r( _do_rollbackszTransaction._do_rollbackcCs tdSr2rr0r'r'r( _do_commitszTransaction._do_commitcCs|jo|jj Sr2)rr#rZr0r'r'r(riszTransaction.is_validcCsz |W5|jrtXdS)a;Close this :class:`.Transaction`. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing transaction. N)rrr!r0r'r'r(rOs  zTransaction.closecCsz |W5|jrtXdS)aRoll back this :class:`.Transaction`. The implementation of this may vary based on the type of transaction in use: * For a simple database transaction (e.g. :class:`.RootTransaction`), it corresponds to a ROLLBACK. * For a :class:`.NestedTransaction`, it corresponds to a "ROLLBACK TO SAVEPOINT" operation. * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two phase transactions may be used. N)rrr"r0r'r'r(rs zTransaction.rollbackcCsz |W5|jrtXdS)aCommit this :class:`.Transaction`. The implementation of this may vary based on the type of transaction in use: * For a simple database transaction (e.g. :class:`.RootTransaction`), it corresponds to a COMMIT. * For a :class:`.NestedTransaction`, it corresponds to a "RELEASE SAVEPOINT" operation. * For a :class:`.TwoPhaseTransaction`, DBAPI-specific methods for two phase transactions may be used. N)rrr#r0r'r'r(r s zTransaction.commitcCs|jSr2)r#r0r'r'r( _get_subject szTransaction._get_subjectcCs|jSr2rr0r'r'r(_transaction_is_active! sz"Transaction._transaction_is_activecCs|j Sr2)r r0r'r'r(_transaction_is_closed$ sz"Transaction._transaction_is_closedN)rrrr __slots___is_rootr)rrr r!r"r#rirOrrr$r&r'r'r'r'r(rs$$  rc@sTeZdZdZdZddZeddZeddZd d Z d d Z d dZ ddZ dS)ruzA 'marker' transaction that is used for nested begin() calls. .. deprecated:: 1.4 future connection for 2.0 won't support this pattern. )r# _is_activercCsp|jdk st|jjs td|jr*ttd||_|j rJt ||j dk r^|j |_n|j|_d|_ dS)NzWthe current transaction on this connection is inactive. Please issue a rollback first.zCalling .begin() when a transaction is already begun, creating a 'sub' transaction, is deprecated and will be removed in 2.0. See the documentation section 'Migrating from the nesting pattern' for background on how to migrate from this pattern.T)rrrr rtrGr rwr#rrrrr*rr'r'r(r)1 s     zMarkerTransaction.__init__cCs|j Sr2r%r0r'r'r(r M sz.MarkerTransaction._deactivated_from_connectioncCs|jo |jjSr2)r*rrr0r'r'r(rQ szMarkerTransaction.is_activecCs d|_dSNF)r*r0r'r'r( _deactivateU szMarkerTransaction._deactivatecCs |dSr2r,r0r'r'r(r!X szMarkerTransaction._do_closecCs$|jr z|jW5|XdSr2)r*r,rrr0r'r'r(r"\ szMarkerTransaction._do_rollbackcCs |dSr2r-r0r'r'r(r#d szMarkerTransaction._do_commitN) rrrrr(r)rr rr,r!r"r#r'r'r'r(ru( s  ruc@sveZdZdZdZdZddZddZedd Z d d Z d d Z ddZ ddZ dddZddZddZddZdS)rsaRepresent the "root" transaction on a :class:`_engine.Connection`. This corresponds to the current "BEGIN/COMMIT/ROLLBACK" that's occurring for the :class:`_engine.Connection`. The :class:`_engine.RootTransaction` is created by calling upon the :meth:`_engine.Connection.begin` method, and remains associated with the :class:`_engine.Connection` throughout its active span. The current :class:`_engine.RootTransaction` in use is accessible via the :attr:`_engine.Connection.get_transaction` method of :class:`_engine.Connection`. In :term:`2.0 style` use, the :class:`_future.Connection` also employs "autobegin" behavior that will create a new :class:`_engine.RootTransaction` whenever a connection in a non-transactional state is used to emit commands on the DBAPI connection. The scope of the :class:`_engine.RootTransaction` in 2.0 style use can be controlled using the :meth:`_future.Connection.commit` and :meth:`_future.Connection.rollback` methods. T)r#rcCs<|jdkst|jrt|||_|||_d|_dSNT)rrrrrr#_connection_begin_implrrr'r'r(r) s zRootTransaction.__init__cCs8|jr|jj|kstd|_n|jj|k r4tddS)NFz0transaction already deassociated from connection)rr#rrr warnr0r'r'r(_deactivate_from_connection s  z+RootTransaction._deactivate_from_connectioncCs |jj|k Sr2)r#rr0r'r'r(r  sz,RootTransaction._deactivated_from_connectioncCs>|jj|kst|jr||jjr2|jj|dSr2)r#rrr_connection_rollback_implr_cancelr1r0r'r'r(r s  zRootTransaction._do_deactivatecCs|j|dSr2)r#rr0r'r'r(r/ sz&RootTransaction._connection_begin_implcCs|jdSr2)r#rr0r'r'r(r2 sz)RootTransaction._connection_rollback_implcCs|jdSr2)r#rr0r'r'r(_connection_commit_impl sz'RootTransaction._connection_commit_implFcCsnz&|jr||jjr$|jjW5|js2|r:||jj|krNd|j_X|jrZt|jj|k sjtdSr2)rr1r#rr2rr3r)r"try_deactivater'r'r( _close_impl s    zRootTransaction._close_implcCs |dSr2r6r0r'r'r(r! szRootTransaction._do_closecCs|jdddS)NT)r5r7r0r'r'r(r" szRootTransaction._do_rollbackcCs|jrL|jj|kstz |W5|jjr8|jj|Xd|j_n"|jj|krd|jn t d|jrxt|jj|k stdS)NThis transaction is inactive) rr#rrrr3r1r4rfr rtr0r'r'r(r# s        zRootTransaction._do_commitN)F)rrrrr)r(r)r1rr rr/r2r4r6r!r"r#r'r'r'r(rsh s   rsc@sbeZdZdZdZddZdddZedd Zd d Z d d Z ddZ ddZ ddZ ddZdS)rxaRepresent a 'nested', or SAVEPOINT transaction. The :class:`.NestedTransaction` object is created by calling the :meth:`_engine.Connection.begin_nested` method of :class:`_engine.Connection`. When using :class:`.NestedTransaction`, the semantics of "begin" / "commit" / "rollback" are as follows: * the "begin" operation corresponds to the "BEGIN SAVEPOINT" command, where the savepoint is given an explicit name that is part of the state of this object. * The :meth:`.NestedTransaction.commit` method corresponds to a "RELEASE SAVEPOINT" operation, using the savepoint identifier associated with this :class:`.NestedTransaction`. * The :meth:`.NestedTransaction.rollback` method corresponds to a "ROLLBACK TO SAVEPOINT" operation, using the savepoint identifier associated with this :class:`.NestedTransaction`. The rationale for mimicking the semantics of an outer transaction in terms of savepoints so that code may deal with a "savepoint" transaction and an "outer" transaction in an agnostic way. .. seealso:: :ref:`session_begin_nested` - ORM version of the SAVEPOINT API. )r#r _savepoint_previous_nestedcCsH|jdk st|jrt|||_|j|_d|_|j |_ ||_ dSr.) rrrrrr#rr9rrr:rr'r'r(r) s  zNestedTransaction.__init__TcCs*|jj|kr|j|j_n|r&tddS)Nz7nested transaction already deassociated from connection)r#rr:r r0)r"r0r'r'r(r1 s   z-NestedTransaction._deactivate_from_connectioncCs |jj|k Sr2)r#rr0r'r'r(r  sz.NestedTransaction._deactivated_from_connectioncCs"d|_||jr|jdSr+)rr1r:r3r0r'r'r(r3! szNestedTransaction._cancelc Cs^z"|jr |jjjr |j|jW5d|_|r:|j|dX|jrFt|rZ|jj|k sZtdS)NF)r0)rr1r#rrr9rr)r"Zdeactivate_from_connectionZwarn_already_deactiver'r'r(r6* s zNestedTransaction._close_implcCs|dddSr+r7r0r'r'r(r8 sz NestedTransaction._do_deactivatecCs|dddS)NTFr7r0r'r'r(r!; szNestedTransaction._do_closecCs|dddSr.r7r0r'r'r(r"> szNestedTransaction._do_rollbackcCsR|jr,z|j|jW5d|_X|n"|jj|krD|jn tddS)NFz#This nested transaction is inactive) rr#rr9r1rrfr rtr0r'r'r(r#A s   zNestedTransaction._do_commitN)T)rrrrr(r)r1rr r3r6rr!r"r#r'r'r'r(rx s   rxcsDeZdZdZdZfddZddZddZd d Zd d Z Z S) r{aRepresent a two-phase transaction. A new :class:`.TwoPhaseTransaction` object may be procured using the :meth:`_engine.Connection.begin_twophase` method. The interface is the same as that of :class:`.Transaction` with the addition of the :meth:`prepare` method. )r#rry _is_preparedcs d|_||_tt||dSr+)r;rysuperr{r))r"r#ryrHr'r(r)c szTwoPhaseTransaction.__init__cCs(|jstd|j|jd|_dS)zqPrepare this :class:`.TwoPhaseTransaction`. After a PREPARE, the transaction can be committed. r8TN)rr rtr#rryr;r0r'r'r(prepareh s zTwoPhaseTransaction.preparecCs|j|dSr2)r#rr0r'r'r(r/s sz*TwoPhaseTransaction._connection_begin_implcCs|j|j|jdSr2)r#rryr;r0r'r'r(r2v sz-TwoPhaseTransaction._connection_rollback_implcCs|j|j|jdSr2)r#rryr;r0r'r'r(r4y sz+TwoPhaseTransaction._connection_commit_impl) rrrrr(r)r>r/r2r4 __classcell__r'r'r=r(r{V s   r{c@seZdZdZeZdZeZdZ dZ dZ dGddZ dd Z ed d Zd d ZddZddZddZeddZeddZeZddZddZdejfddZejdHdd Z Gd!d"d"e!Z"dId#d$Z#e$d%d&d'd(Z%e$d%d)d*d+Z&d,d-Z'ej(d.d/d0d1d2Z)ej(d3d4d0d5d6Z*ddefd7d8Z+efd9d:Z,dJd;d<Z-e$d%d=dKd>d?Z.e$d%d@dLdAdBZ/dCdDZ0dMdEdFZ1dS)NEnginea9 Connects a :class:`~sqlalchemy.pool.Pool` and :class:`~sqlalchemy.engine.interfaces.Dialect` together to provide a source of database connectivity and behavior. This is the **SQLAlchemy 1.x version** of :class:`_engine.Engine`. For the :term:`2.0 style` version, which includes some API differences, see :class:`_future.Engine`. An :class:`_engine.Engine` object is instantiated publicly using the :func:`~sqlalchemy.create_engine` function. .. seealso:: :doc:`/core/engines` :ref:`connections_toplevel` Fzsqlalchemy.engine.EngineNc Csl||_||_||_|r||_||_||_|dkrDtj||jd|_ nd|_ t j ||d|rh|j f|dS)Nr)Z size_alertZechoflag) rurlr logging_nameechorr ZLRUCache_lru_size_alertrr instance_loggerupdate_execution_options) r"rrrCrDrEZquery_cache_sizerWrr'r'r(r) s  zEngine.__init__cCs |jr|jdt||jdS)NziCompiled cache size pruning from %d items to %d. Increase cache size to reduce the frequency of pruning.)r r3r4rcapacity)r"cacher'r'r(rF s zEngine._lru_size_alertcCs|Sr2r'r0r'r'r(r sz Engine.enginecCs|jr|jdS)aClear the compiled cache associated with the dialect. This applies **only** to the built-in cache that is established via the :paramref:`_engine.create_engine.query_cache_size` parameter. It will not impact any dictionary caches that were passed via the :paramref:`.Connection.execution_options.query_cache` parameter. .. versionadded:: 1.4 N)rclearr0r'r'r(clear_compiled_cache s zEngine.clear_compiled_cachecKs.|j||_|j|||j||dS)aUpdate the default execution_options dictionary of this :class:`_engine.Engine`. The given keys/values in \**opt are added to the default execution options that will be used for all connections. The initial contents of this dictionary can be sent via the ``execution_options`` parameter to :func:`_sa.create_engine`. .. seealso:: :meth:`_engine.Connection.execution_options` :meth:`_engine.Engine.execution_options` N)rrUrZset_engine_execution_optionsrr"rVr'r'r(rH szEngine.update_execution_optionscKs |||S)a Return a new :class:`_engine.Engine` that will provide :class:`_engine.Connection` objects with the given execution options. The returned :class:`_engine.Engine` remains related to the original :class:`_engine.Engine` in that it shares the same connection pool and other state: * The :class:`_pool.Pool` used by the new :class:`_engine.Engine` is the same instance. The :meth:`_engine.Engine.dispose` method will replace the connection pool instance for the parent engine as well as this one. * Event listeners are "cascaded" - meaning, the new :class:`_engine.Engine` inherits the events of the parent, and new events can be associated with the new :class:`_engine.Engine` individually. * The logging configuration and logging_name is copied from the parent :class:`_engine.Engine`. The intent of the :meth:`_engine.Engine.execution_options` method is to implement "sharding" schemes where multiple :class:`_engine.Engine` objects refer to the same connection pool, but are differentiated by options that would be consumed by a custom event:: primary_engine = create_engine("mysql://") shard1 = primary_engine.execution_options(shard_id="shard1") shard2 = primary_engine.execution_options(shard_id="shard2") Above, the ``shard1`` engine serves as a factory for :class:`_engine.Connection` objects that will contain the execution option ``shard_id=shard1``, and ``shard2`` will produce :class:`_engine.Connection` objects that contain the execution option ``shard_id=shard2``. An event handler can consume the above execution option to perform a schema switch or other operation, given a connection. Below we emit a MySQL ``use`` statement to switch databases, at the same time keeping track of which database we've established using the :attr:`_engine.Connection.info` dictionary, which gives us a persistent storage space that follows the DBAPI connection:: from sqlalchemy import event from sqlalchemy.engine import Engine shards = {"default": "base", shard_1: "db1", "shard_2": "db2"} @event.listens_for(Engine, "before_cursor_execute") def _switch_shard(conn, cursor, stmt, params, context, executemany): shard_id = conn._execution_options.get('shard_id', "default") current_shard = conn.info.get("current_shard", None) if current_shard != shard_id: cursor.execute("use %s" % shards[shard_id]) conn.info["current_shard"] = shard_id .. seealso:: :meth:`_engine.Connection.execution_options` - update execution options on a :class:`_engine.Connection` object. :meth:`_engine.Engine.update_execution_options` - update the execution options for a given :class:`_engine.Engine` in place. :meth:`_engine.Engine.get_execution_options` ) _option_clsrMr'r'r(rW sJzEngine.execution_optionscCs|jS)zGet the non-SQL options which will take effect during execution. .. versionadded: 1.3 .. seealso:: :meth:`_engine.Engine.execution_options` r/r0r'r'r(rX2 s zEngine.get_execution_optionscCs|jjS)ziString name of the :class:`~sqlalchemy.engine.interfaces.Dialect` in use by this :class:`Engine`.)rrCr0r'r'r(rC= sz Engine.namecCs|jjS)ziDriver name of the :class:`~sqlalchemy.engine.interfaces.Dialect` in use by this :class:`Engine`.)rdriverr0r'r'r(rOD sz Engine.drivercCs d|jfS)Nz Engine(%r))rCr0r'r'r(__repr__M szEngine.__repr__cCs&|j|j|_|j|dS)aDispose of the connection pool used by this :class:`_engine.Engine`. This has the effect of fully closing all **currently checked in** database connections. Connections that are still checked out will **not** be closed, however they will no longer be associated with this :class:`_engine.Engine`, so when they are closed individually, eventually the :class:`_pool.Pool` which they are associated with will be garbage collected and they will be closed out fully, if not already closed on checkin. A new connection pool is created immediately after the old one has been disposed. This new pool, like all SQLAlchemy connection pools, does not make any actual connections to the database until one is first requested, so as long as the :class:`_engine.Engine` isn't used again, no new connections will be made. .. seealso:: :ref:`engine_disposal` N)rdisposeZrecreaterZengine_disposedr0r'r'r(rQP s  zEngine.disposer'c Cs.|}||||W5QRSQRXdSr2)rmr)r"rrrrr'r'r(rm s zEngine._execute_defaultc cs.|dkr$| }|VW5QRXn|VdSr2)rm)r"r#rr'r'r(_optional_conn_ctx_managers s z!Engine._optional_conn_ctx_managerc@s$eZdZddZddZddZdS)zEngine._trans_ctxcCs||_||_||_dSr2)rrr$)r"rrr$r'r'r(r)| szEngine._trans_ctx.__init__cCs|j|jSr2)rrNrr0r'r'r(rN s zEngine._trans_ctx.__enter__cCs,z|j|||W5|js&|jXdSr2)r$rrOrrTrPr'r'r(rT szEngine._trans_ctx.__exit__N)rrrr)rNrTr'r'r'r( _trans_ctx{ srSc Csb|jjr|}n |j|d}z |}Wn(t|W5QRXYnXt|||S)aXReturn a context manager delivering a :class:`_engine.Connection` with a :class:`.Transaction` established. E.g.:: with engine.begin() as conn: conn.execute( text("insert into table (x, y, z) values (1, 2, 3)") ) conn.execute(text("my_special_procedure(5)")) Upon successful operation, the :class:`.Transaction` is committed. If an error is raised, the :class:`.Transaction` is rolled back. Legacy use only: the ``close_with_result`` flag is normally ``False``, and indicates that the :class:`_engine.Connection` will be closed when the operation is complete. When set to ``True``, it indicates the :class:`_engine.Connection` is in "single use" mode, where the :class:`_engine.CursorResult` returned by the first call to :meth:`_engine.Connection.execute` will close the :class:`_engine.Connection` when that :class:`_engine.CursorResult` has exhausted all result rows. .. seealso:: :meth:`_engine.Engine.connect` - procure a :class:`_engine.Connection` from an :class:`_engine.Engine`. :meth:`_engine.Connection.begin` - start a :class:`.Transaction` for a particular :class:`_engine.Connection`. r$) rErGrmrqr rrOr@rS)r"r$rrr'r'r(rq s#    z Engine.beginr zThe :meth:`_engine.Engine.transaction` method is deprecated and will be removed in a future release. Use the :meth:`_engine.Engine.begin` context manager instead.c Os:d|d<| }|j|f||W5QRSQRXdS)aExecute the given function within a transaction boundary. The function is passed a :class:`_engine.Connection` newly procured from :meth:`_engine.Engine.connect` as the first argument, followed by the given \*args and \**kwargs. e.g.:: def do_something(conn, x, y): conn.execute(text("some statement"), {'x':x, 'y':y}) engine.transaction(do_something, 5, 10) The operations inside the function are all invoked within the context of a single :class:`.Transaction`. Upon success, the transaction is committed. If an exception is raised, the transaction is rolled back before propagating the exception. .. note:: The :meth:`.transaction` method is superseded by the usage of the Python ``with:`` statement, which can be used with :meth:`_engine.Engine.begin`:: with engine.begin() as conn: conn.execute(text("some statement"), {'x':5, 'y':10}) .. seealso:: :meth:`_engine.Engine.begin` - engine-level transactional context :meth:`_engine.Connection.transaction` - connection-level version of :meth:`_engine.Engine.transaction` TrN)rmrr"rrr rr'r'r(r s/ zEngine.transactionzThe :meth:`_engine.Engine.run_callable` method is deprecated and will be removed in a future release. Use the :meth:`_engine.Engine.begin` context manager instead.c Os:d|d<| }|j|f||W5QRSQRXdS)aGiven a callable object or function, execute it, passing a :class:`_engine.Connection` as the first argument. The given \*args and \**kwargs are passed subsequent to the :class:`_engine.Connection` argument. This function, along with :meth:`_engine.Connection.run_callable`, allows a function to be run with a :class:`_engine.Connection` or :class:`_engine.Engine` object without the need to know which one is being dealt with. TrN)rmrrUr'r'r(r s zEngine.run_callablec Ks(|}|j||f|W5QRXdSr2)rqr )r"r r r rr'r'r(r  s zEngine._run_ddl_visitorz:meth:`_engine.Engine.execute`zAll statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`.) alternativecOs|jdd}|j|f||S)aExecutes the given construct and returns a :class:`_engine.CursorResult`. The arguments are the same as those used by :meth:`_engine.Connection.execute`. Here, a :class:`_engine.Connection` is acquired using the :meth:`_engine.Engine.connect` method, and the statement executed with that connection. The returned :class:`_engine.CursorResult` is flagged such that when the :class:`_engine.CursorResult` is exhausted and its underlying cursor is closed, the :class:`_engine.Connection` created here will also be closed, which allows its associated DBAPI connection resource to be returned to the connection pool. TrT)rmr)r"rrrr#r'r'r(r s zEngine.executez:meth:`_engine.Engine.scalar`a'All statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`; the :meth:`_future.Result.scalar` method can then be used to return a scalar result.cOs|j|f||Srr)r"rrrr'r'r(r& sz Engine.scalarcCs|jdd}|||||SNTrT)rmr)r"rrrrWr#r'r'r(r7 s zEngine._execute_clauseelementcCs|jdd}|||||SrW)rmr)r"rrrrWr#r'r'r(rC s zEngine._execute_compiledcCs|j||dS)aReturn a new :class:`_engine.Connection` object. The :class:`_engine.Connection` object is a facade that uses a DBAPI connection internally in order to communicate with the database. This connection is procured from the connection-holding :class:`_pool.Pool` referenced by this :class:`_engine.Engine`. When the :meth:`_engine.Connection.close` method of the :class:`_engine.Connection` object is called, the underlying DBAPI connection is then returned to the connection pool, where it may be used again in a subsequent call to :meth:`_engine.Engine.connect`. rT)rErlr'r'r(rmO szEngine.connectzThe :meth:`_engine.Engine.table_names` method is deprecated and will be removed in a future release. Please refer to :meth:`_reflection.Inspector.get_table_names`.c Cs6||"}t|}||W5QRSQRXdS)zReturn a list of all table names available in the database. :param schema: Optional, retrieve names from a non-default schema. :param connection: Optional, use a specified connection. N)rRr inspectZget_table_names)r"rAr#rinspr'r'r( table_names` s  zEngine.table_nameszThe :meth:`_engine.Engine.has_table` method is deprecated and will be removed in a future release. Please refer to :meth:`_reflection.Inspector.has_table`.c Cs:|d&}t|}|j||dW5QRSQRXdS)a`Return True if the given backend has a table of the given name. .. seealso:: :ref:`metadata_reflection_inspector` - detailed schema inspection using the :class:`_reflection.Inspector` interface. :class:`.quoted_name` - used to pass quoting information along with a schema identifier. N)rA)rRr rX has_table)r"Z table_namerArrYr'r'r(r[r s  zEngine.has_tablec Csp|j}z|WS|jjk rj}z:|dkrs^            f@m'71