L iUdZddlmZddlZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"dd l m#Z#dd!l mZdd"l$m%Z%dd!l$mZ&ejNrdd#l m(Z(dd$l m)Z)dd%lm*Z*dd&lm+Z+dd'lm,Z,dd(lm-Z-dd)lm.Z.dd*lm/Z/dd+lm0Z0dd,lm1Z1dd-lm2Z2dd.lm3Z3dd/lm4Z4dd0lm5Z5dd1l6m7Z7dd2l8m9Z9dd3l:m;Z;dd4l#mZ>dd6l=m?Z?dd7l=m@Z@dd8l$mAZAdd9lBmCZCdd:lDmEZEdd;lFmGZGddlKmLZLdd?lKmMZMdd@lKmNZNddAlOmPZPedBeCZQejZSdDeTdE<ejZUdFeTdG<GdHdIee"jdJZWGdKdLeZXGdMdNeZYGdOdPeYZZGdQdReYZ[GdSdTeZZ\GdUdVee#je"jdJZ^GdWdXe#jZ_GdYdZe_e^Z`e`e^_ay)[z@Defines :class:`_engine.Connection` and :class:`_engine.Engine`.) annotationsN)Any)Callable)cast)Iterable)Iterator)List)Mapping)NoReturn)Optional)overload)Tuple)Type)TypeVar)Union) BindTyping)ConnectionEventsTarget) DBAPICursor)ExceptionContext) ExecuteStyle)ExecutionContext)IsolationLevel)_distill_params_20)_distill_raw_params)TransactionalContext)exc) inspection)log)util)compiler) CursorResult) ScalarResult)_AnyExecuteParams)_AnyMultiExecuteParams)_CoreAnyExecuteParams)_CoreMultiExecuteParams)_CoreSingleExecuteParams)_DBAPIAnyExecuteParams)_DBAPISingleExecuteParams)_ExecuteOptions)CompiledCacheType)CoreExecuteOptionsParameter)Dialect)SchemaTranslateMapType) Inspector)URL) dispatcher) _EchoFlagType)_ConnectionFairy)Pool)PoolProxiedConnection) Executable) _InfoType)Compiled)ExecutableDDLElement) InvokeDDLBase)FunctionElement)DefaultGenerator) HasSchemaAttr)SchemaVisitable)TypedReturnsRows_T)boundr,_EMPTY_EXECUTION_OPTSzMapping[str, Any] NO_OPTIONSc eZdZUdZded<ded<dZdZded <d Zd ed <d ed<ded<ded< da dbdZdZ ded<dcdZ dcdZ e dddZ dedZdfdZdgdZedddd d ddddd d dhdZedidZdid Zdjd!Ze dkd"Ze dkd#Ze dkd$Ze dld%Zdmd&Ze dnd'Zdod(Zdld)Ze dpd*Zdqdrd+Zdsd,Zdsd-Zdtd.Z dud/Z!dqdvd0Z"dsd1Z#dsd2Z$dwd3Z%dxdyd4Z&dxdyd5Z'dkd6Z(dkd7Z)dkd8Z*dtd9Z+dud:Z,dzd;Z-d{d<Z.d|d=Z/dsd>Z0dsd?Z1dqd}d@Z2d~dAZ3d~dBZ4ddCZ5ddDZ6ddEZ7ddFZ8dsdGZ9e dqddH ddIZ:e dqddH ddJZ: dqddH ddKZ:e dqddH ddLZ;e dqddH ddMZ; dqddH ddNZ;e dqddH ddOZ ddTZ? ddUZ@ ddVZAeBf ddWZC d ddXZD ddYZE ddZZF dd[ZG dq dd\ZHdd]ZId ZJd ZK dx dd^ZLeM d dd_ZN dd`ZOy) Connectiona:Provides high-level functionality for a wrapped DB-API 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 r/dialect"dispatcher[ConnectionEventsTarget]dispatchzsqlalchemy.engine.ConnectionNzOptional[TransactionalContext]_trans_context_managerFOptional[PoolProxiedConnection]_dbapi_connectionr,_execution_optionsOptional[RootTransaction] _transactionOptional[NestedTransaction]_nested_transactionc||_|jx|_}| |j|_n||_dx|_|_ d|_ d|_ ||_ ||_ |jj|_|*|j j#|j |_|xs|duxr |j$|_|j&|_|j$s|jj$r|j j)|yy#|jj $r}t j|||d}~wwxYw)zConstruct a new Connection.NrF)enginerHraw_connectionrM loaded_dbapiErrorrG$_handle_dbapi_exception_noconnectionrPrR_Connection__savepoint_seq_Connection__in_begin_Connection__can_reconnect_allow_autobegin_should_log_info_echorJ_join _has_eventsrNengine_connect)selfrT connectionr`_allow_revalidater\rHerrs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/engine/base.py__init__zConnection.__init__s= !'/ w   )/)>)>)@&&0D "7;;D4 0 0[[113  !MM//@DM& 4  6F$6$6 #)";";   t{{66 MM ( ( . 77''-- ??&  sDE4E  Er_message_formatterc|j}|r||}tjrdtjz|d<|jj j |g|i|yNr stacklevel)rhr STACKLEVELSTACKLEVEL_OFFSETrTloggerinforbmessageargkwfmts rf _log_infozConnection._log_infosY%% 'lG >> 3#8#88B|  4#44c|j}|r||}tjrdtjz|d<|jj j |g|i|yrj)rhr rlrmrTrndebugrps rf _log_debugzConnection._log_debugsY%% 'lG >> 3#8#88B|     535"5rvc>|jjdd}|S)Nschema_translate_map)rNget)rbr{s rf_schema_translate_mapz Connection._schema_translate_maps(  # # ' '(> E $#rvc|j}|jjdd}|r||vr|jr||S|S)ztReturn the schema name for the given schema item taking into account current schema translate map. r{N)schemarNr|_use_schema_map)rbobjnamer{s rfschema_for_objectzConnection.schema_for_objectsP zz  # # ' '(> E  !,,##'- -Krvc|SNrbs rf __enter__zConnection.__enter__s rvc$|jyr)close)rbtype_value tracebacks rf__exit__zConnection.__exit__s  rv.) compiled_cache logging_tokenisolation_level no_parametersstream_resultsmax_row_buffer yield_perinsertmanyvalues_page_sizer{preserve_rowcountc yrr) rbrrrrrrrrr{ropts rfexecution_optionszConnection.execution_optionssrvc yrrrbrs rfrzConnection.execution_optionss;>rvc |js|jjr|jj|||jj ||_|j j|||S)a0Set non-SQL options for the connection which take effect during execution. This method modifies this :class:`_engine.Connection` **in-place**; the return value is the same :class:`_engine.Connection` object upon which the method is called. Note that this is in contrast to the behavior of the ``execution_options`` methods on other objects such as :meth:`_engine.Engine.execution_options` and :meth:`_sql.Executable.execution_options`. The rationale is that many such execution options necessarily modify the state of the base DBAPI connection in any case so there is no feasible means of keeping the effect of such an option localized to a "sub" connection. .. versionchanged:: 2.0 The :meth:`_engine.Connection.execution_options` method, in contrast to other objects with this method, modifies the connection in-place without creating copy of it. As discussed elsewhere, the :meth:`_engine.Connection.execution_options` method accepts any arbitrary parameters including user defined names. All parameters given are consumable in a number of ways including by using the :meth:`_engine.Connection.get_execution_options` method. See the examples at :meth:`_sql.Executable.execution_options` and :meth:`_engine.Engine.execution_options`. 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 compiled_cache: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. 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`, :class:`_sql.Executable`. 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`, :class:`_engine.Engine`. 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**. The isolation level will remain at the given setting until explicitly changed, or when the DBAPI connection itself is :term:`released` to the connection pool, i.e. the :meth:`_engine.Connection.close` method is called, at which time an event handler will emit additional statements on the DBAPI connection in order to revert the isolation level change. .. note:: The ``isolation_level`` execution option may only be established before the :meth:`_engine.Connection.begin` method is called, as well as before any SQL statements are emitted which would otherwise trigger "autobegin", or directly after a call to :meth:`_engine.Connection.commit` or :meth:`_engine.Connection.rollback`. A database cannot change the isolation level on a transaction in progress. .. 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 selected isolation level re-applied to it automatically. .. seealso:: :ref:`dbapi_autocommit` :meth:`_engine.Connection.get_isolation_level` - view current actual level :param no_parameters: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. 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: :class:`_engine.Connection`, :class:`_sql.Executable`. Indicate to the dialect that results should be "streamed" and not pre-buffered, if possible. For backends such as PostgreSQL, MySQL and MariaDB, this indicates the use of a "server side cursor" as opposed to a client side cursor. Other backends such as that of Oracle Database may already use server side cursors by default. The usage of :paramref:`_engine.Connection.execution_options.stream_results` is usually combined with setting a fixed number of rows to to be fetched in batches, to allow for efficient iteration of database rows while at the same time not loading all result rows into memory at once; this can be configured on a :class:`_engine.Result` object using the :meth:`_engine.Result.yield_per` method, after execution has returned a new :class:`_engine.Result`. If :meth:`_engine.Result.yield_per` is not used, the :paramref:`_engine.Connection.execution_options.stream_results` mode of operation will instead use a dynamically sized buffer which buffers sets of rows at a time, growing on each batch based on a fixed growth size up until a limit which may be configured using the :paramref:`_engine.Connection.execution_options.max_row_buffer` parameter. When using the ORM to fetch ORM mapped objects from a result, :meth:`_engine.Result.yield_per` should always be used with :paramref:`_engine.Connection.execution_options.stream_results`, so that the ORM does not fetch all rows into new ORM objects at once. For typical use, the :paramref:`_engine.Connection.execution_options.yield_per` execution option should be preferred, which sets up both :paramref:`_engine.Connection.execution_options.stream_results` and :meth:`_engine.Result.yield_per` at once. This option is supported both at a core level by :class:`_engine.Connection` as well as by the ORM :class:`_engine.Session`; the latter is described at :ref:`orm_queryguide_yield_per`. .. seealso:: :ref:`engine_stream_results` - background on :paramref:`_engine.Connection.execution_options.stream_results` :paramref:`_engine.Connection.execution_options.max_row_buffer` :paramref:`_engine.Connection.execution_options.yield_per` :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` describing the ORM version of ``yield_per`` :param max_row_buffer: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. Sets a maximum buffer size to use when the :paramref:`_engine.Connection.execution_options.stream_results` execution option is used on a backend that supports server side cursors. The default value if not specified is 1000. .. seealso:: :paramref:`_engine.Connection.execution_options.stream_results` :ref:`engine_stream_results` :param yield_per: Available on: :class:`_engine.Connection`, :class:`_sql.Executable`. Integer value applied which will set the :paramref:`_engine.Connection.execution_options.stream_results` execution option and invoke :meth:`_engine.Result.yield_per` automatically at once. Allows equivalent functionality as is present when using this parameter with the ORM. .. versionadded:: 1.4.40 .. seealso:: :ref:`engine_stream_results` - background and examples on using server side cursors with Core. :ref:`orm_queryguide_yield_per` - in the :ref:`queryguide_toplevel` describing the ORM version of ``yield_per`` :param insertmanyvalues_page_size: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`. Number of rows to format into an INSERT statement when the statement uses "insertmanyvalues" mode, which is a paged form of bulk insert that is used for many backends when using :term:`executemany` execution typically in conjunction with RETURNING. Defaults to 1000. May also be modified on a per-engine basis using the :paramref:`_sa.create_engine.insertmanyvalues_page_size` parameter. .. versionadded:: 2.0 .. seealso:: :ref:`engine_insertmanyvalues` :param schema_translate_map: Available on: :class:`_engine.Connection`, :class:`_engine.Engine`, :class:`_sql.Executable`. 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. .. seealso:: :ref:`schema_translating` :param preserve_rowcount: Boolean; when True, the ``cursor.rowcount`` attribute will be unconditionally memoized within the result and made available via the :attr:`.CursorResult.rowcount` attribute. Normally, this attribute is only preserved for UPDATE and DELETE statements. Using this option, the DBAPIs rowcount value can be accessed for other kinds of statements such as INSERT and SELECT, to the degree that the DBAPI supports these statements. See :attr:`.CursorResult.rowcount` for notes regarding the behavior of this attribute. .. versionadded:: 2.0.28 .. seealso:: :meth:`_engine.Engine.execution_options` :meth:`.Executable.execution_options` :meth:`_engine.Connection.get_execution_options` :ref:`orm_queryguide_execution_options` - documentation on all ORM-specific execution options )r`rTrJ set_connection_execution_optionsrNunionrHrs rfrzConnection.execution_optionss`B   t{{66 MM : :4 E"&"9"9"?"?"D 55dC@ rvc|jS)zGet the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`_engine.Connection.execution_options` rNrs rfget_execution_optionsz Connection.get_execution_options&&&rvc>|j}|duxr |jSr)rMis_validrbpool_proxied_connections rf)_still_open_and_dbapi_connection_is_validz4Connection._still_open_and_dbapi_connection_is_valids)"&"8"8 #4 / 1'00 rvc<|jduxr |j S)z)Return True if this connection is closed.NrMr[rs rfclosedzConnection.closeds#%%-Jd6J6J2JJrvc>|j}|duxr |jS)zReturn True if this connection was invalidated. This does not indicate whether or not the connection was invalidated at the pool level, however Nrrs rf invalidatedzConnection.invalidateds&$#'"8"8&$.G43G3GGrvc|j |jS|jS#tjtjf$rt $r}|j |ddddYd}~yd}~wwxYw)aVThe underlying DB-API connection managed by this Connection. This is a SQLAlchemy connection-pool proxied connection which then has the attribute :attr:`_pool._ConnectionFairy.dbapi_connection` that refers to the actual driver connection. .. seealso:: :ref:`dbapi_connections` N)rM_revalidate_connectionrPendingRollbackErrorResourceClosedError BaseException_handle_dbapi_exceptionrbes rfrczConnection.connection3s|  ! ! ) H2244 )) ) ,,c.E.EF   H,,QdD$GG Hs*,A5A00A5c|jj}|J |jj|S#t$r}|j |ddddYd}~yd}~wwxYw)aReturn the current **actual** isolation level that's present on the database within the scope of this connection. This attribute will perform a live SQL operation against the database 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. This will be one of the four actual isolation modes ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``, ``SERIALIZABLE``. It will **not** include the ``AUTOCOMMIT`` isolation level setting. Third party dialects may also feature additional isolation level settings. .. note:: This method **will not report** on the ``AUTOCOMMIT`` isolation level, which is a separate :term:`dbapi` setting that's independent of **actual** isolation level. When ``AUTOCOMMIT`` is in use, the database connection still has a "traditional" isolation mode in effect, that is typically one of the four values ``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``, ``SERIALIZABLE``. Compare to the :attr:`_engine.Connection.default_isolation_level` accessor which returns the isolation level that is present on the database at initial connection time. .. 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)rcdbapi_connectionrHget_isolation_levelrr)rbrrs rfrzConnection.get_isolation_levelMshJ ??;;+++ D<<334DE E D  ( (D$d C C Ds7 AAAc.|jjS)aThe initial-connection time isolation level associated with the :class:`_engine.Dialect` in use. This value is independent of the :paramref:`.Connection.execution_options.isolation_level` and :paramref:`.Engine.execution_options.isolation_level` execution options, and is determined by the :class:`_engine.Dialect` when the first connection is created, by performing a SQL query against the database for the current isolation level before any additional commands have been emitted. Calling this accessor does not invoke any new SQL queries. .. seealso:: :meth:`_engine.Connection.get_isolation_level` - view current actual isolation 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 )rHdefault_isolation_levelrs rfrz"Connection.default_isolation_levelys6||333rvcRtjd|jdndzd)NzfCan't reconnect until invalid %stransaction is rolled back. Please rollback() fully before proceedingz savepoint 8s2b)code)rrrRrs rf_invalid_transactionzConnection._invalid_transactions5&& ?#77C| M   rvc|jrS|jrG|j|j|jj |_|j Stjd)NThis Connection is closed) r[rrPrrTrUrMrrrs rfrz!Connection._revalidate_connections^   D$4$4  ,))+%)[[%?%?%AD ")) )%%&ABBrvc.|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`. )rcrors rfrozConnection.infos###rvc|jry|jrtjd|jr!|j }|J|j |d|_y)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` Nr)rrrrrrM invalidate)rb exceptionrs rfrzConnection.invalidatesa\     ;;))*EF F  9 9&*&<&< #*6 66 # . .y 9!%rvc|jrtjd|j}|tjd|j y)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). rNz&Can't detach an invalidated Connection)rrrrMInvalidRequestErrordetachrs rfrzConnection.detachsS4 ;;))*EF F"&"8"8 " *))8  &&(rvcX|jr|js|jyyyr)r\rZbeginrs rf _autobeginzConnection._autobegins"   JJL*9 rvc||jt||_|jStjd)a Begin a transaction prior to autobegin occurring. E.g.:: with engine.connect() as conn: with conn.begin() as trans: conn.execute(table.insert(), {"username": "sandy"}) The returned object is an instance of :class:`_engine.RootTransaction`. This object represents the "scope" of the transaction, which completes when either the :meth:`_engine.Transaction.rollback` or :meth:`_engine.Transaction.commit` method is called; the object also works as a context manager as illustrated above. The :meth:`_engine.Connection.begin` method begins a transaction that normally will be begun in any case when the connection is first used to execute a statement. The reason this method might be used would be to invoke the :meth:`_events.ConnectionEvents.begin` event at a specific time, or to organize code within the scope of a connection checkout in terms of context managed blocks, such as:: with engine.connect() as conn: with conn.begin(): conn.execute(...) conn.execute(...) with conn.begin(): conn.execute(...) conn.execute(...) The above code is not fundamentally any different in its behavior than the following code which does not use :meth:`_engine.Connection.begin`; the below style is known as "commit as you go" style:: with engine.connect() as conn: conn.execute(...) conn.execute(...) conn.commit() conn.execute(...) conn.execute(...) conn.commit() From a database point of view, the :meth:`_engine.Connection.begin` method does not emit any SQL or change the state of the underlying DBAPI connection in any way; the Python DBAPI does not have any concept of explicit transaction begin. .. seealso:: :ref:`tutorial_working_with_transactions` - in the :ref:`unified_tutorial` :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` zThis connection has already initialized a SQLAlchemy Transaction() object via begin() or autobegin; can't call begin() here unless rollback() or commit() is called first.)rPRootTransactionrrrs rfrzConnection.beginsB@    $ / 5D $$ $))# rvcP|j|jt|S)a Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle that controls the scope of the SAVEPOINT. E.g.:: with engine.begin() as connection: with connection.begin_nested(): connection.execute(table.insert(), {"username": "sandy"}) The returned object is an instance of :class:`_engine.NestedTransaction`, which includes transactional methods :meth:`_engine.NestedTransaction.commit` and :meth:`_engine.NestedTransaction.rollback`; for a nested transaction, these methods correspond to the operations "RELEASE SAVEPOINT " and "ROLLBACK TO SAVEPOINT ". The name of the savepoint is local to the :class:`_engine.NestedTransaction` object and is generated automatically. Like any other :class:`_engine.Transaction`, the :class:`_engine.NestedTransaction` may be used as a context manager as illustrated above which will "release" or "rollback" corresponding to if the operation within the block were successful or raised an exception. Nested transactions require SAVEPOINT support in the underlying database, else the behavior is undefined. SAVEPOINT is commonly used to run operations within a transaction that may fail, while continuing the outer transaction. E.g.:: from sqlalchemy import exc with engine.begin() as connection: trans = connection.begin_nested() try: connection.execute(table.insert(), {"username": "sandy"}) trans.commit() except exc.IntegrityError: # catch for duplicate username trans.rollback() # rollback to savepoint # outer transaction continues connection.execute(...) If :meth:`_engine.Connection.begin_nested` is called without first calling :meth:`_engine.Connection.begin` or :meth:`_engine.Engine.begin`, the :class:`_engine.Connection` object will "autobegin" the outer transaction first. This outer transaction may be committed using "commit-as-you-go" style, e.g.:: with engine.connect() as connection: # begin() wasn't called with connection.begin_nested(): # will auto-"begin()" first connection.execute(...) # savepoint is released connection.execute(...) # explicitly commit outer transaction connection.commit() # can continue working with connection here .. versionchanged:: 2.0 :meth:`_engine.Connection.begin_nested` will now participate in the connection "autobegin" behavior that is new as of 2.0 / "future" style connections in 1.4. .. seealso:: :meth:`_engine.Connection.begin` :ref:`session_begin_nested` - ORM support for SAVEPOINT )rPrNestedTransactionrs rf begin_nestedzConnection.begin_nestedbs&R    $ OO  &&rvc|jtjd|$|jjj }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` zOCannot start a two phase transaction when a transaction is already in progress.)rPrrrTrH create_xidTwoPhaseTransaction)rbxids rfbegin_twophasezConnection.begin_twophasesT(    ())*  ;++%%002C"4--rvcR|jr|jjyy)aCommit the transaction that is currently in progress. This method commits the current transaction if one has been started. If no transaction was started, the method has no effect, assuming the connection is in a non-invalidated state. A transaction is begun on a :class:`_engine.Connection` automatically whenever a statement is first executed, or when the :meth:`_engine.Connection.begin` method is called. .. note:: The :meth:`_engine.Connection.commit` method only acts upon the primary database transaction that is linked to the :class:`_engine.Connection` object. It does not operate upon a SAVEPOINT that would have been invoked from the :meth:`_engine.Connection.begin_nested` method; for control of a SAVEPOINT, call :meth:`_engine.NestedTransaction.commit` on the :class:`_engine.NestedTransaction` that is returned by the :meth:`_engine.Connection.begin_nested` method itself. N)rPcommitrs rfrzConnection.commits$,       $ $ & rvcR|jr|jjyy)aYRoll back the transaction that is currently in progress. This method rolls back the current transaction if one has been started. If no transaction was started, the method has no effect. If a transaction was started and the connection is in an invalidated state, the transaction is cleared using this method. A transaction is begun on a :class:`_engine.Connection` automatically whenever a statement is first executed, or when the :meth:`_engine.Connection.begin` method is called. .. note:: The :meth:`_engine.Connection.rollback` method only acts upon the primary database transaction that is linked to the :class:`_engine.Connection` object. It does not operate upon a SAVEPOINT that would have been invoked from the :meth:`_engine.Connection.begin_nested` method; for control of a SAVEPOINT, call :meth:`_engine.NestedTransaction.rollback` on the :class:`_engine.NestedTransaction` that is returned by the :meth:`_engine.Connection.begin_nested` method itself. N)rProllbackrs rfrzConnection.rollbacks$.       & & ( rvcL|jjj|Sr)rTrHdo_recover_twophasers rfrecover_twophasezConnection.recover_twophases{{""66t<s ::,,.' 12   t{{66 MM   % $ KK   ( ( 9$DO D  ( (D$d C C D$DOs*/B<< C$CC'C$$C'' C0c|js|jjr|jj||jr|j r[|j r:|jjr|jdn#|jdn|jd |jjj|jyy#t$r}|j|ddddYd}~yd}~wwxYw)Nz4ROLLBACK will be skipped by skip_autocommit_rollbackzYROLLBACK using DBAPI connection.rollback(); set skip_autocommit_rollback to prevent fullyROLLBACK)r`rTrJrrr^rrHskip_autocommit_rollbackru do_rollbackrcrrrs rf_rollback_implzConnection._rollback_implTs   t{{66 MM " "4 (  9 9zz002||<<7 L NN:. H ##//@! :"! H,,QdD$GG Hs2/C## D ,DD c|js|jjr|jj||jr3|j r|j dn|j d |jjj|jy#t$r}|j|ddddYd}~yd}~wwxYw)NzLCOMMIT using DBAPI connection.commit(), has no effect due to autocommit modeCOMMIT) r`rTrJrr^rrurH do_commitrcrrrs rf _commit_implzConnection._commit_implls   t{{66 MM  & ::,,.; x( D KK   ) )$// : D  ( (D$d C C Ds>/B.. C7CCc|js|jjr|jj|||$|xjdz c_d|jz}|jj j |||S)Nrzsa_savepoint_%s)r`rTrJ savepointrYrH do_savepointrbrs rf_savepoint_implzConnection._savepoint_impl}sp   t{{66 MM # #D$ / <  A % $t';';;D ((t4 rvc|js|jjr|jj||d|jr'|jj j ||yyr)r`rTrJrollback_savepointrrHdo_rollback_to_savepointr s rf_rollback_to_savepoint_implz&Connection._rollback_to_savepoint_implsU   t{{66 MM , ,T4 >  9 9 KK   8 8t D :rvc|js|jjr|jj||d|jjj ||yr)r`rTrJrelease_savepointrHdo_release_savepointr s rf_release_savepoint_implz"Connection._release_savepoint_implsG   t{{66 MM + +D$ = 00t D  ( (D$d C C Ds&B B+ B&&B+cz|js|jjr|jj||||jrEt |j tsJ |jjj|||yy#t$r}|j|ddddYd}~yd}~wwxYwr) r`rTrJrollback_twophaserrrPrrHrrrrbr is_preparedrs rf_rollback_twophase_implz"Connection._rollback_twophase_impls   t{{66 MM + +D#{ C  9 9d//1DE EE H ##88#{ : ! H,,QdD$GG Hs)'B B:B55B:c`|js|jjr|jj|||t |j t sJ |jjj|||y#t$r}|j|ddddYd}~yd}~wwxYwr) r`rTrJcommit_twophaserrPrrHrrrr!s rf_commit_twophase_implz Connection._commit_twophase_impls   t{{66 MM ) )$[ A$++-@AAA D KK   2 24k J D  ( (D$d C C Ds'B B-B((B-c|jr|jjd}nd}|jB|j}|rtd|j dn|jd|_d|_y)aClose 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`. This has the effect of also calling :meth:`_engine.Connection.rollback` if any transaction is in place. After :meth:`_engine.Connection.close` is called, the :class:`_engine.Connection` is permanently in a closed state, and will allow no further operations. TFNr5)transaction_reset)rPrrMr_close_specialr[)rb skip_resetconns rfrzConnection.closes.       # # %JJ  ! ! -))D'.==&*> &*D "$rvrcyrrrb statement parametersrs rfscalarzConnection.scalarsrvcyrrr.s rfr1zConnection.scalarsrvct|} |j}||||xstS#t$r}t j ||d}~wwxYw)auExecutes a SQL statement construct and returns a scalar object. This method is shorthand for invoking the :meth:`_engine.Result.scalar` method after invoking the :meth:`_engine.Connection.execute` method. Parameters are equivalent. :return: a scalar Python value representing the first column of the first row returned. N)r_execute_on_scalarrEAttributeErrorrObjectNotExecutableErrorrbr/r0rdistilled_parametersmethres rfr1zConnection.scalarsc" 2*= //D$!/Z  C..y9s B C + AA  Acyrrr.s rfscalarszConnection.scalars"rvcyrrr.s rfr<zConnection.scalars+ rvcF|j|||jS)aExecutes and returns a scalar result set, which yields scalar values from the first column of each row. This method is equivalent to calling :meth:`_engine.Connection.execute` to receive a :class:`_result.Result` object, then invoking the :meth:`_result.Result.scalars` method to produce a :class:`_result.ScalarResult` instance. :return: a :class:`_result.ScalarResult` .. versionadded:: 1.4.24 r,)executer<r.s rfr<zConnection.scalars4s)*|| z5F ') rvcyrrr.s rfrAzConnection.executeMr=rvcyrrr.s rfrAzConnection.executeVr?rvct|} |j}||||xstS#t$r}t j ||d}~wwxYw)aExecutes a SQL statement construct and returns a :class:`_engine.CursorResult`. :param statement: The statement to be executed. This is always an object that is in both the :class:`_expression.ClauseElement` and :class:`_expression.Executable` hierarchies, including: * :class:`_expression.Select` * :class:`_expression.Insert`, :class:`_expression.Update`, :class:`_expression.Delete` * :class:`_expression.TextClause` and :class:`_expression.TextualSelect` * :class:`_schema.DDL` and objects which inherit from :class:`_schema.ExecutableDDLElement` :param parameters: parameters which will be bound into the statement. This may be either a dictionary of parameter names to values, or a mutable sequence (e.g. a list) of dictionaries. When a list of dictionaries is passed, the underlying statement execution will make use of the DBAPI ``cursor.executemany()`` method. When a single dictionary is passed, the DBAPI ``cursor.execute()`` method will be used. :param execution_options: optional dictionary of execution options, which will be associated with the statement execution. This dictionary can provide a subset of the options that are accepted by :meth:`_engine.Connection.execution_options`. :return: a :class:`_engine.Result` object. N)r_execute_on_connectionrEr5rr6r7s rfrAzConnection.execute_sdL 2*= 33D$!/Z  C..y9s B Cr:cD|j|j||S)z%Execute a sql.FunctionElement object.)_execute_clauseelementselect)rbfuncr8rs rf_execute_functionzConnection._execute_functions&** KKM/1B  rvc|jj|}|js|jjr|j |||\}}}}ndx}} |j }||j }|j}|jj||||}jd|d} |js|jjr |j j#|||||| | S#tjtjf$rt$r} |j| ddddYd} ~ d} ~ wwxYw)z&Execute a schema.ColumnDefault object.N)rN merge_withr`rT_invoke_before_exec_eventrMrrHexecution_ctx_cls _init_defaultrrrrr _exec_defaultrJ after_execute) rbdefaultr8revent_multiparams event_paramsr+rHctxrrets rf_execute_defaultzConnection._execute_defaultsX!33>>     t{{66 ..-/@  $! 04 3   D))D|224llG++99t%6Cgt4   t{{66 MM ' '!!   #((#*A*AB   D  ( (D$d C C DsAC;;,E'EEc |jj|j|}|js|jjr|j |||\}}}}ndx}}|j dd}|j }|j||} |j||jj| d|| } |js|jjr |jj|||||| | S)zExecute a schema.DDL object.Nr{)rHr{) rNrLr`rTrMr|rHcompile_execute_contextrN _init_ddlrJrQ) rbddlr8r exec_optsrSrTr{rHcompiledrVs rf _execute_ddlzConnection._execute_ddls**55  # #%6    t{{66 ..)9  $! 04 3  (}}-CTJ,,;;2F ##   % % / /         t{{66 MM ' '!   rvct|dk(rg|d}}n|i}}|jjD]}||||||\}}}|r"t|}|rt j d|r|g}ng}||||fS)NrrzLEvent handler can't return non-empty multiparams and params at the same time)lenrJbefore_executelistrr)rbelemdistilled_paramsrrSrTfns rfrMz$Connection._invoke_before_exec_event s  A %.02B12E| .>| --.. B46!! 5 1D#\  #$56 --2 ,~ ! %'8,FFrvc |jj|j|}|jxs|jj}|r|j |||\}}}}|rt |d}t |dkD}ng}d}|j} |jdd} |jd|jj} |j| | ||| |jjtjz\} } }|j| | jj | ||| ||| | }|r |j"j%|||||S) z#Execute a sql.ClauseElement object.rrFr{Nr)rHr column_keysfor_executemanyr{linting) cache_hit)rNrLr`rTrMsortedrarHr|_compiled_cache_compile_w_cachecompiler_lintingr" WARN_LINTINGrZrN_init_compiledrJrQ)rbrdr8r has_eventsrSrTkeysrirHr{r compiled_sqlextracted_paramsrkrVs rfrGz!Connection._execute_clauseelement7s!33>>  # #%6 %%@)@)@  ..*,=  $! .q12D!"67!;OD#O,,044 "D 7H6K6K dkk997 594I4I)+!5LL11H4I4II 5J5 1 & ##   % % 4 4     $    MM ' '!!   rvc |jj|j|}|js|jjr|j |||\}}}}|j }|j||jj|||||dd }|js|jjr |jj|||||S)ziExecute a sql.Compiled object. TODO: why do we have this? likely deprecate or remove N) rrLrNr`rTrMrHrZrNrqrJrQ)rbr^r8rrSrTrHrVs rf_execute_compiledzConnection._execute_compileds%66AA  # #%6    t{{66 ...0A  $! ,,##   % % 4 4          t{{66 MM ' '!!   rvc t|}|jj|}|j}|j ||j j |d|||}|S)aLExecutes a string SQL statement on the DBAPI cursor directly, without any SQL compilation steps. This can be used to pass any string directly to the ``cursor.execute()`` method of the DBAPI in use. :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. :return: a :class:`_engine.CursorResult`. 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` N)rrNrLrHrZrN_init_statement)rbr/r0rr8rHrVs rfexec_driver_sqlzConnection.exec_driver_sqlsmt 3:> 33>>  ,,##   % % 5 5       rvc*|r(|jdd}|r|jd|d} |j} | |j} |||| |g|i|} |jr|jjr"|jr'|jjs|jn!|jrtj ||j|j# j%| j&t(j*ur|j-|| S|j/|| ||S#tj tj f$rt$r)} |j| t||ddYd} ~ 4d} ~ wwxYw)zdCreate an :class:`.ExecutionContext` and execute, returning a :class:`_engine.CursorResult`.rNT)rr)r|rrMrrrrrrstrrPrrRrrKr_trans_ctx_checkrpre_exec execute_stylerINSERTMANYVALUES_exec_insertmany_context_exec_single_context) rbrH constructorr/r0rargsrsypr+contextrs rfrZzConnection._execute_contexts "&&{D9B$5$;$;'+rB%! ))D|224!t%69=ACG   %%//((00::  % % '  ( ( 1 1$ 7    $ OO   L$A$A A00'B B,,)Z 9((#*A*AB     ( (3y>:tT   s-D==,F)F  Fc p|jtjur0|j}|r |j |j |||j |j|j}}}|js|d} n|} |js|jjr5|jjD]} | |||| ||j\}} |j r}|j#||j%} |jj&s4|j#d| t)j*| d|jn|j#d| d} |j,t.j0urxt3d| } |j4jr4|j4jj6D]} | ||| |sd } n| s |j4j7||| |n| su|j8ri|j4jr3|j4jj:D]} | |||sd } n| s|j4j;|||nvt3d | } |j4jr4|j4jj<D]} | ||| |sd } n| s|j4j=||| ||js|jjr*|jj?|||| ||j|jA|jC} | S#t $r)}|j|t||d|Yd}~7d}~wwxYw#t $r }|j||| ||Yd}~ Sd}~wwxYw) zzcontinue the _execute_context() method for a single DBAPI cursor.execute() or cursor.executemany() call. Nr[%s] %r batchesismulti8[%s] [SQL parameters hidden due to hide_parameters=True]Fr(Tr))" bind_typingr SETINPUTSIZES_prepare_set_input_sizesdo_set_input_sizescursorrrr|r/r0 executemanyr`rTrJbefore_cursor_executer^ru_get_cache_statshide_parameterssql_util _repr_paramsrr EXECUTEMANYrrHdo_executemanyrdo_execute_no_params do_executeafter_cursor_execute post_exec_setup_result_proxy)rbrHrr/r0generic_setinputsizesrr str_statementeffective_parametersrfstats evt_handledresults rfrzConnection._exec_single_context:s   *":": :$+$D$D$F !$..(=w NN       * ""#-a= #-   t{{66mm99 68!('' 73 3  :: NN= ),,.E;;..)), " ' 3 3N " D $$ (@(@@'+-/C($<<++"ll33BB"")0#  +/K!"#LL//%,  *g.C.C<<++"ll33HH"fmW=*.K!"#LL55 w(,.0D($<<++"ll33>>"")0#  +/K!"#LL++ /CW4;;#:#: 22!(''     002F s%003y>:tWh   ( (="6    sEM(A,N A8N A5N BN  N  NN  N5N00N5c j|jtjur|j}nd}|j|j |j }}}|}|jxs|jj}|jjr!|jjj} nd} |jr|jdz} |jjdd} d} |j!||||||D]} | j"r( |j%|j| j"|| j.}| j0}|r+|jj2D]}||||||d\}}|jr|j5t+j,|d | j6d | j8d | j:rd nd | j<rdndd}| j6dk(r |z } nd|} |jj>s*|j5d| t+j@|ddn|j5d|  | D]}|||||sn|j|||||r*|jjC||||||jD| s| | jFz }  |jI| r| |_%|jM}|S#t&$rI}|j)|t+j,| j.| j0d|dYd}~d}~wwxYw#t&$r4}|j)|t+j,||||dYd}~d}~wwxYw#t&$r }|j)|||||Yd}~Sd}~wwxYw)zcontinue the _execute_context() method for an "insertmanyvalues" operation, which will invoke DBAPI cursor.execute() one or more times with individual log and event hook calls. Nrz (insertmanyvalues)rFrT) is_sub_exec /z (ordered unorderedz; batch not supportedr)rinsertmanyvaluesrrrr)'rrrrrr/r0r`rTrHrJrr^rrr|!_deliver_insertmanyvalues_batchesprocessed_setinputsizesrrrr_long_statementreplaced_statementreplaced_parametersrrubatchnum total_batches rows_sorted is_downgradedrrrrcurrent_batch_sizer _rowcountr)rbrHrrrrr0r engine_eventsdo_execute_dispatchrrrowcount imv_batchrsub_stmt sub_paramsrf imv_statsrs rfrz#Connection._exec_insertmany_contexts   *":": :$+$D$D$F !$( ! NN       *  *((CDKK,C,C << # # %%00 #%  ::,,.1FFE#5599   BB    !   q 9I00..!99!33H"66J--==B+- " ,(Hjzzx77AB !)"4"4!5Q%337 ,,2= !..,  %%*Y&E.yk:E{{22NN! --&$&$)NN0  -B "  && " " 22!('' !I888cq 9f      $,!002F c%00 001M1MN!55$( 1Z! ,,,,X6 $ - >   ( (="6    sN'K4M /M  )N 4 M=>MM N*NN N2N--N2c |js|jjr+|jjD]}||||||d\}}|jr#|j ||j d| |j jsdn|j jjD]}|||||sn|j j|||||js|jjr!|jj|||||dyy#t$r}|j|||||Yd}~gd}~wwxYw)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] %rrN) r`rTrJrr^rurHrrrr)rbrr/r0rrfrs rf_cursor_executezConnection._cursor_executessC"   t{{66mm99 (*&)Z%)% :  :: NN9 % NN>: 6 ||//\\**55 P fiW=  P '' :wO   t{{66 MM . .fiWe  7    ( (9j&'   s>AD*!D** E3E  Ec |jy#t$r4|jjjj ddYywxYw)z\Close the given cursor, catching exceptions and turning into log warnings. zError closing cursorT)exc_infoN)r ExceptionrTpoolrnerror)rbrs rf_safe_close_cursorzConnection._safe_close_cursorsG   LLN  KK   # # ) )& *  s:AAcZtj}tj|}|jst ||j jjxrD|j xr5|j j||js |jnd|xs|xr |j |_| } || xr|jnd} |jrutj j#||||j jj|j$j&|j | j)|d|d|_ t ||j jjxs|duxr |duxr| } | r|tj j#||t+t,||j jj|j$j&|j|j | } nd} d} |j j.r|j0j3ddst5|| |j$|j ||||||j| d }|j j6j8D]} ||}| |x|_} |j|jk7r$|j|_| r|j| _|j>} | r|r|jA||js3|r|jC||jEs|jG| r| j)|d|| r| J| j)|d||dJ|dj)|d#t,$r }|} Yd}~d}~wwxYw#|`|jrY|`|jsJ|j}|J| r&|j$jHjK|||jM|wwwxYw)NF)rrHrrT)rconnection_invalidatedrHrskip_user_error_eventsr)'sysrr!is_exit_exception_is_disconnectrrHrVrWr is_disconnectrrMr_reentrant_errorr DBAPIErrorinstancerTrwith_tracebackrrr`rNr|ExceptionContextImplrJ handle_errorchained_exceptionrinvalidate_pool_on_disconnecthandle_dbapi_exceptionrrrr _invalidater)rbrr/r0rrrrrrr should_wrapsqlalchemy_exceptionnewraiserUrfper_fn_raiseddbapi_conn_wrappers rfrz"Connection._handle_dbapi_exceptions&<<> 2215""1dll77==> OLL..262B2BD**#9$7DKK  ->(=%"O 3 3 3   ..)) ))// $ ; ; *nXa[)q 1!%e '%Q (A(A(G(GH%*tO*))  '*~~'>'>A&LL--33$(KK$?$?+/+>+> LL#(? ($(,$H (($2I2I2M2M(%3+(KKLL''1 ,,//<< B "$C!-?EEC1H &&#*;*;;*-*;*;D'+---C55.w..q1&&++F3**,'')--hqk:A+777*99(1+FAM{...qk00!==S%#*V%""''')-)?)?&-9994 ((445GKOOA& (#s9EO&N(9C/O( N>1N93O9N>>OA)P*cJtj}|5t||jjxr|j |dd}t||jj}|rWt jjddtt||jj| |jnd||} nd} d} |jrgt|| ||ddddd||| } |jjD]} | | } | | x| _} | r || j k7r| j | _| r| j%|d||r| J| j%|d||dJ|dj%|d#t$r }|} Yd}~d}~wwxYw)NF)rrrHrr)rrrrVrWrrrrrrrr`rrJrrrr)clsrrHrTrr is_pre_pingrrrrrUrfrrs rfrXz/Connection._handle_dbapi_exception_noconnectionB s<<>  &7''--7''46 !G$8$8$>$>? #&>>#:#:Y"$$**.4.@F**e'4$; $ $(    &$- C&&33   WF);AA- $ 9J9J(J>A>O>O$; ))(1+6A = '3 33&55hqkB IA;* **1+,,Xa[9 9!&HsF  F"FF"c L|d|j|d|j|y)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. )rHrcNr)rHtraverse_single)rbvisitorcallableelementkwargss rf_run_ddl_visitorzConnection._run_ddl_visitor s,  LLT 5; /' "rv)NNTT) rTEnginercrLr`Optional[bool]rdrr\r)rqr|rrrrsrreturnNone)r Optional[SchemaTranslateMapType])rr?r Optional[str]rrG)rrrrrrrr)rOptional[CompiledCacheType]rr|rrrrrrrintrrrrr{rrrrrrrG)rrrrGrr,rrrr7)rr)rzOptional[IsolationLevel])rr )rr9r)rzOptional[BaseException]rrrr)rr)rr)rz Optional[Any]rr)rz List[Any]F)rrrrrr)rrO)rrQ)rrrr)rrrr|)rr|rr)rrrr)rrrr)rrr"rrr)r/TypedReturnsRows[Tuple[_T]]r0"Optional[_CoreSingleExecuteParams]r%Optional[CoreExecuteOptionsParameter]rz Optional[_T])r/r8r0rrrrr)r/rr0Optional[_CoreAnyExecuteParams]rrrzScalarResult[_T])r/r8r0rrrrzScalarResult[Any])r/zTypedReturnsRows[_T]r0rrrrzCursorResult[_T])r/r8r0rrrrCursorResult[Any])rIzFunctionElement[Any]r8r(rr.rr)rRr>r8r(rr.rr)r\r;r8r(rr.rr)rdrrer(rr,rzVTuple[Any, _CoreMultiExecuteParams, _CoreMultiExecuteParams, _CoreSingleExecuteParams])rdr8r8r(rr.rr)r^r:r8r(rr.rr)NN)r/r|r0 Optional[_DBAPIAnyExecuteParams]rrrr)rHr/rzCallable[..., ExecutionContext]r/Union[str, Compiled]r0 Optional[_AnyMultiExecuteParams]rr,rrrsrrr) rHr/rrr/rr0rrr)rHr/rrrr) rrr/r|r0r+rOptional[ExecutionContext]rr)rrrr)rrr/rr0zOptional[_AnyExecuteParams]rOptional[DBAPICursor]rrrrrr )NNTF)rrrHr/rTOptional[Engine]rrrrrrrr rzType[InvokeDDLBase]rr@rrrr)P__name__ __module__ __qualname____doc____annotations___sqla_logger_namespacerKshould_close_with_resultrgrhrurypropertyr}rrrr rrrrrrcrrrrrorrrrrrrrrrrrrrrrrrrrr rrrrrr#r&rr1r<rArJrWr_rMrGrDrwrzrZrrrrrrr classmethodrXrrrvrfrGrGTs000;>B:A %66''++44 7;&*"&!% +/+/4+/$ +/  +/  +/^#" 5 6$$(7: *-#$!*-AD"'4  (   %(?   >>EN '  KK HH(**2*DX448 C $ $9&v")HIVL'\.:'2)4=MKM    !($,H0D"E= $D HD.%`:> DH .7 A   :> DH 7 A  :> DH 7 A  :7; DH .4 A   7; DH   4 A     7; DH 4 A   27; DH '4 A   7; DH   4 A     7;0 DH 0040 A 0  0d  "  6  7    9!9697 9 9v3 !3637 3  3j(G(G2(G+ (G   (GTGG6G7 G  GZ:O 00607 0  0j8>??//47 77"DN __ ) ) 5 IIH I6rvc2|jj|uSr)rcrPrs rfrz,RootTransaction._deactivated_from_connection s++477rvc:|jj|yr)rcrrs rfr2z&RootTransaction._connection_begin_impl s ##D)rvc8|jjyr)rcrrs rf_connection_rollback_implz)RootTransaction._connection_rollback_impl s &&(rvc8|jjyr)rcr rs rf_connection_commit_implz'RootTransaction._connection_commit_impl s $$&rvc, |jr|j|jjr$|jjj |js|r|j |jj |urd|j_ |jrJ|jj |usJy#|js|r|j |jj |urd|j_wwxYwr)rr9rcrR_cancelr5rP)rbtry_deactivates rf _close_implzRootTransaction._close_impl s 4~~..02233;;=~~002++t3/3,>>!!++4777 ~~002++t3/3,4s AC A Dc$|jyrr?rs rfrzRootTransaction._do_close s rvc(|jdy)NT)r>rArs rfrzRootTransaction._do_rollback s -rvc|jr|jj|usJ |j|jjr$|jjj |j d|j_nH|jj|ur|jjntjd|jrJ|jj|usJy#|jjr$|jjj |j wxYw)NThis transaction is inactive) rrcrPr;rRr=r5rrrrs rfr zRootTransaction._do_commit s >>??//47 77 3,,. ??66OO77??A002 ,0DOO (++t3446--.LMM>>!!++4777!??66OO77??A002s DA ENr/rrr)r>rrr)rrrrrrrgr5r rr2r9r;r?rrr rrvrfrr] sU*H+IJ88*)'8 .8rvrcxeZdZUdZdZded<ddZdddZeddZ ddZ dd Z dd Z dd Z dd Zy )raRepresent 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. )rcr _savepoint_previous_nestedr|rFc|jJ|jrtj|||_|jj |_d|_|j|_ ||_yr-) rPrKrr}rcrrFrrRrGrs rfrgzNestedTransaction.__init__ sc&&222  , , 1 1* =$//99; * > >)- &rvc|jj|ur|j|j_y|rtjdyy)Nz7nested transaction already deassociated from connection)rcrRrGr!r4)rbr4s rfr5z-NestedTransaction._deactivate_from_connection s= ?? . .$ 6262G2GDOO /  III rvc2|jj|uSr)rcrRrs rfrz.NestedTransaction._deactivated_from_connection s22$>>rvcd|_|j|jr|jjyyNF)rr5rGr=rs rfr=zNestedTransaction._cancel s7 ((*   ! ! ) ) + !rvc |jr[|jjrE|jjjr%|jj|jd|_|r|j | |jrJ|r|jj |usJyy#d|_|r|j |wwxYw)NF)r4)rrcrPrrFr5rR)rbdeactivate_from_connectionwarn_already_deactives rfr?zNestedTransaction._close_impl s MOO00OO00::;;DOOL"DN)006K0L>>!! %??66dB BB & #DN)006K0L*s A'B11Cc(|jddy)NTFrArs rfrzNestedTransaction._do_close s u%rvc(|jddyr-rArs rfrzNestedTransaction._do_rollback# s t$rvc>|jr> |jj|jd|_|j y|jj |ur|jj ytjd#d|_wxYw)NFz#This nested transaction is inactive) rrcrrFr5rRrrrrs rfr zNestedTransaction._do_commit& s~ >> '77H "'  , , .22d:446--9"'s %B BNr/T)r4rrrrr)rNrrOrrr)rrrrrrrgr5r rr=r?rrr rrvrfrr sg>NIO.??,C*.CGKC C(&%rvrcTeZdZUdZdZded<d fd Zd dZd dZd dZ d d Z xZ S) raRepresent 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 _is_preparedrrc@d|_||_t| |yrL)rUrsuperrg)rbrcr __class__s rfrgzTwoPhaseTransaction.__init__J s! $rvc|jstjd|jj |j d|_y)zqPrepare this :class:`.TwoPhaseTransaction`. After a PREPARE, the transaction can be committed. rDTN)rrrrcrrrUrs rfpreparezTwoPhaseTransaction.prepareO s; ~~))*HI I ..txx8 rvc:|jj|yr)rcrrs rfr2z*TwoPhaseTransaction._connection_begin_implZ s ,,T2rvcd|jj|j|jyr)rcr#rrUrs rfr9z-TwoPhaseTransaction._connection_rollback_impl] s  //$:K:KLrvcd|jj|j|jyr)rcr&rrUrs rfr;z+TwoPhaseTransaction._connection_commit_impl` s  --dhh8I8IJrv)rcrGrrr) rrrrrrrgrZr2r9r; __classcell__)rXs@rfrr; s/(I H% !3MKrvrc:eZdZUdZded<ded<eZded<dZd ed <eZ d ed <d Z ded<dZ d ed<dZ ded<ded<ded<ded<ded<d ed< d1 d2dZ d3dZed4dZd5d Zd6d!Zed"d"d"d"d"d# d7d$Zed8d%Zd8d&Zd9d'Zed:d(Zed:d)Zej2Zd:d*Zd;dd,Zej<d?d-Z d@d.Z!dAd/Z"dBd0Z#y)Cra Connects a :class:`~sqlalchemy.pool.Pool` and :class:`~sqlalchemy.engine.interfaces.Dialect` together to provide a source of database connectivity and behavior. An :class:`_engine.Engine` object is instantiated publicly using the :func:`~sqlalchemy.create_engine` function. .. seealso:: :doc:`/core/engines` :ref:`connections_toplevel` rIrJrrmr,rNFrr`zType[Connection]_connection_clszsqlalchemy.engine.Enginer|r _is_futureNrr}zType[OptionEngine] _option_clsr/rHr6rr2urlrc ||_||_||_|r||_||_||_|dk7r't j||j|_ nd|_ tj|||r|jdi|yy)Nr) size_alertechoflagr) rrcrH logging_nameechorr!LRUCache_lru_size_alertrmr instance_loggerupdate_execution_options) rbrrHrcrhriquery_cache_sizerrs rfrgzEngine.__init__ s   ,D  . q #'== T-A-A$D $(D  D40  )D ) ) >,= > rvc|jr1|jjdt||jyy)NziCompiled cache size pruning from %d items to %d. Increase cache size to reduce the frequency of pruning.)r]rnroracapacity)rbcaches rfrkzEngine._lru_size_alert s9  " KK  JE    #rvc|S)zReturns this :class:`.Engine`. Used for legacy schemes that accept :class:`.Connection` / :class:`.Engine` objects within the same variable. rrs rfrTz Engine.engine s  rvcR|jr|jjyy)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.compiled_cache` parameter. .. versionadded:: 1.4 N)rmclearrs rfclear_compiled_cachezEngine.clear_compiled_cache s$     & & ( rvc |jj|||jj||_|jj||y)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)rJset_engine_execution_optionsrNrrHrs rfrmzEngine.update_execution_options sE" 224="&"9"9"?"?"D 11$J  II   II&&(  %%d+rvc#lK||j5}|dddy|y#1swYyxYwwr)connect)rbrcr+s rf_optional_conn_ctx_managerz!Engine._optional_conn_ctx_manager s?   4      s4(414c#K|j5}|j5|ddddddy#1swYxYw#1swYyxYww)aReturn 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. .. 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`. N)rr)rbr+s rfrz Engine.begin sO2\\^ t         s.AA:A AA AA Ac v|j5}|j||fi|dddy#1swYyxYwr)rr)rbrrrr+s rfrzEngine._run_ddl_visitor s? ZZ\ FT !D ! !/7 Ef E F F Fs/8c$|j|S)a<Return a new :class:`_engine.Connection` object. The :class:`_engine.Connection` acts as a Python context manager, so the typical use of this method looks like:: with engine.connect() as connection: connection.execute(text("insert into table values ('foo')")) connection.commit() Where above, after the block is completed, the connection is "closed" and its underlying DBAPI resources are returned to the connection pool. This also has the effect of rolling back any transaction that was explicitly begun or was begun via autobegin, and will emit the :meth:`_events.ConnectionEvents.rollback` event if one was started and is still in progress. .. seealso:: :meth:`_engine.Engine.begin` )r`rs rfrzEngine.connect s.##D))rvc6|jjS)aCReturn a "raw" DBAPI connection from the connection pool. The returned object is a proxied version of the DBAPI connection object used by the underlying driver in use. The object will have all the same behavior as the real DBAPI connection, except that its ``close()`` method will result in the connection being returned to the pool, rather than being closed for real. This method provides direct DBAPI connection access for special situations when the API provided by :class:`_engine.Connection` is not needed. When a :class:`_engine.Connection` object is already present, the DBAPI connection is available using the :attr:`_engine.Connection.connection` accessor. .. seealso:: :ref:`dbapi_connections` )rrrs rfrUzEngine.raw_connection s,yy  ""rv)NNiNF)rr6rHr/rcr2rhrrizOptional[_EchoFlagType]rnrrzOptional[Mapping[str, Any]]rr)rqzutil.LRUCache[Any, Any]rr)rrrrrrr)rrrr|rrrrr{rrrr OptionEngine)rrrrr)rr|rS)rrrrr)rcrrIterator[Connection])rrrrr)$rrrrrrDrNr`rGr`rrar}rgrkr rTrurmr rrrr~r echo_propertyrirr contextlibcontextmanagerrrrrrUrrvrfrrd sF 1000*??K(2O%2"<C<J>B;B##  J H'+(, #9= %??? ? $ ? & ??7??8 )=*7: *-*-AD 4   (  %( ?     @@N+` '!!## 3   D*(,T15. 8F,F!F F  F*2#rvrceZdZUdZded<ded<ded<ded <d ed <d ed <ded< ddZddZejs9e ddZ e jddZ e ddZ e jddZ yy)OptionEngineMixinFrIrJrrmr/rHr6rr2rcrrzlog.echo_propertyric||_|j|_|j|_|j|_|j|_|j |_|j |_tj||j|jj|j|_ |j|_ |jdi|y)Nrfr) _proxiedrcrHrhrirmrr rlrJr_rNrm)rbproxiedrs rfrgzOptionEngineMixin.__init__ s  ;; #00LL &66&66 D4995 ++G,<,<= ")"<"<%%%:(9:rvc trrrs rfrmz*OptionEngineMixin.update_execution_options rrvc.|jjSrrrrs rfrzOptionEngineMixin.pool s==%% %rvc&||j_yrr)rbrs rfrzOptionEngineMixin.pool s!%DMM rvcj|jjxs|jjddS)Nr`F)rr`__dict__r|rs rfr`zOptionEngineMixin._has_events s/==,, 0A0Au1 rvc"||jd<y)Nr`)r)rbrs rfr`zOptionEngineMixin._has_events$ s+0DMM- (rvN)rrrr.r)rr6)rr6rrr)rrrr) rrr_sa_propagate_class_eventsrrgrmtyping TYPE_CHECKINGr rsetterr`rrvrfrr s!&0000  J H ;;2M;:$     &  &  &  &        1  1% rvrceZdZddZy)rc 0tj|fi|yr)rrmrs rfrmz%OptionEngine.update_execution_options* s''44rvNr)rrrrmrrvrfrr) s5rvr)br __future__rrrrrrrrrr r r r r rrrr interfacesrrrrrrrr!rrrrrrr sqlr"rrr#r$r%r&r'r(r)r*r+r,r-r.r/r0 reflectionr1rcr2eventr3r4rr5r6r7r8 sql._typingr9 sql.compilerr:sql.ddlr;r< sql.functionsr= sql.schemar>r?r@sql.selectablerArB EMPTY_DICTrDrrE InspectablerGrrrrr IdentifiedrrrrbrrvrfrsG" ".#($(&$%&" -213425+-7#2%"#', ''.'/-*,1 T)-8 $ /G%#')?)? )LG%#TJ,'+,'^M&M`i8ki8Xo od&K/&KRA#CNNJ,B,B;,OA#H >1>1B5$f5 "rv