2005-10-18 09:42:00 +04:00
|
|
|
"""Miscellaneous goodies for psycopg2
|
2005-01-20 08:49:40 +03:00
|
|
|
|
2005-10-18 09:42:00 +04:00
|
|
|
This module is a generic place used to hold little helper functions
|
2013-04-26 12:21:56 +04:00
|
|
|
and classes until a better place in the distribution is found.
|
2005-01-20 08:49:40 +03:00
|
|
|
"""
|
2004-10-19 07:17:12 +04:00
|
|
|
# psycopg/extras.py - miscellaneous extra goodies for psycopg
|
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org>
|
2004-10-19 07:17:12 +04:00
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# psycopg2 is free software: you can redistribute it and/or modify it
|
|
|
|
# under the terms of the GNU Lesser General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2004-10-19 07:17:12 +04:00
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# In addition, as a special exception, the copyright holders give
|
|
|
|
# permission to link this program with the OpenSSL library (or with
|
|
|
|
# modified versions of OpenSSL that use the same license as OpenSSL),
|
|
|
|
# and distribute linked combinations including the two.
|
|
|
|
#
|
|
|
|
# You must obey the GNU Lesser General Public License in all respects for
|
|
|
|
# all of the code used other than OpenSSL.
|
|
|
|
#
|
|
|
|
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
|
|
|
|
# License for more details.
|
2004-10-19 07:17:12 +04:00
|
|
|
|
2013-04-07 05:59:30 +04:00
|
|
|
import os as _os
|
|
|
|
import sys as _sys
|
|
|
|
import time as _time
|
|
|
|
import re as _re
|
2006-01-20 07:07:23 +03:00
|
|
|
|
|
|
|
try:
|
2013-04-07 05:59:30 +04:00
|
|
|
import logging as _logging
|
2006-01-20 07:07:23 +03:00
|
|
|
except:
|
2013-04-07 05:59:30 +04:00
|
|
|
_logging = None
|
2008-09-19 23:25:16 +04:00
|
|
|
|
2010-09-27 00:59:54 +04:00
|
|
|
import psycopg2
|
2008-09-19 23:25:16 +04:00
|
|
|
from psycopg2 import extensions as _ext
|
2005-06-24 11:11:44 +04:00
|
|
|
from psycopg2.extensions import cursor as _cursor
|
2005-07-17 08:08:08 +04:00
|
|
|
from psycopg2.extensions import connection as _connection
|
2015-10-15 13:56:21 +03:00
|
|
|
from psycopg2.extensions import adapt as _A, quote_ident
|
2016-10-11 02:10:53 +03:00
|
|
|
|
|
|
|
from psycopg2._psycopg import ( # noqa
|
|
|
|
REPLICATION_PHYSICAL, REPLICATION_LOGICAL,
|
|
|
|
ReplicationConnection as _replicationConnection,
|
|
|
|
ReplicationCursor as _replicationCursor,
|
|
|
|
ReplicationMessage)
|
|
|
|
|
|
|
|
|
|
|
|
# expose the json adaptation stuff into the module
|
|
|
|
from psycopg2._json import ( # noqa
|
|
|
|
json, Json, register_json, register_default_json, register_default_jsonb)
|
|
|
|
|
|
|
|
|
|
|
|
# Expose range-related objects
|
|
|
|
from psycopg2._range import ( # noqa
|
|
|
|
Range, NumericRange, DateRange, DateTimeRange, DateTimeTZRange,
|
|
|
|
register_range, RangeAdapter, RangeCaster)
|
2005-02-27 18:03:53 +03:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
|
2016-10-11 05:58:09 +03:00
|
|
|
# Expose ipaddress-related objects
|
|
|
|
from psycopg2._ipaddress import register_ipaddress # noqa
|
|
|
|
|
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
class DictCursorBase(_cursor):
|
|
|
|
"""Base class for all dict-like cursors."""
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2010-12-12 19:45:21 +03:00
|
|
|
if 'row_factory' in kwargs:
|
2007-01-16 16:45:41 +03:00
|
|
|
row_factory = kwargs['row_factory']
|
|
|
|
del kwargs['row_factory']
|
|
|
|
else:
|
|
|
|
raise NotImplementedError(
|
|
|
|
"DictCursorBase can't be instantiated without a row factory.")
|
2012-09-28 05:51:58 +04:00
|
|
|
super(DictCursorBase, self).__init__(*args, **kwargs)
|
2007-01-16 16:45:41 +03:00
|
|
|
self._query_executed = 0
|
2009-05-09 16:44:59 +04:00
|
|
|
self._prefetch = 0
|
2007-01-16 16:45:41 +03:00
|
|
|
self.row_factory = row_factory
|
|
|
|
|
|
|
|
def fetchone(self):
|
2009-05-09 16:44:59 +04:00
|
|
|
if self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchone()
|
2007-01-16 16:45:41 +03:00
|
|
|
if self._query_executed:
|
|
|
|
self._build_index()
|
2009-05-09 16:44:59 +04:00
|
|
|
if not self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchone()
|
2009-03-02 12:59:52 +03:00
|
|
|
return res
|
2007-01-16 16:45:41 +03:00
|
|
|
|
|
|
|
def fetchmany(self, size=None):
|
2009-05-09 16:44:59 +04:00
|
|
|
if self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchmany(size)
|
2007-01-16 16:45:41 +03:00
|
|
|
if self._query_executed:
|
|
|
|
self._build_index()
|
2009-05-09 16:44:59 +04:00
|
|
|
if not self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchmany(size)
|
2009-03-02 12:59:52 +03:00
|
|
|
return res
|
2007-01-16 16:45:41 +03:00
|
|
|
|
|
|
|
def fetchall(self):
|
2009-05-09 16:44:59 +04:00
|
|
|
if self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchall()
|
2007-01-16 16:45:41 +03:00
|
|
|
if self._query_executed:
|
|
|
|
self._build_index()
|
2009-05-09 16:44:59 +04:00
|
|
|
if not self._prefetch:
|
2012-09-28 05:51:58 +04:00
|
|
|
res = super(DictCursorBase, self).fetchall()
|
2009-03-02 12:59:52 +03:00
|
|
|
return res
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2011-12-12 02:04:42 +04:00
|
|
|
def __iter__(self):
|
2017-01-04 11:45:53 +03:00
|
|
|
try:
|
|
|
|
if self._prefetch:
|
|
|
|
res = super(DictCursorBase, self).__iter__()
|
|
|
|
first = res.next()
|
|
|
|
if self._query_executed:
|
|
|
|
self._build_index()
|
|
|
|
if not self._prefetch:
|
|
|
|
res = super(DictCursorBase, self).__iter__()
|
|
|
|
first = res.next()
|
|
|
|
|
|
|
|
yield first
|
|
|
|
while 1:
|
|
|
|
yield res.next()
|
|
|
|
except StopIteration:
|
|
|
|
return
|
2011-12-12 02:04:42 +04:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2005-07-17 08:08:08 +04:00
|
|
|
class DictConnection(_connection):
|
2010-02-26 03:17:52 +03:00
|
|
|
"""A connection that uses `DictCursor` automatically."""
|
2012-03-26 07:49:54 +04:00
|
|
|
def cursor(self, *args, **kwargs):
|
2012-04-11 20:59:16 +04:00
|
|
|
kwargs.setdefault('cursor_factory', DictCursor)
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(DictConnection, self).cursor(*args, **kwargs)
|
2004-10-19 07:17:12 +04:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
class DictCursor(DictCursorBase):
|
2004-10-19 07:17:12 +04:00
|
|
|
"""A cursor that keeps a list of column name -> index mappings."""
|
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['row_factory'] = DictRow
|
2012-09-28 05:51:58 +04:00
|
|
|
super(DictCursor, self).__init__(*args, **kwargs)
|
2009-05-09 16:44:59 +04:00
|
|
|
self._prefetch = 1
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2010-03-31 03:43:07 +04:00
|
|
|
def execute(self, query, vars=None):
|
2004-10-19 07:17:12 +04:00
|
|
|
self.index = {}
|
2007-01-16 16:45:41 +03:00
|
|
|
self._query_executed = 1
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(DictCursor, self).execute(query, vars)
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2005-12-06 08:55:58 +03:00
|
|
|
def callproc(self, procname, vars=None):
|
|
|
|
self.index = {}
|
2007-01-16 16:45:41 +03:00
|
|
|
self._query_executed = 1
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(DictCursor, self).callproc(procname, vars)
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
def _build_index(self):
|
2007-01-16 16:45:41 +03:00
|
|
|
if self._query_executed == 1 and self.description:
|
2004-10-19 07:17:12 +04:00
|
|
|
for i in range(len(self.description)):
|
|
|
|
self.index[self.description[i][0]] = i
|
2009-05-09 16:44:59 +04:00
|
|
|
self._query_executed = 0
|
2005-03-01 19:41:02 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2004-10-19 07:17:12 +04:00
|
|
|
class DictRow(list):
|
2013-04-26 12:21:56 +04:00
|
|
|
"""A row object that allow by-column-name access to data."""
|
2004-10-19 07:17:12 +04:00
|
|
|
|
2009-05-09 12:19:15 +04:00
|
|
|
__slots__ = ('_index',)
|
|
|
|
|
2004-10-19 07:17:12 +04:00
|
|
|
def __init__(self, cursor):
|
2005-05-10 06:29:24 +04:00
|
|
|
self._index = cursor.index
|
2004-10-19 07:17:12 +04:00
|
|
|
self[:] = [None] * len(cursor.description)
|
|
|
|
|
|
|
|
def __getitem__(self, x):
|
2010-12-23 05:28:19 +03:00
|
|
|
if not isinstance(x, (int, slice)):
|
2005-05-10 06:29:24 +04:00
|
|
|
x = self._index[x]
|
2004-10-19 07:17:12 +04:00
|
|
|
return list.__getitem__(self, x)
|
2005-02-27 18:03:53 +03:00
|
|
|
|
2010-12-01 16:17:12 +03:00
|
|
|
def __setitem__(self, x, v):
|
2010-12-23 05:28:19 +03:00
|
|
|
if not isinstance(x, (int, slice)):
|
2010-12-01 16:17:12 +03:00
|
|
|
x = self._index[x]
|
|
|
|
list.__setitem__(self, x, v)
|
|
|
|
|
2005-04-11 11:20:46 +04:00
|
|
|
def items(self):
|
2010-12-12 19:45:21 +03:00
|
|
|
return list(self.iteritems())
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2005-04-25 08:58:38 +04:00
|
|
|
def keys(self):
|
2006-01-06 05:58:24 +03:00
|
|
|
return self._index.keys()
|
2005-04-25 08:58:38 +04:00
|
|
|
|
2005-05-19 08:48:26 +04:00
|
|
|
def values(self):
|
|
|
|
return tuple(self[:])
|
|
|
|
|
|
|
|
def has_key(self, x):
|
2010-12-12 19:45:21 +03:00
|
|
|
return x in self._index
|
2006-01-06 05:58:24 +03:00
|
|
|
|
2005-05-19 08:48:26 +04:00
|
|
|
def get(self, x, default=None):
|
|
|
|
try:
|
|
|
|
return self[x]
|
|
|
|
except:
|
|
|
|
return default
|
|
|
|
|
2006-10-06 09:22:54 +04:00
|
|
|
def iteritems(self):
|
2010-12-12 19:45:21 +03:00
|
|
|
for n, v in self._index.iteritems():
|
2006-10-06 09:22:54 +04:00
|
|
|
yield n, list.__getitem__(self, v)
|
2005-02-27 18:03:53 +03:00
|
|
|
|
2009-04-19 18:25:12 +04:00
|
|
|
def iterkeys(self):
|
|
|
|
return self._index.iterkeys()
|
|
|
|
|
|
|
|
def itervalues(self):
|
|
|
|
return list.__iter__(self)
|
|
|
|
|
|
|
|
def copy(self):
|
2010-12-12 19:45:21 +03:00
|
|
|
return dict(self.iteritems())
|
2009-04-19 18:25:12 +04:00
|
|
|
|
|
|
|
def __contains__(self, x):
|
2010-12-12 19:45:21 +03:00
|
|
|
return x in self._index
|
|
|
|
|
2012-12-11 05:10:01 +04:00
|
|
|
def __getstate__(self):
|
|
|
|
return self[:], self._index.copy()
|
|
|
|
|
|
|
|
def __setstate__(self, data):
|
|
|
|
self[:] = data[0]
|
|
|
|
self._index = data[1]
|
|
|
|
|
|
|
|
# drop the crusty Py2 methods
|
2013-04-07 05:59:30 +04:00
|
|
|
if _sys.version_info[0] > 2:
|
2016-10-11 02:10:53 +03:00
|
|
|
items = iteritems # noqa
|
|
|
|
keys = iterkeys # noqa
|
|
|
|
values = itervalues # noqa
|
|
|
|
del iteritems, iterkeys, itervalues, has_key
|
2010-12-12 19:45:21 +03:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
|
|
|
|
class RealDictConnection(_connection):
|
2010-02-26 03:17:52 +03:00
|
|
|
"""A connection that uses `RealDictCursor` automatically."""
|
2012-03-26 07:49:54 +04:00
|
|
|
def cursor(self, *args, **kwargs):
|
2012-04-11 20:59:16 +04:00
|
|
|
kwargs.setdefault('cursor_factory', RealDictCursor)
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(RealDictConnection, self).cursor(*args, **kwargs)
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
class RealDictCursor(DictCursorBase):
|
|
|
|
"""A cursor that uses a real dict as the base type for rows.
|
|
|
|
|
|
|
|
Note that this cursor is extremely specialized and does not allow
|
|
|
|
the normal access (using integer indices) to fetched data. If you need
|
|
|
|
to access database rows both as a dictionary and a list, then use
|
2010-02-26 03:17:52 +03:00
|
|
|
the generic `DictCursor` instead of `!RealDictCursor`.
|
2007-01-16 16:45:41 +03:00
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['row_factory'] = RealDictRow
|
2012-09-28 05:51:58 +04:00
|
|
|
super(RealDictCursor, self).__init__(*args, **kwargs)
|
2009-05-09 16:44:59 +04:00
|
|
|
self._prefetch = 0
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2010-03-31 03:43:07 +04:00
|
|
|
def execute(self, query, vars=None):
|
2007-01-16 16:45:41 +03:00
|
|
|
self.column_mapping = []
|
|
|
|
self._query_executed = 1
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(RealDictCursor, self).execute(query, vars)
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
def callproc(self, procname, vars=None):
|
|
|
|
self.column_mapping = []
|
|
|
|
self._query_executed = 1
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(RealDictCursor, self).callproc(procname, vars)
|
2007-01-16 16:45:41 +03:00
|
|
|
|
|
|
|
def _build_index(self):
|
|
|
|
if self._query_executed == 1 and self.description:
|
2009-05-09 16:44:59 +04:00
|
|
|
for i in range(len(self.description)):
|
|
|
|
self.column_mapping.append(self.description[i][0])
|
|
|
|
self._query_executed = 0
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
class RealDictRow(dict):
|
2011-02-19 19:16:28 +03:00
|
|
|
"""A `!dict` subclass representing a data record."""
|
2009-05-09 12:19:15 +04:00
|
|
|
|
2009-05-09 16:44:59 +04:00
|
|
|
__slots__ = ('_column_mapping')
|
2009-05-09 12:19:15 +04:00
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
def __init__(self, cursor):
|
|
|
|
dict.__init__(self)
|
2011-09-12 05:20:53 +04:00
|
|
|
# Required for named cursors
|
|
|
|
if cursor.description and not cursor.column_mapping:
|
|
|
|
cursor._build_index()
|
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
self._column_mapping = cursor.column_mapping
|
|
|
|
|
|
|
|
def __setitem__(self, name, value):
|
2009-05-09 16:44:59 +04:00
|
|
|
if type(name) == int:
|
2007-01-16 16:45:41 +03:00
|
|
|
name = self._column_mapping[name]
|
|
|
|
return dict.__setitem__(self, name, value)
|
|
|
|
|
2012-12-11 03:54:08 +04:00
|
|
|
def __getstate__(self):
|
|
|
|
return (self.copy(), self._column_mapping[:])
|
|
|
|
|
|
|
|
def __setstate__(self, data):
|
|
|
|
self.update(data[0])
|
|
|
|
self._column_mapping = data[1]
|
|
|
|
|
2007-01-16 16:45:41 +03:00
|
|
|
|
2010-11-06 04:39:43 +03:00
|
|
|
class NamedTupleConnection(_connection):
|
|
|
|
"""A connection that uses `NamedTupleCursor` automatically."""
|
|
|
|
def cursor(self, *args, **kwargs):
|
2012-04-11 20:59:16 +04:00
|
|
|
kwargs.setdefault('cursor_factory', NamedTupleCursor)
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(NamedTupleConnection, self).cursor(*args, **kwargs)
|
2010-11-06 04:39:43 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2010-11-06 04:39:43 +03:00
|
|
|
class NamedTupleCursor(_cursor):
|
2011-02-19 19:16:28 +03:00
|
|
|
"""A cursor that generates results as `~collections.namedtuple`.
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
`!fetch*()` methods will return named tuples instead of regular tuples, so
|
|
|
|
their elements can be accessed both as regular numeric items as well as
|
|
|
|
attributes.
|
|
|
|
|
|
|
|
>>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
|
|
|
|
>>> rec = nt_cur.fetchone()
|
|
|
|
>>> rec
|
|
|
|
Record(id=1, num=100, data="abc'def")
|
|
|
|
>>> rec[1]
|
|
|
|
100
|
|
|
|
>>> rec.data
|
|
|
|
"abc'def"
|
|
|
|
"""
|
2010-11-11 13:26:36 +03:00
|
|
|
Record = None
|
|
|
|
|
|
|
|
def execute(self, query, vars=None):
|
|
|
|
self.Record = None
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(NamedTupleCursor, self).execute(query, vars)
|
2010-11-11 13:26:36 +03:00
|
|
|
|
|
|
|
def executemany(self, query, vars):
|
|
|
|
self.Record = None
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(NamedTupleCursor, self).executemany(query, vars)
|
2010-11-11 13:26:36 +03:00
|
|
|
|
|
|
|
def callproc(self, procname, vars=None):
|
|
|
|
self.Record = None
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(NamedTupleCursor, self).callproc(procname, vars)
|
2010-11-11 13:26:36 +03:00
|
|
|
|
2010-11-06 04:39:43 +03:00
|
|
|
def fetchone(self):
|
2012-09-28 05:51:58 +04:00
|
|
|
t = super(NamedTupleCursor, self).fetchone()
|
2010-11-06 04:39:43 +03:00
|
|
|
if t is not None:
|
2010-11-11 13:26:36 +03:00
|
|
|
nt = self.Record
|
|
|
|
if nt is None:
|
|
|
|
nt = self.Record = self._make_nt()
|
2012-09-20 19:27:50 +04:00
|
|
|
return nt._make(t)
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
def fetchmany(self, size=None):
|
2012-09-28 05:51:58 +04:00
|
|
|
ts = super(NamedTupleCursor, self).fetchmany(size)
|
2010-11-11 13:26:36 +03:00
|
|
|
nt = self.Record
|
|
|
|
if nt is None:
|
|
|
|
nt = self.Record = self._make_nt()
|
2012-09-20 19:27:50 +04:00
|
|
|
return map(nt._make, ts)
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
def fetchall(self):
|
2012-09-28 05:51:58 +04:00
|
|
|
ts = super(NamedTupleCursor, self).fetchall()
|
2010-11-11 13:26:36 +03:00
|
|
|
nt = self.Record
|
|
|
|
if nt is None:
|
|
|
|
nt = self.Record = self._make_nt()
|
2012-09-20 19:27:50 +04:00
|
|
|
return map(nt._make, ts)
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
def __iter__(self):
|
2017-01-04 11:45:53 +03:00
|
|
|
try:
|
|
|
|
it = super(NamedTupleCursor, self).__iter__()
|
|
|
|
t = it.next()
|
2012-02-24 02:58:58 +04:00
|
|
|
|
2017-01-04 11:45:53 +03:00
|
|
|
nt = self.Record
|
|
|
|
if nt is None:
|
|
|
|
nt = self.Record = self._make_nt()
|
2012-02-24 02:58:58 +04:00
|
|
|
|
2017-01-04 11:45:53 +03:00
|
|
|
yield nt._make(t)
|
2012-02-24 02:58:58 +04:00
|
|
|
|
2017-01-04 11:45:53 +03:00
|
|
|
while 1:
|
|
|
|
yield nt._make(it.next())
|
|
|
|
except StopIteration:
|
|
|
|
return
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
from collections import namedtuple
|
2017-11-21 07:00:35 +03:00
|
|
|
except ImportError as _exc:
|
2010-11-06 04:39:43 +03:00
|
|
|
def _make_nt(self):
|
|
|
|
raise self._exc
|
|
|
|
else:
|
|
|
|
def _make_nt(self, namedtuple=namedtuple):
|
2018-05-14 01:51:21 +03:00
|
|
|
# ascii except alnum and underscore
|
|
|
|
nochars = ' !"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~'
|
|
|
|
re_clean = _re.compile('[' + _re.escape(nochars) + ']')
|
|
|
|
|
2018-01-29 05:41:44 +03:00
|
|
|
def f(s):
|
2018-05-14 01:51:21 +03:00
|
|
|
s = re_clean.sub('_', s)
|
2018-01-29 05:41:44 +03:00
|
|
|
# Python identifier cannot start with numbers, namedtuple fields
|
|
|
|
# cannot start with underscore. So...
|
2018-05-14 01:51:21 +03:00
|
|
|
if s[0] == '_' or '0' <= s[0] <= '9':
|
2018-01-29 05:41:44 +03:00
|
|
|
s = 'f' + s
|
|
|
|
|
|
|
|
return s
|
|
|
|
|
|
|
|
return namedtuple(
|
|
|
|
"Record", [f(d[0]) for d in self.description or ()])
|
2010-11-06 04:39:43 +03:00
|
|
|
|
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
class LoggingConnection(_connection):
|
2010-02-13 05:10:51 +03:00
|
|
|
"""A connection that logs all queries to a file or logger__ object.
|
|
|
|
|
|
|
|
.. __: http://docs.python.org/library/logging.html
|
|
|
|
"""
|
2006-01-20 07:07:23 +03:00
|
|
|
|
|
|
|
def initialize(self, logobj):
|
2011-02-19 19:16:28 +03:00
|
|
|
"""Initialize the connection to log to `!logobj`.
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2011-02-19 19:16:28 +03:00
|
|
|
The `!logobj` parameter can be an open file object or a Logger
|
2010-02-13 05:10:51 +03:00
|
|
|
instance from the standard logging module.
|
2006-01-20 07:07:23 +03:00
|
|
|
"""
|
|
|
|
self._logobj = logobj
|
2013-04-07 05:59:30 +04:00
|
|
|
if _logging and isinstance(logobj, _logging.Logger):
|
2006-01-20 07:07:23 +03:00
|
|
|
self.log = self._logtologger
|
|
|
|
else:
|
|
|
|
self.log = self._logtofile
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def filter(self, msg, curs):
|
|
|
|
"""Filter the query before logging it.
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
This is the method to overwrite to filter unwanted queries out of the
|
|
|
|
log or to add some extra data to the output. The default implementation
|
|
|
|
just does nothing.
|
|
|
|
"""
|
|
|
|
return msg
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def _logtofile(self, msg, curs):
|
|
|
|
msg = self.filter(msg, curs)
|
2016-10-11 02:10:53 +03:00
|
|
|
if msg:
|
2016-12-30 00:36:04 +03:00
|
|
|
if _sys.version_info[0] >= 3 and isinstance(msg, bytes):
|
|
|
|
msg = msg.decode(_ext.encodings[self.encoding], 'replace')
|
2016-10-11 02:10:53 +03:00
|
|
|
self._logobj.write(msg + _os.linesep)
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def _logtologger(self, msg, curs):
|
|
|
|
msg = self.filter(msg, curs)
|
2016-10-11 02:10:53 +03:00
|
|
|
if msg:
|
|
|
|
self._logobj.debug(msg)
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def _check(self):
|
|
|
|
if not hasattr(self, '_logobj'):
|
|
|
|
raise self.ProgrammingError(
|
|
|
|
"LoggingConnection object has not been initialize()d")
|
2012-04-11 20:59:16 +04:00
|
|
|
|
|
|
|
def cursor(self, *args, **kwargs):
|
2006-01-20 07:07:23 +03:00
|
|
|
self._check()
|
2012-04-11 20:59:16 +04:00
|
|
|
kwargs.setdefault('cursor_factory', LoggingCursor)
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(LoggingConnection, self).cursor(*args, **kwargs)
|
2007-09-01 13:32:42 +04:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
class LoggingCursor(_cursor):
|
|
|
|
"""A cursor that logs queries using its connection logging facilities."""
|
|
|
|
|
2010-03-31 03:43:07 +04:00
|
|
|
def execute(self, query, vars=None):
|
2006-01-20 07:07:23 +03:00
|
|
|
try:
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(LoggingCursor, self).execute(query, vars)
|
2006-01-20 07:07:23 +03:00
|
|
|
finally:
|
|
|
|
self.connection.log(self.query, self)
|
|
|
|
|
|
|
|
def callproc(self, procname, vars=None):
|
|
|
|
try:
|
2012-09-28 05:51:58 +04:00
|
|
|
return super(LoggingCursor, self).callproc(procname, vars)
|
2006-01-20 07:07:23 +03:00
|
|
|
finally:
|
|
|
|
self.connection.log(self.query, self)
|
|
|
|
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
class MinTimeLoggingConnection(LoggingConnection):
|
|
|
|
"""A connection that logs queries based on execution time.
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2010-02-26 03:17:52 +03:00
|
|
|
This is just an example of how to sub-class `LoggingConnection` to
|
2010-02-13 05:10:51 +03:00
|
|
|
provide some extra filtering for the logged queries. Both the
|
2013-04-26 12:21:56 +04:00
|
|
|
`initialize()` and `filter()` methods are overwritten to make sure
|
2010-02-13 05:10:51 +03:00
|
|
|
that only queries executing for more than ``mintime`` ms are logged.
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2010-02-13 05:10:51 +03:00
|
|
|
Note that this connection uses the specialized cursor
|
2010-02-26 03:17:52 +03:00
|
|
|
`MinTimeLoggingCursor`.
|
2006-01-20 07:07:23 +03:00
|
|
|
"""
|
|
|
|
def initialize(self, logobj, mintime=0):
|
|
|
|
LoggingConnection.initialize(self, logobj)
|
|
|
|
self._mintime = mintime
|
2009-05-09 16:44:59 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def filter(self, msg, curs):
|
2013-04-07 05:59:30 +04:00
|
|
|
t = (_time.time() - curs.timestamp) * 1000
|
2006-01-20 07:07:23 +03:00
|
|
|
if t > self._mintime:
|
2017-11-03 12:30:06 +03:00
|
|
|
if _sys.version_info[0] >= 3 and isinstance(msg, bytes):
|
|
|
|
msg = msg.decode(_ext.encodings[self.encoding], 'replace')
|
2013-04-07 05:59:30 +04:00
|
|
|
return msg + _os.linesep + " (execution time: %d ms)" % t
|
2006-01-20 07:07:23 +03:00
|
|
|
|
2012-04-11 20:59:16 +04:00
|
|
|
def cursor(self, *args, **kwargs):
|
|
|
|
kwargs.setdefault('cursor_factory', MinTimeLoggingCursor)
|
|
|
|
return LoggingConnection.cursor(self, *args, **kwargs)
|
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
class MinTimeLoggingCursor(LoggingCursor):
|
2010-02-26 03:17:52 +03:00
|
|
|
"""The cursor sub-class companion to `MinTimeLoggingConnection`."""
|
2006-01-20 07:07:23 +03:00
|
|
|
|
2010-03-31 03:43:07 +04:00
|
|
|
def execute(self, query, vars=None):
|
2013-04-07 05:59:30 +04:00
|
|
|
self.timestamp = _time.time()
|
2010-03-31 03:43:07 +04:00
|
|
|
return LoggingCursor.execute(self, query, vars)
|
2012-04-11 20:59:16 +04:00
|
|
|
|
2006-01-20 07:07:23 +03:00
|
|
|
def callproc(self, procname, vars=None):
|
2013-04-07 05:59:30 +04:00
|
|
|
self.timestamp = _time.time()
|
2015-04-23 17:00:16 +03:00
|
|
|
return LoggingCursor.callproc(self, procname, vars)
|
2006-09-10 18:50:03 +04:00
|
|
|
|
2008-09-19 23:25:16 +04:00
|
|
|
|
2016-03-08 17:44:29 +03:00
|
|
|
class LogicalReplicationConnection(_replicationConnection):
|
2015-10-01 16:34:51 +03:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2015-10-27 20:21:24 +03:00
|
|
|
kwargs['replication_type'] = REPLICATION_LOGICAL
|
2015-10-01 16:34:51 +03:00
|
|
|
super(LogicalReplicationConnection, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
|
2016-03-08 17:44:29 +03:00
|
|
|
class PhysicalReplicationConnection(_replicationConnection):
|
2015-10-01 16:34:51 +03:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2015-10-27 20:21:24 +03:00
|
|
|
kwargs['replication_type'] = REPLICATION_PHYSICAL
|
2015-10-01 16:34:51 +03:00
|
|
|
super(PhysicalReplicationConnection, self).__init__(*args, **kwargs)
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
|
2015-10-19 16:42:42 +03:00
|
|
|
class StopReplication(Exception):
|
|
|
|
"""
|
|
|
|
Exception used to break out of the endless loop in
|
2015-10-19 21:00:39 +03:00
|
|
|
`~ReplicationCursor.consume_stream()`.
|
2015-10-19 16:42:42 +03:00
|
|
|
|
|
|
|
Subclass of `~exceptions.Exception`. Intentionally *not* inherited from
|
|
|
|
`~psycopg2.Error` as occurrence of this exception does not indicate an
|
|
|
|
error.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2015-10-19 21:00:39 +03:00
|
|
|
class ReplicationCursor(_replicationCursor):
|
2015-10-20 13:36:13 +03:00
|
|
|
"""A cursor used for communication on replication connections."""
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-01 16:34:51 +03:00
|
|
|
def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None):
|
2015-06-01 12:35:05 +03:00
|
|
|
"""Create streaming replication slot."""
|
|
|
|
|
2015-10-15 13:56:21 +03:00
|
|
|
command = "CREATE_REPLICATION_SLOT %s " % quote_ident(slot_name, self)
|
2015-10-01 16:34:51 +03:00
|
|
|
|
|
|
|
if slot_type is None:
|
|
|
|
slot_type = self.connection.replication_type
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
if slot_type == REPLICATION_LOGICAL:
|
|
|
|
if output_plugin is None:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"output plugin name is required to create "
|
|
|
|
"logical replication slot")
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-27 20:21:24 +03:00
|
|
|
command += "LOGICAL %s" % quote_ident(output_plugin, self)
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
elif slot_type == REPLICATION_PHYSICAL:
|
|
|
|
if output_plugin is not None:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"cannot specify output plugin name when creating "
|
|
|
|
"physical replication slot")
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-27 20:21:24 +03:00
|
|
|
command += "PHYSICAL"
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
else:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"unrecognized replication type: %s" % repr(slot_type))
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-06-11 13:20:52 +03:00
|
|
|
self.execute(command)
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
def drop_replication_slot(self, slot_name):
|
|
|
|
"""Drop streaming replication slot."""
|
|
|
|
|
2015-10-15 13:56:21 +03:00
|
|
|
command = "DROP_REPLICATION_SLOT %s" % quote_ident(slot_name, self)
|
2015-06-11 13:20:52 +03:00
|
|
|
self.execute(command)
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-01 20:28:00 +03:00
|
|
|
def start_replication(self, slot_name=None, slot_type=None, start_lsn=0,
|
2015-10-23 12:31:55 +03:00
|
|
|
timeline=0, options=None, decode=False):
|
2015-10-01 20:28:00 +03:00
|
|
|
"""Start replication stream."""
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
command = "START_REPLICATION "
|
|
|
|
|
2015-10-01 16:34:51 +03:00
|
|
|
if slot_type is None:
|
|
|
|
slot_type = self.connection.replication_type
|
|
|
|
|
2015-10-01 12:08:56 +03:00
|
|
|
if slot_type == REPLICATION_LOGICAL:
|
|
|
|
if slot_name:
|
2015-10-15 13:56:21 +03:00
|
|
|
command += "SLOT %s " % quote_ident(slot_name, self)
|
2015-10-01 12:08:56 +03:00
|
|
|
else:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"slot name is required for logical replication")
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-27 20:21:24 +03:00
|
|
|
command += "LOGICAL "
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
elif slot_type == REPLICATION_PHYSICAL:
|
2015-10-01 12:08:56 +03:00
|
|
|
if slot_name:
|
2015-10-15 13:56:21 +03:00
|
|
|
command += "SLOT %s " % quote_ident(slot_name, self)
|
2015-10-01 12:08:56 +03:00
|
|
|
# don't add "PHYSICAL", before 9.4 it was just START_REPLICATION XXX/XXX
|
2015-10-01 16:34:51 +03:00
|
|
|
|
2015-06-01 12:35:05 +03:00
|
|
|
else:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"unrecognized replication type: %s" % repr(slot_type))
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-01 12:08:56 +03:00
|
|
|
if type(start_lsn) is str:
|
|
|
|
lsn = start_lsn.split('/')
|
|
|
|
lsn = "%X/%08X" % (int(lsn[0], 16), int(lsn[1], 16))
|
|
|
|
else:
|
2016-10-11 02:10:53 +03:00
|
|
|
lsn = "%X/%08X" % ((start_lsn >> 32) & 0xFFFFFFFF,
|
|
|
|
start_lsn & 0xFFFFFFFF)
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2015-10-01 12:08:56 +03:00
|
|
|
command += lsn
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
if timeline != 0:
|
|
|
|
if slot_type == REPLICATION_LOGICAL:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"cannot specify timeline for logical replication")
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
command += " TIMELINE %d" % timeline
|
|
|
|
|
|
|
|
if options:
|
|
|
|
if slot_type == REPLICATION_PHYSICAL:
|
2016-10-11 02:10:53 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"cannot specify output plugin options for physical replication")
|
2015-06-01 12:35:05 +03:00
|
|
|
|
|
|
|
command += " ("
|
2016-10-11 02:10:53 +03:00
|
|
|
for k, v in options.iteritems():
|
2015-06-01 12:35:05 +03:00
|
|
|
if not command.endswith('('):
|
|
|
|
command += ", "
|
2015-10-15 13:56:21 +03:00
|
|
|
command += "%s %s" % (quote_ident(k, self), _A(str(v)))
|
2015-06-01 12:35:05 +03:00
|
|
|
command += ")"
|
|
|
|
|
2015-10-23 12:31:55 +03:00
|
|
|
self.start_replication_expert(command, decode=decode)
|
2015-06-10 10:06:08 +03:00
|
|
|
|
|
|
|
# allows replication cursors to be used in select.select() directly
|
|
|
|
def fileno(self):
|
|
|
|
return self.connection.fileno()
|
2015-06-05 18:44:09 +03:00
|
|
|
|
2015-06-01 12:35:05 +03:00
|
|
|
|
2008-09-19 23:25:16 +04:00
|
|
|
# a dbtype and adapter for Python UUID type
|
|
|
|
|
2011-06-28 19:12:43 +04:00
|
|
|
class UUID_adapter(object):
|
|
|
|
"""Adapt Python's uuid.UUID__ type to PostgreSQL's uuid__.
|
2008-09-19 23:25:16 +04:00
|
|
|
|
2011-06-28 19:12:43 +04:00
|
|
|
.. __: http://docs.python.org/library/uuid.html
|
2012-02-28 20:28:07 +04:00
|
|
|
.. __: http://www.postgresql.org/docs/current/static/datatype-uuid.html
|
2011-06-28 19:12:43 +04:00
|
|
|
"""
|
2010-02-13 05:10:51 +03:00
|
|
|
|
2011-06-28 19:12:43 +04:00
|
|
|
def __init__(self, uuid):
|
|
|
|
self._uuid = uuid
|
|
|
|
|
2013-04-07 21:06:43 +04:00
|
|
|
def __conform__(self, proto):
|
|
|
|
if proto is _ext.ISQLQuote:
|
|
|
|
return self
|
2011-06-28 19:12:43 +04:00
|
|
|
|
|
|
|
def getquoted(self):
|
2016-08-15 03:55:57 +03:00
|
|
|
return ("'%s'::uuid" % self._uuid).encode('utf8')
|
2011-06-28 19:12:43 +04:00
|
|
|
|
2013-04-07 21:06:43 +04:00
|
|
|
def __str__(self):
|
|
|
|
return "'%s'::uuid" % self._uuid
|
2011-06-28 19:12:43 +04:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2011-06-28 19:12:43 +04:00
|
|
|
def register_uuid(oids=None, conn_or_curs=None):
|
2012-02-24 03:51:28 +04:00
|
|
|
"""Create the UUID type and an uuid.UUID adapter.
|
|
|
|
|
|
|
|
:param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence
|
|
|
|
with oids of the type and the array. If not specified, use PostgreSQL
|
|
|
|
standard oids.
|
|
|
|
:param conn_or_curs: where to register the typecaster. If not specified,
|
|
|
|
register it globally.
|
|
|
|
"""
|
2011-06-28 19:12:43 +04:00
|
|
|
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
if not oids:
|
|
|
|
oid1 = 2950
|
|
|
|
oid2 = 2951
|
2012-02-24 03:51:28 +04:00
|
|
|
elif isinstance(oids, (list, tuple)):
|
2011-06-28 19:12:43 +04:00
|
|
|
oid1, oid2 = oids
|
|
|
|
else:
|
|
|
|
oid1 = oids
|
|
|
|
oid2 = 2951
|
|
|
|
|
|
|
|
_ext.UUID = _ext.new_type((oid1, ), "UUID",
|
|
|
|
lambda data, cursor: data and uuid.UUID(data) or None)
|
2012-02-23 18:37:15 +04:00
|
|
|
_ext.UUIDARRAY = _ext.new_array_type((oid2,), "UUID[]", _ext.UUID)
|
2011-06-28 19:12:43 +04:00
|
|
|
|
|
|
|
_ext.register_type(_ext.UUID, conn_or_curs)
|
|
|
|
_ext.register_type(_ext.UUIDARRAY, conn_or_curs)
|
|
|
|
_ext.register_adapter(uuid.UUID, UUID_adapter)
|
|
|
|
|
|
|
|
return _ext.UUID
|
2008-09-19 23:25:16 +04:00
|
|
|
|
|
|
|
|
2008-09-24 03:27:52 +04:00
|
|
|
# a type, dbtype and adapter for PostgreSQL inet type
|
|
|
|
|
|
|
|
class Inet(object):
|
|
|
|
"""Wrap a string to allow for correct SQL-quoting of inet values.
|
|
|
|
|
|
|
|
Note that this adapter does NOT check the passed value to make
|
|
|
|
sure it really is an inet-compatible address but DOES call adapt()
|
|
|
|
on it to make sure it is impossible to execute an SQL-injection
|
|
|
|
by passing an evil value to the initializer.
|
|
|
|
"""
|
|
|
|
def __init__(self, addr):
|
2010-02-13 05:14:38 +03:00
|
|
|
self.addr = addr
|
2012-02-24 03:56:55 +04:00
|
|
|
|
2010-02-14 23:14:17 +03:00
|
|
|
def __repr__(self):
|
|
|
|
return "%s(%r)" % (self.__class__.__name__, self.addr)
|
|
|
|
|
2008-09-24 03:27:52 +04:00
|
|
|
def prepare(self, conn):
|
|
|
|
self._conn = conn
|
2012-02-24 03:56:55 +04:00
|
|
|
|
2008-09-24 03:27:52 +04:00
|
|
|
def getquoted(self):
|
2010-02-14 23:14:17 +03:00
|
|
|
obj = _A(self.addr)
|
2008-09-24 03:27:52 +04:00
|
|
|
if hasattr(obj, 'prepare'):
|
|
|
|
obj.prepare(self._conn)
|
2016-08-15 03:55:57 +03:00
|
|
|
return obj.getquoted() + b"::inet"
|
2008-09-24 03:27:52 +04:00
|
|
|
|
2013-04-07 21:06:43 +04:00
|
|
|
def __conform__(self, proto):
|
|
|
|
if proto is _ext.ISQLQuote:
|
2010-09-26 02:55:55 +04:00
|
|
|
return self
|
|
|
|
|
2008-09-24 03:27:52 +04:00
|
|
|
def __str__(self):
|
|
|
|
return str(self.addr)
|
2012-02-24 03:56:55 +04:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2009-03-02 12:59:52 +03:00
|
|
|
def register_inet(oid=None, conn_or_curs=None):
|
2012-02-24 03:56:55 +04:00
|
|
|
"""Create the INET type and an Inet adapter.
|
|
|
|
|
|
|
|
:param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence
|
|
|
|
with oids of the type and the array. If not specified, use PostgreSQL
|
|
|
|
standard oids.
|
|
|
|
:param conn_or_curs: where to register the typecaster. If not specified,
|
|
|
|
register it globally.
|
|
|
|
"""
|
2016-10-11 03:33:04 +03:00
|
|
|
import warnings
|
|
|
|
warnings.warn(
|
|
|
|
"the inet adapter is deprecated, it's not very useful",
|
|
|
|
DeprecationWarning)
|
|
|
|
|
2012-02-24 03:56:55 +04:00
|
|
|
if not oid:
|
|
|
|
oid1 = 869
|
|
|
|
oid2 = 1041
|
|
|
|
elif isinstance(oid, (list, tuple)):
|
|
|
|
oid1, oid2 = oid
|
|
|
|
else:
|
|
|
|
oid1 = oid
|
|
|
|
oid2 = 1041
|
|
|
|
|
|
|
|
_ext.INET = _ext.new_type((oid1, ), "INET",
|
2008-09-24 03:27:52 +04:00
|
|
|
lambda data, cursor: data and Inet(data) or None)
|
2012-02-24 03:56:55 +04:00
|
|
|
_ext.INETARRAY = _ext.new_array_type((oid2, ), "INETARRAY", _ext.INET)
|
|
|
|
|
2009-03-02 12:59:52 +03:00
|
|
|
_ext.register_type(_ext.INET, conn_or_curs)
|
2012-02-24 03:56:55 +04:00
|
|
|
_ext.register_type(_ext.INETARRAY, conn_or_curs)
|
|
|
|
|
2008-09-24 03:27:52 +04:00
|
|
|
return _ext.INET
|
|
|
|
|
|
|
|
|
2009-03-02 13:07:17 +03:00
|
|
|
def register_tstz_w_secs(oids=None, conn_or_curs=None):
|
2010-05-20 05:10:33 +04:00
|
|
|
"""The function used to register an alternate type caster for
|
|
|
|
:sql:`TIMESTAMP WITH TIME ZONE` to deal with historical time zones with
|
|
|
|
seconds in the UTC offset.
|
2009-03-02 13:07:17 +03:00
|
|
|
|
2010-05-20 05:10:33 +04:00
|
|
|
These are now correctly handled by the default type caster, so currently
|
|
|
|
the function doesn't do anything.
|
|
|
|
"""
|
2013-04-07 05:59:30 +04:00
|
|
|
import warnings
|
2010-07-13 16:26:52 +04:00
|
|
|
warnings.warn("deprecated", DeprecationWarning)
|
2009-03-02 13:07:17 +03:00
|
|
|
|
|
|
|
|
2010-04-04 06:07:43 +04:00
|
|
|
def wait_select(conn):
|
2010-04-02 04:56:38 +04:00
|
|
|
"""Wait until a connection or cursor has data available.
|
|
|
|
|
|
|
|
The function is an example of a wait callback to be registered with
|
2013-04-07 05:59:30 +04:00
|
|
|
`~psycopg2.extensions.set_wait_callback()`. This function uses
|
|
|
|
:py:func:`~select.select()` to wait for data available.
|
|
|
|
|
2010-04-02 04:56:38 +04:00
|
|
|
"""
|
2013-04-07 05:59:30 +04:00
|
|
|
import select
|
|
|
|
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
|
|
|
|
|
2010-04-02 04:56:38 +04:00
|
|
|
while 1:
|
2015-10-01 17:26:13 +03:00
|
|
|
try:
|
|
|
|
state = conn.poll()
|
|
|
|
if state == POLL_OK:
|
|
|
|
break
|
|
|
|
elif state == POLL_READ:
|
|
|
|
select.select([conn.fileno()], [], [])
|
|
|
|
elif state == POLL_WRITE:
|
|
|
|
select.select([], [conn.fileno()], [])
|
|
|
|
else:
|
|
|
|
raise conn.OperationalError("bad state from poll: %s" % state)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
conn.cancel()
|
|
|
|
# the loop will be broken by a server error
|
|
|
|
continue
|
2010-04-02 04:56:38 +04:00
|
|
|
|
|
|
|
|
2012-08-15 02:26:17 +04:00
|
|
|
def _solve_conn_curs(conn_or_curs):
|
|
|
|
"""Return the connection and a DBAPI cursor from a connection or cursor."""
|
2012-09-19 07:26:35 +04:00
|
|
|
if conn_or_curs is None:
|
|
|
|
raise psycopg2.ProgrammingError("no connection or cursor provided")
|
|
|
|
|
2012-08-15 02:26:17 +04:00
|
|
|
if hasattr(conn_or_curs, 'execute'):
|
|
|
|
conn = conn_or_curs.connection
|
|
|
|
curs = conn.cursor(cursor_factory=_cursor)
|
|
|
|
else:
|
|
|
|
conn = conn_or_curs
|
|
|
|
curs = conn.cursor(cursor_factory=_cursor)
|
|
|
|
|
|
|
|
return conn, curs
|
|
|
|
|
|
|
|
|
2010-09-26 02:13:51 +04:00
|
|
|
class HstoreAdapter(object):
|
|
|
|
"""Adapt a Python dict to the hstore syntax."""
|
|
|
|
def __init__(self, wrapped):
|
|
|
|
self.wrapped = wrapped
|
|
|
|
|
|
|
|
def prepare(self, conn):
|
|
|
|
self.conn = conn
|
|
|
|
|
2010-09-27 04:45:16 +04:00
|
|
|
# use an old-style getquoted implementation if required
|
|
|
|
if conn.server_version < 90000:
|
|
|
|
self.getquoted = self._getquoted_8
|
2010-09-26 02:13:51 +04:00
|
|
|
|
|
|
|
def _getquoted_8(self):
|
|
|
|
"""Use the operators available in PG pre-9.0."""
|
2010-09-27 01:30:23 +04:00
|
|
|
if not self.wrapped:
|
2016-08-15 03:55:57 +03:00
|
|
|
return b"''::hstore"
|
2010-09-27 01:30:23 +04:00
|
|
|
|
2010-09-26 02:13:51 +04:00
|
|
|
adapt = _ext.adapt
|
|
|
|
rv = []
|
|
|
|
for k, v in self.wrapped.iteritems():
|
|
|
|
k = adapt(k)
|
|
|
|
k.prepare(self.conn)
|
|
|
|
k = k.getquoted()
|
|
|
|
|
|
|
|
if v is not None:
|
|
|
|
v = adapt(v)
|
|
|
|
v.prepare(self.conn)
|
|
|
|
v = v.getquoted()
|
|
|
|
else:
|
2016-08-15 03:55:57 +03:00
|
|
|
v = b'NULL'
|
2010-09-26 02:13:51 +04:00
|
|
|
|
2010-12-29 05:45:24 +03:00
|
|
|
# XXX this b'ing is painfully inefficient!
|
2016-08-15 03:55:57 +03:00
|
|
|
rv.append(b"(" + k + b" => " + v + b")")
|
2010-09-26 02:13:51 +04:00
|
|
|
|
2016-08-15 03:55:57 +03:00
|
|
|
return b"(" + b'||'.join(rv) + b")"
|
2010-09-26 02:13:51 +04:00
|
|
|
|
|
|
|
def _getquoted_9(self):
|
|
|
|
"""Use the hstore(text[], text[]) function."""
|
2010-09-27 01:30:23 +04:00
|
|
|
if not self.wrapped:
|
2016-08-15 03:55:57 +03:00
|
|
|
return b"''::hstore"
|
2010-09-27 01:30:23 +04:00
|
|
|
|
2010-09-26 02:13:51 +04:00
|
|
|
k = _ext.adapt(self.wrapped.keys())
|
|
|
|
k.prepare(self.conn)
|
|
|
|
v = _ext.adapt(self.wrapped.values())
|
|
|
|
v.prepare(self.conn)
|
2016-08-15 03:55:57 +03:00
|
|
|
return b"hstore(" + k.getquoted() + b", " + v.getquoted() + b")"
|
2010-09-26 02:13:51 +04:00
|
|
|
|
2010-09-27 04:45:16 +04:00
|
|
|
getquoted = _getquoted_9
|
|
|
|
|
2013-04-07 05:59:30 +04:00
|
|
|
_re_hstore = _re.compile(r"""
|
2010-09-27 00:59:54 +04:00
|
|
|
# hstore key:
|
2010-09-27 01:53:02 +04:00
|
|
|
# a string of normal or escaped chars
|
|
|
|
"((?: [^"\\] | \\. )*)"
|
2010-09-27 00:59:54 +04:00
|
|
|
\s*=>\s* # hstore value
|
|
|
|
(?:
|
|
|
|
NULL # the value can be null - not catched
|
2010-09-27 01:53:02 +04:00
|
|
|
# or a quoted string like the key
|
|
|
|
| "((?: [^"\\] | \\. )*)"
|
2010-09-27 00:59:54 +04:00
|
|
|
)
|
|
|
|
(?:\s*,\s*|$) # pairs separated by comma or end of string.
|
2013-04-07 05:59:30 +04:00
|
|
|
""", _re.VERBOSE)
|
2010-09-27 00:59:54 +04:00
|
|
|
|
2010-12-29 05:45:24 +03:00
|
|
|
@classmethod
|
2013-04-07 05:59:30 +04:00
|
|
|
def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")):
|
2010-09-27 00:59:54 +04:00
|
|
|
"""Parse an hstore representation in a Python string.
|
|
|
|
|
|
|
|
The hstore is represented as something like::
|
|
|
|
|
|
|
|
"a"=>"1", "b"=>"2"
|
|
|
|
|
|
|
|
with backslash-escaped strings.
|
|
|
|
"""
|
|
|
|
if s is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
rv = {}
|
|
|
|
start = 0
|
|
|
|
for m in self._re_hstore.finditer(s):
|
|
|
|
if m is None or m.start() != start:
|
|
|
|
raise psycopg2.InterfaceError(
|
|
|
|
"error parsing hstore pair at char %d" % start)
|
2010-12-29 05:45:24 +03:00
|
|
|
k = _bsdec.sub(r'\1', m.group(1))
|
2010-09-27 00:59:54 +04:00
|
|
|
v = m.group(2)
|
|
|
|
if v is not None:
|
2010-12-29 05:45:24 +03:00
|
|
|
v = _bsdec.sub(r'\1', v)
|
2010-09-27 00:59:54 +04:00
|
|
|
|
|
|
|
rv[k] = v
|
|
|
|
start = m.end()
|
|
|
|
|
|
|
|
if start < len(s):
|
|
|
|
raise psycopg2.InterfaceError(
|
|
|
|
"error parsing hstore: unparsed data after char %d" % start)
|
|
|
|
|
|
|
|
return rv
|
|
|
|
|
2010-12-29 05:45:24 +03:00
|
|
|
@classmethod
|
2010-09-27 03:49:31 +04:00
|
|
|
def parse_unicode(self, s, cur):
|
|
|
|
"""Parse an hstore returning unicode keys and values."""
|
2010-12-29 05:45:24 +03:00
|
|
|
if s is None:
|
|
|
|
return None
|
2010-09-27 03:49:31 +04:00
|
|
|
|
2010-12-29 05:45:24 +03:00
|
|
|
s = s.decode(_ext.encodings[cur.connection.encoding])
|
|
|
|
return self.parse(s, cur)
|
2010-09-27 03:49:31 +04:00
|
|
|
|
2010-11-19 06:51:53 +03:00
|
|
|
@classmethod
|
2010-09-27 04:46:54 +04:00
|
|
|
def get_oids(self, conn_or_curs):
|
2011-02-25 03:19:49 +03:00
|
|
|
"""Return the lists of OID of the hstore and hstore[] types.
|
2010-09-27 04:46:54 +04:00
|
|
|
"""
|
2012-08-15 02:26:17 +04:00
|
|
|
conn, curs = _solve_conn_curs(conn_or_curs)
|
2010-09-27 01:11:06 +04:00
|
|
|
|
2010-09-27 04:46:54 +04:00
|
|
|
# Store the transaction status of the connection to revert it after use
|
|
|
|
conn_status = conn.status
|
2010-09-27 01:11:06 +04:00
|
|
|
|
2010-11-19 06:51:53 +03:00
|
|
|
# column typarray not available before PG 8.3
|
|
|
|
typarray = conn.server_version >= 80300 and "typarray" or "NULL"
|
|
|
|
|
2011-02-25 03:19:49 +03:00
|
|
|
rv0, rv1 = [], []
|
|
|
|
|
2010-09-27 04:46:54 +04:00
|
|
|
# get the oid for the hstore
|
|
|
|
curs.execute("""\
|
2010-11-19 06:51:53 +03:00
|
|
|
SELECT t.oid, %s
|
2010-09-27 01:11:06 +04:00
|
|
|
FROM pg_type t JOIN pg_namespace ns
|
|
|
|
ON typnamespace = ns.oid
|
2011-02-25 03:19:49 +03:00
|
|
|
WHERE typname = 'hstore';
|
2010-11-19 06:51:53 +03:00
|
|
|
""" % typarray)
|
2011-02-25 03:19:49 +03:00
|
|
|
for oids in curs:
|
|
|
|
rv0.append(oids[0])
|
|
|
|
rv1.append(oids[1])
|
2010-09-27 01:11:06 +04:00
|
|
|
|
2010-09-27 04:46:54 +04:00
|
|
|
# revert the status of the connection as before the command
|
|
|
|
if (conn_status != _ext.STATUS_IN_TRANSACTION
|
2011-12-15 23:28:04 +04:00
|
|
|
and not conn.autocommit):
|
2010-09-27 04:46:54 +04:00
|
|
|
conn.rollback()
|
2010-09-27 01:11:06 +04:00
|
|
|
|
2011-02-25 03:19:49 +03:00
|
|
|
return tuple(rv0), tuple(rv1)
|
2010-09-27 04:46:54 +04:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2011-09-22 21:53:21 +04:00
|
|
|
def register_hstore(conn_or_curs, globally=False, unicode=False,
|
2016-10-11 02:10:53 +03:00
|
|
|
oid=None, array_oid=None):
|
2016-09-17 22:36:19 +03:00
|
|
|
r"""Register adapter and typecaster for `!dict`\-\ |hstore| conversions.
|
2010-09-28 03:33:34 +04:00
|
|
|
|
2011-02-21 03:58:52 +03:00
|
|
|
:param conn_or_curs: a connection or cursor: the typecaster will be
|
|
|
|
registered only on this object unless *globally* is set to `!True`
|
2011-02-25 03:19:49 +03:00
|
|
|
:param globally: register the adapter globally, not only on *conn_or_curs*
|
2011-02-21 03:58:52 +03:00
|
|
|
:param unicode: if `!True`, keys and values returned from the database
|
|
|
|
will be `!unicode` instead of `!str`. The option is not available on
|
|
|
|
Python 3
|
|
|
|
:param oid: the OID of the |hstore| type if known. If not, it will be
|
2011-09-22 21:53:21 +04:00
|
|
|
queried on *conn_or_curs*.
|
|
|
|
:param array_oid: the OID of the |hstore| array type if known. If not, it
|
|
|
|
will be queried on *conn_or_curs*.
|
2011-02-21 03:58:52 +03:00
|
|
|
|
|
|
|
The connection or cursor passed to the function will be used to query the
|
|
|
|
database and look for the OID of the |hstore| type (which may be different
|
|
|
|
across databases). If querying is not desirable (e.g. with
|
|
|
|
:ref:`asynchronous connections <async-support>`) you may specify it in the
|
2011-09-22 21:53:21 +04:00
|
|
|
*oid* parameter, which can be found using a query such as :sql:`SELECT
|
|
|
|
'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid*
|
|
|
|
using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`.
|
|
|
|
|
2011-02-21 03:58:52 +03:00
|
|
|
Note that, when passing a dictionary from Python to the database, both
|
|
|
|
strings and unicode keys and values are supported. Dictionaries returned
|
|
|
|
from the database have keys/values according to the *unicode* parameter.
|
2010-09-28 03:33:34 +04:00
|
|
|
|
|
|
|
The |hstore| contrib module must be already installed in the database
|
|
|
|
(executing the ``hstore.sql`` script in your ``contrib`` directory).
|
|
|
|
Raise `~psycopg2.ProgrammingError` if the type is not found.
|
2010-09-27 04:46:54 +04:00
|
|
|
"""
|
2011-02-21 03:58:52 +03:00
|
|
|
if oid is None:
|
|
|
|
oid = HstoreAdapter.get_oids(conn_or_curs)
|
2011-02-25 04:37:02 +03:00
|
|
|
if oid is None or not oid[0]:
|
2011-02-21 03:58:52 +03:00
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"hstore type not found in the database. "
|
|
|
|
"please install it from your 'contrib/hstore.sql' file")
|
|
|
|
else:
|
2011-09-22 21:53:21 +04:00
|
|
|
array_oid = oid[1]
|
|
|
|
oid = oid[0]
|
2010-09-27 01:11:06 +04:00
|
|
|
|
2011-02-25 03:19:49 +03:00
|
|
|
if isinstance(oid, int):
|
|
|
|
oid = (oid,)
|
|
|
|
|
2011-09-22 21:53:21 +04:00
|
|
|
if array_oid is not None:
|
|
|
|
if isinstance(array_oid, int):
|
|
|
|
array_oid = (array_oid,)
|
|
|
|
else:
|
|
|
|
array_oid = tuple([x for x in array_oid if x])
|
|
|
|
|
2010-09-27 01:11:06 +04:00
|
|
|
# create and register the typecaster
|
2013-04-07 05:59:30 +04:00
|
|
|
if _sys.version_info[0] < 3 and unicode:
|
2010-09-27 03:49:31 +04:00
|
|
|
cast = HstoreAdapter.parse_unicode
|
|
|
|
else:
|
|
|
|
cast = HstoreAdapter.parse
|
|
|
|
|
2011-02-25 03:19:49 +03:00
|
|
|
HSTORE = _ext.new_type(oid, "HSTORE", cast)
|
2010-09-27 04:46:54 +04:00
|
|
|
_ext.register_type(HSTORE, not globally and conn_or_curs or None)
|
2010-09-27 01:11:06 +04:00
|
|
|
_ext.register_adapter(dict, HstoreAdapter)
|
|
|
|
|
2011-09-22 21:53:21 +04:00
|
|
|
if array_oid:
|
|
|
|
HSTOREARRAY = _ext.new_array_type(array_oid, "HSTOREARRAY", HSTORE)
|
|
|
|
_ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None)
|
|
|
|
|
2010-09-26 02:13:51 +04:00
|
|
|
|
2011-01-02 02:34:13 +03:00
|
|
|
class CompositeCaster(object):
|
|
|
|
"""Helps conversion of a PostgreSQL composite type into a Python object.
|
|
|
|
|
|
|
|
The class is usually created by the `register_composite()` function.
|
2011-09-22 21:55:33 +04:00
|
|
|
You may want to create and register manually instances of the class if
|
|
|
|
querying the database at registration time is not desirable (such as when
|
|
|
|
using an :ref:`asynchronous connections <async-support>`).
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
"""
|
2012-09-22 18:10:40 +04:00
|
|
|
def __init__(self, name, oid, attrs, array_oid=None, schema=None):
|
2011-01-02 02:34:13 +03:00
|
|
|
self.name = name
|
2012-09-22 18:10:40 +04:00
|
|
|
self.schema = schema
|
2011-01-02 02:34:13 +03:00
|
|
|
self.oid = oid
|
2011-09-22 21:55:33 +04:00
|
|
|
self.array_oid = array_oid
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
self.attnames = [a[0] for a in attrs]
|
|
|
|
self.atttypes = [a[1] for a in attrs]
|
2011-01-03 21:27:26 +03:00
|
|
|
self._create_type(name, self.attnames)
|
2011-01-02 02:34:13 +03:00
|
|
|
self.typecaster = _ext.new_type((oid,), name, self.parse)
|
2011-09-22 21:55:33 +04:00
|
|
|
if array_oid:
|
|
|
|
self.array_typecaster = _ext.new_array_type(
|
|
|
|
(array_oid,), "%sARRAY" % name, self.typecaster)
|
|
|
|
else:
|
|
|
|
self.array_typecaster = None
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
def parse(self, s, curs):
|
|
|
|
if s is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
tokens = self.tokenize(s)
|
|
|
|
if len(tokens) != len(self.atttypes):
|
|
|
|
raise psycopg2.DataError(
|
2011-12-15 23:23:08 +04:00
|
|
|
"expecting %d components for the type %s, %d found instead" %
|
|
|
|
(len(self.atttypes), self.name, len(tokens)))
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
values = [curs.cast(oid, token)
|
|
|
|
for oid, token in zip(self.atttypes, tokens)]
|
2012-09-22 04:46:53 +04:00
|
|
|
|
|
|
|
return self.make(values)
|
|
|
|
|
|
|
|
def make(self, values):
|
2012-09-22 05:01:04 +04:00
|
|
|
"""Return a new Python object representing the data being casted.
|
|
|
|
|
|
|
|
*values* is the list of attributes, already casted into their Python
|
|
|
|
representation.
|
|
|
|
|
|
|
|
You can subclass this method to :ref:`customize the composite cast
|
|
|
|
<custom-composite>`.
|
|
|
|
"""
|
|
|
|
|
2012-09-22 04:46:53 +04:00
|
|
|
return self._ctor(values)
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2013-04-07 05:59:30 +04:00
|
|
|
_re_tokenize = _re.compile(r"""
|
2012-02-23 18:31:16 +04:00
|
|
|
\(? ([,)]) # an empty token, representing NULL
|
2011-01-02 02:34:13 +03:00
|
|
|
| \(? " ((?: [^"] | "")*) " [,)] # or a quoted string
|
2012-02-23 18:31:16 +04:00
|
|
|
| \(? ([^",)]+) [,)] # or an unquoted string
|
2013-04-07 05:59:30 +04:00
|
|
|
""", _re.VERBOSE)
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2013-04-07 05:59:30 +04:00
|
|
|
_re_undouble = _re.compile(r'(["\\])\1')
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tokenize(self, s):
|
|
|
|
rv = []
|
|
|
|
for m in self._re_tokenize.finditer(s):
|
|
|
|
if m is None:
|
2012-02-23 18:29:39 +04:00
|
|
|
raise psycopg2.InterfaceError("can't parse type: %r" % s)
|
2012-12-03 18:19:09 +04:00
|
|
|
if m.group(1) is not None:
|
2011-01-02 02:34:13 +03:00
|
|
|
rv.append(None)
|
2012-12-03 18:19:09 +04:00
|
|
|
elif m.group(2) is not None:
|
2011-01-02 02:34:13 +03:00
|
|
|
rv.append(self._re_undouble.sub(r"\1", m.group(2)))
|
|
|
|
else:
|
|
|
|
rv.append(m.group(3))
|
|
|
|
|
|
|
|
return rv
|
|
|
|
|
|
|
|
def _create_type(self, name, attnames):
|
|
|
|
try:
|
|
|
|
from collections import namedtuple
|
|
|
|
except ImportError:
|
2011-01-03 21:27:26 +03:00
|
|
|
self.type = tuple
|
2012-09-20 19:27:50 +04:00
|
|
|
self._ctor = self.type
|
2011-01-02 02:34:13 +03:00
|
|
|
else:
|
2011-01-03 21:27:26 +03:00
|
|
|
self.type = namedtuple(name, attnames)
|
2012-09-20 19:27:50 +04:00
|
|
|
self._ctor = self.type._make
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _from_db(self, name, conn_or_curs):
|
|
|
|
"""Return a `CompositeCaster` instance for the type *name*.
|
|
|
|
|
|
|
|
Raise `ProgrammingError` if the type is not found.
|
|
|
|
"""
|
2012-08-15 02:26:17 +04:00
|
|
|
conn, curs = _solve_conn_curs(conn_or_curs)
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
# Store the transaction status of the connection to revert it after use
|
|
|
|
conn_status = conn.status
|
|
|
|
|
2011-02-09 04:20:25 +03:00
|
|
|
# Use the correct schema
|
|
|
|
if '.' in name:
|
|
|
|
schema, tname = name.split('.', 1)
|
|
|
|
else:
|
|
|
|
tname = name
|
|
|
|
schema = 'public'
|
|
|
|
|
2011-09-22 21:55:33 +04:00
|
|
|
# column typarray not available before PG 8.3
|
|
|
|
typarray = conn.server_version >= 80300 and "typarray" or "NULL"
|
|
|
|
|
2011-01-02 02:34:13 +03:00
|
|
|
# get the type oid and attributes
|
|
|
|
curs.execute("""\
|
2011-09-22 21:55:33 +04:00
|
|
|
SELECT t.oid, %s, attname, atttypid
|
2011-01-02 02:34:13 +03:00
|
|
|
FROM pg_type t
|
|
|
|
JOIN pg_namespace ns ON typnamespace = ns.oid
|
|
|
|
JOIN pg_attribute a ON attrelid = typrelid
|
2011-12-16 00:11:17 +04:00
|
|
|
WHERE typname = %%s AND nspname = %%s
|
|
|
|
AND attnum > 0 AND NOT attisdropped
|
2011-02-09 03:11:36 +03:00
|
|
|
ORDER BY attnum;
|
2011-09-22 21:55:33 +04:00
|
|
|
""" % typarray, (tname, schema))
|
2011-01-02 02:34:13 +03:00
|
|
|
|
|
|
|
recs = curs.fetchall()
|
|
|
|
|
|
|
|
# revert the status of the connection as before the command
|
|
|
|
if (conn_status != _ext.STATUS_IN_TRANSACTION
|
2011-12-15 23:28:04 +04:00
|
|
|
and not conn.autocommit):
|
2011-01-02 02:34:13 +03:00
|
|
|
conn.rollback()
|
|
|
|
|
|
|
|
if not recs:
|
|
|
|
raise psycopg2.ProgrammingError(
|
|
|
|
"PostgreSQL type '%s' not found" % name)
|
|
|
|
|
|
|
|
type_oid = recs[0][0]
|
2011-09-22 21:55:33 +04:00
|
|
|
array_oid = recs[0][1]
|
2016-10-11 02:10:53 +03:00
|
|
|
type_attrs = [(r[2], r[3]) for r in recs]
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2012-09-22 04:46:53 +04:00
|
|
|
return self(tname, type_oid, type_attrs,
|
2012-09-22 18:10:40 +04:00
|
|
|
array_oid=array_oid, schema=schema)
|
2011-01-02 02:34:13 +03:00
|
|
|
|
2016-10-11 02:10:53 +03:00
|
|
|
|
2012-09-22 04:46:53 +04:00
|
|
|
def register_composite(name, conn_or_curs, globally=False, factory=None):
|
2011-01-02 02:34:13 +03:00
|
|
|
"""Register a typecaster to convert a composite type into a tuple.
|
|
|
|
|
|
|
|
:param name: the name of a PostgreSQL composite type, e.g. created using
|
|
|
|
the |CREATE TYPE|_ command
|
|
|
|
:param conn_or_curs: a connection or cursor used to find the type oid and
|
|
|
|
components; the typecaster is registered in a scope limited to this
|
2011-02-19 19:16:28 +03:00
|
|
|
object, unless *globally* is set to `!True`
|
|
|
|
:param globally: if `!False` (default) register the typecaster only on
|
2011-01-02 02:34:13 +03:00
|
|
|
*conn_or_curs*, otherwise register it globally
|
2012-09-22 04:46:53 +04:00
|
|
|
:param factory: if specified it should be a `CompositeCaster` subclass: use
|
|
|
|
it to :ref:`customize how to cast composite types <custom-composite>`
|
|
|
|
:return: the registered `CompositeCaster` or *factory* instance
|
|
|
|
responsible for the conversion
|
2011-01-02 02:34:13 +03:00
|
|
|
"""
|
2012-09-22 04:46:53 +04:00
|
|
|
if factory is None:
|
|
|
|
factory = CompositeCaster
|
|
|
|
|
|
|
|
caster = factory._from_db(name, conn_or_curs)
|
2011-01-02 02:34:13 +03:00
|
|
|
_ext.register_type(caster.typecaster, not globally and conn_or_curs or None)
|
|
|
|
|
2011-09-22 21:55:33 +04:00
|
|
|
if caster.array_typecaster is not None:
|
2016-10-11 02:10:53 +03:00
|
|
|
_ext.register_type(
|
|
|
|
caster.array_typecaster, not globally and conn_or_curs or None)
|
2011-09-22 21:55:33 +04:00
|
|
|
|
2011-01-02 02:34:13 +03:00
|
|
|
return caster
|
2017-02-01 04:59:47 +03:00
|
|
|
|
|
|
|
|
|
|
|
def _paginate(seq, page_size):
|
|
|
|
"""Consume an iterable and return it in chunks.
|
|
|
|
|
|
|
|
Every chunk is at most `page_size`. Never return an empty chunk.
|
|
|
|
"""
|
|
|
|
page = []
|
|
|
|
it = iter(seq)
|
|
|
|
while 1:
|
|
|
|
try:
|
|
|
|
for i in xrange(page_size):
|
|
|
|
page.append(it.next())
|
|
|
|
yield page
|
|
|
|
page = []
|
|
|
|
except StopIteration:
|
|
|
|
if page:
|
|
|
|
yield page
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
def execute_batch(cur, sql, argslist, page_size=100):
|
2017-02-07 14:36:37 +03:00
|
|
|
r"""Execute groups of statements in fewer server roundtrips.
|
2017-02-01 04:59:47 +03:00
|
|
|
|
|
|
|
Execute *sql* several times, against all parameters set (sequences or
|
|
|
|
mappings) found in *argslist*.
|
|
|
|
|
2017-02-02 19:02:33 +03:00
|
|
|
The function is semantically similar to
|
|
|
|
|
|
|
|
.. parsed-literal::
|
|
|
|
|
|
|
|
*cur*\.\ `~cursor.executemany`\ (\ *sql*\ , *argslist*\ )
|
|
|
|
|
|
|
|
but has a different implementation: Psycopg will join the statements into
|
|
|
|
fewer multi-statement commands, each one containing at most *page_size*
|
|
|
|
statements, resulting in a reduced number of server roundtrips.
|
2017-02-01 04:59:47 +03:00
|
|
|
|
2017-08-31 18:34:04 +03:00
|
|
|
After the execution of the function the `cursor.rowcount` property will
|
2017-03-28 12:37:04 +03:00
|
|
|
**not** contain a total result.
|
|
|
|
|
2017-02-01 04:59:47 +03:00
|
|
|
"""
|
|
|
|
for page in _paginate(argslist, page_size=page_size):
|
|
|
|
sqls = [cur.mogrify(sql, args) for args in page]
|
2017-02-01 05:36:54 +03:00
|
|
|
cur.execute(b";".join(sqls))
|
2017-02-01 04:59:47 +03:00
|
|
|
|
|
|
|
|
|
|
|
def execute_values(cur, sql, argslist, template=None, page_size=100):
|
|
|
|
'''Execute a statement using :sql:`VALUES` with a sequence of parameters.
|
|
|
|
|
2017-02-02 19:02:33 +03:00
|
|
|
:param cur: the cursor to use to execute the query.
|
2017-02-01 04:59:47 +03:00
|
|
|
|
2017-02-02 19:02:33 +03:00
|
|
|
:param sql: the query to execute. It must contain a single ``%s``
|
|
|
|
placeholder, which will be replaced by a `VALUES list`__.
|
|
|
|
Example: ``"INSERT INTO mytable (id, f1, f2) VALUES %s"``.
|
2017-02-01 04:59:47 +03:00
|
|
|
|
2017-02-02 19:02:33 +03:00
|
|
|
:param argslist: sequence of sequences or dictionaries with the arguments
|
|
|
|
to send to the query. The type and content must be consistent with
|
|
|
|
*template*.
|
|
|
|
|
|
|
|
:param template: the snippet to merge to every item in *argslist* to
|
2017-08-31 18:34:04 +03:00
|
|
|
compose the query.
|
|
|
|
|
|
|
|
- If the *argslist* items are sequences it should contain positional
|
|
|
|
placeholders (e.g. ``"(%s, %s, %s)"``, or ``"(%s, %s, 42)``" if there
|
|
|
|
are constants value...).
|
|
|
|
|
|
|
|
- If the *argslist* items are mappings it should contain named
|
|
|
|
placeholders (e.g. ``"(%(id)s, %(f1)s, 42)"``).
|
|
|
|
|
2017-02-02 19:02:33 +03:00
|
|
|
If not specified, assume the arguments are sequence and use a simple
|
|
|
|
positional template (i.e. ``(%s, %s, ...)``), with the number of
|
|
|
|
placeholders sniffed by the first element in *argslist*.
|
|
|
|
|
|
|
|
:param page_size: maximum number of *argslist* items to include in every
|
|
|
|
statement. If there are more items the function will execute more than
|
|
|
|
one statement.
|
|
|
|
|
|
|
|
.. __: https://www.postgresql.org/docs/current/static/queries-values.html
|
2017-02-01 04:59:47 +03:00
|
|
|
|
2017-08-31 18:34:04 +03:00
|
|
|
After the execution of the function the `cursor.rowcount` property will
|
2017-03-28 12:37:04 +03:00
|
|
|
**not** contain a total result.
|
|
|
|
|
2017-02-01 04:59:47 +03:00
|
|
|
While :sql:`INSERT` is an obvious candidate for this function it is
|
|
|
|
possible to use it with other statements, for example::
|
|
|
|
|
|
|
|
>>> cur.execute(
|
|
|
|
... "create table test (id int primary key, v1 int, v2 int)")
|
|
|
|
|
|
|
|
>>> execute_values(cur,
|
|
|
|
... "INSERT INTO test (id, v1, v2) VALUES %s",
|
|
|
|
... [(1, 2, 3), (4, 5, 6), (7, 8, 9)])
|
|
|
|
|
|
|
|
>>> execute_values(cur,
|
|
|
|
... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1)
|
|
|
|
... WHERE test.id = data.id""",
|
|
|
|
... [(1, 20), (4, 50)])
|
|
|
|
|
|
|
|
>>> cur.execute("select * from test order by id")
|
|
|
|
>>> cur.fetchall()
|
|
|
|
[(1, 20, 3), (4, 50, 6), (7, 8, 9)])
|
|
|
|
|
|
|
|
'''
|
2017-02-02 20:29:17 +03:00
|
|
|
# we can't just use sql % vals because vals is bytes: if sql is bytes
|
|
|
|
# there will be some decoding error because of stupid codec used, and Py3
|
|
|
|
# doesn't implement % on bytes.
|
|
|
|
if not isinstance(sql, bytes):
|
|
|
|
sql = sql.encode(_ext.encodings[cur.connection.encoding])
|
|
|
|
pre, post = _split_sql(sql)
|
|
|
|
|
2017-02-01 04:59:47 +03:00
|
|
|
for page in _paginate(argslist, page_size=page_size):
|
|
|
|
if template is None:
|
2017-02-02 20:42:06 +03:00
|
|
|
template = b'(' + b','.join([b'%s'] * len(page[0])) + b')'
|
|
|
|
parts = pre[:]
|
2017-02-02 20:29:17 +03:00
|
|
|
for args in page:
|
|
|
|
parts.append(cur.mogrify(template, args))
|
|
|
|
parts.append(b',')
|
2017-02-02 20:42:06 +03:00
|
|
|
parts[-1:] = post
|
2017-02-02 20:29:17 +03:00
|
|
|
cur.execute(b''.join(parts))
|
|
|
|
|
|
|
|
|
|
|
|
def _split_sql(sql):
|
|
|
|
"""Split *sql* on a single ``%s`` placeholder.
|
|
|
|
|
2017-02-02 20:42:06 +03:00
|
|
|
Split on the %s, perform %% replacement and return pre, post lists of
|
|
|
|
snippets.
|
2017-02-02 20:29:17 +03:00
|
|
|
"""
|
|
|
|
curr = pre = []
|
|
|
|
post = []
|
|
|
|
tokens = _re.split(br'(%.)', sql)
|
|
|
|
for token in tokens:
|
|
|
|
if len(token) != 2 or token[:1] != b'%':
|
|
|
|
curr.append(token)
|
|
|
|
continue
|
|
|
|
|
|
|
|
if token[1:] == b's':
|
|
|
|
if curr is pre:
|
|
|
|
curr = post
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
"the query contains more than one '%s' placeholder")
|
|
|
|
elif token[1:] == b'%':
|
|
|
|
curr.append(b'%')
|
|
|
|
else:
|
|
|
|
raise ValueError("unsupported format character: '%s'"
|
|
|
|
% token[1:].decode('ascii', 'replace'))
|
|
|
|
|
|
|
|
if curr is pre:
|
|
|
|
raise ValueError("the query doesn't contain any '%s' placeholder")
|
|
|
|
|
2017-02-02 20:42:06 +03:00
|
|
|
return pre, post
|