U
    9a                  $   @   s  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 zddlmZ  W n e!k
rR   dZ Y nX G dd dej"Z#G dd dej$Z%G dd dej&Z'G d d! d!ej(Z)G d"d# d#eZ*G d$d% d%eZ+G d&d' d'ej,Z-G d(d) d)ej.Z/G d*d+ d+ej0Z1G d,d- d-ej2Z3G d.d/ d/ej0j4Z5G d0d1 d1ej0j6Z7G d2d3 d3ej0j8Z9G d4d5 d5ej:Z;G d6d7 d7eZ<G d8d9 d9ej=Z>G d:d; d;eZ?G d<d= d=eZ@G d>d? d?eZAG d@dA dAeZBG dBdC dCeZCG dDdE dEZDG dFdG dGeDZEG dHdI dIZFG dJdK dKeFZGG dLdM dMZHeHjIdNeHjJdOeHjKdPeHjLdQeHjMdReHjdSeHjNdTeHjOdUeHjPdVeHjQdWeHjRdXeHjSdYeHjTdZeHj0d[eHj2d\eHjd]eHjd^eHjUd_iZVG d`da daeZWeWZXdS )ba  
.. 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.

    N   )json)_DECIMAL_TYPES)_FLOAT_TYPES)
_INT_TYPESENUMINTERVAL)OID)
PGCompiler)	PGDialect)PGExecutionContext)PGIdentifierPreparer)REGCLASSUUID   )exc)pool)
processors)util)sqltypes)asyncio)await_fallback)
await_onlyc                   @   s   e Zd Zdd ZdS )AsyncpgTimec                 C   s   |j S N)TIMEselfdbapi r"   J/tmp/pip-unpacked-wheel-7pet0iyd/sqlalchemy/dialects/postgresql/asyncpg.pyget_dbapi_type   s    zAsyncpgTime.get_dbapi_typeN__name__
__module____qualname__r$   r"   r"   r"   r#   r      s   r   c                   @   s   e Zd Zdd ZdS )AsyncpgDatec                 C   s   |j S r   )DATEr   r"   r"   r#   r$      s    zAsyncpgDate.get_dbapi_typeNr%   r"   r"   r"   r#   r)      s   r)   c                   @   s   e Zd Zdd ZdS )AsyncpgDateTimec                 C   s   | j r|jS |jS d S r   )timezoneTIMESTAMP_W_TZ	TIMESTAMPr   r"   r"   r#   r$      s    zAsyncpgDateTime.get_dbapi_typeNr%   r"   r"   r"   r#   r+      s   r+   c                   @   s   e Zd Zdd ZdS )AsyncpgBooleanc                 C   s   |j S r   )BOOLEANr   r"   r"   r#   r$      s    zAsyncpgBoolean.get_dbapi_typeNr%   r"   r"   r"   r#   r/      s   r/   c                   @   s    e Zd Zdd Zedd ZdS )AsyncPgIntervalc                 C   s   |j S r   r	   r   r"   r"   r#   r$      s    zAsyncPgInterval.get_dbapi_typec                 K   s   t |jdS )N)Z	precision)r1   Zsecond_precision)clsintervalkwr"   r"   r#   adapt_emulated_to_native   s    z(AsyncPgInterval.adapt_emulated_to_nativeN)r&   r'   r(   r$   classmethodr5   r"   r"   r"   r#   r1      s   r1   c                   @   s   e Zd Zdd ZdS )AsyncPgEnumc                 C   s   |j S r   r   r   r"   r"   r#   r$      s    zAsyncPgEnum.get_dbapi_typeNr%   r"   r"   r"   r#   r7      s   r7   c                   @   s   e Zd Zdd ZdS )AsyncpgIntegerc                 C   s   |j S r   INTEGERr   r"   r"   r#   r$      s    zAsyncpgInteger.get_dbapi_typeNr%   r"   r"   r"   r#   r8      s   r8   c                   @   s   e Zd Zdd ZdS )AsyncpgBigIntegerc                 C   s   |j S r   )
BIGINTEGERr   r"   r"   r#   r$      s    z AsyncpgBigInteger.get_dbapi_typeNr%   r"   r"   r"   r#   r;      s   r;   c                   @   s   e Zd Zdd Zdd ZdS )AsyncpgJSONc                 C   s   |j S r   )JSONr   r"   r"   r#   r$      s    zAsyncpgJSON.get_dbapi_typec                 C   s   d S r   r"   r    dialectcoltyper"   r"   r#   result_processor   s    zAsyncpgJSON.result_processorNr&   r'   r(   r$   rB   r"   r"   r"   r#   r=      s   r=   c                   @   s   e Zd Zdd Zdd ZdS )AsyncpgJSONBc                 C   s   |j S r   )JSONBr   r"   r"   r#   r$      s    zAsyncpgJSONB.get_dbapi_typec                 C   s   d S r   r"   r?   r"   r"   r#   rB      s    zAsyncpgJSONB.result_processorNrC   r"   r"   r"   r#   rD      s   rD   c                   @   s   e Zd Zdd ZdS )AsyncpgJSONIndexTypec                 C   s   t dd S )Nzshould not be hereNotImplementedErrorr   r"   r"   r#   r$      s    z#AsyncpgJSONIndexType.get_dbapi_typeNr%   r"   r"   r"   r#   rF      s   rF   c                   @   s   e Zd Zdd ZdS )AsyncpgJSONIntIndexTypec                 C   s   |j S r   r9   r   r"   r"   r#   r$      s    z&AsyncpgJSONIntIndexType.get_dbapi_typeNr%   r"   r"   r"   r#   rI      s   rI   c                   @   s   e Zd Zdd ZdS )AsyncpgJSONStrIndexTypec                 C   s   |j S r   STRINGr   r"   r"   r#   r$      s    z&AsyncpgJSONStrIndexType.get_dbapi_typeNr%   r"   r"   r"   r#   rJ      s   rJ   c                   @   s   e Zd Zdd ZdS )AsyncpgJSONPathTypec                 C   s   dd }|S )Nc                 S   s$   t | tjjstdd | D }|S )Nc                 S   s   g | ]}t |qS r"   )r   	text_type).0elemr"   r"   r#   
<listcomp>   s     zGAsyncpgJSONPathType.bind_processor.<locals>.process.<locals>.<listcomp>)
isinstancer   collections_abcSequenceAssertionError)valuetokensr"   r"   r#   process   s    z3AsyncpgJSONPathType.bind_processor.<locals>.processr"   r    r@   rX   r"   r"   r#   bind_processor   s    z"AsyncpgJSONPathType.bind_processorN)r&   r'   r(   rZ   r"   r"   r"   r#   rM      s   rM   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )AsyncpgUUIDc                 C   s   |j S r   r   r   r"   r"   r#   r$      s    zAsyncpgUUID.get_dbapi_typec                 C   s   | j s|jrdd }|S d S )Nc                 S   s   | d k	rt | } | S r   )_python_UUIDrV   r"   r"   r#   rX      s    z+AsyncpgUUID.bind_processor.<locals>.processZas_uuiduse_native_uuidrY   r"   r"   r#   rZ      s    zAsyncpgUUID.bind_processorc                 C   s   | j s|jrdd }|S d S )Nc                 S   s   | d k	rt | } | S r   )strr]   r"   r"   r#   rX      s    z-AsyncpgUUID.result_processor.<locals>.processr^   )r    r@   rA   rX   r"   r"   r#   rB      s    zAsyncpgUUID.result_processorN)r&   r'   r(   r$   rZ   rB   r"   r"   r"   r#   r[      s   
r[   c                   @   s   e Zd Zdd Zdd ZdS )AsyncpgNumericc                 C   s   d S r   r"   )r    r@   r"   r"   r#   rZ      s    zAsyncpgNumeric.bind_processorc                 C   sv   | j rB|tkrttj| jS |tks.|tkr2d S t	
d| n0|tkrNd S |tks^|tkrdtjS t	
d| d S )NzUnknown PG numeric type: %d)Z	asdecimalr   r   Zto_decimal_processor_factorydecimalDecimalZ_effective_decimal_return_scaler   r   r   ZInvalidRequestErrorZto_floatr?   r"   r"   r#   rB      s$     zAsyncpgNumeric.result_processorN)r&   r'   r(   rZ   rB   r"   r"   r"   r#   ra      s   ra   c                   @   s   e Zd Zdd ZdS )AsyncpgREGCLASSc                 C   s   |j S r   rK   r   r"   r"   r#   r$     s    zAsyncpgREGCLASS.get_dbapi_typeNr%   r"   r"   r"   r#   rd     s   rd   c                   @   s   e Zd Zdd ZdS )
AsyncpgOIDc                 C   s   |j S r   r9   r   r"   r"   r#   r$     s    zAsyncpgOID.get_dbapi_typeNr%   r"   r"   r"   r#   re     s   re   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 r   )rR   r@   r!   InvalidCachedStatementErrorInternalServerError_invalidate_schema_cache)r    er"   r"   r#   handle_dbapi_exception"  s    z1PGExecutionContext_asyncpg.handle_dbapi_exceptionc                 C   s4   | j r| j  | jj| j_| js&d S tjh| _d S r   )	Zisddlr@   ri   _invalidate_schema_cache_asofcursorZcompiledAsyncAdapt_asyncpg_dbapir   Zexclude_set_input_sizesr    r"   r"   r#   pre_exec,  s    
z#PGExecutionContext_asyncpg.pre_execc                 C   s   | j jddS )NT)server_side)Z_dbapi_connectionrm   ro   r"   r"   r#   create_server_side_cursor<  s    z4PGExecutionContext_asyncpg.create_server_side_cursorN)r&   r'   r(   rk   rp   rr   r"   r"   r"   r#   rf   !  s   
rf   c                   @   s   e Zd ZdS )PGCompiler_asyncpgNr&   r'   r(   r"   r"   r"   r#   rs   @  s   rs   c                   @   s   e Zd ZdS )PGIdentifierPreparer_asyncpgNrt   r"   r"   r"   r#   ru   D  s   ru   c                   @   s   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 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_inputsizes_cursorrl   Fc                 C   s<   || _ |j| _g | _d | _d | _d| _d| _d | _d| _d S )Nr   r   )	rw   rx   ry   r~   rz   r{   r|   r}   rl   r    adapt_connectionr"   r"   r#   __init__W  s    z"AsyncAdapt_asyncpg_cursor.__init__c                 C   s   g | j d d < d S r   ry   ro   r"   r"   r#   closeb  s    zAsyncAdapt_asyncpg_cursor.closec                 C   s   | j | d S r   )rw   _handle_exceptionr    errorr"   r"   r#   r   e  s    z+AsyncAdapt_asyncpg_cursor._handle_exceptionc                 C   sF   | j stdd t|dD S tdd tdd | j D dD S d S )Nc                 s   s   | ]\}}d | V  qdS )$%dNr"   )rO   idx_r"   r"   r#   	<genexpr>j  s     zDAsyncAdapt_asyncpg_cursor._parameter_placeholders.<locals>.<genexpr>r   c                 s   s*   | ]"\}}|rd ||f nd| V  qdS )z$%d::%sr   Nr"   )rO   r   typr"   r"   r#   r   m  s   c                 s   s   | ]}t |V  qd S r   )	_pg_typesget)rO   r   r"   r"   r#   r   p  s     )r}   tuple	enumerate)r    paramsr"   r"   r#   _parameter_placeholdersh  s     z1AsyncAdapt_asyncpg_cursor._parameter_placeholdersc           	         s&  | j }|j4 I d H   |js,| I d H  |d k	rD|| | }nd}z||| jI d H \}}|rxdd |D | _nd | _| jr|j	| I d H | _
d| _nB|j| I d H | _| }td|}|rt|d| _nd| _W n. tk
r } z| | W 5 d }~X Y nX W 5 Q I d H R X d S )Nr"   c              	   S   s$   g | ]}|j |jjd d d d d fqS r   )nametypeoid)rO   attrr"   r"   r#   rQ     s   
zBAsyncAdapt_asyncpg_cursor._prepare_and_execute.<locals>.<listcomp>r   z"(?:UPDATE|DELETE|INSERT \d+) (\d+)r   )rw   _execute_mutex_started_start_transactionr   _preparerl   rz   rq   rm   r~   r|   fetchry   Zget_statusmsgrematchintgroup	Exceptionr   )	r    	operation
parametersr   prepared_stmt
attributesstatusregr   r"   r"   r#   _prepare_and_executet  sB     

 
z.AsyncAdapt_asyncpg_cursor._prepare_and_executec                    s   | j }|j4 I d H  || jI d H  |js<| I d H  || |d  }z(| j||I d H W W  5 Q I d H R  S  t	k
r } z| 
| W 5 d }~X Y nX W 5 Q I d H R X d S Nr   )rw   r   _check_type_cache_invalidationrl   r   r   r   rx   executemanyr   r   )r    r   seq_of_parametersr   r   r"   r"   r#   _executemany  s"    
 z&AsyncAdapt_asyncpg_cursor._executemanyNc                 C   s   | j | || d S r   )rw   await_r   )r    r   r   r"   r"   r#   execute  s    
z!AsyncAdapt_asyncpg_cursor.executec                 C   s   | j | ||S r   )rw   r   r   r    r   r   r"   r"   r#   r     s    
z%AsyncAdapt_asyncpg_cursor.executemanyc                 G   s
   || _ d S r   )r}   )r    Z
inputsizesr"   r"   r#   setinputsizes  s    z'AsyncAdapt_asyncpg_cursor.setinputsizesc                 c   s   | j r| j dV  q d S r   ry   popro   r"   r"   r#   __iter__  s    z"AsyncAdapt_asyncpg_cursor.__iter__c                 C   s   | j r| j dS d S d S r   r   ro   r"   r"   r#   fetchone  s    z"AsyncAdapt_asyncpg_cursor.fetchonec                 C   s8   |d kr| j }| jd| }| j|d  | jd d < |S r   )r{   ry   )r    sizeretvalr"   r"   r#   	fetchmany  s
    z#AsyncAdapt_asyncpg_cursor.fetchmanyc                 C   s    | j d d  }g | j d d < |S r   r   )r    r   r"   r"   r#   fetchall  s    z"AsyncAdapt_asyncpg_cursor.fetchall)N)N)r&   r'   r(   	__slots__rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r"   r"   r"   r#   rv   H  s   6

rv   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 | _d S r   )superr   r   r   r   	__class__r"   r#   r     s    z%AsyncAdapt_asyncpg_ss_cursor.__init__c                 C   s   d | _ d | _d S r   )r~   r   ro   r"   r"   r#   r     s    z"AsyncAdapt_asyncpg_ss_cursor.closec                 C   s$   | j | jd}t|| _d S )N2   )rw   r   r~   r   collectionsdequer   )r    Znew_rowsr"   r"   r#   _buffer_rows  s    z)AsyncAdapt_asyncpg_ss_cursor._buffer_rowsc                 C   s   | S r   r"   ro   r"   r"   r#   	__aiter__  s    z&AsyncAdapt_asyncpg_ss_cursor.__aiter__c                 C  s8   | j s|   | j r"| j  V  q|   | j sq4qd S r   r   r   popleftro   r"   r"   r#   	__anext__  s    z&AsyncAdapt_asyncpg_ss_cursor.__anext__c                 C   s"   | j s|   | j sd S | j  S r   r   ro   r"   r"   r#   r     s
    z%AsyncAdapt_asyncpg_ss_cursor.fetchoneNc                 C   sz   |d kr|   S | js|   t| j}t|}||krV|| j| j	||  |d| }t
||d  | _|S r   )r   r   r   listlenextendrw   r   r~   r   r   r   )r    r   bufZlbresultr"   r"   r#   r     s    
z&AsyncAdapt_asyncpg_ss_cursor.fetchmanyc                 C   s,   t | jt | j|   }| j  |S r   )r   r   rw   r   _allclear)r    retr"   r"   r#   r     s
    

z%AsyncAdapt_asyncpg_ss_cursor.fetchallc                    s0   g }| j dI d H }|r,|| qqq,q|S )Ni  )r~   r   r   )r    Zrowsbatchr"   r"   r#   r   %  s    
z!AsyncAdapt_asyncpg_ss_cursor._allc                 C   s   t dd S )Nz2server side cursor doesn't support executemany yetrG   r   r"   r"   r#   r   3  s    z(AsyncAdapt_asyncpg_ss_cursor.executemany)N)r&   r'   r(   rq   r   r   r   r   r   r   r   r   r   r   r   __classcell__r"   r"   r   r#   r     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dZdd Zdd Zdd ZdS )AsyncAdapt_asyncpg_connection)r!   rx   isolation_level_isolation_settingreadonly
deferrable_transactionr   _prepared_statement_cacherl   r   d   c                 C   s`   || _ || _d | _| _d| _d| _d | _d| _t | _	t
 | _|rVt|| _nd | _d S )Nread_committedF)r!   rx   r   r   r   r   r   r   timerl   r   Lockr   r   ZLRUCacher   )r    r!   
connectionprepared_statement_cache_sizer"   r"   r#   r   J  s    

z&AsyncAdapt_asyncpg_connection.__init__c                    s$   || j kr | j I d H  || _ d S r   )rl   rx   Zreload_schema_state)r    invalidate_timestampr"   r"   r#   r   \  s    
z<AsyncAdapt_asyncpg_connection._check_type_cache_invalidationc                    s   |  |I d H  | j}|d kr@| j|I d H }| }||fS ||krf|| \}}}||krf||fS | j|I d H }| }||t f||< ||fS r   )r   r   rx   prepareZget_attributesr   )r    r   r   cacher   r   Zcached_timestampr"   r"   r#   r   a  s    z&AsyncAdapt_asyncpg_connection._preparec                 C   s   | j  rd | _d| _t|tjsz| jj}t	|j
D ]>}||kr4|| dt	||f }t|dd  |_|_||q4|n|d S )NFz%s: %ssqlstate)rx   	is_closedr   r   rR   rn   Errorr!   _asyncpg_error_translater   __mro__getattrZpgcoder   )r    r   Zexception_mappingZsuper_Ztranslated_errorr"   r"   r#   r   |  s     

z/AsyncAdapt_asyncpg_connection._handle_exceptionc                 C   s
   | j dkS N
autocommit)r   ro   r"   r"   r#   r     s    z(AsyncAdapt_asyncpg_connection.autocommitc                 C   s   |rd| _ n| j| _ d S r   )r   r   r    rV   r"   r"   r#   r     s    c                 C   s   | j r|   | | _| _d S r   )r   rollbackr   r   )r    levelr"   r"   r#   set_isolation_level  s    z1AsyncAdapt_asyncpg_connection.set_isolation_levelc              
      st   | j dkrd S z.| jj| j | j| jd| _| j I d H  W n, tk
rh } z| | W 5 d }~X Y nX d| _	d S )Nr   )Z	isolationr   r   T)
r   rx   Ztransactionr   r   r   startr   r   r   r   r"   r"   r#   r     s    
z0AsyncAdapt_asyncpg_connection._start_transactionFc                 C   s   |rt | S t| S d S r   )r   rv   )r    rq   r"   r"   r#   rm     s    z$AsyncAdapt_asyncpg_connection.cursorc              
   C   s`   | j r\zFz| | j  W n, tk
rH } z| | W 5 d }~X Y nX W 5 d | _d| _ X d S NF)r   r   r   r   r   r   r   r"   r"   r#   r     s     z&AsyncAdapt_asyncpg_connection.rollbackc              
   C   s`   | j r\zFz| | j  W n, tk
rH } z| | W 5 d }~X Y nX W 5 d | _d| _ X d S r   )r   r   r   commitr   r   r   r"   r"   r#   r     s     z$AsyncAdapt_asyncpg_connection.commitc                 C   s   |    | | j  d S r   )r   r   rx   r   ro   r"   r"   r#   r     s    z#AsyncAdapt_asyncpg_connection.closeN)r   )F)r&   r'   r(   r   staticmethodr   r   r   r   r   r   propertyr   setterr   r   rm   r   r   r   r"   r"   r"   r#   r   9  s    





r   c                   @   s   e Zd ZdZeeZdS )%AsyncAdaptFallback_asyncpg_connectionr"   N)r&   r'   r(   r   r   r   r   r"   r"   r"   r#   r     s   r   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jdd Zdd  Zed!Zed"Zed#Zed$Zed%Zed&Zed'Zed(Zed)Zed*Z ed+Z!ed,Z"ed-Z#ed.Z$ed/Z%ed0Z&ed1Z'ed2Z(eZ)e(Z*d3S )4rn   c                 C   s   || _ d| _d S )Nformat)asyncpgZ
paramstyler    r   r"   r"   r#   r     s    z!AsyncAdapt_asyncpg_dbapi.__init__c                 O   s^   | dd}| dd}t|r>t| t| jj|||dS t| t| jj|||dS d S )Nasync_fallbackFr   r   )r   )	r   r   asboolr   r   r   connectr   r   )r    argr4   r   r   r"   r"   r#   r     s      
z AsyncAdapt_asyncpg_dbapi.connectc                   @   s   e Zd ZdS )zAsyncAdapt_asyncpg_dbapi.ErrorNrt   r"   r"   r"   r#   r     s   r   c                   @   s   e Zd ZdS )z AsyncAdapt_asyncpg_dbapi.WarningNrt   r"   r"   r"   r#   Warning  s   r   c                   @   s   e Zd ZdS )z'AsyncAdapt_asyncpg_dbapi.InterfaceErrorNrt   r"   r"   r"   r#   InterfaceError  s   r   c                   @   s   e Zd ZdS )z&AsyncAdapt_asyncpg_dbapi.DatabaseErrorNrt   r"   r"   r"   r#   DatabaseError  s   r   c                   @   s   e Zd ZdS )z&AsyncAdapt_asyncpg_dbapi.InternalErrorNrt   r"   r"   r"   r#   InternalError  s   r   c                   @   s   e Zd ZdS )z)AsyncAdapt_asyncpg_dbapi.OperationalErrorNrt   r"   r"   r"   r#   OperationalError  s   r   c                   @   s   e Zd ZdS )z)AsyncAdapt_asyncpg_dbapi.ProgrammingErrorNrt   r"   r"   r"   r#   ProgrammingError  s   r   c                   @   s   e Zd ZdS )z'AsyncAdapt_asyncpg_dbapi.IntegrityErrorNrt   r"   r"   r"   r#   IntegrityError  s   r  c                   @   s   e Zd ZdS )z"AsyncAdapt_asyncpg_dbapi.DataErrorNrt   r"   r"   r"   r#   	DataError  s   r  c                   @   s   e Zd ZdS )z*AsyncAdapt_asyncpg_dbapi.NotSupportedErrorNrt   r"   r"   r"   r#   NotSupportedError
  s   r  c                   @   s   e Zd ZdS )z,AsyncAdapt_asyncpg_dbapi.InternalServerErrorNrt   r"   r"   r"   r#   rh     s   rh   c                       s   e Zd Z fddZ  ZS )z4AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementErrorc                    s   t tj| |d  d S )Nzc (SQLAlchemy asyncpg dialect will now invalidate all prepared caches in response to this exception))r   rn   rg   r   )r    messager   r"   r#   r     s     z=AsyncAdapt_asyncpg_dbapi.InvalidCachedStatementError.__init__)r&   r'   r(   r   r   r"   r"   r   r#   rg     s   rg   c                 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 r   )r   
exceptionsZ!IntegrityConstraintViolationErrorr  ZPostgresErrorr   ZSyntaxOrAccessErrorr   r   rg   rh   r   r"   r"   r#   r     s          z1AsyncAdapt_asyncpg_dbapi._asyncpg_error_translatec                 C   s   |S r   r"   r   r"   r"   r#   Binary&  s    zAsyncAdapt_asyncpg_dbapi.BinaryrL   r.   r-   r   r*   r
   NUMBERFLOATr0   r:   r<   BYTESDECIMALr>   rE   r   r   BYTEAN)+r&   r'   r(   r   r   r   r   r   r   r   r   r   r   r  r  r  rh   rg   r   memoized_propertyr   r  symbolrL   r.   r-   r   r*   r
   r  r  r0   r:   r<   r	  r
  r>   rE   r   r   r  ZDATETIMEBINARYr"   r"   r"   r#   rn     sJ   	


















rn   Zvarchar	timestampztimestamp with time zonedater   r3   numericfloatboolintegerZbigintbytesrb   r   jsonbenumuuidZbyteac                )       sP  e 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ejejeejeejeejeeee e!ej"e#ej$e%ej&e'ej(e)ej*e+e,j-e.ej*j/e0ej*j1e2ej*j3e4ej*j5e6ej7e8e9e:e;e<iZdZ=dZ>dd Z?ej@dd	 ZAeBd
d ZCej@dd ZDdd ZEdd ZFdd ZGdd ZHdd ZIdd ZJeBdd ZKdd ZLdd ZM fd d!ZN  ZOS )"PGDialect_asyncpgr   Tr   Fr   c                 C   s   t   | _d S r   )r   rl   ro   r"   r"   r#   ri     s    z*PGDialect_asyncpg._invalidate_schema_cachec                 C   s8   | j r0t| j dr0tdd td| j jD S dS d S )N__version__c                 S   s   g | ]}t |qS r"   )r   )rO   xr"   r"   r#   rQ     s   z4PGDialect_asyncpg._dbapi_version.<locals>.<listcomp>z(\d+)(?:[-\.]?|$))c   r  r  )r!   hasattrr   r   findallr  ro   r"   r"   r#   _dbapi_version  s     	z PGDialect_asyncpg._dbapi_versionc                 C   s   t tdS )Nr   )rn   
__import__)r2   r"   r"   r#   r!     s    zPGDialect_asyncpg.dbapic                 C   s   dddddS )Nr   r   Zrepeatable_readZserializable)Z
AUTOCOMMITzREAD COMMITTEDzREPEATABLE READZSERIALIZABLEr"   ro   r"   r"   r#   _isolation_lookup  s
    z#PGDialect_asyncpg._isolation_lookupc                 C   sp   z| j |dd }W nJ tk
r` } z,tjtd|| jd| j f |d W 5 d }~X Y nX |	| d S )Nr    zLInvalid value '%s' for isolation_level. Valid isolation levels for %s are %sz, )Zreplace_context)
r!  replaceKeyErrorr   Zraise_r   ArgumentErrorr   joinr   )r    r   r   errr"   r"   r#   r     s    	z%PGDialect_asyncpg.set_isolation_levelc                 C   s
   ||_ d S r   r   r    r   rV   r"   r"   r#   set_readonly  s    zPGDialect_asyncpg.set_readonlyc                 C   s   |j S r   r(  r    r   r"   r"   r#   get_readonly  s    zPGDialect_asyncpg.get_readonlyc                 C   s
   ||_ d S r   r   r)  r"   r"   r#   set_deferrable  s    z PGDialect_asyncpg.set_deferrablec                 C   s   |j S r   r-  r+  r"   r"   r#   get_deferrable  s    z PGDialect_asyncpg.get_deferrablec                 C   s<   |j dd}||j t|dt t|dt g |fS )Nuser)usernamer   port)Ztranslate_connect_argsupdatequeryr   Zcoerce_kw_typer   )r    urloptsr"   r"   r#   create_connect_args  s
    z%PGDialect_asyncpg.create_connect_argsc                 C   s(   |j dd}t|rtjS tjS d S )Nr   F)r4  r   r   r   r   ZFallbackAsyncAdaptedQueuePoolZAsyncAdaptedQueuePool)r2   r5  r   r"   r"   r#   get_pool_class  s    
z PGDialect_asyncpg.get_pool_classc                 C   s,   |r|j  S t|| jjo&dt|kS d S )Nzconnection is closed)rx   r   rR   r!   r   r`   )r    rj   r   rm   r"   r"   r#   is_disconnect  s    
 
zPGDialect_asyncpg.is_disconnectc                 C   s6   | j r|jdd |D   n|jf dd |D  d S )Nc                 S   s   g | ]\}}}|qS r"   r"   rO   keyZdbtypeZsqltyper"   r"   r#   rQ     s     z8PGDialect_asyncpg.do_set_input_sizes.<locals>.<listcomp>c                 S   s   i | ]\}}}|r||qS r"   r"   r:  r"   r"   r#   
<dictcomp>  s    z8PGDialect_asyncpg.do_set_input_sizes.<locals>.<dictcomp>)
positionalr   )r    rm   Zlist_of_tuplescontextr"   r"   r#   do_set_input_sizes  s    z$PGDialect_asyncpg.do_set_input_sizesc                    s\   t t|  dd | jp tjfdd fdd fddfd	d
}|S )Nc                 S   s   d|    S )N   )encode)Z	str_valuer"   r"   r#   _jsonb_encoder  s    z4PGDialect_asyncpg.on_connect.<locals>._jsonb_encoderc                    s    |   S r   decodeZ	bin_valuedeserializerr"   r#   _json_decoder  s    z3PGDialect_asyncpg.on_connect.<locals>._json_decoderc                    s    | dd    S )Nr   rC  rE  rF  r"   r#   _jsonb_decoder  s    z4PGDialect_asyncpg.on_connect.<locals>._jsonb_decoderc                    s>   | j jdtj dddI dH  | j jddddI dH  dS )a  set up type decoders at the asyncpg level.

            these are set_type_codec() calls to normalize
            There was a tentative decoder for the "char" datatype here
            to have it return strings however this type is actually a binary
            type that other drivers are likely mis-interpreting.

            See https://github.com/MagicStack/asyncpg/issues/623 for reference
            on why it's set up this way.
            r   Z
pg_catalogbinary)encoderdecoderZschemar   Nr  )rx   Zset_type_codecr`   rA  conn)rH  rI  rB  r"   r#   _setup_type_codecs  s    z8PGDialect_asyncpg.on_connect.<locals>._setup_type_codecsc                    s"   |   |  d k	r|  d S r   )r   rM  )rO  super_connectr"   r#   r     s    z-PGDialect_asyncpg.on_connect.<locals>.connect)r   r  
on_connectZ_json_deserializer_py_jsonloads)r    r   r   )rH  rI  rB  rO  rG  rP  r#   rQ    s    zPGDialect_asyncpg.on_connect)Pr&   r'   r(   ZdriverZsupports_statement_cacheZsupports_unicode_statementsZsupports_server_side_cursorsZsupports_unicode_bindsZdefault_paramstyleZsupports_sane_multi_rowcountrf   Zexecution_ctx_clsrs   Zstatement_compilerru   preparerZuse_setinputsizesr_   r   Zupdate_copyr   Zcolspecsr   Timer   Dater)   DateTimer+   ZIntervalr1   r
   r   r[   Booleanr/   Integerr8   
BigIntegerr;   Numericra   r>   r=   r   rE   rD   JSONPathTyperM   JSONIndexTyperF   JSONIntIndexTyperI   JSONStrIndexTyperJ   Enumr7   r   re   r   rd   Zis_asyncrl   ri   r  r  r6   r!   r!  r   r*  r,  r.  r/  r7  r8  r9  r?  rQ  r   r"   r"   r   r#   r  V  s                      



	r  )Y__doc__r   rb   r   rR  r   r    baser   r   r   r   r
   r   r   r   r   r   r   r   r   r   r   r   Zsqlr   Zutil.concurrencyr   r   r   r  r\   ImportErrorrU  r   rV  r)   rW  r+   rX  r/   r1   r7   rY  r8   rZ  r;   r>   r=   rE   rD   r]  rF   r^  rI   r_  rJ   r\  rM   r[   r[  ra   rd   re   rf   rs   ru   rv   r   r   r   rn   rL   r.   r-   r*   r   r  r  r0   r:   r<   r	  r
  r  r   r  r@   r"   r"   r"   r#   <module>   s   ^


 T i                   D