3
,sYB                 @   st   d Z ddlZddlmZ ddlmZmZmZ G dd deZ	G dd de
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>}.
    N)threads)reflectlogcompatc               @   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 | _| j  d S )N)_pool_connection	reconnect)selfpoolr   r   r   __init__!   s    zConnection.__init__c             C   s   d S )Nr   )r   r   r   r   close'   s    zConnection.closec          	   C   s   | j js| jj  d S y8| jj  | jj }|j| j j |j  | jj  d S    t	j
d d Y nX | j j| j | j jrt	jd t d S )NzRollback failedzConnection lost.)r   r   r   rollbackcursorexecutegood_sqlr   commitr   err
disconnectnoisymsgr   )r   Zcursr   r   r   r   2   s     




zConnection.rollbackc             C   s(   | j d k	r| jj| j  | jj | _ d S )N)r   r   r   connect)r   r   r   r   r   I   s    
zConnection.reconnectc             C   s   t | j|S )N)getattrr   )r   namer   r   r   __getattr__O   s    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   || _ || _| j  d S )N)r   r   reopen)r   r   Z
connectionr   r   r   r   _   s    zTransaction.__init__c             C   s   | j }d | _ |j  d S )N)_cursorr   )r   r$   r   r   r   r   e   s    zTransaction.closec          	   C   sr   | j d k	r| j  y| jj | _ d S    | jjs6 ntjd d Y nX | jjrZtj	d | j  | j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#   k   s    

zTransaction.reopenc             C   s   | j j  d | _d S )N)r   r   r$   )r   r   r   r   r      s    
zTransaction.reconnectc             C   s   t | j|S )N)r   r$   )r   r    r   r   r   r!      s    zTransaction.__getattr__)
r   r   r	   r
   r$   r   r   r#   r   r!   r   r   r   r   r"   T   s   r"   c               @   s   e Zd ZdZdj 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j|| _t| jdddkr.tjd t| jdddk rJtjd |jd	d}|dkrjdd
lm	} || _
|| _|| _x6| jD ],}d|f }||krt| |||  ||= qW t| j| j| _t| j| j| _i | _ddlm} ddlm} |j| _|j| 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'})

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

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

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

        @param 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.

        @param 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.

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

        @param cp_reactor: use this reactor instead of the global reactor
            (added in Twisted 10.2).
        @type cp_reactor: L{IReactorCore} provider
        ZapilevelNz2.0z'DB API module not DB API 2.0 compliant.Zthreadsafetyr      z+DB API module not sufficiently thread-safe.Z
cp_reactor)reactorzcp_%s)
threadpool)
threadable)	dbapiNamer   ZnamedModuledbapir   r   r   poptwisted.internetr)   _reactorconnargsconnkwCP_ARGSsetattrminmaxconnectionstwisted.pythonr*   r+   ZgetThreadIDthreadIDZ
ThreadPoolZcallWhenRunning_startstartID)	r   r,   r1   r2   r)   argZcpArgr*   r+   r   r   r   r      s2    #



zConnectionPool.__init__c             C   s   d | _ | j S )N)r;   start)r   r   r   r   r:      s    zConnectionPool._startc             C   s.   | j s*| jj  | jjdd| j| _d| _ dS )z
        Start the connection pool.

        If you are using the reactor normally, this function does *not*
        need to be called.
        ZduringZshutdownTN)runningr*   r=   r0   ZaddSystemEventTrigger
finalClose
shutdownID)r   r   r   r   r=      s
    
zConnectionPool.startc             O   s(   ddl m} tj|| j| j|f||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   )r)   )r/   r)   r   deferToThreadPoolr*   _runWithConnection)r   funcargskwr)   r   r   r   runWithConnection  s    
z ConnectionPool.runWithConnectionc       	      O   sx   | j | }y||f||}|j  |S    tj \}}}y|j  W n   tjd d Y nX tj|| Y nX d S )NzRollback failed)	connectionFactoryr   sysexc_infor   r   r   r   reraise)	r   rC   rD   rE   connresultexcTypeexcValueexcTracebackr   r   r   rB   '  s    
z!ConnectionPool._runWithConnectionc             O   s(   ddl m} tj|| j| j|f||S )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   )r)   )r/   r)   r   rA   r*   _runInteraction)r   interactionrD   rE   r)   r   r   r   runInteraction6  s    
zConnectionPool.runInteractionc             O   s   | j | jf||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}.
        )rR   	_runQuery)r   rD   rE   r   r   r   runQueryX  s    zConnectionPool.runQueryc             O   s   | j | jf||S )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}.
        )rR   _runOperation)r   rD   rE   r   r   r   runOperationm  s    zConnectionPool.runOperationc             C   s@   | j r| jj| j  d| _ | jr4| jj| j d| _| j  dS )zC
        Close all pool connections and shutdown the pool.
        N)r@   r0   ZremoveSystemEventTriggerr;   r?   )r   r   r   r   r     s    zConnectionPool.closec             C   sB   d| _ | jj  d| _x| jj D ]}| j| q"W | jj  dS )zE
        This should only be called by the shutdown trigger.
        NF)r@   r*   stopr>   r7   values_closeclear)r   rK   r   r   r   r?     s    
zConnectionPool.finalClosec             C   sx   | j  }| jj|}|dkrt| jrDtjd| j| jp4d| jp<df  | j	j
| j| j}| jdkrj| j| || 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: %s %s%s )r9   r7   getr   r   r   r,   r1   r2   r-   r   openfun)r   tidrK   r   r   r   r     s    



zConnectionPool.connectc             C   s>   | j  }|| jj|k	r td|dk	r:| j| | j|= 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)r9   r7   r\   	ExceptionrY   )r   rK   r^   r   r   r   r     s    
zConnectionPool.disconnectc          	   C   sB   | j rtjd| jf  y|j  W n   tjd d Y nX d S )Nzadbapi closing: %szConnection close failed)r   r   r   r,   r   r   )r   rK   r   r   r   rY     s    zConnectionPool._closec       
      O   s   | j | }| j| |}y$||f||}|j  |j  |S    tj \}}}	y|j  W n   tjd d Y nX t	j
||	 Y nX d S )NzRollback failed)rG   transactionFactoryr   r   rH   rI   r   r   r   r   rJ   )
r   rQ   rD   rE   rK   transrL   rM   rN   rO   r   r   r   rP     s    
zConnectionPool._runInteractionc             O   s   |j || |j S )N)r   Zfetchall)r   ra   rD   rE   r   r   r   rS     s    zConnectionPool._runQueryc             O   s   |j || d S )N)r   )r   ra   rD   rE   r   r   r   rU     s    zConnectionPool._runOperationc          	   C   s&   | j | j| j| j| j| j| j| jdS )N)r,   r5   r6   r   r   r   r1   r2   )r,   r5   r6   r   r   r   r1   r2   )r   r   r   r   __getstate__  s    zConnectionPool.__getstate__c             C   s"   || _ | j| jf| j| j d S )N)__dict__r   r,   r1   r2   )r   stater   r   r   __setstate__  s    zConnectionPool.__setstate__)%r   r   r	   r
   splitr3   r   r5   r6   r    r]   r   r   r>   r   rG   r"   r`   r@   r   r:   r=   rF   rB   rR   rT   rV   r   r?   r   r   rY   rP   rS   rU   rb   re   r   r   r   r   r%      s>   I"	r%   )r
   rH   r/   r   r8   r   r   r   r_   r   objectr   r"   r%   __all__r   r   r   r   <module>   s   <5  s