L ia zddlmZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z#ddl m$Z%ddl m&Z&dd l'm(Z(dd!l'm)Z)dd"lm*Z*dd#l+m,Z,dd$l-m.Z.dd%l-m/Z/erfdd&l0m1Z1dd'l2m3Z3dd(l2m4Z4dd)l2m5Z5dd*l2m6Z6dd+l2m7Z7dd,l2m8Z8dd-l2m9Z9dd.l2m:Z:dd/l2m;Z;dd0lm?Z?dd2l@mAZAdd3l@mBZBdd4lCmDZDdd5lEmFZFdd6lGmHZHe/d7ZIed8e9ZJdRd;ZK dS dTd<ZLdUd=ZMGd>d?ZNeje!d@dAgggdBCGdDdEee!edEeNZPeje&dFdGggdHgdICGdJd:ee&eNZQGdKdLee)edLZRe dVdMZSe dWdNZS dXdOZSejeP dYdPZUejeQ dZdQZVy)[) annotationsN)Any) AsyncIterator)Callable)Dict) Generator)NoReturn)Optional)overload)Tuple)Type) TYPE_CHECKING)TypeVar)Union)exc)asyncstartablecontext)GeneratorStartableContext)ProxyComparable)StartableContext)_ensure_sync_result) AsyncResult)AsyncScalarResult) inspection)util) Connection) create_engine)create_pool_from_url)Engine)NestedTransaction) Transaction) ArgumentError)greenlet_spawn) Concatenate) ParamSpec) CursorResult)_CoreAnyExecuteParams)_CoreSingleExecuteParams)_DBAPIAnyExecuteParams)_ExecuteOptions)CompiledCacheType)CoreExecuteOptionsParameter)Dialect)IsolationLevel)SchemaTranslateMapType) ScalarResult)URL)Pool)PoolProxiedConnection) _InfoType) Executable)TypedReturnsRows_P_T)bound AsyncEnginec |jddrtjdd|d<|jddr)|jddr t d d fd }||d<t |fi|t S) a Create a new async engine instance. Arguments passed to :func:`_asyncio.create_async_engine` are mostly identical to those passed to the :func:`_sa.create_engine` function. The specified dialect must be an asyncio-compatible dialect such as :ref:`dialect-postgresql-asyncpg`. .. versionadded:: 1.4 :param async_creator: an async callable which returns a driver-level asyncio connection. If given, the function should take no arguments, and return a new asyncio connection from the underlying asyncio database driver; the connection will be wrapped in the appropriate structures to be used with the :class:`.AsyncEngine`. Note that the parameters specified in the URL are not applied here, and the creator function should use its own connection parameters. This parameter is the asyncio equivalent of the :paramref:`_sa.create_engine.creator` parameter of the :func:`_sa.create_engine` function. .. versionadded:: 2.0.16 server_side_cursorsFz}Can't set server_side_cursors for async engine globally; use the connection.stream() method for an async streaming result setT _is_async async_creatorNcreatorz?Can only specify one of 'async_creator' or 'creator', not both.cPjjjS)N)async_creator_fn)dialectdbapiconnect)r? sync_enginesc/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/engine.pyr@z$create_async_engine..creatoros,&&,,44!.5 returnr)get async_excAsyncMethodRequiredpopr#_create_enginer;)urlkwr@r?rFs @@rGcreate_async_enginerRFs4 vv#U+++ #  B{OFF?D1M 66)T "    9  ++K { ##rHc |jDcic]%\}}|j|r|t|d|'}}}d|d<|j||j d}t |fi|Scc}}w)aCreate a new AsyncEngine instance using a configuration dictionary. This function is analogous to the :func:`_sa.engine_from_config` function in SQLAlchemy Core, except that the requested dialect must be an asyncio-compatible dialect such as :ref:`dialect-postgresql-asyncpg`. The argument signature of the function is identical to that of :func:`_sa.engine_from_config`. .. versionadded:: 1.4.29 NT_coerce_configrP)items startswithlenupdaterNrR) configurationprefixkwargskeyvalueoptionsrPs rGasync_engine_from_configr_|s (--/ C >>& ! CKME!G !%G  NN6 ++e C s .g ..s*A4c $d|d<t|fi|S)aVCreate a new async engine instance. Arguments passed to :func:`_asyncio.create_async_pool_from_url` are mostly identical to those passed to the :func:`_sa.create_pool_from_url` function. The specified dialect must be an asyncio-compatible dialect such as :ref:`dialect-postgresql-asyncpg`. .. versionadded:: 2.0.10 Tr>)_create_pool_from_url)rPr[s rGcreate_async_pool_from_urlrbsF;  / //rHc"eZdZdZeddZy)AsyncConnectable)_slots_dispatch __weakref__ctd)Nzasynchronous events are not implemented at this time. Apply synchronous listeners to the AsyncEngine.sync_engine or AsyncConnection.sync_connection attributes.)NotImplementedError)clss rG_no_async_engine_eventsz(AsyncConnectable._no_async_engine_eventss! :  rHNrJr )__name__ __module__ __qualname__ __slots__ classmethodrjrHrGrdrds0I  rHrdz:class:`_engine.Connection`z!:class:`_asyncio.AsyncConnection`)closed invalidatedrCdefault_isolation_level) classmethodsmethods attributesc eZdZUdZdZ d: d;dZded< ded< e dd Z e d?d Z d@d Z e jdAdZe jdBdZdCdZdCdZ d: dDdZdEdZdFdZdFdZdGdZdGdZedddd d ddddd d dHdZedIdZdIdZdJdZdJdZdJdZdJd Z dK dLd!Ze d:dd" dMd#Z e d:dd" dNd$Z e! d:dd" dOd%Z e d:dd" dPd&Z"e d:dd" dQd'Z" d:dd" dQd(Z"e d:dd" dRd)Z#e d:dd" dSd*Z# d:dd" dSd+Z#e d:dd" dTd,Z$e d:dd" dUd-Z$ d:dd" dUd.Z$e d:dd" dVd/Z%e d:dd" dWd0Z%e! d:dd" dXd1Z% dYd2Z&dZd3Z'd[d4Z(e d\d5Z)e d\d6Z*e d]d7Z+e+jXd^d8Z+e d\d9Z-y)_AsyncConnectionaAn asyncio proxy for a :class:`_engine.Connection`. :class:`_asyncio.AsyncConnection` is acquired using the :meth:`_asyncio.AsyncEngine.connect` method of :class:`_asyncio.AsyncEngine`:: from sqlalchemy.ext.asyncio import create_async_engine engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname") async with engine.connect() as conn: result = await conn.execute(select(table)) .. versionadded:: 1.4 )enginerFsync_connectionNr{Optional[Connection]c`||_|j|_|j||_yN)rzrF_assign_proxiedr{)self async_enginer{s rG__init__zAsyncConnection.__init__s, # '33#33ODrHr rFc Tttj|j|Sr~)ryr;_retrieve_proxy_for_targetrzritarget additional_kws rG_regenerate_proxy_for_targetz,AsyncConnection._regenerate_proxy_for_targets%  2 26== A6  rHFcK|jrtjd|jt |j j d{|_|S7w)zzStart this :class:`_asyncio.AsyncConnection` object's context outside of using a Python ``with:`` block. zconnection is already startedN)r{rInvalidRequestErrorrr$rFrEr is_ctxmanagers rGstartzAsyncConnection.start sY   ))*IJ J#33 !1!1!9!9: :   ;sAA#A!A#c,tjd)zeNot implemented for async; call :meth:`_asyncio.AsyncConnection.get_raw_connection`. zAsyncConnection.connection accessor is not implemented as the attribute may need to reconnect on an invalidated connection. Use the get_raw_connection() method.)rrrs rG connectionzAsyncConnection.connections %% 3  rHcTKtt|jdd{S7w)aReturn the pooled DBAPI-level connection in use by this :class:`_asyncio.AsyncConnection`. This is a SQLAlchemy connection-pool proxied connection which then has the attribute :attr:`_pool._ConnectionFairy.driver_connection` that refers to the actual driver connection. Its :attr:`_pool._ConnectionFairy.dbapi_connection` refers instead to an :class:`_engine.AdaptedConnection` instance that adapts the driver connection to the DBAPI protocol. rN)r$getattr_proxiedrs rGget_raw_connectionz"AsyncConnection.get_raw_connection"s!$GT]]LIIIIs (&(c.|jjS)aReturn the :attr:`_engine.Connection.info` dictionary of the underlying :class:`_engine.Connection`. This dictionary is freely writable for user-defined state to be associated with the database connection. This attribute is only available if the :class:`.AsyncConnection` is currently connected. If the :attr:`.AsyncConnection.closed` attribute is ``True``, then accessing this attribute will raise :class:`.ResourceClosedError`. .. versionadded:: 1.4.0b2 )rinfors rGrzAsyncConnection.info2s }}!!!rHcR|js|j|jSr~)r{_raise_for_not_startedrs rGrzAsyncConnection._proxiedDs###  ' ' )###rHc4|jsJt|S)z1Begin a transaction prior to autobegin occurring.rAsyncTransactionrs rGbeginzAsyncConnection.beginJs}}}%%rHc8|jsJt|dS)z;Begin a nested transaction and return a transaction handle.T)nestedrrs rG begin_nestedzAsyncConnection.begin_nestedOs}}}T22rHc`Kt|jj|d{S7w)zInvalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. See the method :meth:`_engine.Connection.invalidate` for full detail on this method. ) exceptionN)r$r invalidate)rrs rGrzAsyncConnection.invalidateTs.$ MM $ $     s %.,.c\Kt|jjd{S7wr~)r$rget_isolation_levelrs rGrz#AsyncConnection.get_isolation_levelcs!#DMM$E$EFFFF #,*,c6|jjS)z,Return True if a transaction is in progress.)rin_transactionrs rGrzAsyncConnection.in_transactionfs}}++--rHc6|jjS)zYReturn True if a transaction is in progress. .. versionadded:: 1.4.0b2 )rin_nested_transactionrs rGrz%AsyncConnection.in_nested_transactionks }}2244rHcf|jj}|tj|Sy)aReturn an :class:`.AsyncTransaction` representing the current transaction, if any. This makes use of the underlying synchronous connection's :meth:`_engine.Connection.get_transaction` method to get the current :class:`_engine.Transaction`, which is then proxied in a new :class:`.AsyncTransaction` object. .. versionadded:: 1.4.0b2 N)rget_transactionrrrtranss rGrzAsyncConnection.get_transactionss0 --/  #>>uE ErHcf|jj}|tj|Sy)aReturn an :class:`.AsyncTransaction` representing the current nested (savepoint) transaction, if any. This makes use of the underlying synchronous connection's :meth:`_engine.Connection.get_nested_transaction` method to get the current :class:`_engine.Transaction`, which is then proxied in a new :class:`.AsyncTransaction` object. .. versionadded:: 1.4.0b2 N)rget_nested_transactionrrrs rGrz&AsyncConnection.get_nested_transactions0 446  #>>uE ErH.) compiled_cache logging_tokenisolation_level no_parametersstream_resultsmax_row_buffer yield_perinsertmanyvalues_page_sizeschema_translate_mappreserve_rowcountc  Kywr~rq) rrrrrrrrrrropts rGexecution_optionsz!AsyncConnection.execution_optionss c Kywr~rqrrs rGrz!AsyncConnection.execution_optionss FIrcrK|j}t|jfi|d{}||usJ|S7 w)a'Set non-SQL options for the connection which take effect during execution. This returns this :class:`_asyncio.AsyncConnection` object with the new options added. See :meth:`_engine.Connection.execution_options` for full details on this method. N)rr$r)rrconnc2s rGrz!AsyncConnection.execution_optionss@}}!$"8"8@C@ @Tzz As &75 7c^Kt|jjd{y7w)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. Nr$rcommitrs rGrzAsyncConnection.commits T]]11222 #-+-c^Kt|jjd{y7w)a&Roll 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. Nr$rrollbackrs rGrzAsyncConnection.rollbacks T]]33444rc^Kt|jjd{y7w)zClose this :class:`_asyncio.AsyncConnection`. This has the effect of also rolling back the transaction if one is in place. Nr$rclosers rGrzAsyncConnection.closes T]]00111rc@K|jd{y7w)aA synonym for :meth:`_asyncio.AsyncConnection.close`. The :meth:`_asyncio.AsyncConnection.aclose` name is specifically to support the Python standard library ``@contextlib.aclosing`` context manager function. .. versionadded:: 2.0.20 Nrrs rGaclosezAsyncConnection.aclosesjjls cKt|jj|||dd{}t||jd{S7"7w)zaExecutes a driver-level SQL string and return buffered :class:`_engine.Result`. T)_require_awaitN)r$rexec_driver_sqlrr statement parametersrresults rGrzAsyncConnection.exec_driver_sqlsT& MM ) )      )1E1EFFF G!(AA AA AArcyr~rqrrrrs rGstreamzAsyncConnection.streams69rHcyr~rqrs rGrzAsyncConnection.streams7:rHc K|jjstjdt |j j ||tjj|ddidd{}|jjsJt|} |tj|j}tj |d{y7n7#t"$rYywxYww)aKExecute a statement and return an awaitable yielding a :class:`_asyncio.AsyncResult` object. E.g.:: result = await conn.stream(stmt) async for row in result: print(f"{row}") The :meth:`.AsyncConnection.stream` method supports optional context manager use against the :class:`.AsyncResult` object, as in:: async with conn.stream(stmt) as result: async for row in result: print(f"{row}") In the above pattern, the :meth:`.AsyncResult.close` method is invoked unconditionally, even if the iterator is interrupted by an exception throw. Context manager use remains optional, however, and the function may be called in either an ``async with fn():`` or ``await fn()`` style. .. versionadded:: 2.0.0b3 added context manager support :return: an awaitable object that will yield an :class:`_asyncio.AsyncResult` object. .. seealso:: :meth:`.AsyncConnection.stream_scalars` zmCant use `stream` or `stream_scalars` with the current dialect since it does not support server side cursors.rTrrN)rCsupports_server_side_cursorsrrr$rexecuter EMPTY_DICT merge_withcontext_is_server_siderasyncio create_taskrshield GeneratorExit)rrrrrartasks rGrzAsyncConnection.streamsT||88))I  & MM ! !  "oo88!$4d#;   ~~----   'H&&rxxz2D..& & &# " '    sHA3C75C$6'C7C(#;C7C&C7&C7( C41C73C44C7c Kywr~rqrs rGrzAsyncConnection.execute[ rc Kywr~rqrs rGrzAsyncConnection.executed  rcKt|jj|||dd{}t||jd{S7"7w)aExecutes a SQL statement construct and return a buffered :class:`_engine.Result`. :param object: 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. TrN)r$rrrrs rGrzAsyncConnection.executemsRL& MM ! !  /   )>>> ?rc Kywr~rqrs rGscalarzAsyncConnection.scalars rc Kywr~rqrs rGrzAsyncConnection.scalars rcfK|j|||d{}|jS7w)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. rN)rrrs rGrzAsyncConnection.scalars;"|| z5F$  }} 1/1c Kywr~rqrs rGscalarszAsyncConnection.scalarsrrc Kywr~rqrs rGrzAsyncConnection.scalarsrrcfK|j|||d{}|jS7w)aiExecutes a SQL statement construct and returns a scalar objects. This method is shorthand for invoking the :meth:`_engine.Result.scalars` method after invoking the :meth:`_engine.Connection.execute` method. Parameters are equivalent. :return: a :class:`_engine.ScalarResult` object. .. versionadded:: 1.4.24 rN)rrrs rGrzAsyncConnection.scalarss<$|| z5F$  ~~ rcyr~rqrs rGstream_scalarszAsyncConnection.stream_scalarss str: """A synchronous function that does not require awaiting :param conn: a Core SQLAlchemy Connection, used synchronously :return: an optional return value is supported """ conn.execute(some_table.insert().values(int_col=arg1, str_col=arg2)) return "success" async def do_something_async(async_engine: AsyncEngine) -> None: """an async function that uses awaiting""" async with async_engine.begin() as async_conn: # run do_something_with_core() with a sync-style # Connection, proxied into an awaitable return_code = await async_conn.run_sync( do_something_with_core, 5, "strval" ) print(return_code) This method maintains the asyncio event loop all the way through to the database connection by running the given callable in a specially instrumented greenlet. The most rudimentary use of :meth:`.AsyncConnection.run_sync` is to invoke methods such as :meth:`_schema.MetaData.create_all`, given an :class:`.AsyncConnection` that needs to be provided to :meth:`_schema.MetaData.create_all` as a :class:`_engine.Connection` object:: # run metadata.create_all(conn) with a sync-style Connection, # proxied into an awaitable with async_engine.begin() as conn: await conn.run_sync(metadata.create_all) .. note:: The provided callable is invoked inline within the asyncio event loop, and will block on traditional IO calls. IO within this callable should only call into SQLAlchemy's asyncio database APIs which will be properly adapted to the greenlet context. .. seealso:: :meth:`.AsyncSession.run_sync` :ref:`session_run_sync` rFN)r$r)rfnargrQs rGrun_synczAsyncConnection.run_sync4sAH$   # 49 =?    s )')c>|jjSr~)r __await__rs rGrzAsyncConnection.__await__|szz|%%''rHcKtj|j}tj|d{y7wr~)rrrr)rtype_r] tracebackrs rG __aexit__zAsyncConnection.__aexit__s.""4::<0nnT"""s DH .7 A   :> DH 7 A  :> DH 7 A  ,7; DH .4 A   7; DH   4 A     7; DH   4 A    .:>? DH ?.?7? A ? : ??:>@ DH @@7@ A @ ; @@:>2# DH 2#2#72# A 2# / 2#2#hF 5F F  F F P(# $ $)) %% ^^%%!5!5rHryz:class:`_engine.Engine`z:class:`_asyncio.AsyncEngine`)clear_compiled_cacheupdate_execution_optionsget_execution_options)rPpoolrCrznamedriverechoc>eZdZUdZdZeZded<ded< d!dZe jd"dZ e d#dZ ejd$d Zd%d Zd&d Zed d d d d d  d'dZed(dZd(dZd)d*dZd+dZd,dZd-dZed.dZej6d/dZed0dZej6d1dZed2dZej6d3dZed4dZed4dZed4dZ ed4dZ!e!j6d5dZ!y )6r;aQAn asyncio proxy for a :class:`_engine.Engine`. :class:`_asyncio.AsyncEngine` is acquired using the :func:`_asyncio.create_async_engine` function:: from sqlalchemy.ext.asyncio import create_async_engine engine = create_async_engine("postgresql+asyncpg://user:pass@host/dbname") .. versionadded:: 1.4 rFzType[AsyncConnection]_connection_clsr c|jjs-tjd|jjd|j ||_y)NzFThe asyncio extension requires an async driver to be used. The loaded z is not async.)rCis_asyncrrr.rrF)rrFs rGrzAsyncEngine.__init__ sX""++)))1188;>K  // <rHc|jSr~)rFrs rGrzAsyncEngine._proxiedsrHc t|Sr~)r;rs rGrz(AsyncEngine._regenerate_proxy_for_targets6""rHc"K|j}|4d{|j4d{|dddd{dddd{y7C7,7#1d{7swY)xYw7 #1d{7swYyxYww)aReturn a context manager which when entered will deliver an :class:`_asyncio.AsyncConnection` with an :class:`_asyncio.AsyncTransaction` established. E.g.:: async with async_engine.begin() as conn: await conn.execute( text("insert into table (x, y, z) values (1, 2, 3)") ) await conn.execute(text("my_special_procedure(5)")) N)rEr)rrs rGrzAsyncEngine.begins||~  zz|                 sBABA:AA:A# A:A!A: BA8BA:!A:#A5 )A,*A5 1A:8B:B B B Bc$|j|S)aReturn an :class:`_asyncio.AsyncConnection` object. The :class:`_asyncio.AsyncConnection` will procure a database connection from the underlying connection pool when it is entered as an async context manager:: async with async_engine.connect() as conn: result = await conn.execute(select(user_table)) The :class:`_asyncio.AsyncConnection` may also be started outside of a context manager by invoking its :meth:`_asyncio.AsyncConnection.start` method. )r1rs rGrEzAsyncEngine.connect0s ##D))rHc\Kt|jjd{S7w)zReturn a "raw" DBAPI connection from the connection pool. .. seealso:: :ref:`dbapi_connections` N)r$rFraw_connectionrs rGr9zAsyncEngine.raw_connectionBs%$D$4$4$C$CDDDDr.)rrrrrc yr~rq)rrrrrrrs rGrzAsyncEngine.execution_optionsLsrHc yr~rqrs rGrzAsyncEngine.execution_optionsXszAsyncEngine.disposegs$.T--55UCCCs %/-/c6|jjS)a-Clear the compiled cache associated with the dialect. .. container:: class_bases Proxied for the :class:`_engine.Engine` class on behalf of the :class:`_asyncio.AsyncEngine` class. 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 )rr)rs rGr)z AsyncEngine.clear_compiled_caches$}}1133rHc :|jjdi|S)aUpdate the default execution_options dictionary of this :class:`_engine.Engine`. .. container:: class_bases Proxied for the :class:`_engine.Engine` class on behalf of the :class:`_asyncio.AsyncEngine` class. 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` rq)rr*rs rGr*z$AsyncEngine.update_execution_optionss06t}}55<<r)r*r+r&rPr(r,rCrzr-r.r/rqrHrGr;r;s $I-rsh#  '+!"'% 5C,& .&$-:=;46@,3;-!-(&2t_ T3$n2?/!/+./JM//2 0   !'  W 5J&'W 5 W 5x #  N I"/&)+;I" I"\ YNK "23E"FYNx L L !  5  o&  'k"     # rH