summaryrefslogtreecommitdiff
path: root/python/skytools/psycopgwrapper.py
diff options
context:
space:
mode:
authorMarko Kreen2007-07-23 14:16:22 +0000
committerMarko Kreen2007-07-23 14:16:22 +0000
commita03667304da8e8b3a28d8f76fdb6cac14d0e967f (patch)
tree10e424fe6c81467d8882b5d0e57dcd002a1e07cf /python/skytools/psycopgwrapper.py
parent868c7b200a9fa6ea9ac1fb4dcf2beb16422d6d37 (diff)
skytools: separate psycopg specific code
Diffstat (limited to 'python/skytools/psycopgwrapper.py')
-rw-r--r--python/skytools/psycopgwrapper.py68
1 files changed, 68 insertions, 0 deletions
diff --git a/python/skytools/psycopgwrapper.py b/python/skytools/psycopgwrapper.py
new file mode 100644
index 00000000..36b41124
--- /dev/null
+++ b/python/skytools/psycopgwrapper.py
@@ -0,0 +1,68 @@
+
+"""Wrapper around psycopg1/2.
+
+Preferred is psycopg2, fallback to psycopg1.
+
+Interface provided is psycopg1:
+ - dict* methods.
+ - new columns can be assigned to row.
+
+"""
+
+__all__ = ["QuotedString", "connect_database"]
+
+try:
+ ##from psycopg2.psycopg1 import connect as _pgconnect
+ # psycopg2.psycopg1.cursor is too backwards compatible,
+ # to the point of avoiding optimized access.
+ # only backwards compat thing we need is dict* methods
+
+ import psycopg2.extensions, psycopg2.extras
+ from psycopg2.extensions import QuotedString
+
+ class _CompatRow(psycopg2.extras.DictRow):
+ """Allow setting fields by name."""
+ def __setitem__(self, k, v):
+ if type(k) != int:
+ if k not in self._index:
+ self._index[k] = len(self._index)
+ k = self._index[k]
+ while k >= len(self):
+ self.append(None)
+ return list.__setitem__(self, k, v)
+
+ class _CompatCursor(psycopg2.extras.DictCursor):
+ """Regular psycopg2 DictCursor with dict* methods."""
+ def __init__(self, *args, **kwargs):
+ psycopg2.extras.DictCursor.__init__(self, *args, **kwargs)
+ self.row_factory = _CompatRow
+ dictfetchone = psycopg2.extras.DictCursor.fetchone
+ dictfetchall = psycopg2.extras.DictCursor.fetchall
+ dictfetchmany = psycopg2.extras.DictCursor.fetchmany
+
+ class _CompatConnection(psycopg2.extensions.connection):
+ """Connection object that uses _CompatCursor."""
+ def cursor(self):
+ return psycopg2.extensions.connection.cursor(self, cursor_factory = _CompatCursor)
+
+ def _pgconnect(cstr):
+ """Create a psycopg2 connection."""
+ return _CompatConnection(cstr)
+
+except ImportError:
+ # use psycopg 1
+ from psycopg import connect as _pgconnect
+
+def connect_database(connstr):
+ """Create a db connection with connect_timeout option.
+
+ Default connect_timeout is 15, to change put it directly into dsn.
+ """
+
+ # allow override
+ if connstr.find("connect_timeout") < 0:
+ connstr += " connect_timeout=15"
+
+ # create connection
+ return _pgconnect(connstr)
+