o
    bA                     @   sf   d Z ddlmZ ddlmZmZ G dd deZG dd dZG dd	 d	Z	G d
d dZ
d	dgZdS )zg
An asynchronous mapping to U{DB-API
2.0<http://www.python.org/topics/database/DatabaseAPI-2.0.html>}.
    )threads)logreflectc                   @   s   e Zd ZdZdS )ConnectionLostzb
    This exception means that a db connection has been lost.  Client code may
    try again.
    N)__name__
__module____qualname____doc__ r
   r
   ;/usr/lib/python3/dist-packages/twisted/enterprise/adbapi.pyr      s    r   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )
Connectiona  
    A wrapper for a DB-API connection instance.

    The wrapper passes almost everything to the wrapped connection and so has
    the same API. However, the L{Connection} knows about its pool and also
    handle reconnecting should when the real connection dies.
    c                 C   s   || _ d | _|   d S N)_pool_connection	reconnect)selfpoolr
   r
   r   __init__      zConnection.__init__c                 C   s   d S r   r
   r   r
   r
   r   close$   s   zConnection.closec                 C   s   | j js| j  d S z| j  | j }|| j j |  | j  W d S  t	y7   t
d d Y nw | j | j | j jrHt
d t )NRollback failedzConnection lost.)r   r   r   rollbackcursorexecutegood_sqlr   commitBaseExceptionr   err
disconnectnoisymsgr   )r   cursr
   r
   r   r   .   s"   




zConnection.rollbackc                 C   s(   | j d ur| j| j  | j | _ d S r   )r   r   r   connectr   r
   r
   r   r   D   s   
zConnection.reconnectc                 C      t | j|S r   )getattrr   r   namer
   r
   r   __getattr__I      zConnection.__getattr__N)	r   r   r   r	   r   r   r   r   r(   r
   r
   r
   r   r      s    
r   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S )Transactiona  
    A lightweight wrapper for a DB-API 'cursor' object.

    Relays attribute access to the DB cursor. That is, you can call
    C{execute()}, C{fetchall()}, etc., and they will be called on the
    underlying DB-API cursor object. Attributes will also be retrieved from
    there.
    Nc                 C   s   || _ || _|   d S r   )r   r   reopen)r   r   
connectionr
   r
   r   r   Y   r   zTransaction.__init__c                 C   s   | j }d | _ |  d S r   )_cursorr   )r   r-   r
   r
   r   r   ^   r   zTransaction.closec                 C   sx   | j d ur	|   z	| j | _ W d S  ty&   | jjs td d Y nw | jj	r0t
d |   | j | _ d S )NzCursor creation failedzConnection lost, reconnecting)r-   r   r   r   r   r   r   r   r   r    r!   r   r
   r
   r   r+   c   s   

zTransaction.reopenc                 C   s   | j   d | _d S r   )r   r   r-   r   r
   r
   r   r   v   s   

zTransaction.reconnectc                 C   r$   r   )r%   r-   r&   r
   r
   r   r(   z   r)   zTransaction.__getattr__)
r   r   r   r	   r-   r   r   r+   r   r(   r
   r
   r
   r   r*   M   s    	r*   c                   @   s   e Zd ZdZd ZdZdZdZdZ	dZ
dZdZdZeZeZdZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Z d$d% Z!d&d' Z"d(d) Z#d*d+ Z$dS ),ConnectionPoola  
    Represent a pool of connections to a DB-API 2.0 compliant database.

    @ivar connectionFactory: factory for connections, default to L{Connection}.
    @type connectionFactory: any callable.

    @ivar transactionFactory: factory for transactions, default to
        L{Transaction}.
    @type transactionFactory: any callable

    @ivar shutdownID: L{None} or a handle on the shutdown event trigger which
        will be used to stop the connection pool workers when the reactor
        stops.

    @ivar _reactor: The reactor which will be used to schedule startup and
        shutdown events.
    @type _reactor: L{IReactorCore} provider
    z-min max name noisy openfun reconnect good_sqlF      Nzselect 1c           	      O   s  || _ t|| _t| jdddkrtd t| jdddk r%td |d	d}|du r5dd
lm	} || _
|| _|| _| jD ]}d| }||v rWt| |||  ||= qAt| j| j| _t| j| j| _i | _ddlm}m} |j| _|| j| j| _| j
| j| _dS )a  
        Create a new L{ConnectionPool}.

        Any positional or keyword arguments other than those documented here
        are passed to the DB-API object when connecting. Use these arguments to
        pass database names, usernames, passwords, etc.

        @param dbapiName: an import string to use to obtain a DB-API compatible
            module (e.g. C{'pyPgSQL.PgSQL'})

        @keyword cp_min: the minimum number of connections in pool (default 3)

        @keyword cp_max: the maximum number of connections in pool (default 5)

        @keyword cp_noisy: generate informational log messages during operation
            (default C{False})

        @keyword cp_openfun: a callback invoked after every C{connect()} on the
            underlying DB-API object. The callback is passed a new DB-API
            connection object. This callback can setup per-connection state
            such as charset, timezone, etc.

        @keyword cp_reconnect: detect connections which have failed and reconnect
            (default C{False}). Failed connections may result in
            L{ConnectionLost} exceptions, which indicate the query may need to
            be re-sent.

        @keyword cp_good_sql: an sql query which should always succeed and change
            no state (default C{'select 1'})

        @keyword cp_reactor: use this reactor instead of the global reactor
            (added in Twisted 10.2).
        @type cp_reactor: L{IReactorCore} provider
        apilevelNz2.0z'DB API module not DB API 2.0 compliant.threadsafetyr      z+DB API module not sufficiently thread-safe.
cp_reactor)reactorcp_)
threadable
threadpool)	dbapiNamer   namedModuledbapir%   r   r!   poptwisted.internetr5   _reactorconnargsconnkwCP_ARGSsetattrminmaxconnectionstwisted.pythonr7   r8   getThreadIDthreadID
ThreadPoolcallWhenRunning_startstartID)	r   r9   r?   r@   r5   argcpArgr7   r8   r
   r
   r   r      s2   #



zConnectionPool.__init__c                 C   s   d | _ |  S r   )rL   startr   r
   r
   r   rK      s   zConnectionPool._startc                 C   s2   | j s| j  | jdd| j| _d| _ dS dS )z
        Start the connection pool.

        If you are using the reactor normally, this function does *not*
        need to be called.
        duringshutdownTN)runningr8   rO   r>   addSystemEventTrigger
finalClose
shutdownIDr   r
   r
   r   rO      s   

zConnectionPool.startc                 O   $   t j| j| j| j|g|R i |S )a  
        Execute a function with a database connection and return the result.

        @param func: A callable object of one argument which will be executed
            in a thread with a connection from the pool. It will be passed as
            its first argument a L{Connection} instance (whose interface is
            mostly identical to that of a connection object for your DB-API
            module of choice), and its results will be returned as a
            L{Deferred}. If the method raises an exception the transaction will
            be rolled back. Otherwise, the transaction will be committed.
            B{Note} that this function is B{not} run in the main thread: it
            must be threadsafe.

        @param args: positional arguments to be passed to func

        @param kw: keyword arguments to be passed to func

        @return: a L{Deferred} which will fire the return value of
            C{func(Transaction(...), *args, **kw)}, or a
            L{twisted.python.failure.Failure}.
        )r   deferToThreadPoolr>   r8   _runWithConnection)r   funcargskwr
   r
   r   runWithConnection   s   z ConnectionPool.runWithConnectionc                 O   sj   |  | }z||g|R i |}|  |W S  ty4   z|  W   ty3   td d Y  w w Nr   )connectionFactoryr   r   r   r   r   )r   rY   rZ   r[   connresultr
   r
   r   rX     s   

z!ConnectionPool._runWithConnectionc                 O   rV   )a  
        Interact with the database and return the result.

        The 'interaction' is a callable object which will be executed in a
        thread using a pooled connection. It will be passed an L{Transaction}
        object as an argument (whose interface is identical to that of the
        database cursor for your DB-API module of choice), and its results will
        be returned as a L{Deferred}. If running the method raises an
        exception, the transaction will be rolled back. If the method returns a
        value, the transaction will be committed.

        NOTE that the function you pass is *not* run in the main thread: you
        may have to worry about thread-safety in the function you pass to this
        if it tries to use non-local objects.

        @param interaction: a callable object whose first argument is an
            L{adbapi.Transaction}.

        @param args: additional positional arguments to be passed to
            interaction

        @param kw: keyword arguments to be passed to interaction

        @return: a Deferred which will fire the return value of
            C{interaction(Transaction(...), *args, **kw)}, or a
            L{twisted.python.failure.Failure}.
        )r   rW   r>   r8   _runInteraction)r   interactionrZ   r[   r
   r
   r   runInteraction$  s   zConnectionPool.runInteractionc                 O      | j | jg|R i |S )aY  
        Execute an SQL query and return the result.

        A DB-API cursor which will be invoked with C{cursor.execute(*args,
        **kw)}. The exact nature of the arguments will depend on the specific
        flavor of DB-API being used, but the first argument in C{*args} be an
        SQL statement. The result of a subsequent C{cursor.fetchall()} will be
        fired to the L{Deferred} which is returned. If either the 'execute' or
        'fetchall' methods raise an exception, the transaction will be rolled
        back and a L{twisted.python.failure.Failure} returned.

        The C{*args} and C{**kw} arguments will be passed to the DB-API
        cursor's 'execute' method.

        @return: a L{Deferred} which will fire the return value of a DB-API
            cursor's 'fetchall' method, or a L{twisted.python.failure.Failure}.
        )rc   	_runQueryr   rZ   r[   r
   r
   r   runQueryI  s   zConnectionPool.runQueryc                 O   rd   )aK  
        Execute an SQL query and return L{None}.

        A DB-API cursor which will be invoked with C{cursor.execute(*args,
        **kw)}. The exact nature of the arguments will depend on the specific
        flavor of DB-API being used, but the first argument in C{*args} will be
        an SQL statement. This method will not attempt to fetch any results
        from the query and is thus suitable for C{INSERT}, C{DELETE}, and other
        SQL statements which do not return values. If the 'execute' method
        raises an exception, the transaction will be rolled back and a
        L{Failure} returned.

        The C{*args} and C{*kw} arguments will be passed to the DB-API cursor's
        'execute' method.

        @return: a L{Deferred} which will fire with L{None} or a
            L{twisted.python.failure.Failure}.
        )rc   _runOperationrf   r
   r
   r   runOperation]  s   zConnectionPool.runOperationc                 C   s@   | j r| j| j  d| _ | jr| j| j d| _|   dS )zC
        Close all pool connections and shutdown the pool.
        N)rU   r>   removeSystemEventTriggerrL   rT   r   r
   r
   r   r   r  s   zConnectionPool.closec                 C   s>   d| _ | j  d| _| j D ]}| | q| j  dS )zE
        This should only be called by the shutdown trigger.
        NF)rU   r8   stoprR   rE   values_closeclearr   r_   r
   r
   r   rT   ~  s   
zConnectionPool.finalClosec                 C   sl   |   }| j|}|du r4| jrtd| j  | jj| j	i | j
}| jdur/| | || j|< |S )a  
        Return a database connection when one becomes available.

        This method blocks and should be run in a thread from the internal
        threadpool. Don't call this method directly from non-threaded code.
        Using this method outside the external threadpool may exceed the
        maximum number of connections in the pool.

        @return: a database connection from the pool.
        Nzadbapi connecting: )rH   rE   getr    r   r!   r9   r;   r#   r?   r@   openfun)r   tidr_   r
   r
   r   r#     s   


zConnectionPool.connectc                 C   sB   |   }|| j|urtd|dur| | | j|= dS dS )a  
        Disconnect a database connection associated with this pool.

        Note: This function should only be used by the same thread which called
        L{ConnectionPool.connect}. As with C{connect}, this function is not
        used in normal non-threaded Twisted code.
        zwrong connection for threadN)rH   rE   rp   	Exceptionrm   )r   r_   rr   r
   r
   r   r     s   
zConnectionPool.disconnectc                 C   sH   | j rtd| j  z|  W d S  ty#   td d Y d S w )Nzadbapi closing: zConnection close failed)r    r   r!   r9   r   r   r   ro   r
   r
   r   rm     s   zConnectionPool._closec                 O   s~   |  | }| | |}z||g|R i |}|  |  |W S  ty>   z|  W   ty=   td d Y  w w r]   )r^   transactionFactoryr   r   r   r   r   r   )r   rb   rZ   r[   r_   transr`   r
   r
   r   ra     s    

zConnectionPool._runInteractionc                 O   s   |j |i | | S r   )r   fetchallr   ru   rZ   r[   r
   r
   r   re     s   zConnectionPool._runQueryc                 O   s   |j |i | d S r   )r   rw   r
   r
   r   rh     s   zConnectionPool._runOperationc              	   C   s&   | j | j| j| j| j| j| j| jdS )Nr9   rC   rD   r    r   r   r?   r@   rx   r   r
   r
   r   __getstate__  s   zConnectionPool.__getstate__c                 C   s(   || _ | j| jg| jR i | j d S r   )__dict__r   r9   r?   r@   )r   stater
   r
   r   __setstate__  s   "zConnectionPool.__setstate__)%r   r   r   r	   splitrA   r    rC   rD   r'   rq   r   r   rR   r   r^   r*   rt   rU   r   rK   rO   r\   rX   rc   rg   ri   r   rT   r#   r   rm   ra   re   rh   ry   r|   r
   r
   r
   r   r.   ~   s@    G%r.   N)r	   r=   r   rF   r   r   rs   r   r   r*   r.   __all__r
   r
   r
   r   <module>   s   71  b