Merge from trunk
[plcapi.git] / trunk / psycopg2 / ZPsycopgDA / pool.py
1 # ZPsycopgDA/pool.py - ZPsycopgDA Zope product: connection pooling
2 #
3 # Copyright (C) 2004 Federico Di Gregorio <fog@initd.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2, or (at your option) any later
8 # version.
9 #
10 # Or, at your option this program (ZPsycopgDA) can be distributed under the
11 # Zope Public License (ZPL) Version 1.0, as published on the Zope web site,
12 # http://www.zope.org/Resources/ZPL.
13 #
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
16 # or FITNESS FOR A PARTICULAR PURPOSE.
17 #
18 # See the LICENSE file for details.
19
20 # all the connections are held in a pool of pools, directly accessible by the
21 # ZPsycopgDA code in db.py
22
23 import threading
24 import psycopg2.pool
25
26 _connections_pool = {}
27 _connections_lock = threading.Lock()
28
29 def getpool(dsn, create=True):
30     _connections_lock.acquire()
31     try:
32         if not _connections_pool.has_key(dsn) and create:
33             _connections_pool[dsn] = \
34                 psycopg2.pool.PersistentConnectionPool(4, 200, dsn)
35     finally:
36         _connections_lock.release()
37     return _connections_pool[dsn]
38
39 def flushpool(dsn):
40     _connections_lock.acquire()
41     try:
42         _connections_pool[dsn].closeall()
43         del _connections_pool[dsn]
44     finally:
45         _connections_lock.release()
46         
47 def getconn(dsn, create=True):
48     return getpool(dsn, create=create).getconn()
49
50 def putconn(dsn, conn, close=False):
51     getpool(dsn).putconn(conn, close=close)