o
    gC                     @  s  d Z ddlmZ ddlm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% ddl&m'Z' ddl(m)Z) dd l(m*Z* dd!l(m+Z+ G d"d# d#eZ,G d$d% d%e'j-Z.G d&d' d'eZ/G d(d) d)e'j0Z1G d*d+ d+eZ2G d,d- d-eZ3G d.d/ d/e'j4Z5G d0d1 d1e'j6Z7G d2d3 d3e'j8Z9G d4d5 d5eZ:G d6d7 d7eZ;G d8d9 d9e'j<Z=G d:d; d;e'j>Z?G d<d= d=e'j@ZAG d>d? d?ejBZCG d@dA dAejDZEG dBdC dCe'jBjFZGG dDdE dEe'jBjHZIG dFdG dGe'jBjJZKG dHdI dIejLZMG dJdK dKe'jNZOG dLdM dMeOe'jPZQG dNdO dOeZRG dPdQ dQeZSG dRdS dSe'jTZUG dTdU dUejVZWG dVdW dWejXZYG dXdY dYeZZG dZd[ d[eZ[G d\d] d]eZ\G d^d_ d_Z]G d`da dae]Z^G dbdc dce$Z_G ddde dee_Z`G dfdg dgZaG dhdi dieZbebZcdS )ja  
.. 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"
    )

.. 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_multihost:

Multihost Connections
--------------------------

The asyncpg dialect features support for multiple fallback hosts in the
same way as that of the psycopg2 and psycopg dialects.  The
syntax is the same,
using ``host=<host>:<port>`` combinations as additional query string arguments;
however, there is no default port, so all hosts must have a complete port number
present, otherwise an exception is raised::

    engine = create_async_engine(
        "postgresql+asyncpg://user:password@/dbname?host=HostA:5432&host=HostB:5432&host=HostC:5432"
    )

For complete background on this syntax, see :ref:`psycopg2_multi_host`.

.. versionadded:: 2.0.18

.. seealso::

    :ref:`psycopg2_multi_host`

.. _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.

.. _asyncpg_prepared_statement_name:

Prepared Statement Name with PGBouncer
--------------------------------------

By default, asyncpg enumerates prepared statements in numeric order, which
can lead to errors if a name has already been taken for another prepared
statement. This issue can arise if your application uses database proxies
such as PgBouncer to handle connections. One possible workaround is to
use dynamic prepared statement names, which asyncpg now supports through
an optional ``name`` value for the statement name. This allows you to
generate your own unique names that won't conflict with existing ones.
To achieve this, you can provide a function that will be called every time
a prepared statement is prepared::

    from uuid import uuid4

    engine = create_async_engine(
        "postgresql+asyncpg://user:pass@somepgbouncer/dbname",
        poolclass=NullPool,
        connect_args={
            "prepared_statement_name_func": lambda: f"__asyncpg_{uuid4()}__",
        },
    )

.. seealso::

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

   https://github.com/sqlalchemy/sqlalchemy/issues/6467

.. warning:: When using PGBouncer, to prevent a buildup of useless prepared statements in
   your application, it's important to use the :class:`.NullPool` pool
   class, and to configure PgBouncer to use `DISCARD <https://www.postgresql.org/docs/current/sql-discard.html>`_
   when returning connections.  The DISCARD command is used to release resources held by the db connection,
   including prepared statements. Without proper setup, prepared statements can
   accumulate quickly and cause performance issues.

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

    )annotations)dequeN   )json)ranges)ARRAY)_DECIMAL_TYPES)_FLOAT_TYPES)
_INT_TYPES)ENUM)INTERVAL)OID)
PGCompiler)	PGDialect)PGExecutionContext)PGIdentifierPreparer)REGCLASS)	REGCONFIG)BIT)BYTEA)CITEXT   )exc)pool)util)AdaptedConnection)
processors)sqltypes)asyncio)await_fallback)
await_onlyc                   @     e Zd ZdZdS )AsyncpgARRAYTN__name__
__module____qualname__render_bind_cast r(   r(   h/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/postgresql/asyncpg.pyr"          r"   c                   @  r!   )AsyncpgStringTNr#   r(   r(   r(   r)   r+      r*   r+   c                   @  r!   )AsyncpgREGCONFIGTNr#   r(   r(   r(   r)   r,      r*   r,   c                   @  r!   )AsyncpgTimeTNr#   r(   r(   r(   r)   r-      r*   r-   c                   @  r!   )
AsyncpgBitTNr#   r(   r(   r(   r)   r.      r*   r.   c                   @  r!   )AsyncpgByteATNr#   r(   r(   r(   r)   r/      r*   r/   c                   @  r!   )AsyncpgDateTNr#   r(   r(   r(   r)   r0      r*   r0   c                   @  r!   )AsyncpgDateTimeTNr#   r(   r(   r(   r)   r1      r*   r1   c                   @  r!   )AsyncpgBooleanTNr#   r(   r(   r(   r)   r2      r*   r2   c                   @  s   e Zd ZdZedd ZdS )AsyncPgIntervalTc                 K  s   t |jdS )N)	precision)r3   second_precision)clsintervalkwr(   r(   r)   adapt_emulated_to_native      z(AsyncPgInterval.adapt_emulated_to_nativeN)r$   r%   r&   r'   classmethodr9   r(   r(   r(   r)   r3      s    r3   c                   @  r!   )AsyncPgEnumTNr#   r(   r(   r(   r)   r<     r*   r<   c                   @  r!   )AsyncpgIntegerTNr#   r(   r(   r(   r)   r=     r*   r=   c                   @  r!   )AsyncpgSmallIntegerTNr#   r(   r(   r(   r)   r>     r*   r>   c                   @  r!   )AsyncpgBigIntegerTNr#   r(   r(   r(   r)   r?     r*   r?   c                   @     e Zd Zdd ZdS )AsyncpgJSONc                 C     d S Nr(   selfdialectcoltyper(   r(   r)   result_processor     zAsyncpgJSON.result_processorNr$   r%   r&   rH   r(   r(   r(   r)   rA         rA   c                   @  r@   )AsyncpgJSONBc                 C  rB   rC   r(   rD   r(   r(   r)   rH     rI   zAsyncpgJSONB.result_processorNrJ   r(   r(   r(   r)   rL     rK   rL   c                   @     e Zd ZdS )AsyncpgJSONIndexTypeNr$   r%   r&   r(   r(   r(   r)   rN         rN   c                   @     e Zd ZdZdZdS )AsyncpgJSONIntIndexTypejson_int_indexTNr$   r%   r&   __visit_name__r'   r(   r(   r(   r)   rR   "      rR   c                   @  rQ   )AsyncpgJSONStrIndexTypejson_str_indexTNrT   r(   r(   r(   r)   rW   (  rV   rW   c                   @  r@   )AsyncpgJSONPathTypec                 C  s   dd }|S )Nc                 S  s(   t | tr| S | rdd | D }|S g S )Nc                 S     g | ]}t |qS r(   )str.0elemr(   r(   r)   
<listcomp>6      zGAsyncpgJSONPathType.bind_processor.<locals>.process.<locals>.<listcomp>
isinstancer[   )valuetokensr(   r(   r)   process0  s   
z3AsyncpgJSONPathType.bind_processor.<locals>.processr(   )rE   rF   re   r(   r(   r)   bind_processor/  s   z"AsyncpgJSONPathType.bind_processorN)r$   r%   r&   rf   r(   r(   r(   r)   rY   .  rK   rY   c                   @  s    e Zd ZdZdd Zdd ZdS )AsyncpgNumericTc                 C  rB   rC   r(   )rE   rF   r(   r(   r)   rf   A  rI   zAsyncpgNumeric.bind_processorc                 C  sp   | j r |tv rttj| jS |tv s|tv rd S t	
d| |tv r&d S |tv s.|tv r1tjS t	
d| )NzUnknown PG numeric type: %d)	asdecimalr	   r   to_decimal_processor_factorydecimalDecimal_effective_decimal_return_scaler   r
   r   InvalidRequestErrorto_floatrD   r(   r(   r)   rH   D  s"   zAsyncpgNumeric.result_processorN)r$   r%   r&   r'   rf   rH   r(   r(   r(   r)   rg   >  s    rg   c                   @  rQ   )AsyncpgFloatfloatTNrT   r(   r(   r(   r)   ro   ]  s    ro   c                   @  r!   )AsyncpgREGCLASSTNr#   r(   r(   r(   r)   rq   b  r*   rq   c                   @  r!   )
AsyncpgOIDTNr#   r(   r(   r(   r)   rr   f  r*   rr   c                   @  r!   )AsyncpgCHARTNr#   r(   r(   r(   r)   rs   j  r*   rs   c                   @     e Zd Zdd Zdd ZdS )_AsyncpgRangec                   s   |j jj  fdd}|S )Nc                   <   t | tjr | j| j| jd dk| jd dk| jd} | S Nr   [r   ])	lower_inc	upper_incemptyrb   r   Rangelowerupperboundsr|   rc   asyncpg_Ranger(   r)   to_ranger     z._AsyncpgRange.bind_processor.<locals>.to_range)dbapiasyncpgr~   rE   rF   r   r(   r   r)   rf   o  s   
z_AsyncpgRange.bind_processorc                 C     dd }|S )Nc                 S  L   | d ur$| j }tj| j| j|s| jrdnd |s| jrdnd |d} | S Nrx   (ry   ))r   r|   isemptyr   r~   r   r   rz   r{   )rc   r|   r(   r(   r)   r        z0_AsyncpgRange.result_processor.<locals>.to_ranger(   )rE   rF   rG   r   r(   r(   r)   rH     s   z_AsyncpgRange.result_processorNr$   r%   r&   rf   rH   r(   r(   r(   r)   ru   n  s    ru   c                   @  rt   )_AsyncpgMultiRangec                   s$   |j jjtd   fdd}|S )Nc                   s0   t | tfr	| S fdd  fdd| D S )Nc                   rv   rw   r}   r   r   r(   r)   r     r   zE_AsyncpgMultiRange.bind_processor.<locals>.to_range.<locals>.to_rangec                   s   g | ]} |qS r(   r(   )r]   elementr   r(   r)   r_     r`   zG_AsyncpgMultiRange.bind_processor.<locals>.to_range.<locals>.<listcomp>ra   r   NoneTyper   r   r)   r     s   z3_AsyncpgMultiRange.bind_processor.<locals>.to_range)r   r   r~   typer   r(   r   r)   rf     s   
z!_AsyncpgMultiRange.bind_processorc                 C  r   )Nc                   s,   dd  | d urt  fdd| D } | S )Nc                 S  r   r   r   )rvaluer|   r(   r(   r)   r     r   zM_AsyncpgMultiRange.result_processor.<locals>.to_range_array.<locals>.to_rangec                 3  s    | ]} |V  qd S rC   r(   r\   r   r(   r)   	<genexpr>  s    zN_AsyncpgMultiRange.result_processor.<locals>.to_range_array.<locals>.<genexpr>)r   
MultiRanger   r(   r   r)   to_range_array  s   z;_AsyncpgMultiRange.result_processor.<locals>.to_range_arrayr(   )rE   rF   rG   r   r(   r(   r)   rH     s   z#_AsyncpgMultiRange.result_processorNr   r(   r(   r(   r)   r     s    r   c                   @  s$   e Zd Zdd Zdd Zdd ZdS )PGExecutionContext_asyncpgc                 C  s,   t || jjj| jjjfr| j  d S d S rC   )rb   rF   r   InvalidCachedStatementErrorInternalServerError_invalidate_schema_cache)rE   er(   r(   r)   handle_dbapi_exception  s   z1PGExecutionContext_asyncpg.handle_dbapi_exceptionc                 C  s*   | j r| j  | jj| j_| jsd S d S rC   )isddlrF   r   _invalidate_schema_cache_asofcursorcompiledrE   r(   r(   r)   pre_exec  s   
z#PGExecutionContext_asyncpg.pre_execc                 C  s   | j jddS )NT)server_side)_dbapi_connectionr   r   r(   r(   r)   create_server_side_cursor     z4PGExecutionContext_asyncpg.create_server_side_cursorN)r$   r%   r&   r   r   r   r(   r(   r(   r)   r     s    
r   c                   @  rM   )PGCompiler_asyncpgNrO   r(   r(   r(   r)   r     rP   r   c                   @  rM   )PGIdentifierPreparer_asyncpgNrO   r(   r(   r(   r)   r     rP   r   c                   @  sx   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dddZ
dd Zdd Zdd Zdd ZdddZdd ZdS )AsyncAdapt_asyncpg_cursor)_adapt_connection_connection_rowsdescription	arraysizerowcount_cursorr   Fc                 C  s8   || _ |j| _t | _d | _d | _d| _d| _d| _d S )Nr   r   )	r   r   r   r   r   r   r   r   r   rE   adapt_connectionr(   r(   r)   __init__  s   
z"AsyncAdapt_asyncpg_cursor.__init__c                 C  s   | j   d S rC   )r   clearr   r(   r(   r)   close  r   zAsyncAdapt_asyncpg_cursor.closec                 C  s   | j | d S rC   )r   _handle_exceptionrE   errorr(   r(   r)   r     s   z+AsyncAdapt_asyncpg_cursor._handle_exceptionc           	        sP  | j }|j4 I d H  |js| I d H  |d u rd}zQ||| jI d H \}}|r4dd |D | _nd | _| jrG|j| I d H | _	d| _
n%t|j| I d H | _| }td|p\d}|rit|d| _
nd| _
W n ty } z| | W Y d }~nd }~ww W d   I d H  d S W d   I d H  d S 1 I d H sw   Y  d S )Nr(   c              	   S  s$   g | ]}|j |jjd d d d d fqS rC   )namer   oid)r]   attrr(   r(   r)   r_     s    
zBAsyncAdapt_asyncpg_cursor._prepare_and_execute.<locals>.<listcomp>r   z)(?:SELECT|UPDATE|DELETE|INSERT \d+) (\d+) r   )r   _execute_mutex_started_start_transaction_preparer   r   r   r   r   r   r   fetchr   get_statusmsgrematchintgroup	Exceptionr   )	rE   	operation
parametersr   prepared_stmt
attributesstatusregr   r(   r(   r)   _prepare_and_execute  sJ   

-.z.AsyncAdapt_asyncpg_cursor._prepare_and_executec                   s   | j }d | _|j4 I d H L || jI d H  |js"| I d H  z| j||I d H W W  d   I d H  S  t	yN } z| 
| W Y d }~nd }~ww W d   I d H  d S 1 I d H s`w   Y  d S rC   )r   r   r   _check_type_cache_invalidationr   r   r   r   executemanyr   r   )rE   r   seq_of_parametersr   r   r(   r(   r)   _executemany0  s(   

.z&AsyncAdapt_asyncpg_cursor._executemanyNc                 C  s   | j | || d S rC   )r   await_r   )rE   r   r   r(   r(   r)   executeC  s   
z!AsyncAdapt_asyncpg_cursor.executec                 C  s   | j | ||S rC   )r   r   r   rE   r   r   r(   r(   r)   r   H  s   
z%AsyncAdapt_asyncpg_cursor.executemanyc                 G  s   t  rC   NotImplementedError)rE   
inputsizesr(   r(   r)   setinputsizesM     z'AsyncAdapt_asyncpg_cursor.setinputsizesc                 c  s"    | j r| j  V  | j sd S d S rC   r   popleftr   r(   r(   r)   __iter__P  s   z"AsyncAdapt_asyncpg_cursor.__iter__c                 C  s   | j r| j  S d S rC   r   r   r(   r(   r)   fetchoneT  s   
z"AsyncAdapt_asyncpg_cursor.fetchonec                   s4   |d u r| j }| j  fddtt|t D S )Nc                      g | ]}   qS r(   r   r]   _rrr(   r)   r_   _  r`   z7AsyncAdapt_asyncpg_cursor.fetchmany.<locals>.<listcomp>)r   r   rangeminlen)rE   sizer(   r   r)   	fetchmanyZ  s    z#AsyncAdapt_asyncpg_cursor.fetchmanyc                 C  s   t | j}| j  |S rC   )listr   r   )rE   retvalr(   r(   r)   fetchalla  s   

z"AsyncAdapt_asyncpg_cursor.fetchallrC   )r$   r%   r&   	__slots__r   r   r   r   r   r   r   r   r   r   r   r   r   r(   r(   r(   r)   r     s    
2

r   c                      sn   e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	dd Z
dddZdd Zdd Zdd Z  ZS )AsyncAdapt_asyncpg_ss_cursorT)
_rowbufferc                   s   t  | t | _d S rC   )superr   r   r   r   	__class__r(   r)   r   k  s   z%AsyncAdapt_asyncpg_ss_cursor.__init__c                 C  s   d | _ | j  d S rC   )r   r   r   r   r(   r(   r)   r   o  s   z"AsyncAdapt_asyncpg_ss_cursor.closec                 C  s2   | j d usJ | j| j d}| j| d S )N2   )r   r   r   r   r   extend)rE   new_rowsr(   r(   r)   _buffer_rowss  s   z)AsyncAdapt_asyncpg_ss_cursor._buffer_rowsc                 C     | S rC   r(   r   r(   r(   r)   	__aiter__x  rI   z&AsyncAdapt_asyncpg_ss_cursor.__aiter__c                 C s0   	 | j r| j  V  | j s|   | j sd S qrC   )r   r   r   r   r(   r(   r)   	__anext__{  s   z&AsyncAdapt_asyncpg_ss_cursor.__anext__c                 C  s"   | j s|   | j sd S | j  S rC   )r   r   r   r   r(   r(   r)   r     s
   
z%AsyncAdapt_asyncpg_ss_cursor.fetchoneNc                   s   |d u r|   S | js|   | jd usJ | j t }||kr0 | j| j||   fddt	t
|t D S )Nc                   r   r(   r   r   rbr(   r)   r_     r`   z:AsyncAdapt_asyncpg_ss_cursor.fetchmany.<locals>.<listcomp>)r   r   r   r   r   r   r   r   r   r   r   )rE   r   lbr(   r  r)   r     s    z&AsyncAdapt_asyncpg_ss_cursor.fetchmanyc                 C  s.   t | j}|| j|   | j  |S rC   )r   r   r   r   r   _allr   )rE   retr(   r(   r)   r     s   

z%AsyncAdapt_asyncpg_ss_cursor.fetchallc                   s0   g }	 | j dI d H }|r|| q	 |S )NTi  )r   r   r   )rE   rowsbatchr(   r(   r)   r    s   
z!AsyncAdapt_asyncpg_ss_cursor._allc                 C  s   t d)Nz2server side cursor doesn't support executemany yetr   r   r(   r(   r)   r     s   z(AsyncAdapt_asyncpg_ss_cursor.executemanyrC   )r$   r%   r&   r   r   r   r   r   r   r   r   r   r   r  r   __classcell__r(   r(   r   r)   r   g  s    	
r   c                   @  s   e Zd ZdZeeZ		d(ddZdd Zdd	 Z	d
d Z
edd Zejdd Zdd Zdd Zdd Zdd Zd)ddZdd Zdd Zdd Zd d! Zd"d# Zd$d% Zed&d' ZdS )*AsyncAdapt_asyncpg_connection)r   isolation_level_isolation_settingreadonly
deferrable_transactionr   _prepared_statement_cache_prepared_statement_name_funcr   r   d   Nc                 C  sv   || _ || _d | _| _d| _d| _d | _d| _t | _	t
 | _|r+t|| _nd | _|r5|| _d S | j| _d S )Nread_committedF)r   r   r
  r  r  r  r  r   timer   r   Lockr   r   LRUCacher  r  _default_name_func)rE   r   
connectionprepared_statement_cache_sizeprepared_statement_name_funcr(   r(   r)   r     s"   


z&AsyncAdapt_asyncpg_connection.__init__c                   s*   || j kr| j I d H  || _ d S d S rC   )r   r   reload_schema_state)rE   invalidate_timestampr(   r(   r)   r     s
   

z<AsyncAdapt_asyncpg_connection._check_type_cache_invalidationc                   s   |  |I d H  | j}|d u r%| jj||  dI d H }| }||fS ||v r8|| \}}}||kr8||fS | jj||  dI d H }| }||t f||< ||fS )N)r   )r   r  r   preparer  get_attributesr  )rE   r   r  cacher   r   cached_timestampr(   r(   r)   r     s&   z&AsyncAdapt_asyncpg_connection._preparec                 C  s|   | j  rd | _d| _t|tjs<| jj}t	|j
D ]}||v r9|| dt	||f }t|dd  |_|_||q||)NFz%s: %ssqlstate)r   	is_closedr  r   rb   AsyncAdapt_asyncpg_dbapiErrorr   _asyncpg_error_translater   __mro__getattrpgcoder   )rE   r   exception_mappingsuper_translated_errorr(   r(   r)   r     s    


	z/AsyncAdapt_asyncpg_connection._handle_exceptionc                 C  s
   | j dkS N
autocommit)r
  r   r(   r(   r)   r,    s   
z(AsyncAdapt_asyncpg_connection.autocommitc                 C  s   |rd| _ d S | j| _ d S r+  )r
  r  rE   rc   r(   r(   r)   r,  "  s   
c              
   C  sF   z
|  |  }W d S  ty" } z| | W Y d }~d S d }~ww rC   )r   _async_pingr   r   )rE   r   r   r(   r(   r)   ping)  s   z"AsyncAdapt_asyncpg_connection.pingc                   s|   | j d u r3| jdkr3| j }| I d H  z| jdI d H  W | I d H  d S | I d H  w | jdI d H  d S )Nr,  ;)r  r
  r   transactionstartfetchrowrollback)rE   trr(   r(   r)   r.  /  s   
"z)AsyncAdapt_asyncpg_connection._async_pingc                 C  s   | j r|   | | _| _d S rC   )r   r4  r
  r  )rE   levelr(   r(   r)   set_isolation_level<  s   z1AsyncAdapt_asyncpg_connection.set_isolation_levelc              
     sz   | j dkrd S z| jj| j | j| jd| _| j I d H  W n ty7 } z| | W Y d }~d S d }~ww d| _	d S )Nr,  )	isolationr  r  T)
r
  r   r1  r  r  r  r2  r   r   r   r   r(   r(   r)   r   A  s   

z0AsyncAdapt_asyncpg_connection._start_transactionFc                 C  s   |rt | S t| S rC   )r   r   )rE   r   r(   r(   r)   r   Q  s   z$AsyncAdapt_asyncpg_connection.cursorc                   4   z| j  I d H  W d | _ d| _d S d | _ d| _w NF)r  r4  r   r   r(   r(   r)   _rollback_and_discardW     
z3AsyncAdapt_asyncpg_connection._rollback_and_discardc                   r9  r:  )r  commitr   r   r(   r(   r)   _commit_and_discard`  r<  z1AsyncAdapt_asyncpg_connection._commit_and_discardc              
   C  \   | j r,z| |   d | _d| _ W d S  ty+ } z| | W Y d }~d S d }~ww d S r:  )r   r   r;  r  r   r   r   r(   r(   r)   r4  i     z&AsyncAdapt_asyncpg_connection.rollbackc              
   C  r?  r:  )r   r   r>  r  r   r   r   r(   r(   r)   r=  t  r@  z$AsyncAdapt_asyncpg_connection.commitc                 C  s   |    | | j  d S rC   )r4  r   r   r   r   r(   r(   r)   r     s   z#AsyncAdapt_asyncpg_connection.closec                 C  sf   t j r)z| | jjdd W n tjtjt	| j
jjfy(   | j  Y nw | j  d| _d S )N   )timeoutF)r   concurrencyin_greenletr   r   r   r   TimeoutErrorCancelledErrorOSErrorr   r   PostgresError	terminater   r   r(   r(   r)   rI    s   



z'AsyncAdapt_asyncpg_connection.terminatec                   C  rB   rC   r(   r(   r(   r(   r)   r    s   z0AsyncAdapt_asyncpg_connection._default_name_func)r  N)F)r$   r%   r&   r   staticmethodr    r   r   r   r   r   propertyr,  setterr/  r.  r7  r   r   r;  r>  r4  r=  r   rI  r  r(   r(   r(   r)   r	    s4    



		r	  c                   @  s   e Zd ZdZeeZdS )%AsyncAdaptFallback_asyncpg_connectionr(   N)r$   r%   r&   r   rJ  r   r   r(   r(   r(   r)   rM    s    rM  c                   @  s  e Zd Zdd Zdd ZG dd deZG dd deZG d	d
 d
eZG dd deZ	G dd de	Z
G dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de
ZG dd deZedZedZedZejd d! Zd"d# Zd$S )%r"  c                 C  s   || _ d| _d S )Nnumeric_dollar)r   
paramstylerE   r   r(   r(   r)   r     s   
z!AsyncAdapt_asyncpg_dbapi.__init__c                 O  sz   | dd}| d| jj}| dd}| dd }t|r.t| t||i |||dS t| t||i |||dS )Nasync_fallbackFasync_creator_fnr  r  r  )r  r  )	popr   connectr   asboolrM  r   r	  r    )rE   argr8   rQ  
creator_fnr  r  r(   r(   r)   rT    s*   
z AsyncAdapt_asyncpg_dbapi.connectc                   @  rM   )zAsyncAdapt_asyncpg_dbapi.ErrorNrO   r(   r(   r(   r)   r#    rP   r#  c                   @  rM   )z AsyncAdapt_asyncpg_dbapi.WarningNrO   r(   r(   r(   r)   Warning  rP   rX  c                   @  rM   )z'AsyncAdapt_asyncpg_dbapi.InterfaceErrorNrO   r(   r(   r(   r)   InterfaceError  rP   rY  c                   @  rM   )z&AsyncAdapt_asyncpg_dbapi.DatabaseErrorNrO   r(   r(   r(   r)   DatabaseError  rP   rZ  c                   @  rM   )z&AsyncAdapt_asyncpg_dbapi.InternalErrorNrO   r(   r(   r(   r)   InternalError  rP   r[  c                   @  rM   )z)AsyncAdapt_asyncpg_dbapi.OperationalErrorNrO   r(   r(   r(   r)   OperationalError  rP   r\  c                   @  rM   )z)AsyncAdapt_asyncpg_dbapi.ProgrammingErrorNrO   r(   r(   r(   r)   ProgrammingError  rP   r]  c                   @  rM   )z'AsyncAdapt_asyncpg_dbapi.IntegrityErrorNrO   r(   r(   r(   r)   IntegrityError  rP   r^  c                   @  rM   )z"AsyncAdapt_asyncpg_dbapi.DataErrorNrO   r(   r(   r(   r)   	DataError  rP   r_  c                   @  rM   )z*AsyncAdapt_asyncpg_dbapi.NotSupportedErrorNrO   r(   r(   r(   r)   NotSupportedError  rP   r`  c                   @  rM   )z,AsyncAdapt_asyncpg_dbapi.InternalServerErrorNrO   r(   r(   r(   r)   r     rP   r   c                      s   e Zd Z fddZ  ZS )z4AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementErrorc                   s   t  |d  d S )Nzc (SQLAlchemy asyncpg dialect will now invalidate all prepared caches in response to this exception))r   r   )rE   messager   r(   r)   r     s   z=AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementError.__init__)r$   r%   r&   r   r  r(   r(   r   r)   r     s    r   STRINGNUMBERDATETIMEc                 C  sH   dd l }|jj| j|jj| j|jj| j|jj| j|jj	| j	|jj
| j
iS )Nr   )r   
exceptions!IntegrityConstraintViolationErrorr^  rH  r#  SyntaxOrAccessErrorr]  rY  r   r   rP  r(   r(   r)   r$    s   





z1AsyncAdapt_asyncpg_dbapi._asyncpg_error_translatec                 C  s   |S rC   r(   r-  r(   r(   r)   Binary  rI   zAsyncAdapt_asyncpg_dbapi.BinaryN)r$   r%   r&   r   rT  r   r#  rX  rY  rZ  r[  r\  r]  r^  r_  r`  r   r   r   symbolrb  rc  rd  memoized_propertyr$  rh  r(   r(   r(   r)   r"    s*    
	


r"  c                      s  e Zd ZdZdZdZdZdZdZdZ	e
ZeZeZeeji ejeejeeeeeeeejeej e!ej"e#ej$e%e&e%ej'e(ej)e*ej+e,ej-e.ej/e0ej1e2ej3e4ej5e6e7j8e9ej3j:e;ej3j<e=ej3j>e?ej3j@eAejBeCeDeEeFeGejHeIeJjKeLeJjMeNiZdZOdZPdd ZQejRdd	 ZSeTd
d ZUejRdd ZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\d0ddZ]dd Z^d d! Z_eTd"d# Z`d$d% Zad&d' Zbd(d) Zcd*d+ Zd fd,d-Zed.d/ Zf  ZgS )1PGDialect_asyncpgr   TrN  Fr   c                 C  s   t   | _d S rC   )r  r   r   r(   r(   r)   r   9  r   z*PGDialect_asyncpg._invalidate_schema_cachec                 C  s4   | j rt| j drtdd td| j jD S dS )N__version__c                 S  rZ   r(   )r   )r]   xr(   r(   r)   r_   @  s    z4PGDialect_asyncpg._dbapi_version.<locals>.<listcomp>z(\d+)(?:[-\.]?|$))c   rn  rn  )r   hasattrtupler   findallrl  r   r(   r(   r)   _dbapi_version<  s   	z PGDialect_asyncpg._dbapi_versionc                 C  s   t tdS )Nr   )r"  
__import__)r6   r(   r(   r)   import_dbapiJ  r:   zPGDialect_asyncpg.import_dbapic                 C  s   dddddS )Nr,  r  repeatable_readserializable)
AUTOCOMMITzREAD COMMITTEDzREPEATABLE READSERIALIZABLEr(   r   r(   r(   r)   _isolation_lookupN  s
   z#PGDialect_asyncpg._isolation_lookupc                 C  s
   t | jS rC   )r   ry  rE   dbapi_connectionr(   r(   r)   get_isolation_level_valuesW     
z,PGDialect_asyncpg.get_isolation_level_valuesc                 C  s   | | j|  d S rC   )r7  ry  )rE   r{  r6  r(   r(   r)   r7  Z  s   z%PGDialect_asyncpg.set_isolation_levelc                 C  
   ||_ d S rC   r  rE   r  rc   r(   r(   r)   set_readonly]  r}  zPGDialect_asyncpg.set_readonlyc                 C     |j S rC   r  rE   r  r(   r(   r)   get_readonly`  r   zPGDialect_asyncpg.get_readonlyc                 C  r~  rC   r  r  r(   r(   r)   set_deferrablec  r}  z PGDialect_asyncpg.set_deferrablec                 C  r  rC   r  r  r(   r(   r)   get_deferrablef  r   z PGDialect_asyncpg.get_deferrablereturnNonec                 C  s   |   d S rC   )rI  rz  r(   r(   r)   do_terminatei     zPGDialect_asyncpg.do_terminatec                 C  s   |j dd}| |\}}||j |rQ|sJ t|dkr2|d |d< |d d ur1|d |d< n&t|s;tdt|sDtdt||d< t||d< nt	
|dt t	
|d	t g |fS )
Nuser)usernamer   r   hostportzBAll hosts are required to be present for asyncpg multiple host URLzBAll ports are required to be present for asyncpg multiple host URLr  )translate_connect_args_split_multihost_from_urlupdatequeryr   allr   ArgumentErrorr   r   coerce_kw_typer   )rE   urlopts
multihosts
multiportsr(   r(   r)   create_connect_argsl  s.   z%PGDialect_asyncpg.create_connect_argsc                 C  s   |   dS )NT)r/  rz  r(   r(   r)   do_ping  s   zPGDialect_asyncpg.do_pingc                 C  s$   |j dd}t|rtjS tjS )NrQ  F)r  getr   rU  r   FallbackAsyncAdaptedQueuePoolAsyncAdaptedQueuePool)r6   r  rQ  r(   r(   r)   get_pool_class  s   
z PGDialect_asyncpg.get_pool_classc                 C  s(   |r|j  S t|| jjodt|v S )Nzconnection is closed)r   r!  rb   r   rY  r[   )rE   r   r  r   r(   r(   r)   is_disconnect  s   

zPGDialect_asyncpg.is_disconnectc                   s@   |j }| jp	tj  fdd}|jdtj|dddI dH  dS )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                   s    |   S rC   decode	bin_valuedeserializerr(   r)   _json_decoder  r  zAPGDialect_asyncpg.setup_asyncpg_json_codec.<locals>._json_decoderr   
pg_catalogbinaryencoderdecoderschemaformatN)r   _json_deserializer_py_jsonloadsset_type_codecr[   encode)rE   connasyncpg_connectionr  r(   r  r)   setup_asyncpg_json_codec  s   
z*PGDialect_asyncpg.setup_asyncpg_json_codecc                   sR   |j }| jp	tj dd }| jptj  fdd}|jd||dddI d	H  d	S )
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                 S  s   d|    S )N   )r  )	str_valuer(   r(   r)   _jsonb_encoder  s   zCPGDialect_asyncpg.setup_asyncpg_jsonb_codec.<locals>._jsonb_encoderc                   s    | dd    S )Nr   r  r  r  r(   r)   _jsonb_decoder  s   zCPGDialect_asyncpg.setup_asyncpg_jsonb_codec.<locals>._jsonb_decoderjsonbr  r  r  N)r   r  r  r  r  )rE   r  r  r  r  r(   r  r)   setup_asyncpg_jsonb_codec  s   
z+PGDialect_asyncpg.setup_asyncpg_jsonb_codecc                   sP   |j }|jddd dd dddI d H  |jdd	d d
d dddI d H  d S )Ninetc                 S  r   rC   r(   sr(   r(   r)   <lambda>      z@PGDialect_asyncpg._disable_asyncpg_inet_codecs.<locals>.<lambda>c                 S  r   rC   r(   r  r(   r(   r)   r    r  r  textr  cidrc                 S  r   rC   r(   r  r(   r(   r)   r    r  c                 S  r   rC   r(   r  r(   r(   r)   r    r  )r   r  )rE   r  r  r(   r(   r)   _disable_asyncpg_inet_codecs  s    z.PGDialect_asyncpg._disable_asyncpg_inet_codecsc                   s   t    fd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                   sR   |   |  |   |   jdu r|   |  d ur'|  d S d S r:  )r   r  r  _native_inet_typesr  )r  rE   super_connectr(   r)   rT    s   
z-PGDialect_asyncpg.on_connect.<locals>.connect)r   
on_connect)rE   rT  r   r  r)   r    s   
	zPGDialect_asyncpg.on_connectc                 C  r  rC   )r   r  r(   r(   r)   get_driver_connection  r   z'PGDialect_asyncpg.get_driver_connection)r  r  )hr$   r%   r&   driversupports_statement_cachesupports_server_side_cursorsr'   has_terminatedefault_paramstylesupports_sane_multi_rowcountr   execution_ctx_clsr   statement_compilerr   preparerr   update_copyr   colspecsr   Stringr+   r   r"   r   r.   r   r   r,   Timer-   Dater0   DateTimer1   Intervalr3   r   Booleanr2   Integerr=   SmallIntegerr>   
BigIntegerr?   Numericrg   Floatro   JSONrA   LargeBinaryr/   r   JSONBrL   JSONPathTyperY   JSONIndexTyperN   JSONIntIndexTyperR   JSONStrIndexTyperW   Enumr<   r   rr   r   rq   CHARrs   r   AbstractSingleRangeru   AbstractMultiRanger   is_asyncr   r   rj  rr  r;   rt  ry  r|  r7  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r(   r(   r   r)   rk    s    	
"




!rk  )d__doc__
__future__r   collectionsr   rj   r   r  r   r  r   r   arrayr   PGARRAYbaser   r	   r
   r   r   r   r   r   r   r   r   r   typesr   r   r   r   r   r   enginer   r   sqlr   util.concurrencyr   r   r    r"   r  r+   r,   r  r-   r.   r/   r  r0   r  r1   r  r2   r3   r<   r  r=   r  r>   r  r?   r  rA   r  rL   r  rN   r  rR   r  rW   r  rY   r  rg   r  ro   rq   rr   r  rs   AbstractSingleRangeImplru   AbstractMultiRangeImplr   r   r   r   r   r   r	  rM  r"  rk  rF   r(   r(   r(   r)   <module>   s    +!/ O m]  