
    >|h"-                         d 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
 dZdZ G d d	e      Z G d
 de      Z G d de      ZeZeZ G d d      Z G d d      Zy)aA  PooledPg - pooling for classic PyGreSQL connections.

Implements a pool of steady, thread-safe cached connections
to a PostgreSQL database which are transparently reused,
using the classic (not DB-API 2 compliant) PyGreSQL API.

This should result in a speedup for persistent applications such as the
application server of "Webware for Python," without loss of robustness.

Robustness is provided by using "hardened" SteadyPg connections.
Even if the underlying database is restarted and all connections
are lost, they will be automatically and transparently reopened.
However, since you don't want this to happen in the middle of a database
transaction, you must explicitly start transactions with the begin()
method so that SteadyPg knows that the underlying connection shall not
be replaced and errors passed on until the transaction is completed.

Measures are taken to make the pool of connections thread-safe
regardless of the fact that the classic PyGreSQL pg module itself
is not thread-safe at the connection level.

For more information on PostgreSQL, see:
    https://www.postgresql.org/
For more information on PyGreSQL, see:
    http://www.pygresql.org
For more information on Webware for Python, see:
    https://webwareforpython.github.io/w4py/


Usage:

First you need to set up the database connection pool by creating
an instance of PooledPg, passing the following parameters:

    mincached: the initial number of connections in the pool
        (the default of 0 means no connections are made at startup)
    maxcached: the maximum number of connections in the pool
        (the default value of 0 or None means unlimited pool size)
    maxconnections: maximum number of connections generally allowed
        (the default value of 0 or None means any number of connections)
    blocking: determines behavior when exceeding the maximum
        (if this is set to true, block and wait until the number of
        connections decreases, but by default an error will be reported)
    maxusage: maximum number of reuses of a single connection
        (the default of 0 or None means unlimited reuse)
        When this maximum usage number of the connection is reached,
        the connection is automatically reset (closed and reopened).
    setsession: an optional list of SQL commands that may serve to
        prepare the session, e.g. ["set datestyle to german", ...]

    Additionally, you have to pass the parameters for the actual
    PostgreSQL connection which are passed via PyGreSQL,
    such as the names of the host, database, user, password etc.

For instance, if you want a pool of at least five connections
to your local database 'mydb':

    from dbutils.pooled_pg import PooledPg
    pool = PooledPg(5, dbname='mydb')

Once you have set up the connection pool you can request
database connections from that pool:

    db = pool.connection()

You can use these connections just as if they were ordinary
classic PyGreSQL API connections.  Actually what you get is a
proxy class for the hardened SteadyPg version of the connection.

The connection will not be shared with other threads.  If you don't need
it anymore, you should immediately return it to the pool with db.close().
You can get another connection in the same way or with db.reopen().

Warning: In a threaded environment, never do the following:

    res = pool.connection().query(...).getresult()

This would release the connection too early for reuse which may be
fatal because the connections are not thread-safe.  Make sure that the
connection object stays alive as long as you are using it, like that:

    db = pool.connection()
    res = db.query(...).getresult()
    db.close()  # or del db

You can also a context manager for simpler code:

    with pool.connection() as db:
        res = db.query(...).getresult()

Note that you need to explicitly start transactions by calling the
begin() method.  This ensures that the transparent reopening will be
suspended until the end of the transaction, and that the connection will
be rolled back before being given back to the connection pool.  To end
transactions, use one of the end(), commit() or rollback() methods.


Ideas for improvement:

* Add a thread for monitoring, restarting (or closing) bad or expired
  connections (similar to DBConnectionPool/ResourcePool by Warren Smith).
* Optionally log usage, bad connections and exceeding of limits.


Copyright, credits and license:

* Contributed as supplement for Webware for Python and PyGreSQL
  by Christoph Zwerschke in September 2005
* Based on the code of DBPool, contributed to Webware for Python
  by Dan Green in December 2000

Licensed under the MIT license.
    )suppress)EmptyFullQueue   )__version__)SteadyPgConnection   c                       e Zd ZdZy)PooledPgErrorzGeneral PooledPg error.N__name__
__module____qualname____doc__     P/var/www/html/test/engine/venv/lib/python3.12/site-packages/dbutils/pooled_pg.pyr   r   ~   s    !r   r   c                       e Zd ZdZy)InvalidConnectionErrorzDatabase connection is invalid.Nr   r   r   r   r   r      s    )r   r   c                       e Zd ZdZy)TooManyConnectionsErrorz*Too many database connections were opened.Nr   r   r   r   r   r      s    4r   r   c                   @    e Zd ZdZeZ	 	 	 d	dZd Zd Zd Z	d Z
d Zy)
PooledPgzPool for classic PyGreSQL connections.

    After you have created the connection pool, you can use
    connection() to get pooled, steady PostgreSQL connections.
    Nc                    ||	c| _         | _        || _        || _        |xs d| _        |d}|d}|d}|r||k  r|}|r"||k  r|}ddlm}
  |
|      | _        || _        nd| _        t        |      | _
        t        |      D cg c]  }| j                          }}|r"|j                         j                          |r!yyc c}w )ac  Set up the PostgreSQL connection pool.

        mincached: initial number of connections in the pool
            (0 means no connections are made at startup)
        maxcached: maximum number of connections in the pool
            (0 or None means unlimited pool size)
        maxconnections: maximum number of connections generally allowed
            (0 or None means an arbitrary number of connections)
        blocking: determines behavior when exceeding the maximum
            (if this is set to true, block and wait until the number of
            connections decreases, otherwise an error will be reported)
        maxusage: maximum number of reuses of a single connection
            (0 or None means unlimited reuse)
            When this maximum usage number of the connection is reached,
            the connection is automatically reset (closed and reopened).
        setsession: optional list of SQL commands that may serve to prepare
            the session, e.g. ["set datestyle to ...", "set time zone ..."]
        reset: how connections should be reset when returned to the pool
            (0 or None to rollback transactions started with begin(),
            1 to always issue a rollback, 2 for a complete reset)
        args, kwargs: the parameters that shall be used to establish
            the PostgreSQL connections using class PyGreSQL pg.DB()
        r   N)	Semaphore)_args_kwargs	_maxusage_setsession_reset	threadingr   _connections	_blockingr   _cacherange
connectionpopclose)self	mincached	maxcachedmaxconnectionsblockingmaxusage
setsessionresetargskwargsr   iidles                r   __init__zPooledPg.__init__   s    8 $( 
DL!%jqII!NY.!I	)!*+ ). 9D%DN $DI&+0+;<a!<<HHJ  =s   Cc                 t    t        | j                  | j                  dg| j                  i | j                  S )z-Get a steady, unpooled PostgreSQL connection.T)r	   r   r    r   r   r*   s    r   steady_connectionzPooledPg.steady_connection   s7    !$..$2B2BD ?#'::?15? 	?r   c                     | j                   r+| j                   j                  | j                        st        	 | j                  j                         }t        | |      S # t        $ r | j                         }Y 'w xY w)z9Get a steady, cached PostgreSQL connection from the pool.)	r#   acquirer$   r   r%   
get_nowaitr   r9   PooledPgConnectionr*   cons     r   r'   zPooledPg.connection   sm    T%6%6%>%>t~~%N))	+++((*C "$,,  	+((*C	+s   A A;:A;c                    	 | j                   t        k(  r|j                          nG| j                   t        k(  s|j                  r(t        t              5  |j                          ddd       | j                  j                  |       | j                  r| j                  j                          yy# 1 sw Y   LxY w# t        $ r |j                          Y Ow xY w)z*Put a connection back into the pool cache.N)r!   RESET_COMPLETELYr1   RESET_ALWAYS_ROLLBACK_transactionr   	Exceptionrollbackr%   
put_nowaitr   r)   r#   releaser>   s     r   cachezPooledPg.cache   s    	{{..		 559I9Ii( #LLN#KK""3' %%' # #  	IIK	s*   AB< B0%#B< 0B95B< <CCc                    	 	 | j                   j                         }t        t              5  |j	                          ddd       | j
                  r| j
                  j                          j# 1 sw Y   0xY w# t        $ r Y yw xY w)z"Close all connections in the pool.N)r%   r<   r   rD   r)   r#   rG   r   r>   s     r   r)   zPooledPg.close   su    kk,,.i(  IIK $$%%--/      s'   )A8 A,.A8 ,A51A8 8	BBc                 4    	 | j                          y#  Y yxY w)zDelete the pool.Nr)   r8   s    r   __del__zPooledPg.__del__       	JJL	    )r   r   r   FNNN)r   r   r   r   r   versionr6   r9   r'   rH   r)   rL   r   r   r   r   r      s8     G *+',265n?
-(
r   r   c                   :    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
y	)
r=   z.Proxy class for pooled PostgreSQL connections.c                      || _         || _        y)zCreate a pooled DB-API 2 connection.

        pool: the corresponding PooledPg instance
        con: the underlying SteadyPg connection
        N)_pool_con)r*   poolr?   s      r   r6   zPooledPgConnection.__init__  s     
	r   c                 v    | j                   r-| j                  j                  | j                          d| _         yy)zClose the pooled connection.N)rS   rR   rH   r8   s    r   r)   zPooledPgConnection.close  s-     99JJTYY'DI r   c                     | j                   r| j                   j                          y| j                  j                         | _         y)zReopen the pooled connection.N)rS   reopenrR   r'   r8   s    r   rW   zPooledPgConnection.reopen  s/    
 99II

--/DIr   c                 R    | j                   rt        | j                   |      S t        )zProxy all members of the class.)rS   getattrr   )r*   names     r   __getattr__zPooledPgConnection.__getattr__!  s     99499d++$$r   c                 4    	 | j                          y#  Y yxY w)zDelete the pooled connection.NrK   r8   s    r   rL   zPooledPgConnection.__del__'  rM   rN   c                     | S )z+Enter a runtime context for the connection.r   r8   s    r   	__enter__zPooledPgConnection.__enter__/  s    r   c                 $    | j                          y)z*Exit a runtime context for the connection.NrK   )r*   excs     r   __exit__zPooledPgConnection.__exit__3  s    

r   N)r   r   r   r   r6   r)   rW   r[   rL   r^   ra   r   r   r   r=   r=     s(    80%r   r=   N)r   
contextlibr   queuer   r   r    r   	steady_pgr	   rB   rA   rD   r   r   r   InvalidConnectionTooManyConnectionsr   r=   r   r   r   <module>rh      st   pd   $ $  )   "I "*] *5m 5
 + , o oh2 2r   