author | Radek Brich <radek.brich@devl.cz> |
Thu, 15 Dec 2011 18:21:41 +0100 | |
changeset 24 | 5664afa530e5 |
parent 23 | dc2dbe872fc8 |
child 26 | 7f219da7ab71 |
permissions | -rw-r--r-- |
0 | 1 |
# -*- coding: utf-8 -*- |
2 |
# |
|
3 |
# PgManager - manage database connections |
|
4 |
# |
|
5 |
# Requires: Python 2.6, psycopg2 |
|
6 |
# |
|
9
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
7 |
# Part of pgtoolkit |
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
8 |
# http://hg.devl.cz/pgtoolkit |
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
9 |
# |
0 | 10 |
# Copyright (c) 2010, 2011 Radek Brich <radek.brich@devl.cz> |
11 |
# |
|
12 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
|
13 |
# of this software and associated documentation files (the "Software"), to deal |
|
14 |
# in the Software without restriction, including without limitation the rights |
|
15 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
|
16 |
# copies of the Software, and to permit persons to whom the Software is |
|
17 |
# furnished to do so, subject to the following conditions: |
|
18 |
# |
|
19 |
# The above copyright notice and this permission notice shall be included in |
|
20 |
# all copies or substantial portions of the Software. |
|
21 |
# |
|
22 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
23 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
24 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
25 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
26 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
27 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
|
28 |
# THE SOFTWARE. |
|
29 |
||
30 |
"""Postgres database connection manager |
|
31 |
||
32 |
PgManager wraps psycopg2 connect function, adding following features: |
|
33 |
||
34 |
* Manage database connection parameters - link connection parameters |
|
35 |
to an unique identifier, retrieve connection object by this identifier |
|
36 |
||
37 |
* Connection pooling - connections with same identifier are pooled and reused |
|
38 |
||
39 |
* Easy query using the with statement - retrieve cursor directly by connection |
|
40 |
identifier, don't worry about connections |
|
41 |
||
42 |
* Dict rows - cursor has additional methods like fetchall_dict(), which |
|
43 |
returns dict row instead of ordinary list-like row |
|
44 |
||
45 |
Example: |
|
46 |
||
47 |
import pgmanager |
|
48 |
||
49 |
pgm = pgmanager.get_instance() |
|
50 |
pgm.create_conn(hostaddr='127.0.0.1', dbname='postgres') |
|
51 |
||
52 |
with pgm.cursor() as curs: |
|
53 |
curs.execute('SELECT now() AS now') |
|
54 |
row = curs.fetchone_dict() |
|
55 |
print row.now |
|
56 |
||
57 |
First, we have obtained PgManager instance. This is like calling |
|
58 |
PgManager(), although in our example the instance is global. That means |
|
59 |
getting the instance in another module brings us all the defined connections |
|
60 |
etc. |
|
61 |
||
9
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
62 |
On second line we have created connection named 'default' (this name can be left out). |
0 | 63 |
The with statement obtains connection (actually connects to database when needed), |
9
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
64 |
then returns cursor for this connection. At the end of with statement, |
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
65 |
the connection is returned to the pool or closed (depending on number of connections |
2fcc8ef0b97d
Reorganize again :-) Add setup.py.
Radek Brich <radek.brich@devl.cz>
parents:
8
diff
changeset
|
66 |
in pool and on setting of keep_open parameter). |
0 | 67 |
|
68 |
The row returned by fetchone_dict() is special dict object, which can be accessed |
|
69 |
using item or attribute access, that is row['now'] or row.now. |
|
70 |
""" |
|
71 |
||
72 |
from contextlib import contextmanager |
|
73 |
import logging |
|
74 |
import threading |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
75 |
import multiprocessing |
0 | 76 |
import select |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
77 |
import socket |
0 | 78 |
|
79 |
import psycopg2 |
|
80 |
import psycopg2.extensions |
|
81 |
||
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
82 |
from psycopg2 import DatabaseError, IntegrityError, OperationalError |
0 | 83 |
|
84 |
||
20
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
85 |
log = logging.getLogger("pgmanager") |
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
86 |
|
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
87 |
|
0 | 88 |
class PgManagerError(Exception): |
89 |
||
90 |
pass |
|
91 |
||
92 |
||
93 |
class ConnectionInfo: |
|
94 |
||
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
95 |
def __init__(self, dsn, isolation_level=None, keep_alive=True, |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
96 |
init_statement=None, keep_open=1): |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
97 |
|
0 | 98 |
self.dsn = dsn |
99 |
self.isolation_level = isolation_level |
|
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
100 |
self.keep_alive = keep_alive |
0 | 101 |
self.init_statement = init_statement |
102 |
self.keep_open = keep_open |
|
103 |
||
104 |
||
105 |
class RowDict(dict): |
|
106 |
||
107 |
def __getattr__(self, key): |
|
108 |
return self[key] |
|
109 |
||
110 |
||
111 |
class Cursor(psycopg2.extensions.cursor): |
|
112 |
||
113 |
def execute(self, query, args=None): |
|
114 |
try: |
|
115 |
return super(Cursor, self).execute(query, args) |
|
116 |
finally: |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
117 |
if self.query: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
118 |
log.debug(self.query.decode('utf8')) |
0 | 119 |
|
120 |
def callproc(self, procname, args=None): |
|
121 |
try: |
|
122 |
return super(Cursor, self).callproc(procname, args) |
|
123 |
finally: |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
124 |
if self.query: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
125 |
log.debug(self.query.decode('utf8')) |
0 | 126 |
|
127 |
def row_dict(self, row, lstrip=None): |
|
128 |
adjustname = lambda a: a |
|
129 |
if lstrip: |
|
130 |
adjustname = lambda a: a.lstrip(lstrip) |
|
131 |
return RowDict(zip([adjustname(desc[0]) for desc in self.description], row)) |
|
132 |
||
133 |
def fetchone_dict(self, lstrip=None): |
|
134 |
row = super(Cursor, self).fetchone() |
|
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
135 |
if row is None: |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
136 |
return None |
0 | 137 |
return self.row_dict(row, lstrip) |
138 |
||
139 |
def fetchall_dict(self, lstrip=None): |
|
140 |
rows = super(Cursor, self).fetchall() |
|
141 |
return [self.row_dict(row, lstrip) for row in rows] |
|
142 |
||
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
143 |
def fetchone_adapted(self): |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
144 |
'''Like fetchone() but values are quoted for direct inclusion in SQL query. |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
145 |
|
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
146 |
This is useful when you need to generate SQL script from data returned |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
147 |
by the query. Use mogrify() for simple cases. |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
148 |
|
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
149 |
''' |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
150 |
row = super(Cursor, self).fetchone() |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
151 |
if row is None: |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
152 |
return None |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
153 |
return [self.mogrify('%s', [x]).decode('utf8') for x in row] |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
154 |
|
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
155 |
def fetchall_adapted(self): |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
156 |
'''Like fetchall() but values are quoted for direct inclusion in SQL query.''' |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
157 |
rows = super(Cursor, self).fetchall() |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
158 |
return [[self.mogrify('%s', [x]).decode('utf8') for x in row] for row in rows] |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
159 |
|
0 | 160 |
|
161 |
class Connection(psycopg2.extensions.connection): |
|
162 |
||
163 |
def cursor(self, name=None): |
|
164 |
if name is None: |
|
165 |
return super(Connection, self).cursor(cursor_factory=Cursor) |
|
166 |
else: |
|
167 |
return super(Connection, self).cursor(name, cursor_factory=Cursor) |
|
168 |
||
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
169 |
def keep_alive(self): |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
170 |
'''Set socket to keepalive mode. Must be called before any query.''' |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
171 |
sock = socket.fromfd(self.fileno(), socket.AF_INET, socket.SOCK_STREAM) |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
172 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) |
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
173 |
try: |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
174 |
# Maximum keep-alive probes before asuming the connection is lost |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
175 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
176 |
# Interval (in seconds) between keep-alive probes |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
177 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 2) |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
178 |
# Maximum idle time (in seconds) before start sending keep-alive probes |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
179 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10) |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
180 |
except socket.error: |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
181 |
pass |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
182 |
|
0 | 183 |
|
184 |
class PgManager: |
|
185 |
||
186 |
def __init__(self): |
|
187 |
self.conn_known = {} # available connections |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
188 |
self.conn_pool = {} # active connetions |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
189 |
self.lock = threading.Lock() # mutual exclusion for threads |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
190 |
self.pid = multiprocessing.current_process().pid # forking check |
0 | 191 |
|
192 |
def __del__(self): |
|
193 |
for conn in tuple(self.conn_known.keys()): |
|
194 |
self.destroy_conn(conn) |
|
195 |
||
23
dc2dbe872fc8
Add keep_open parameter to create_conn.
Radek Brich <brich.radek@ifortuna.cz>
parents:
20
diff
changeset
|
196 |
def create_conn(self, name='default', keep_open=1, isolation_level=None, keep_alive=True, dsn=None, **kw): |
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
197 |
'''Create named connection. |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
198 |
|
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
199 |
name -- name for connection (default is "default") |
23
dc2dbe872fc8
Add keep_open parameter to create_conn.
Radek Brich <brich.radek@ifortuna.cz>
parents:
20
diff
changeset
|
200 |
keep_open -- how many connections will be kept open in pool (more connections will still be created, |
dc2dbe872fc8
Add keep_open parameter to create_conn.
Radek Brich <brich.radek@ifortuna.cz>
parents:
20
diff
changeset
|
201 |
but they will be closed by put_conn) |
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
202 |
isolation_level -- "autocommit", "read_committed", "serializable" or None for driver default |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
203 |
keep_alive -- set socket to keepalive mode |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
204 |
dsn -- string with connection parameters (dsn means Data Source Name) |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
205 |
|
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
206 |
Alternative for dsn is keyword args (same names as in dsn). |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
207 |
|
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
208 |
''' |
0 | 209 |
if name in self.conn_known: |
2 | 210 |
raise PgManagerError('Connection name "%s" already registered.' % name) |
0 | 211 |
|
212 |
if dsn is None: |
|
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
213 |
dsn = ' '.join([x[0]+'='+str(x[1]) for x in kw.items() if x[1] is not None]) |
0 | 214 |
|
215 |
isolation_level = self._normalize_isolation_level(isolation_level) |
|
23
dc2dbe872fc8
Add keep_open parameter to create_conn.
Radek Brich <brich.radek@ifortuna.cz>
parents:
20
diff
changeset
|
216 |
ci = ConnectionInfo(dsn, isolation_level, keep_alive, keep_open=keep_open) |
0 | 217 |
|
218 |
self.conn_known[name] = ci |
|
219 |
self.conn_pool[name] = [] |
|
220 |
||
221 |
def close_conn(self, name='default'): |
|
222 |
'''Close all connections of given name. |
|
223 |
||
224 |
Connection credentials are still saved. |
|
225 |
||
226 |
''' |
|
227 |
while len(self.conn_pool[name]): |
|
228 |
conn = self.conn_pool[name].pop() |
|
229 |
conn.close() |
|
230 |
||
231 |
def destroy_conn(self, name='default'): |
|
232 |
'''Destroy connection. |
|
233 |
||
234 |
Counterpart of create_conn. |
|
235 |
||
236 |
''' |
|
237 |
if not name in self.conn_known: |
|
2 | 238 |
raise PgManagerError('Connection name "%s" not registered.' % name) |
0 | 239 |
|
240 |
self.close_conn(name) |
|
241 |
||
242 |
del self.conn_known[name] |
|
243 |
del self.conn_pool[name] |
|
244 |
||
245 |
def get_conn(self, name='default'): |
|
246 |
'''Get connection of name 'name' from pool.''' |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
247 |
self._check_fork() |
0 | 248 |
self.lock.acquire() |
249 |
try: |
|
250 |
if not name in self.conn_known: |
|
2 | 251 |
raise PgManagerError("Connection name '%s' not registered." % name) |
0 | 252 |
|
253 |
conn = None |
|
254 |
while len(self.conn_pool[name]) and conn is None: |
|
255 |
conn = self.conn_pool[name].pop() |
|
256 |
if conn.closed: |
|
257 |
conn = None |
|
258 |
||
259 |
if conn is None: |
|
260 |
ci = self.conn_known[name] |
|
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
261 |
conn = self._connect(ci) |
0 | 262 |
finally: |
263 |
self.lock.release() |
|
264 |
return conn |
|
265 |
||
266 |
def put_conn(self, conn, name='default'): |
|
267 |
'''Put connection back to pool. |
|
268 |
||
269 |
Name must be same as used for get_conn, |
|
270 |
otherwise things become broken. |
|
271 |
||
272 |
''' |
|
273 |
self.lock.acquire() |
|
274 |
try: |
|
275 |
if not name in self.conn_known: |
|
2 | 276 |
raise PgManagerError("Connection name '%s' not registered." % name) |
0 | 277 |
|
278 |
if len(self.conn_pool[name]) >= self.conn_known[name].keep_open: |
|
279 |
conn.close() |
|
280 |
return |
|
281 |
||
282 |
if conn.get_transaction_status() == psycopg2.extensions.TRANSACTION_STATUS_UNKNOWN: |
|
283 |
conn.close() |
|
284 |
return |
|
285 |
||
286 |
# connection returned to the pool must not be in transaction |
|
287 |
if conn.get_transaction_status() != psycopg2.extensions.TRANSACTION_STATUS_IDLE: |
|
288 |
conn.rollback() |
|
289 |
||
290 |
self.conn_pool[name].append(conn) |
|
291 |
finally: |
|
292 |
self.lock.release() |
|
293 |
||
294 |
@contextmanager |
|
295 |
def cursor(self, name='default'): |
|
296 |
'''Cursor context. |
|
297 |
||
298 |
Uses any connection of name 'name' from pool |
|
299 |
and returns cursor for that connection. |
|
300 |
||
301 |
''' |
|
302 |
conn = self.get_conn(name) |
|
303 |
||
304 |
try: |
|
305 |
curs = conn.cursor() |
|
306 |
yield curs |
|
307 |
finally: |
|
308 |
curs.close() |
|
309 |
self.put_conn(conn, name) |
|
310 |
||
311 |
def wait_for_notify(self, name='default', timeout=5): |
|
312 |
'''Wait for asynchronous notifies, return the last one. |
|
313 |
||
314 |
Returns None on timeout. |
|
315 |
||
316 |
''' |
|
317 |
conn = self.get_conn(name) |
|
318 |
||
319 |
try: |
|
320 |
# any residual notify? |
|
321 |
# then return it, that should not break anything |
|
322 |
if conn.notifies: |
|
323 |
return conn.notifies.pop() |
|
324 |
||
325 |
if select.select([conn], [], [], timeout) == ([], [], []): |
|
326 |
# timeout |
|
327 |
return None |
|
328 |
else: |
|
329 |
conn.poll() |
|
330 |
||
331 |
# return just the last notify (we do not care for older ones) |
|
332 |
if conn.notifies: |
|
333 |
return conn.notifies.pop() |
|
334 |
return None |
|
335 |
finally: |
|
336 |
# clean notifies |
|
337 |
while conn.notifies: |
|
338 |
conn.notifies.pop() |
|
339 |
self.put_conn(conn, name) |
|
340 |
||
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
341 |
def _connect(self, ci): |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
342 |
conn = psycopg2.connect(ci.dsn, connection_factory=Connection) |
19
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
343 |
if ci.keep_alive: |
e526ca146fa9
Add documentation for create_conn(). Fix keep_alive - do not crash if socket settings are not supported.
Radek Brich <radek.brich@devl.cz>
parents:
9
diff
changeset
|
344 |
conn.keep_alive() |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
345 |
if not ci.isolation_level is None: |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
346 |
conn.set_isolation_level(ci.isolation_level) |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
347 |
if ci.init_statement: |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
348 |
curs = conn.cursor() |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
349 |
curs.execute(ci.init_statement) |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
350 |
curs.close() |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
351 |
return conn |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
352 |
|
0 | 353 |
def _normalize_isolation_level(self, level): |
354 |
if type(level) == str: |
|
355 |
if level.lower() == 'autocommit': |
|
356 |
return psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT |
|
357 |
if level.lower() == 'read_committed': |
|
358 |
return psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED |
|
359 |
if level.lower() == 'serializable': |
|
360 |
return psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE |
|
361 |
raise PgManagerError('Unknown isolation level name: "%s"', level) |
|
362 |
return level |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
363 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
364 |
def _check_fork(self): |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
365 |
'''Check if process was forked (PID has changed). |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
366 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
367 |
If it was, clean parent's connections. |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
368 |
New connections are created for children. |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
369 |
Known connection credentials are inherited, but not shared. |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
370 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
371 |
''' |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
372 |
if self.pid == multiprocessing.current_process().pid: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
373 |
# PID has not changed |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
374 |
return |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
375 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
376 |
# update saved PID |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
377 |
self.pid = multiprocessing.current_process().pid |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
378 |
# reinitialize lock |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
379 |
self.lock = threading.Lock() |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
380 |
# clean parent's connections |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
381 |
for name in self.conn_pool: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
382 |
self.conn_pool[name] = [] |
0 | 383 |
|
20
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
384 |
@classmethod |
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
385 |
def get_instance(cls): |
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
386 |
if not hasattr(cls, '_instance'): |
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
387 |
cls._instance = cls() |
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
388 |
return cls._instance |
0 | 389 |
|
390 |
||
391 |
def get_instance(): |
|
20
73f0d53fef6b
PgManager: Do not add NullHandler to logger. Rewrite get_instance(). ToolBase: fix prepare_conns() method.
Radek Brich <radek.brich@devl.cz>
parents:
19
diff
changeset
|
392 |
return PgManager.get_instance() |
0 | 393 |