
    +h|                        d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  	 ddl!mZ"  G d dejH                        Z% G d dejL                        Z' G d d ejP                        Z) G d! d"ejT                        Z+ G d# d$e      Z, G d% d&e      Z- G d' d(ej\                        Z/ G d) d*ej`                        Z1 G d+ d,ejd                        Z3 G d- d.ejh                        Z5 G d/ d0ejd                  jl                        Z7 G d1 d2ejd                  jp                        Z9 G d3 d4ejd                  jt                        Z; G d5 d6ejx                        Z= G d7 d8e      Z> G d9 d:ej~                        Z@ G d; d<e@      ZA G d= d>e      ZB G d? d@e      ZC G dA dBe      ZD G dC dDe      ZE G dE dFe      ZF G dG dH      ZG G dI dJeG      ZH G dK dLe      ZI G dM dNeI      ZJ G dO dP      ZKi eKj                  dQeKj                  dReKj                  dSeKj                  dTeKj                  dUeKj                  dVeKj                  dWeKj                  dXeKj                  dYeKj                  dZeKj                  d[eKj                  d\eKj                  d]eKj                  d^eKjd                  d_eKjh                  d`eKj                  daeKj(                  dbeKj                  dciZZ G dd dee      Z[e[Z\y# e#$ r dZ"Y w xY w)fa  
.. dialect:: postgresql+asyncpg
    :name: asyncpg
    :dbapi: asyncpg
    :connectstring: postgresql+asyncpg://user:password@host:port/dbname[?key=value&key=value...]
    :url: https://magicstack.github.io/asyncpg/

The asyncpg dialect is SQLAlchemy's first Python asyncio dialect.

Using a special asyncio mediation layer, the asyncpg dialect is usable
as the backend for the :ref:`SQLAlchemy asyncio <asyncio_toplevel>`
extension package.

This dialect should normally be used only with the
:func:`_asyncio.create_async_engine` engine creation function::

    from sqlalchemy.ext.asyncio import create_async_engine
    engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname")

The dialect can also be run as a "synchronous" dialect within the
:func:`_sa.create_engine` function, which will pass "await" calls into
an ad-hoc event loop.  This mode of operation is of **limited use**
and is for special testing scenarios only.  The mode can be enabled by
adding the SQLAlchemy-specific flag ``async_fallback`` to the URL
in conjunction with :func:`_sa.create_engine`::

    # for testing purposes only; do not use in production!
    engine = create_engine("postgresql+asyncpg://user:pass@hostname/dbname?async_fallback=true")


.. versionadded:: 1.4

.. note::

    By default asyncpg does not decode the ``json`` and ``jsonb`` types and
    returns them as strings. SQLAlchemy sets default type decoder for ``json``
    and ``jsonb`` types using the python builtin ``json.loads`` function.
    The json implementation used can be changed by setting the attribute
    ``json_deserializer`` when creating the engine with
    :func:`create_engine` or :func:`create_async_engine`.


.. _asyncpg_prepared_statement_cache:

Prepared Statement Cache
--------------------------

The asyncpg SQLAlchemy dialect makes use of ``asyncpg.connection.prepare()``
for all statements.   The prepared statement objects are cached after
construction which appears to grant a 10% or more performance improvement for
statement invocation.   The cache is on a per-DBAPI connection basis, which
means that the primary storage for prepared statements is within DBAPI
connections pooled within the connection pool.   The size of this cache
defaults to 100 statements per DBAPI connection and may be adjusted using the
``prepared_statement_cache_size`` DBAPI argument (note that while this argument
is implemented by SQLAlchemy, it is part of the DBAPI emulation portion of the
asyncpg dialect, therefore is handled as a DBAPI argument, not a dialect
argument)::


    engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=500")

To disable the prepared statement cache, use a value of zero::

    engine = create_async_engine("postgresql+asyncpg://user:pass@hostname/dbname?prepared_statement_cache_size=0")

.. versionadded:: 1.4.0b2 Added ``prepared_statement_cache_size`` for asyncpg.


.. warning::  The ``asyncpg`` database driver necessarily uses caches for
   PostgreSQL type OIDs, which become stale when custom PostgreSQL datatypes
   such as ``ENUM`` objects are changed via DDL operations.   Additionally,
   prepared statements themselves which are optionally cached by SQLAlchemy's
   driver as described above may also become "stale" when DDL has been emitted
   to the PostgreSQL database which modifies the tables or other objects
   involved in a particular prepared statement.

   The SQLAlchemy asyncpg dialect will invalidate these caches within its local
   process when statements that represent DDL are emitted on a local
   connection, but this is only controllable within a single Python process /
   database engine.     If DDL changes are made from other database engines
   and/or processes, a running application may encounter asyncpg exceptions
   ``InvalidCachedStatementError`` and/or ``InternalServerError("cache lookup
   failed for type <oid>")`` if it refers to pooled database connections which
   operated upon the previous structures. The SQLAlchemy asyncpg dialect will
   recover from these error cases when the driver raises these exceptions by
   clearing its internal caches as well as those of the asyncpg driver in
   response to them, but cannot prevent them from being raised in the first
   place if the cached prepared statement or asyncpg type caches have gone
   stale, nor can it retry the statement as the PostgreSQL transaction is
   invalidated when these errors occur.

Disabling the PostgreSQL JIT to improve ENUM datatype handling
---------------------------------------------------------------

Asyncpg has an `issue <https://github.com/MagicStack/asyncpg/issues/727>`_ when
using PostgreSQL ENUM datatypes, where upon the creation of new database
connections, an expensive query may be emitted in order to retrieve metadata
regarding custom types which has been shown to negatively affect performance.
To mitigate this issue, the PostgreSQL "jit" setting may be disabled from the
client using this setting passed to :func:`_asyncio.create_async_engine`::

    engine = create_async_engine(
        "postgresql+asyncpg://user:password@localhost/tmp",
        connect_args={"server_settings": {"jit": "off"}},
    )

.. seealso::

    https://github.com/MagicStack/asyncpg/issues/727

    N   )json)_DECIMAL_TYPES)_FLOAT_TYPES)
_INT_TYPESENUMINTERVAL)OID)
PGCompiler)	PGDialect)PGExecutionContext)PGIdentifierPreparer)REGCLASSUUID   )exc)pool)
processors)util)AdaptedConnection)sqltypes)asyncio)await_fallback)
await_onlyc                       e Zd Zd Zy)AsyncpgTimec                 J    | j                   r|j                  S |j                  S N)timezone	TIME_W_TZTIMEselfdbapis     Y/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/asyncpg.pyget_dbapi_typezAsyncpgTime.get_dbapi_type   s    ==??"::    N__name__
__module____qualname__r)    r*   r(   r   r      s    r*   r   c                       e Zd Zd Zy)AsyncpgDatec                     |j                   S r!   )DATEr%   s     r(   r)   zAsyncpgDate.get_dbapi_type       zzr*   Nr+   r/   r*   r(   r1   r1          r*   r1   c                       e Zd Zd Zy)AsyncpgDateTimec                 J    | j                   r|j                  S |j                  S r!   )r"   TIMESTAMP_W_TZ	TIMESTAMPr%   s     r(   r)   zAsyncpgDateTime.get_dbapi_type   s    =='''??"r*   Nr+   r/   r*   r(   r7   r7      s    #r*   r7   c                       e Zd Zd Zy)AsyncpgBooleanc                     |j                   S r!   )BOOLEANr%   s     r(   r)   zAsyncpgBoolean.get_dbapi_type       }}r*   Nr+   r/   r*   r(   r<   r<          r*   r<   c                   "    e Zd Zd Zed        Zy)AsyncPgIntervalc                     |j                   S r!   r
   r%   s     r(   r)   zAsyncPgInterval.get_dbapi_type   s    ~~r*   c                 .    t        |j                        S )N)	precision)rB   second_precision)clsintervalkws      r(   adapt_emulated_to_nativez(AsyncPgInterval.adapt_emulated_to_native   s     )B)BCCr*   N)r,   r-   r.   r)   classmethodrJ   r/   r*   r(   rB   rB      s     D Dr*   rB   c                       e Zd Zd Zy)AsyncPgEnumc                     |j                   S r!   r   r%   s     r(   r)   zAsyncPgEnum.get_dbapi_type   r4   r*   Nr+   r/   r*   r(   rM   rM      r5   r*   rM   c                       e Zd Zd Zy)AsyncpgIntegerc                     |j                   S r!   INTEGERr%   s     r(   r)   zAsyncpgInteger.get_dbapi_type   r?   r*   Nr+   r/   r*   r(   rP   rP      r@   r*   rP   c                       e Zd Zd Zy)AsyncpgBigIntegerc                     |j                   S r!   )
BIGINTEGERr%   s     r(   r)   z AsyncpgBigInteger.get_dbapi_type   s    r*   Nr+   r/   r*   r(   rU   rU      s     r*   rU   c                       e Zd Zd Zd Zy)AsyncpgJSONc                     |j                   S r!   )JSONr%   s     r(   r)   zAsyncpgJSON.get_dbapi_type   r4   r*   c                      y r!   r/   r&   dialectcoltypes      r(   result_processorzAsyncpgJSON.result_processor       r*   Nr,   r-   r.   r)   r`   r/   r*   r(   rY   rY      s    r*   rY   c                       e Zd Zd Zd Zy)AsyncpgJSONBc                     |j                   S r!   )JSONBr%   s     r(   r)   zAsyncpgJSONB.get_dbapi_type       {{r*   c                      y r!   r/   r]   s      r(   r`   zAsyncpgJSONB.result_processor   ra   r*   Nrb   r/   r*   r(   rd   rd      s    r*   rd   c                       e Zd Zd Zy)AsyncpgJSONIndexTypec                     t        d      )Nzshould not be hereNotImplementedErrorr%   s     r(   r)   z#AsyncpgJSONIndexType.get_dbapi_type   s    !"677r*   Nr+   r/   r*   r(   rj   rj      s    8r*   rj   c                       e Zd Zd Zy)AsyncpgJSONIntIndexTypec                     |j                   S r!   rR   r%   s     r(   r)   z&AsyncpgJSONIntIndexType.get_dbapi_type   r?   r*   Nr+   r/   r*   r(   ro   ro      r@   r*   ro   c                       e Zd Zd Zy)AsyncpgJSONStrIndexTypec                     |j                   S r!   STRINGr%   s     r(   r)   z&AsyncpgJSONStrIndexType.get_dbapi_type       ||r*   Nr+   r/   r*   r(   rr   rr          r*   rr   c                       e Zd Zd Zy)AsyncpgJSONPathTypec                     d }|S )Nc                     t        | t        j                  j                        sJ | D cg c]  }t        j                  |       }}|S c c}w r!   )
isinstancer   collections_abcSequence	text_type)valueelemtokenss      r(   processz3AsyncpgJSONPathType.bind_processor.<locals>.process   sD    eT%9%9%B%BCCC7<=tdnnT*=F=M >s   Ar/   r&   r^   r   s      r(   bind_processorz"AsyncpgJSONPathType.bind_processor   s    	
 r*   N)r,   r-   r.   r   r/   r*   r(   ry   ry      s    r*   ry   c                       e Zd Zd Zd Zd Zy)AsyncpgUUIDc                     |j                   S r!   r   r%   s     r(   r)   zAsyncpgUUID.get_dbapi_type   r4   r*   c                 @    | j                   s|j                  rd }|S y y )Nc                      | t        |       } | S r!   )_python_UUIDr   s    r(   r   z+AsyncpgUUID.bind_processor.<locals>.process   s    $(/Er*   as_uuiduse_native_uuidr   s      r(   r   zAsyncpgUUID.bind_processor   $    || 7 7
 N !8|r*   c                 @    | j                   s|j                  rd }|S y y )Nc                      | t        |       } | S r!   )strr   s    r(   r   z-AsyncpgUUID.result_processor.<locals>.process	  s    $JEr*   r   )r&   r^   r_   r   s       r(   r`   zAsyncpgUUID.result_processor  r   r*   Nr,   r-   r.   r)   r   r`   r/   r*   r(   r   r      s    r*   r   c                       e Zd Zd Zd Zd Zy)AsyncpgNumericc                     |j                   S r!   )NUMBERr%   s     r(   r)   zAsyncpgNumeric.get_dbapi_type  rv   r*   c                      y r!   r/   )r&   r^   s     r(   r   zAsyncpgNumeric.bind_processor  ra   r*   c                 Z   | j                   r_|t        v r.t        j                  t        j
                  | j                        S |t        v s|t        v ry t        j                  d|z        |t        v ry |t        v s|t        v rt        j                  S t        j                  d|z        )NzUnknown PG numeric type: %d)	asdecimalr   r   to_decimal_processor_factorydecimalDecimal_effective_decimal_return_scaler   r   r   InvalidRequestErrorto_floatr]   s      r(   r`   zAsyncpgNumeric.result_processor  s    >>,&!>>OOT%I%I  N*g.C--1G;  ,&N*g.C!***--1G; r*   Nr   r/   r*   r(   r   r     s    r*   r   c                       e Zd Zd Zy)AsyncpgFloatc                     |j                   S r!   )FLOATr%   s     r(   r)   zAsyncpgFloat.get_dbapi_type2  rg   r*   Nr+   r/   r*   r(   r   r   1  s    r*   r   c                       e Zd Zd Zy)AsyncpgREGCLASSc                     |j                   S r!   rt   r%   s     r(   r)   zAsyncpgREGCLASS.get_dbapi_type7  rv   r*   Nr+   r/   r*   r(   r   r   6  rw   r*   r   c                       e Zd Zd Zy)
AsyncpgOIDc                     |j                   S r!   rR   r%   s     r(   r)   zAsyncpgOID.get_dbapi_type<  r?   r*   Nr+   r/   r*   r(   r   r   ;  r@   r*   r   c                       e Zd Zd Zd Zd Zy)PGExecutionContext_asyncpgc                     t        || j                  j                  j                  | j                  j                  j                  f      r| j                  j                          y y r!   )r|   r^   r'   InvalidCachedStatementErrorInternalServerError_invalidate_schema_cache)r&   es     r(   handle_dbapi_exceptionz1PGExecutionContext_asyncpg.handle_dbapi_exceptionA  sO    "">>""66
 LL113
r*   c                     | j                   r| j                  j                          | j                  j                  | j                  _        | j
                  sy t        j                  h| _        y r!   )	isddlr^   r   _invalidate_schema_cache_asofcursorcompiledAsyncAdapt_asyncpg_dbapir	   exclude_set_input_sizesr&   s    r(   pre_execz#PGExecutionContext_asyncpg.pre_execK  sT    ::LL113 LL66 	1 }}
 )A(E(E'F$r*   c                 :    | j                   j                  d      S )NT)server_side)_dbapi_connectionr   r   s    r(   create_server_side_cursorz4PGExecutionContext_asyncpg.create_server_side_cursor[  s    %%,,,>>r*   N)r,   r-   r.   r   r   r   r/   r*   r(   r   r   @  s    4G ?r*   r   c                       e Zd Zy)PGCompiler_asyncpgNr,   r-   r.   r/   r*   r(   r   r   _      r*   r   c                       e Zd Zy)PGIdentifierPreparer_asyncpgNr   r/   r*   r(   r   r   c  r   r*   r   c                   f    e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
dd
Zd Zd Zd Zd ZddZd Zy	)AsyncAdapt_asyncpg_cursor)	_adapt_connection_connection_rowsdescription	arraysizerowcount_inputsizes_cursorr   Fc                     || _         |j                  | _        g | _        d | _        d | _        d| _        d| _        d | _        d| _        y )Nr   r   )	r   r   r   r   r   r   r   r   r   )r&   adapt_connections     r(   __init__z"AsyncAdapt_asyncpg_cursor.__init__v  sL    !1+77
-.*r*   c                 "    g | j                   d d  y r!   r   r   s    r(   closezAsyncAdapt_asyncpg_cursor.close  s    

1r*   c                 :    | j                   j                  |       y r!   )r   _handle_exceptionr&   errors     r(   r   z+AsyncAdapt_asyncpg_cursor._handle_exception  s    007r*   c                     | j                   st        d t        |d      D              S t        d t        d | j                   D        d      D              S )Nc              3   ,   K   | ]  \  }}d |z    yw)$%dNr/   ).0idx_s      r(   	<genexpr>zDAsyncAdapt_asyncpg_cursor._parameter_placeholders.<locals>.<genexpr>  s     HaHs   r   c              3   >   K   | ]  \  }}|rd ||fz  nd|z    yw)z$%d::%sr   Nr/   )r   r   typs      r(   r   zDAsyncAdapt_asyncpg_cursor._parameter_placeholders.<locals>.<genexpr>  s0      C +.	S#J&53;>s   c              3   F   K   | ]  }t         j                  |        y wr!   )	_pg_typesget)r   r   s     r(   r   zDAsyncAdapt_asyncpg_cursor._parameter_placeholders.<locals>.<genexpr>  s     DCY]]3'Ds   !)r   tuple	enumerate)r&   paramss     r(   _parameter_placeholdersz1AsyncAdapt_asyncpg_cursor._parameter_placeholders  sR    H9VQ3GHHH  )D43C3CDa!  r*   c                   K   | j                   }|j                  4 d {    |j                  s|j                          d {    ||| j	                  |      z  }nd}	 |j                  || j                         d {   \  }}|r;|D cg c])  }|j                  |j                  j                  d d d d d f+ c}| _
        nd | _
        | j                  r$ |j                  |  d {   | _        d| _        nk |j                  |  d {   | _        |j#                         }t%        j&                  d|      }|r t)        |j+                  d            | _        nd| _        d d d       d {    y 7 Z7 97 c c}w 7 7 x# t,        $ r}	| j/                  |	       Y d }	~	Ad }	~	ww xY w7 =# 1 d {  7  sw Y   y xY ww)Nr/   r   z)(?:SELECT|UPDATE|DELETE|INSERT \d+) (\d+)r   )r   _execute_mutex_started_start_transactionr   _preparer   nametypeoidr   r   r   r   r   fetchr   get_statusmsgrematchintgroup	Exceptionr   )
r&   	operation
parametersr   prepared_stmt
attributesattrstatusregr   s
             r(   _prepare_and_executez.AsyncAdapt_asyncpg_cursor._prepare_and_execute  s    11#22 1	. 1	.#,,&99;;;%%(D(D) 	  
%.2B2K2KtAA3 -)z  %/( ! !II IIMM     (D$ (,D$##)=)=)=z)J#JDL$&DM':}':':J'G!GDJ*88:F((DfC (+CIIaL(9(*]1	. 1	. 1	. <-
(  $K "H  .&&u--.a1	. 1	. 1	. 1	.s   GE9G F3E<F3"F
E?F
.F=.F
+F,#F
FAF
(G3F14G<F3?F
F
F

	F.F)$F3)F..F31G3G9F<:GGc                 $  K   | j                   }|j                  4 d {    |j                  | j                         d {    |j                  s|j                          d {    || j                  |d         z  }	 | j                  j                  ||       d {   cd d d       d {    S 7 7 w7 U7 7 # t        $ r}| j                  |       Y d }~nd }~ww xY wd d d       d {  7   y # 1 d {  7  sw Y   y xY wwNr   )r   r   _check_type_cache_invalidationr   r   r   r   r   executemanyr   r   )r&   r   seq_of_parametersr   r   s        r(   _executemanyz&AsyncAdapt_asyncpg_cursor._executemany  s	    11#22 	. 	."AA22   $,,&99;;;!D$@$@!!$% I.!--990 	. 	. 	.
 <	.   .&&u--.!	. 	. 	. 	. 	.s   DB8DC;B:#C;&B<'C;C"B>#C&D2C 3D:C;<C;>C D	C&C!C;!C&&C;)D4C75D;DDD	DNc                 Z    | j                   j                  | j                  ||             y r!   )r   await_r  )r&   r   r   s      r(   executez!AsyncAdapt_asyncpg_cursor.execute  s&    %%%%i<	
r*   c                 X    | j                   j                  | j                  ||            S r!   )r   r
  r  r&   r   r  s      r(   r  z%AsyncAdapt_asyncpg_cursor.executemany  s,    %%,,i):;
 	
r*   c                     || _         y r!   )r   )r&   
inputsizess     r(   setinputsizesz'AsyncAdapt_asyncpg_cursor.setinputsizes  s
    %r*   c              #   z   K   | j                   r+| j                   j                  d       | j                   r*y y wr  r   popr   s    r(   __iter__z"AsyncAdapt_asyncpg_cursor.__iter__  s)     jj**..## jjs   6;;c                 R    | j                   r| j                   j                  d      S y r  r  r   s    r(   fetchonez"AsyncAdapt_asyncpg_cursor.fetchone  s    ::::>>!$$r*   c                 x    || j                   }| j                  d| }| j                  |d  | j                  d d  |S r  )r   r   )r&   sizeretvals      r(   	fetchmanyz#AsyncAdapt_asyncpg_cursor.fetchmany  s=    <>>DAd#

45)

1r*   c                 B    | j                   d d  }g | j                   d d  |S r!   r   )r&   r  s     r(   fetchallz"AsyncAdapt_asyncpg_cursor.fetchall  s!    A

1r*   r!   )r,   r-   r.   	__slots__r   r   r   r   r   r  r  r  r  r  r  r  r  r  r/   r*   r(   r   r   g  sR    
I K	/8	4.l.,



&$r*   r   c                   ^     e Zd ZdZdZ fdZd Zd Zd Zd Z	d Z
dd	Zd
 Zd Zd Z xZS )AsyncAdapt_asyncpg_ss_cursorT)
_rowbufferc                 :    t         t        |   |       d | _        y r!   )superr  r   r   )r&   r   	__class__s     r(   r   z%AsyncAdapt_asyncpg_ss_cursor.__init__  s    *D:;KLr*   c                      d | _         d | _        y r!   )r   r   r   s    r(   r   z"AsyncAdapt_asyncpg_ss_cursor.close  s    r*   c                     | j                   j                  | j                  j                  d            }t	        j
                  |      | _        y )N2   )r   r
  r   r   collectionsdequer   )r&   new_rowss     r(   _buffer_rowsz)AsyncAdapt_asyncpg_ss_cursor._buffer_rows  s9    ))001C1CB1GH%++H5r*   c                     | S r!   r/   r   s    r(   	__aiter__z&AsyncAdapt_asyncpg_ss_cursor.__aiter__  s    r*   c                   K   | j                   s| j                          	 | j                   r*| j                   j                          | j                   r*| j                          | j                   sy Twr!   r   r*  popleftr   s    r(   	__anext__z&AsyncAdapt_asyncpg_ss_cursor.__anext__  s\     //oo--// // ?? s   AA4A4c                     | j                   s| j                          | j                   sy | j                   j                         S r!   r.  r   s    r(   r  z%AsyncAdapt_asyncpg_ss_cursor.fetchone#  s2    ??&&((r*   c                 |   || j                         S | j                  s| j                          t        | j                        }t	        |      }||kD  rF|j                  | j                  j                  | j                  j                  ||z
                     |d| }t        j                  ||d        | _        |S r  )r  r   r*  listlenextendr   r
  r   r   r'  r(  )r&   r  buflbresults        r(   r  z&AsyncAdapt_asyncpg_ss_cursor.fetchmany*  s    <==?"4??#X"9JJ&&--dll.@.@.KL Qt%++CJ7r*   c                     t        | j                        t        | j                  j                  | j	                                     z   }| j                  j                          |S r!   )r3  r   r   r
  _allclear)r&   rets     r(   r  z%AsyncAdapt_asyncpg_ss_cursor.fetchall<  sM    4??#d""))$))+6'
 
 	
r*   c                    K   g }	 | j                   j                  d       d {   }|r|j                  |       8	 |S 7 w)Ni  )r   r   r5  )r&   rowsbatchs      r(   r:  z!AsyncAdapt_asyncpg_ss_cursor._allC  sF      ,,,,T22EE" 3s   "AA Ac                     t        d      )Nz2server side cursor doesn't support executemany yetrl   r  s      r(   r  z(AsyncAdapt_asyncpg_ss_cursor.executemanyQ  s    !@
 	
r*   r!   )r,   r-   r.   r   r  r   r   r*  r,  r0  r  r  r  r:  r  __classcell__r#  s   @r(   r  r    s?    KI6
)$
r*   r  c                       e Zd ZdZ ee      ZddZd Zd Z	d Z
ed        Zej                  d        Zd Zd	 Zdd
Zd Zd Zd Zd Zy)AsyncAdapt_asyncpg_connection)r'   r   isolation_level_isolation_settingreadonly
deferrable_transactionr   _prepared_statement_cacher   r   c                     || _         || _        dx| _        | _        d| _        d| _        d | _        d| _        t        j                         | _	        t        j                         | _        |rt        j                  |      | _        y d | _        y )Nread_committedF)r'   r   rE  rF  rG  rH  rI  r   timer   r   Lockr   r   LRUCacherJ  )r&   r'   
connectionprepared_statement_cache_sizes       r(   r   z&AsyncAdapt_asyncpg_connection.__init__h  s{    
%9IIt6 -1YY[*%lln(-1]]-.D* .2D*r*   c                    K   || j                   kD  r*| j                  j                          d {    || _         y y 7 wr!   )r   r   reload_schema_state)r&   invalidate_timestamps     r(   r  z<AsyncAdapt_asyncpg_connection._check_type_cache_invalidationz  s=     $"D"DD""668881ED. E8s   -?=?c                   K   | j                  |       d {    | j                  }|7| j                  j                  |       d {   }|j	                         }||fS ||v r||   \  }}}||kD  r||fS | j                  j                  |       d {   }|j	                         }||t        j
                         f||<   ||fS 7 7 7 6wr!   )r  rJ  r   prepareget_attributesrM  )r&   r   rT  cacher   r   cached_timestamps          r(   r   z&AsyncAdapt_asyncpg_connection._prepare  s     112FGGG..="&"2"2":":9"EEM&557J *,,
 :?	:J7M:'7
  "66$j00"..66yAA"113
):tyy{Cij((1 	H F  Bs4   CC0CC
	ACC3C
CCc                 `   | j                   j                         rd | _        d| _        t	        |t
        j                        sk| j                  j                  }t        |      j                  D ];  }||v s ||   t        |      d|      }t        |dd       x|_        |_        || ||)NFz: sqlstate)r   	is_closedrI  r   r|   r   Errorr'   _asyncpg_error_translater   __mro__getattrpgcoder[  )r&   r   exception_mappingsuper_translated_errors        r(   r   z/AsyncAdapt_asyncpg_connection._handle_exception  s    %%' $D!DM%!9!?!?@ $

 C Cu+-- 
..'@'8'@$(K7($
  z489$+(1*5
 Kr*   c                      | j                   dk(  S N
autocommit)rE  r   s    r(   rg  z(AsyncAdapt_asyncpg_connection.autocommit  s    ##|33r*   c                 :    |rd| _         y | j                  | _         y rf  )rE  rF  r&   r   s     r(   rg  z(AsyncAdapt_asyncpg_connection.autocommit  s    #/D #'#:#:D r*   c                 X    | j                   r| j                          |x| _        | _        y r!   )r   rollbackrE  rF  )r&   levels     r(   set_isolation_levelz1AsyncAdapt_asyncpg_connection.set_isolation_level  s"    ==MMO9>>t6r*   c                 T  K   | j                   dk(  ry 	 | j                  j                  | j                   | j                  | j                        | _        | j
                  j                          d {    d| _        y 7 # t        $ r}| j                  |       Y d }~y d }~ww xY ww)Nrg  )	isolationrG  rH  T)
rE  r   transactionrG  rH  rI  startr   r   r   r   s     r(   r   z0AsyncAdapt_asyncpg_connection._start_transaction  s     </
	! $ 0 0 < <..?? != !D
 ##))+++ !DM	 , 	*""5))	*sA   B(AB 2A?3B 7B(?B 	B%
B B( B%%B(c                 2    |rt        |       S t        |       S r!   )r  r   )r&   r   s     r(   r   z$AsyncAdapt_asyncpg_connection.cursor  s    /55,T22r*   c                    | j                   r9	 | j                  | j                  j                                d | _        d| _         y y # t        $ r}| j                  |       Y d }~/d }~ww xY w# d | _        d| _         w xY wNF)r   r
  rI  rk  r   r   r   s     r(   rk  z&AsyncAdapt_asyncpg_connection.rollback  st    ==&D--6689 %)! %   .&&u--. %)! %)   )A 	A+A&!A. &A++A. .A>c                    | j                   r9	 | j                  | j                  j                                d | _        d| _         y y # t        $ r}| j                  |       Y d }~/d }~ww xY w# d | _        d| _         w xY wrt  )r   r
  rI  commitr   r   r   s     r(   rw  z$AsyncAdapt_asyncpg_connection.commit  st    ==&D--4467 %)! %   .&&u--. %)! %ru  c                 v    | j                          | j                  | j                  j                                y r!   )rk  r
  r   r   r   s    r(   r   z#AsyncAdapt_asyncpg_connection.close  s&    D$$**,-r*   c                 8    | j                   j                          y r!   )r   	terminater   s    r(   rz  z'AsyncAdapt_asyncpg_connection.terminate  s    ""$r*   N)d   )F)r,   r-   r.   r  staticmethodr   r
  r   r  r   r   propertyrg  setterrm  r   r   rk  rw  r   rz  r/   r*   r(   rD  rD  W  s{    I *%F2$F
)6, 4 4 ; ;?
! 3&&.
%r*   rD  c                        e Zd ZdZ ee      Zy)%AsyncAdaptFallback_asyncpg_connectionr/   N)r,   r-   r.   r  r|  r   r
  r/   r*   r(   r  r    s    I.)Fr*   r  c                      e Zd Zd Zd Z G d de      Z G d de      Z G d de      Z G d	 d
e      Z	 G d de	      Z
 G d de	      Z G d de	      Z G d de	      Z G d de	      Z G d de	      Z G d de
      Z G d de      Zej&                  d        Zd Z ej,                  d      Z ej,                  d      Z ej,                  d      Z ej,                  d       Z ej,                  d!      Z ej,                  d"      Z ej,                  d#      Z ej,                  d$      Z ej,                  d%      Z ej,                  d&      Z  ej,                  d'      Z! ej,                  d(      Z" ej,                  d)      Z# ej,                  d*      Z$ ej,                  d+      Z% ej,                  d,      Z& ej,                  d-      Z' ej,                  d.      Z( ej,                  d/      Z)eZ*e)Z+y0)1r   c                      || _         d| _        y )Nformat)asyncpg
paramstyler&   r  s     r(   r   z!AsyncAdapt_asyncpg_dbapi.__init__  s    "r*   c           
      8   |j                  dd      }|j                  dd      }t        j                  |      r1t        | t	         | j
                  j                  |i |      |      S t        | t         | j
                  j                  |i |      |      S )Nasync_fallbackFrQ  r{  )rQ  )	r  r   asboolr  r   r  connectrD  r   )r&   argrI   r  rQ  s        r(   r  z AsyncAdapt_asyncpg_dbapi.connect  s     0%8(*+S)
% ;;~&83t||33S?B?@.K  1/4<<//;;<.K r*   c                       e Zd Zy)AsyncAdapt_asyncpg_dbapi.ErrorNr   r/   r*   r(   r]  r        r*   r]  c                       e Zd Zy) AsyncAdapt_asyncpg_dbapi.WarningNr   r/   r*   r(   Warningr    r  r*   r  c                       e Zd Zy)'AsyncAdapt_asyncpg_dbapi.InterfaceErrorNr   r/   r*   r(   InterfaceErrorr    r  r*   r  c                       e Zd Zy)&AsyncAdapt_asyncpg_dbapi.DatabaseErrorNr   r/   r*   r(   DatabaseErrorr    r  r*   r  c                       e Zd Zy)&AsyncAdapt_asyncpg_dbapi.InternalErrorNr   r/   r*   r(   InternalErrorr    r  r*   r  c                       e Zd Zy))AsyncAdapt_asyncpg_dbapi.OperationalErrorNr   r/   r*   r(   OperationalErrorr    r  r*   r  c                       e Zd Zy))AsyncAdapt_asyncpg_dbapi.ProgrammingErrorNr   r/   r*   r(   ProgrammingErrorr  "  r  r*   r  c                       e Zd Zy)'AsyncAdapt_asyncpg_dbapi.IntegrityErrorNr   r/   r*   r(   IntegrityErrorr  %  r  r*   r  c                       e Zd Zy)"AsyncAdapt_asyncpg_dbapi.DataErrorNr   r/   r*   r(   	DataErrorr  (  r  r*   r  c                       e Zd Zy)*AsyncAdapt_asyncpg_dbapi.NotSupportedErrorNr   r/   r*   r(   NotSupportedErrorr  +  r  r*   r  c                       e Zd Zy),AsyncAdapt_asyncpg_dbapi.InternalServerErrorNr   r/   r*   r(   r   r  .  r  r*   r   c                        e Zd Z fdZ xZS )4AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementErrorc                 H    t         t        j                  |   	 |dz          y )Nzc (SQLAlchemy asyncpg dialect will now invalidate all prepared caches in response to this exception))r"  r   r   r   )r&   messager#  s     r(   r   z=AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementError.__init__2  s-    (DDd E Er*   )r,   r-   r.   r   rA  rB  s   @r(   r   r  1  s    	 	r*   r   c                    dd l }|j                  j                  | j                  |j                  j                  | j
                  |j                  j                  | j                  |j                  j                  | j                  |j                  j                  | j                  |j                  j                  | j                  iS r  )r  
exceptions!IntegrityConstraintViolationErrorr  PostgresErrorr]  SyntaxOrAccessErrorr  r  r   r   r  s     r(   r^  z1AsyncAdapt_asyncpg_dbapi._asyncpg_error_translate:  s     @@$BUBU,,djj22D4I4I--t/B/B::D<\<\22D4L4L
 	
r*   c                     |S r!   r/   ri  s     r(   BinaryzAsyncAdapt_asyncpg_dbapi.BinaryG  s    r*   ru   r:   r9   r$   r#   r3   r   r   r   r>   rS   rW   BYTESDECIMALr[   rf   r	   r   BYTEAN),r,   r-   r.   r   r  r   r]  r  r  r  r  r  r  r  r  r  r   r   r   memoized_propertyr^  r  symbolru   r:   r9   r$   r#   r3   r   r   r   r>   rS   rW   r  r  r[   rf   r	   r   r  DATETIMEBINARYr/   r*   r(   r   r     s   #$	 )    = =  M M m &7  


 

 T[["FK(I T[[!12N4;;vDK(I4;;vDt{{:&HT[["FDKK Edkk)$Gdkk)$G\*JDKK Edkk)$G4;;vDDKK E4;;vD4;;vDDKK EHFr*   r   varchar	timestampztimestamp with time zonedaterM  ztime with time zonerH   numericfloatboolintegerbigintbytesr   r   jsonbenumuuidbyteac            
       R    e Zd ZdZdZdZdZdZdZdZ	dZ
eZeZeZdZdZ ej(                  ej,                  i ej0                  eej4                  eej8                  eej<                  ee ee!e"ejF                  e$ejJ                  e&ejN                  e(ejR                  e*ejV                  e,ejZ                  e.e/j`                  e1ejZ                  jd                  e3ejZ                  jh                  e5ejZ                  jl                  e7ejZ                  jp                  e9ejt                  e;e<e=e>e?i      ZdZ@dZAd ZBej                  d        ZDeEd        ZFej                  d	        ZGd
 ZHd ZId ZJd ZKd ZLddZMd ZNeEd        ZOd ZPd ZQd ZRd ZS fdZTd ZU xZVS )PGDialect_asyncpgr  Tr  Fr   c                 6    t        j                          | _        y r!   )rM  r   r   s    r(   r   z*PGDialect_asyncpg._invalidate_schema_cache  s    -1YY[*r*   c                     | j                   r`t        | j                   d      rJt        t        j                  d| j                   j
                        D cg c]  }t        |       c}      S yc c}w )N__version__z(\d+)(?:[-\.]?|$))c   r  r  )r'   hasattrr   r   findallr  r   )r&   xs     r(   _dbapi_versionz PGDialect_asyncpg._dbapi_version  sa    ::'$**m<  ZZ,djj.D.D F   s   A.c                 *    t        t        d            S )Nr  )r   
__import__)rG   s    r(   r'   zPGDialect_asyncpg.dbapi  s    '
9(=>>r*   c                     dddddS )Nrg  rL  repeatable_readserializable)
AUTOCOMMITzREAD COMMITTEDzREPEATABLE READSERIALIZABLEr/   r   s    r(   _isolation_lookupz#PGDialect_asyncpg._isolation_lookup  s     '.0*	
 	
r*   c                 >   	 | j                   |j                  dd         }|j                  |       y # t        $ r`}t        j                  t        j                  d|d| j                  ddj                  | j                               |       Y d }~vd }~ww xY w)Nr    zInvalid value 'z2' for isolation_level. Valid isolation levels for z are z, )replace_context)
r  replaceKeyErrorr   raise_r   ArgumentErrorr   joinrm  )r&   rP  rl  errs       r(   rm  z%PGDialect_asyncpg.set_isolation_level  s    
	**5==c+BCE 	&&u-  	KK!! dii43I3I)JL
 !$ 	s   3 	BABBc                     ||_         y r!   rG  r&   rP  r   s      r(   set_readonlyzPGDialect_asyncpg.set_readonly  s
    #
r*   c                     |j                   S r!   r  r&   rP  s     r(   get_readonlyzPGDialect_asyncpg.get_readonly  s    """r*   c                     ||_         y r!   rH  r  s      r(   set_deferrablez PGDialect_asyncpg.set_deferrable  s
     %
r*   c                     |j                   S r!   r  r  s     r(   get_deferrablez PGDialect_asyncpg.get_deferrable  s    $$$r*   c                 $    |j                          y r!   )rz  )r&   dbapi_connections     r(   do_terminatezPGDialect_asyncpg.do_terminate  s    ""$r*   c                     |j                  d      }|j                  |j                         t        j                  |dt
               t        j                  |dt
               g |fS )Nuser)usernamerQ  port)translate_connect_argsupdatequeryr   coerce_kw_typer   )r&   urloptss      r(   create_connect_argsz%PGDialect_asyncpg.create_connect_args  sT    ))6):CIID"A3GD&#.Dzr*   c                     |j                   j                  dd      }t        j                  |      rt        j
                  S t        j                  S )Nr  F)r  r   r   r  r   FallbackAsyncAdaptedQueuePoolAsyncAdaptedQueuePool)rG   r  r  s      r(   get_pool_classz PGDialect_asyncpg.get_pool_class  s=     '7?;;~&555---r*   c                     |r|j                   j                         S t        || j                  j                        xr dt        |      v S )Nzconnection is closed)r   r\  r|   r'   r  r   )r&   r   rP  r   s       r(   is_disconnectzPGDialect_asyncpg.is_disconnect  sG    ))33554::,, 3(CF23r*   c                     | j                   r& |j                  |D cg c]  \  }}}|
 c}}}  y  |j                  di |D ci c]  \  }}}|r|| c}}} y c c}}}w c c}}}w )Nr/   )
positionalr  )r&   r   list_of_tuplescontextkeydbtypesqltypes          r(   do_set_input_sizesz$PGDialect_asyncpg.do_set_input_sizes  s}    ?? F  5CDD1S&'&D !F    1? ,VW K Es   AA&c                    K   |j                   }| j                  xs t        j                  fd}|j	                  dt
        j                  |dd       d{    y7 w)zset up JSON codec for asyncpg.

        This occurs for all new connections and
        can be overridden by third party dialects.

        .. versionadded:: 1.4.27

        c                 0     | j                               S r!   decode	bin_valuedeserializers    r(   _json_decoderzAPGDialect_asyncpg.setup_asyncpg_json_codec.<locals>._json_decoder  s    	 0 0 233r*   r   
pg_catalogbinaryencoderdecoderschemar  N)r   _json_deserializer_py_jsonloadsset_type_codecr   encode)r&   connasyncpg_connectionr  r  s       @r(   setup_asyncpg_json_codecz*PGDialect_asyncpg.setup_asyncpg_json_codec  s`      "--..@(..	4 !//JJ! 0 
 	
 	
s   AA"A A"c                    K   |j                   }| j                  xs t        j                  d }| j                  xs t        j                  fd}|j	                  d||dd       d{    y7 w)zset up JSONB codec for asyncpg.

        This occurs for all new connections and
        can be overridden by third party dialects.

        .. versionadded:: 1.4.27

        c                 (    d| j                         z   S )N   )r   )	str_values    r(   _jsonb_encoderzCPGDialect_asyncpg.setup_asyncpg_jsonb_codec.<locals>._jsonb_encoder2  s     Y--///r*   c                 6     | dd  j                               S )Nr   r  r  s    r(   _jsonb_decoderzCPGDialect_asyncpg.setup_asyncpg_jsonb_codec.<locals>._jsonb_decoder9  s      	!" 4 4 677r*   r  r  r  r  N)r   r  r  r  r  )r&   r!  r"  r(  r*  r  s        @r(   setup_asyncpg_jsonb_codecz+PGDialect_asyncpg.setup_asyncpg_jsonb_codec%  sw      "--..@(..	0
 ..@(..	8
 !//"" 0 
 	
 	
s   A*A5-A3.A5c                 <     t         t                   fd}|S )zon_connect for asyncpg

        A major component of this for asyncpg is to set up type decoders at the
        asyncpg level.

        See https://github.com/MagicStack/asyncpg/issues/623 for
        notes on JSON/JSONB implementation.

        c                     | j                  j                  |              | j                  j                  |              	 |        y y r!   )r
  r#  r+  )r!  r&   super_connects    r(   r  z-PGDialect_asyncpg.on_connect.<locals>.connectS  sD    KK55d;<KK66t<=(d# )r*   )r"  r  
on_connect)r&   r  r.  r#  s   ` @r(   r/  zPGDialect_asyncpg.on_connectF  s!     /AC	$ r*   c                     |j                   S r!   )r   r  s     r(   get_driver_connectionz'PGDialect_asyncpg.get_driver_connection[  s    %%%r*   )returnN)Wr,   r-   r.   driversupports_statement_cachesupports_unicode_statementssupports_server_side_cursorssupports_unicode_bindshas_terminatedefault_paramstylesupports_sane_multi_rowcountr   execution_ctx_clsr   statement_compilerr   prepareruse_setinputsizesr   r   update_copyr   colspecsr   Timer   Dater1   DateTimer7   IntervalrB   r   r   r   Booleanr<   IntegerrP   
BigIntegerrU   Numericr   Floatr   r[   rY   r   rf   rd   JSONPathTypery   JSONIndexTyperj   JSONIntIndexTypero   JSONStrIndexTyperr   EnumrM   r   r   r   r   is_asyncr   r   r  r  rK   r'   r  rm  r  r  r  r  r  r  r  r  r  r#  r+  r/  r1  rA  rB  s   @r(   r  r  y  sd   F#"&#' !M!#( 2++HOt	
MM;	
MM;	
 	
 		

 o	
 +	
 n	
 n	
 !2	
 n	
 NNL	
 MM;	
 JJ	
 MM&&(;	
 MM'')=	
  MM**,C!	
" MM**,C#	
$ MM;o)	
H2 H$%!9 
    ? ? 

 
.$#&%% . .3
0
B*&r*   r  )]__doc__r'  r   r   r  r   rM   baser   r   r   r	   r   r   r   r   r   r   r   r   r   r   r   r   enginer   sqlr   util.concurrencyr   r   r   r  r   ImportErrorrA  r   rB  r1   rC  r7   rE  r<   rB   rM   rF  rP   rG  rU   r[   rY   rf   rd   rK  rj   rL  ro   rM  rr   rJ  ry   r   rH  r   r   r   r   r   r   r   r   r  rD  r  r   ru   r:   r9   r3   r$   r#   r   r   r>   rS   rW   r  r  r  r   r  r^   r/   r*   r(   <module>rW     s  ob    	            $ &       '  ' . *)
(-- (-- 
#h'' #X%% 
Dh D$ 
X%% 
 ++  
$)) 4:: 88==66 8
hmm<< 
hmm<< 
$++ $ 2X%% @> 
h 
 
?!3 ?>	 		#7 	Y YxQ
#< Q
hY%$5 Y%x*,I *f fR##Y&& ++-G !!6	
 !!6 &&(= %%z ##Y ""G $$f $$i '' ""G $$i !!6  ""G!" !!6#$ !!6""G'	.c&	 c&L O  Ls   M0 0M;:M;