
    ci:              	          d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	 ddl
mZ ddlmZmZmZ ddlmZ ddlmZmZmZmZmZ dd	lmZ d
dlmZ d
dlmZ g dZeee e e e gef   Z! ejD                  d      Z#eed      Z$dejJ                  deddfdZ&dejJ                  de'ddfdZ( e)       Z*ee+eejJ                     eg ef   f      Z,de,fdZ- G d d      Z.ddddee ef   deej^                     dede.fdZ0y) z*
Core implementation of aiosqlite proxies
    N)AsyncIterator	GeneratorIterable)partial)Path)EmptyQueueSimpleQueue)Thread)AnyCallableLiteralOptionalUnion)warn   )contextmanager)Cursor)connect
Connectionr   	aiosqlite)DEFERRED	IMMEDIATE	EXCLUSIVEfutresultreturnc                 H    | j                         s| j                  |       yy)z9Set the result of a future if it hasn't been set already.N)done
set_result)r   r   s     5/tmp/pip-target-z3e9_cxr/lib/python/aiosqlite/core.pyr    r        s    88:v     ec                 H    | j                         s| j                  |       yy)z<Set the exception of a future if it hasn't been set already.N)r   set_exception)r   r#   s     r!   r%   r%   &   s    88:! r"   txc                    	 | j                         \  }}	 t        j                  d|        |       }|r%|j                         j	                  t
        ||       t        j                  d|       |t        u ry	 y# t        $ rG}t        j                  d|       |r%|j                         j	                  t        ||       Y d}~Ld}~ww xY w)zJ
    Execute function calls on a separate thread.

    :meta private:
    zexecuting %szoperation %s completedzreturning exception %sN)	getLOGdebugget_loopcall_soon_threadsafer    _STOP_RUNNING_SENTINELBaseExceptionr%   )r&   futurefunctionr   r#   s        r!   _connection_worker_threadr1   0   s     
 668	QIInh/ZF!66z66RII.9// 0 $  	QII.2!66}faP	Qs   A"A; ;	C=CCc                      e Zd Z	 d@deg ej
                  f   dedeej                     ddfdZ
d Zdeej                     fdZedej
                  fd	       Zd
ededeej$                     fdZd
ededeej$                     fdZd ZdAdZdeedd f   fdZdAdZdBdZedefd       ZdBdZdBdZ dBdZ!e	 d@d
edeee      defd       Z"e	 d@d
edeee      deej$                     fd       Z#e	 d@d
edeee      deej$                     fd       Z$ed
edeee      defd       Z%ededefd       Z&dBdZ'	 dCdeded ed!e(ddf
d"Z)ede(fd#       Z*edee   fd$       Z+e+jX                  d%e-ddfd&       Z+edee.   fd'       Z/e/jX                  d(ee.   ddfd)       Z/edee0gef   fd*       Z1e1jX                  d(ee0gef   ddfd+       Z1edefd,       Z2d%e(ddfd-Z3d.efd/Z4d0eg ee   f   d1eddfd2Z5d0eddfd3Z6d4ee7   ddfd5Z8de9e   fd6Z:d7dd8d9d:d;e;d ej
                  f   d<ed=eeeeegdf      ded>e<ddfd?Z=y)Dr   N	connectoriter_chunk_sizeloopr   c                     d| _         d | _        || _        t               | _        || _        t        t        | j                  f      | _        |t        dt               y y )NT)targetargsz8aiosqlite.Connection no longer uses the `loop` parameter)_running_connection
_connectorr
   _tx_iter_chunk_sizer   r1   _threadr   DeprecationWarning)selfr3   r4   r5   s       r!   __init__zConnection.__init__O   sY     9=#(] /%>dhh[QJ" r"   c                 h    | j                   y t        | dt        d       | j                          y )Nzi was deleted before being closed. Please use 'async with' or '.close()' to close the connection properly.r   )
stacklevel)r:   r   ResourceWarningstopr@   s    r!   __del__zConnection.__del__b   s=    #( Z Z 	
 			r"   c                      d _          fd}	 t        j                         j                         } j
                  j                  ||f       |S # t        $ r d}Y ,w xY w)zBStop the background thread. Prefer `async with` or `await close()`Fc                  j     j                   ! j                   j                          d  _         t        S N)r:   closer-   rF   s   r!   close_and_stopz'Connection.stop.<locals>.close_and_stopx   s/    +  &&(#' ))r"   N)r9   asyncioget_event_loopcreate_future	Exceptionr<   
put_nowait)r@   rL   r/   s   `  r!   rE   zConnection.stopt   s_    	*	++-;;=F 	V^45	  	F	s   "A AAc                 H    | j                   t        d      | j                   S )Nzno active connection)r:   
ValueErrorrF   s    r!   _connzConnection._conn   s&    #344r"   sql
parametersc                 |    | j                   j                  ||      }|j                  d       |j                         S )NzSELECT last_insert_rowid())rT   executefetchoner@   rU   rV   cursors       r!   _execute_insertzConnection._execute_insert   s2    ##C434  r"   c                 Z    | j                   j                  ||      }|j                         S rJ   )rT   rX   fetchallrZ   s       r!   _execute_fetchallzConnection._execute_fetchall   s%    ##C4  r"   c                   K   | j                   r| j                  st        d      t        |g|i |}t	        j
                         j                         }| j                  j                  ||f       | d{   S 7 w)z8Queue a function with the given arguments for execution.zConnection closedN)	r9   r:   rS   r   rM   rN   rO   r<   rQ   )r@   fnr8   kwargsr0   r/   s         r!   _executezConnection._execute   sm     }}D$4$40112///'')779VX./||s   A7B 9A>:B c                 *  K   | j                   [	 t        j                         j                         }| j                  j                  || j                  f       | d{   | _         | S | S 7 # t        $ r | j                          d| _          w xY ww)z&Connect to the actual sqlite database.N)	r:   rM   rN   rO   r<   rQ   r;   r.   rE   r@   r/   s     r!   _connectzConnection._connect   s     # //1??A##VT__$=>)/<  t $0  		#' s/   BAA. A,	A. (B,A. ."BBc                 r    | j                   j                          | j                         j                         S rJ   )r>   startrf   	__await__rF   s    r!   ri   zConnection.__await__   s'    }}((**r"   c                 "   K   |  d {   S 7 wrJ    rF   s    r!   
__aenter__zConnection.__aenter__   s     zzs   c                 @   K   | j                          d {    y 7 wrJ   )rK   )r@   exc_typeexc_valexc_tbs       r!   	__aexit__zConnection.__aexit__   s     jjls   c                 |   K   t        | | j                  | j                  j                         d{         S 7 w)z<Create an aiosqlite cursor wrapping a sqlite3 cursor object.N)r   rc   rT   r[   rF   s    r!   r[   zConnection.cursor   s.      d$--

0A0A"BBCCBs   /<:
	<c                 j   K   | j                  | j                  j                         d{    y7 w)zCommit the current transaction.N)rc   rT   commitrF   s    r!   rt   zConnection.commit   s"     mmDJJ--...   )313c                 j   K   | j                  | j                  j                         d{    y7 w)z"Roll back the current transaction.N)rc   rT   rollbackrF   s    r!   rw   zConnection.rollback   s"     mmDJJ//000ru   c                 n  K   | j                   y	 | j                  | j                  j                         d{    	 d| _         | j                         }|r| d{    yy7 *# t        $ r t
        j                  d        w xY w7 +# d| _         | j                         }|r| d{  7   w w xY ww)z9Complete queued queries/cursors and close the connection.Nz+exception occurred while closing connection)r:   rc   rT   rK   rP   r)   inforE   re   s     r!   rK   zConnection.close   s      #		--

 0 0111
  $DYY[F  2 	HHBC	   $DYY[F sU   B5(A& A$A& B5B	B5$A& & BB 	B5B2*B-+B22B5c                    K   |g }| j                  | j                  j                  ||       d{   }t        | |      S 7 w)z6Helper to create a cursor and execute the given query.N)rc   rT   rX   r   rZ   s       r!   rX   zConnection.execute   sE     
 J}}TZZ%7%7jIIdF## Js   /AAAc                 `   K   |g }| j                  | j                  ||       d{   S 7 w)z/Helper to insert and get the last_insert_rowid.N)rc   r\   r@   rU   rV   s      r!   execute_insertzConnection.execute_insert   s2     
 J]]4#7#7jIIII   %.,.c                 `   K   |g }| j                  | j                  ||       d{   S 7 w)z2Helper to execute a query and return all the data.N)rc   r_   r|   s      r!   execute_fetchallzConnection.execute_fetchall   s2     
 J]]4#9#93
KKKKr~   c                    K   | j                  | j                  j                  ||       d{   }t        | |      S 7 w)z;Helper to create a cursor and execute the given multiquery.N)rc   rT   executemanyr   rZ   s       r!   r   zConnection.executemany   s:     
 }}TZZ%;%;S*MMdF## Ns   +A >A 
sql_scriptc                    K   | j                  | j                  j                  |       d{   }t        | |      S 7 w)z4Helper to create a cursor and execute a user script.N)rc   rT   executescriptr   )r@   r   r[   s      r!   r   zConnection.executescript   s8      }}TZZ%=%=zJJdF## Ks   *?=?c                 >   K   | j                   j                         S w)zInterrupt pending queries.)rT   	interruptrF   s    r!   r   zConnection.interrupt  s     zz##%%s   name
num_paramsfuncdeterministicc                 t   K   | j                  | j                  j                  ||||       d{    y7 w)a/  
        Create user-defined function that can be later used
        within SQL statements. Must be run within the same thread
        that query executions take place so instead of executing directly
        against the connection, we defer this to `run` function.

        If ``deterministic`` is true, the created function is marked as deterministic,
        which allows SQLite to perform additional optimizations. This flag is supported
        by SQLite 3.8.3 or higher, ``NotSupportedError`` will be raised if used with
        older versions.
        )r   N)rc   rT   create_function)r@   r   r   r   r   s        r!   r   zConnection.create_function  s<      mmJJ&&'  
 	
 	
s   .868c                 .    | j                   j                  S rJ   )rT   in_transactionrF   s    r!   r   zConnection.in_transaction  s    zz(((r"   c                 .    | j                   j                  S rJ   rT   isolation_levelrF   s    r!   r   zConnection.isolation_level   s    zz)))r"   valuec                 &    || j                   _        y rJ   r   r@   r   s     r!   r   zConnection.isolation_level$  s    %*

"r"   c                 .    | j                   j                  S rJ   rT   row_factoryrF   s    r!   r   zConnection.row_factory(  s    zz%%%r"   factoryc                 &    || j                   _        y rJ   r   r@   r   s     r!   r   zConnection.row_factory,  s    !(

r"   c                 .    | j                   j                  S rJ   rT   text_factoryrF   s    r!   r   zConnection.text_factory0  s    zz&&&r"   c                 &    || j                   _        y rJ   r   r   s     r!   r   zConnection.text_factory4  s    ")

r"   c                 .    | j                   j                  S rJ   )rT   total_changesrF   s    r!   r   zConnection.total_changes8  s    zz'''r"   c                 l   K   | j                  | j                  j                  |       d {    y 7 wrJ   )rc   rT   enable_load_extensionr   s     r!   r   z Connection.enable_load_extension<  s$     mmDJJ<<eDDD   *424pathc                 l   K   | j                  | j                  j                  |       d {    y 7 wrJ   )rc   rT   load_extension)r@   r   s     r!   r   zConnection.load_extension?  s$     mmDJJ55t<<<r   handlernc                 n   K   | j                  | j                  j                  ||       d {    y 7 wrJ   )rc   rT   set_progress_handler)r@   r   r   s      r!   r   zConnection.set_progress_handlerB  s(      mmDJJ;;WaHHHs   +535c                 l   K   | j                  | j                  j                  |       d {    y 7 wrJ   )rc   rT   set_trace_callback)r@   r   s     r!   r   zConnection.set_trace_callbackG  s$     mmDJJ997CCCr   authorizer_callbackc                 l   K   | j                  | j                  j                  |       d{    y7 w)aG  
        Set an authorizer callback to control database access.

        The authorizer callback is invoked for each SQL statement that is prepared,
        and controls whether specific operations are permitted.

        Example::

            import sqlite3

            def restrict_drops(action_code, arg1, arg2, db_name, trigger_name):
                # Deny all DROP operations
                if action_code == sqlite3.SQLITE_DROP_TABLE:
                    return sqlite3.SQLITE_DENY
                # Allow everything else
                return sqlite3.SQLITE_OK

            await conn.set_authorizer(restrict_drops)

        See ``sqlite3`` documentation for details:
        https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.set_authorizer

        :param authorizer_callback: An optional callable that receives five arguments:

            - ``action_code`` (int): The action to be authorized (e.g., ``SQLITE_READ``)
            - ``arg1`` (str): First argument, meaning depends on ``action_code``
            - ``arg2`` (str): Second argument, meaning depends on ``action_code``
            - ``db_name`` (str): Database name (e.g., ``"main"``, ``"temp"``)
            - ``trigger_name`` (str): Name of trigger or view that is doing the access,
              or ``None``

            The callback should return:

            - ``SQLITE_OK`` (0): Allow the operation
            - ``SQLITE_DENY`` (1): Deny the operation, raise ``sqlite3.DatabaseError``
            - ``SQLITE_IGNORE`` (2): Treat operation as no-op

            Pass ``None`` to remove the authorizer.
        N)rc   rT   set_authorizer)r@   r   s     r!   r   zConnection.set_authorizerJ  s(     T mmDJJ557JKKKr   c                r   K   t                fd} j                  |      }t        j                  |      }	 	 j	                         }|n| | d{    y# t
        $ rH |j                         rt        j                  d       Y ;t        j                  d       d{  7   Y \w xY w7 Yw)z
        Return an async iterator to dump the database in SQL text format.

        Example::

            async for line in db.iterdump():
                ...

        c                      	 j                   j                         D ]  } j                  |         j                  d        y # t        $ r( t        j                  d       j                  d         w xY w)Nzexception while dumping db)rT   iterdumprQ   rP   r)   	exception)line
dump_queuer@   s    r!   dumperz#Connection.iterdump.<locals>.dumper  sm     JJ//1 0D))$/0%%d+ :;%%d+s   AA 1A6Nziterdump completed unexpectedlyg{Gz?)
r	   rc   rM   ensure_future
get_nowaitr   r   r)   warningsleep)r@   r   r   taskr   r   s   `    @r!   r   zConnection.iterdumpv  s      "G
		 mmF#$$S)*&0&;&;&=<
  

  *99;KK ABmmD)))* 	sX   8B7A! B7A! B7B5B7!.B2B7B2)B,*B2/B71B22B7r   maing      ?pagesprogressr   r   r7   r   r   r   c                   K   t        |t              r|j                  }| j                  | j                  j                  |||||       d{    y7 w)z
        Make a backup of the current database to the target database.

        Takes either a standard sqlite3 or aiosqlite Connection object as the target.
        r   N)
isinstancer   rT   rc   backup)r@   r7   r   r   r   r   s         r!   r   zConnection.backup  sR      fj)\\FmmJJ  
 	
 	
s   AAAArJ   )r   r   )r   N)F)>__name__
__module____qualname__r   sqlite3r   intr   rM   AbstractEventLooprA   rG   FuturerE   propertyrT   strr   Rowr\   r   r_   rc   rf   r   ri   rl   rq   r   r   r[   rt   rw   rK   rX   r}   r   r   r   r   boolr   r   r   setterIsolationLeveltyper   bytesr   r   r   r   r   r   AuthorizerCallbackr   r   r   r   floatr   rk   r"   r!   r   r   N   s   
 59	B 2 223  w001	
 
&$hw~~. $  w))    !3 !C !HW[[<Q !
!S !c !hw{{>S !
+9S$%<= + Df D D/1" >B$$$,Xc]$;$	$ $ >BJJ$,Xc]$;J	'++	J J >BLL$,Xc]$;L	'++	L L $$$,Xc]$;$	$ $ $c $f $ $
&
 QV

%(
08
IM
	
, ) ) ) *# * * +^ + + + &Xd^ & & )8D> )d ) ) 'hw|4 ' ' *HeWc\$: *t * * (s ( (E E$ E= =IHSM 12I7:I	I
D DT D*L#+,>#?*L	*LX(c 2 (\ >B
lG$6$667
 	

 8S#sOT$9:;
 
 
 

r"   r   @   )r4   r5   databaser5   rb   c                p     |t        dt               dt        j                  f fd}t        ||      S )z<Create and return a connection proxy to the sqlite database.z7aiosqlite.connect() no longer uses the `loop` parameterr   c                      t        t              r} n-t        t              rj                  d      } nt              } t	        j
                  | fi S )Nzutf-8)r   r   r   decoder   r   )locr   rb   s    r!   r3   zconnect.<locals>.connector  sG    h$C%(//'*Ch-Cs-f--r"   )r   r?   r   r   )r   r4   r5   rb   r3   s   `  ` r!   r   r     s:     E	

.w)) . i11r"   )1__doc__rM   loggingr   collections.abcr   r   r   	functoolsr   pathlibr   queuer   r	   r
   	threadingr   typingr   r   r   r   r   warningsr   contextr   r[   r   __all__r   r   r   	getLoggerr)   r   r   r    r.   r%   objectr-   tuple_TxQueuer1   r   r   r   rk   r"   r!   <module>r      sK      > >   + +  : :  # 
-sCc37<= g$ '"FGHGNN C D w~~ - D    uXgnn5xC7HHIJQ( Q<j
 j
` 04	2CI2 7,,
-	2
 2 2r"   