author | Radek Brich <radek.brich@devl.cz> |
Mon, 05 Mar 2012 18:36:46 +0100 | |
changeset 31 | c2e6e24b83d9 |
parent 26 | 7f219da7ab71 |
child 33 | bd0beda49bcb |
permissions | -rw-r--r-- |
0 | 1 |
# -*- coding: utf-8 -*- |
2 |
# |
|
3 |
# PgManager - manage database connections |
|
4 |
# |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
5 |
# Requires: Python 3.2, psycopg2 |
0 | 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 |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
73 |
from collections import OrderedDict |
0 | 74 |
import logging |
75 |
import threading |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
76 |
import multiprocessing |
0 | 77 |
import select |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
78 |
import socket |
0 | 79 |
|
80 |
import psycopg2 |
|
81 |
import psycopg2.extensions |
|
82 |
||
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
|
83 |
from psycopg2 import DatabaseError, IntegrityError, OperationalError |
0 | 84 |
|
85 |
||
26
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
86 |
log_sql = logging.getLogger("pgmanager_sql") |
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
87 |
log_notices = logging.getLogger("pgmanager_notices") |
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
|
88 |
|
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
|
89 |
|
0 | 90 |
class PgManagerError(Exception): |
91 |
||
92 |
pass |
|
93 |
||
94 |
||
95 |
class ConnectionInfo: |
|
96 |
||
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
|
97 |
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
|
98 |
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
|
99 |
|
0 | 100 |
self.dsn = dsn |
101 |
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
|
102 |
self.keep_alive = keep_alive |
0 | 103 |
self.init_statement = init_statement |
104 |
self.keep_open = keep_open |
|
105 |
||
106 |
||
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
107 |
class RowDict(OrderedDict): |
0 | 108 |
|
109 |
def __getattr__(self, key): |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
110 |
try: |
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
111 |
return self[key] |
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
112 |
except KeyError: |
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
113 |
raise AttributeError(key) |
0 | 114 |
|
115 |
||
116 |
class Cursor(psycopg2.extensions.cursor): |
|
117 |
||
118 |
def execute(self, query, args=None): |
|
119 |
try: |
|
120 |
return super(Cursor, self).execute(query, args) |
|
121 |
finally: |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
122 |
if self.query: |
26
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
123 |
log_sql.info(self.query.decode('utf8')) |
0 | 124 |
|
125 |
def callproc(self, procname, args=None): |
|
126 |
try: |
|
127 |
return super(Cursor, self).callproc(procname, args) |
|
128 |
finally: |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
129 |
if self.query: |
26
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
130 |
log_sql.info(self.query.decode('utf8')) |
0 | 131 |
|
132 |
def row_dict(self, row, lstrip=None): |
|
133 |
adjustname = lambda a: a |
|
134 |
if lstrip: |
|
135 |
adjustname = lambda a: a.lstrip(lstrip) |
|
136 |
return RowDict(zip([adjustname(desc[0]) for desc in self.description], row)) |
|
137 |
||
138 |
def fetchone_dict(self, lstrip=None): |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
139 |
'''Return one row as OrderedDict''' |
0 | 140 |
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
|
141 |
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
|
142 |
return None |
0 | 143 |
return self.row_dict(row, lstrip) |
144 |
||
145 |
def fetchall_dict(self, lstrip=None): |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
146 |
'''Return all rows as OrderedDict''' |
0 | 147 |
rows = super(Cursor, self).fetchall() |
148 |
return [self.row_dict(row, lstrip) for row in rows] |
|
149 |
||
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
150 |
def fetchone_adapted(self, lstrip=None): |
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
151 |
'''Like fetchone_dict() but values are quoted for direct inclusion in SQL query. |
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
152 |
|
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
153 |
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
|
154 |
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
|
155 |
|
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
156 |
''' |
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
157 |
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
|
158 |
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
|
159 |
return None |
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
160 |
return self.row_dict([self.mogrify('%s', [x]).decode('utf8') for x in row], lstrip) |
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
161 |
|
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
162 |
def fetchall_adapted(self, lstrip=None): |
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
163 |
'''Like fetchall_dict() but values are quoted for direct inclusion in SQL query.''' |
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
164 |
rows = super(Cursor, self).fetchall() |
31
c2e6e24b83d9
Add browser - database schema browser using tuikit (curses UI). Add listdepends - tool which shows depending views for column. Update pgdatadiff - allow composite primary key. Update pgmanager - RowDict is now OrderedDict. Drop support for Python2.x.
Radek Brich <radek.brich@devl.cz>
parents:
26
diff
changeset
|
165 |
return [self.row_dict([self.mogrify('%s', [x]).decode('utf8') for x in row], lstrip) for row in rows] |
7
685b20d2d3ab
Reorganize directories. PgDataDiff - reworked. PgManager - add fetchone_adapted, fetchall_adapted to cursor.
Radek Brich <radek.brich@devl.cz>
parents:
4
diff
changeset
|
166 |
|
0 | 167 |
|
168 |
class Connection(psycopg2.extensions.connection): |
|
169 |
||
170 |
def cursor(self, name=None): |
|
171 |
if name is None: |
|
172 |
return super(Connection, self).cursor(cursor_factory=Cursor) |
|
173 |
else: |
|
174 |
return super(Connection, self).cursor(name, cursor_factory=Cursor) |
|
175 |
||
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
176 |
def keep_alive(self): |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
177 |
'''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
|
178 |
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
|
179 |
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
|
180 |
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
|
181 |
# 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
|
182 |
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
|
183 |
# 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
|
184 |
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
|
185 |
# 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
|
186 |
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
|
187 |
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
|
188 |
pass |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
189 |
|
0 | 190 |
|
191 |
class PgManager: |
|
192 |
||
193 |
def __init__(self): |
|
194 |
self.conn_known = {} # available connections |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
195 |
self.conn_pool = {} # active connetions |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
196 |
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
|
197 |
self.pid = multiprocessing.current_process().pid # forking check |
0 | 198 |
|
199 |
def __del__(self): |
|
200 |
for conn in tuple(self.conn_known.keys()): |
|
201 |
self.destroy_conn(conn) |
|
202 |
||
23
dc2dbe872fc8
Add keep_open parameter to create_conn.
Radek Brich <brich.radek@ifortuna.cz>
parents:
20
diff
changeset
|
203 |
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
|
204 |
'''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
|
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 |
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
|
207 |
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
|
208 |
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
|
209 |
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
|
210 |
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
|
211 |
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
|
212 |
|
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 |
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
|
214 |
|
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
|
215 |
''' |
0 | 216 |
if name in self.conn_known: |
2 | 217 |
raise PgManagerError('Connection name "%s" already registered.' % name) |
0 | 218 |
|
219 |
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
|
220 |
dsn = ' '.join([x[0]+'='+str(x[1]) for x in kw.items() if x[1] is not None]) |
0 | 221 |
|
222 |
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
|
223 |
ci = ConnectionInfo(dsn, isolation_level, keep_alive, keep_open=keep_open) |
0 | 224 |
|
225 |
self.conn_known[name] = ci |
|
226 |
self.conn_pool[name] = [] |
|
227 |
||
228 |
def close_conn(self, name='default'): |
|
229 |
'''Close all connections of given name. |
|
230 |
||
231 |
Connection credentials are still saved. |
|
232 |
||
233 |
''' |
|
234 |
while len(self.conn_pool[name]): |
|
235 |
conn = self.conn_pool[name].pop() |
|
236 |
conn.close() |
|
237 |
||
238 |
def destroy_conn(self, name='default'): |
|
239 |
'''Destroy connection. |
|
240 |
||
241 |
Counterpart of create_conn. |
|
242 |
||
243 |
''' |
|
244 |
if not name in self.conn_known: |
|
2 | 245 |
raise PgManagerError('Connection name "%s" not registered.' % name) |
0 | 246 |
|
247 |
self.close_conn(name) |
|
248 |
||
249 |
del self.conn_known[name] |
|
250 |
del self.conn_pool[name] |
|
251 |
||
252 |
def get_conn(self, name='default'): |
|
253 |
'''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
|
254 |
self._check_fork() |
0 | 255 |
self.lock.acquire() |
256 |
try: |
|
257 |
if not name in self.conn_known: |
|
2 | 258 |
raise PgManagerError("Connection name '%s' not registered." % name) |
0 | 259 |
|
260 |
conn = None |
|
261 |
while len(self.conn_pool[name]) and conn is None: |
|
262 |
conn = self.conn_pool[name].pop() |
|
263 |
if conn.closed: |
|
264 |
conn = None |
|
265 |
||
266 |
if conn is None: |
|
267 |
ci = self.conn_known[name] |
|
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
268 |
conn = self._connect(ci) |
0 | 269 |
finally: |
270 |
self.lock.release() |
|
271 |
return conn |
|
272 |
||
273 |
def put_conn(self, conn, name='default'): |
|
274 |
'''Put connection back to pool. |
|
275 |
||
276 |
Name must be same as used for get_conn, |
|
277 |
otherwise things become broken. |
|
278 |
||
279 |
''' |
|
280 |
self.lock.acquire() |
|
281 |
try: |
|
282 |
if not name in self.conn_known: |
|
2 | 283 |
raise PgManagerError("Connection name '%s' not registered." % name) |
0 | 284 |
|
285 |
if len(self.conn_pool[name]) >= self.conn_known[name].keep_open: |
|
286 |
conn.close() |
|
287 |
return |
|
288 |
||
289 |
if conn.get_transaction_status() == psycopg2.extensions.TRANSACTION_STATUS_UNKNOWN: |
|
290 |
conn.close() |
|
291 |
return |
|
292 |
||
293 |
# connection returned to the pool must not be in transaction |
|
294 |
if conn.get_transaction_status() != psycopg2.extensions.TRANSACTION_STATUS_IDLE: |
|
295 |
conn.rollback() |
|
296 |
||
297 |
self.conn_pool[name].append(conn) |
|
298 |
finally: |
|
299 |
self.lock.release() |
|
300 |
||
301 |
@contextmanager |
|
302 |
def cursor(self, name='default'): |
|
303 |
'''Cursor context. |
|
304 |
||
305 |
Uses any connection of name 'name' from pool |
|
306 |
and returns cursor for that connection. |
|
307 |
||
308 |
''' |
|
309 |
conn = self.get_conn(name) |
|
310 |
||
311 |
try: |
|
312 |
curs = conn.cursor() |
|
313 |
yield curs |
|
314 |
finally: |
|
315 |
curs.close() |
|
26
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
316 |
self.log_notices(conn) |
0 | 317 |
self.put_conn(conn, name) |
318 |
||
26
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
319 |
def log_notices(self, conn): |
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
320 |
for notice in conn.notices: |
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
321 |
log_notices.info(notice.rstrip()) |
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
322 |
conn.notices[:] = [] |
7f219da7ab71
Add logging mechanism for notices from postgres server. Rename SQL log to "pgmanager_sql".
Radek Brich <radek.brich@devl.cz>
parents:
24
diff
changeset
|
323 |
|
0 | 324 |
def wait_for_notify(self, name='default', timeout=5): |
325 |
'''Wait for asynchronous notifies, return the last one. |
|
326 |
||
327 |
Returns None on timeout. |
|
328 |
||
329 |
''' |
|
330 |
conn = self.get_conn(name) |
|
331 |
||
332 |
try: |
|
333 |
# any residual notify? |
|
334 |
# then return it, that should not break anything |
|
335 |
if conn.notifies: |
|
336 |
return conn.notifies.pop() |
|
337 |
||
338 |
if select.select([conn], [], [], timeout) == ([], [], []): |
|
339 |
# timeout |
|
340 |
return None |
|
341 |
else: |
|
342 |
conn.poll() |
|
343 |
||
344 |
# return just the last notify (we do not care for older ones) |
|
345 |
if conn.notifies: |
|
346 |
return conn.notifies.pop() |
|
347 |
return None |
|
348 |
finally: |
|
349 |
# clean notifies |
|
350 |
while conn.notifies: |
|
351 |
conn.notifies.pop() |
|
352 |
self.put_conn(conn, name) |
|
353 |
||
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
354 |
def _connect(self, ci): |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
355 |
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
|
356 |
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
|
357 |
conn.keep_alive() |
8
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
358 |
if not ci.isolation_level is None: |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
359 |
conn.set_isolation_level(ci.isolation_level) |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
360 |
if ci.init_statement: |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
361 |
curs = conn.cursor() |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
362 |
curs.execute(ci.init_statement) |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
363 |
curs.close() |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
364 |
return conn |
2911935c524d
pgmanager: Add keep_alive support.
Radek Brich <radek.brich@devl.cz>
parents:
7
diff
changeset
|
365 |
|
0 | 366 |
def _normalize_isolation_level(self, level): |
367 |
if type(level) == str: |
|
368 |
if level.lower() == 'autocommit': |
|
369 |
return psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT |
|
370 |
if level.lower() == 'read_committed': |
|
371 |
return psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED |
|
372 |
if level.lower() == 'serializable': |
|
373 |
return psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE |
|
374 |
raise PgManagerError('Unknown isolation level name: "%s"', level) |
|
375 |
return level |
|
24
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
376 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
377 |
def _check_fork(self): |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
378 |
'''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
|
379 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
380 |
If it was, clean parent's connections. |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
381 |
New connections are created for children. |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
382 |
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
|
383 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
384 |
''' |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
385 |
if self.pid == multiprocessing.current_process().pid: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
386 |
# PID has not changed |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
387 |
return |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
388 |
|
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
389 |
# update saved PID |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
390 |
self.pid = multiprocessing.current_process().pid |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
391 |
# reinitialize lock |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
392 |
self.lock = threading.Lock() |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
393 |
# clean parent's connections |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
394 |
for name in self.conn_pool: |
5664afa530e5
PgManager: Add partial support for multiprocessing.
Radek Brich <radek.brich@devl.cz>
parents:
23
diff
changeset
|
395 |
self.conn_pool[name] = [] |
0 | 396 |
|
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
|
397 |
@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
|
398 |
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
|
399 |
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
|
400 |
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
|
401 |
return cls._instance |
0 | 402 |
|
403 |
||
404 |
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
|
405 |
return PgManager.get_instance() |
0 | 406 |