2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
8 import psycopg2.extensions
9 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
10 # UNICODEARRAY not exported yet
11 psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY)
14 from types import StringTypes, NoneType
18 from pprint import pformat
20 from sfa.util.faults import *
21 from sfa.util.debug import *
24 is8bit = re.compile("[\x80-\xff]").search
26 def unicast(typecast):
28 pgdb returns raw UTF-8 strings. This function casts strings that
29 apppear to contain non-ASCII characters to unicode objects.
32 def wrapper(*args, **kwds):
33 value = typecast(*args, **kwds)
35 # pgdb always encodes unicode objects as UTF-8 regardless of
36 # the DB encoding (and gives you no option for overriding
37 # the encoding), so always decode 8-bit objects as UTF-8.
38 if isinstance(value, str) and is8bit(value):
39 value = unicode(value, "utf-8")
45 pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
48 def __init__(self, config):
52 self.connection = None
55 if self.connection is None:
56 # (Re)initialize database connection
59 # Try UNIX socket first
60 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
61 password = self.config.SFA_PLC_DB_PASSWORD,
62 database = self.config.SFA_PLC_DB_NAME)
63 except psycopg2.OperationalError:
65 self.connection = psycopg2.connect(user = self.config.SFA_PLC_DB_USER,
66 password = self.config.SFA_PLC_DB_PASSWORD,
67 database = self.config.SFA_PLC_DB_NAME,
68 host = self.config.SFA_PLC_DB_HOST,
69 port = self.config.SFA_PLC_DB_PORT)
70 self.connection.set_client_encoding("UNICODE")
72 self.connection = pgdb.connect(user = self.config.SFA_PLC_DB_USER,
73 password = self.config.SFA_PLC_DB_PASSWORD,
74 host = "%s:%d" % (self.config.SFA_PLC_DB_HOST, self.config.SFA_PLC_DB_PORT),
75 database = self.config.SFA_PLC_DB_NAME)
77 (self.rowcount, self.description, self.lastrowid) = \
80 return self.connection.cursor()
83 if self.connection is not None:
84 self.connection.close()
85 self.connection = None
87 def quote(self, value):
89 Returns quoted version of the specified value.
92 # The pgdb._quote function is good enough for general SQL
93 # quoting, except for array types.
94 if isinstance(value, (list, tuple, set)):
95 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
97 return pgdb._quote(value)
99 quote = classmethod(quote)
101 def param(self, name, value):
102 # None is converted to the unquoted string NULL
103 if isinstance(value, NoneType):
105 # True and False are also converted to unquoted strings
106 elif isinstance(value, bool):
108 elif isinstance(value, float):
110 elif not isinstance(value, StringTypes):
115 return '%(' + name + ')' + conversion
117 param = classmethod(param)
119 def begin_work(self):
120 # Implicit in pgdb.connect()
124 self.connection.commit()
127 self.connection.rollback()
129 def do(self, query, params = None):
130 cursor = self.execute(query, params)
134 def next_id(self, table_name, primary_key):
135 sequence = "%(table_name)s_%(primary_key)s_seq" % locals()
136 sql = "SELECT nextval('%(sequence)s')" % locals()
137 rows = self.selectall(sql, hashref = False)
143 def last_insert_id(self, table_name, primary_key):
144 if isinstance(self.lastrowid, int):
145 sql = "SELECT %s FROM %s WHERE oid = %d" % \
146 (primary_key, table_name, self.lastrowid)
147 rows = self.selectall(sql, hashref = False)
153 # modified for psycopg2-2.0.7
154 # executemany is undefined for SELECT's
155 # see http://www.python.org/dev/peps/pep-0249/
156 # accepts either None, a single dict, a tuple of single dict - in which case it execute's
157 # or a tuple of several dicts, in which case it executemany's
158 def execute(self, query, params = None):
160 cursor = self.cursor()
163 # psycopg2 requires %()s format for all parameters,
164 # regardless of type.
165 # this needs to be done carefully though as with pattern-based filters
166 # we might have percents embedded in the query
167 # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
169 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
170 # rewrite wildcards set by Filter.py as '***' into '%'
171 query = query.replace ('***','%')
175 print >> log,'execute0',query
176 cursor.execute(query)
177 elif isinstance(params,dict):
179 print >> log,'execute-dict: params',params,'query',query%params
180 cursor.execute(query,params)
181 elif isinstance(params,tuple) and len(params)==1:
183 print >> log,'execute-tuple',query%params[0]
184 cursor.execute(query,params[0])
188 for params in param_seq:
189 print >> log,'executemany',query%params
190 cursor.executemany(query, param_seq)
191 (self.rowcount, self.description, self.lastrowid) = \
192 (cursor.rowcount, cursor.description, cursor.lastrowid)
198 uuid = commands.getoutput("uuidgen")
199 print >> log, "Database error %s:" % uuid
201 print >> log, "Query:"
203 print >> log, "Params:"
204 print >> log, pformat(params)
205 raise GeniDBError("Please contact support")
209 def selectall(self, query, params = None, hashref = True, key_field = None):
211 Return each row as a dictionary keyed on field name (like DBI
212 selectrow_hashref()). If key_field is specified, return rows
213 as a dictionary keyed on the specified field (like DBI
214 selectall_hashref()).
216 If params is specified, the specified parameters will be bound
220 cursor = self.execute(query, params)
221 rows = cursor.fetchall()
224 if hashref or key_field is not None:
225 # Return each row as a dictionary keyed on field name
226 # (like DBI selectrow_hashref()).
227 labels = [column[0] for column in self.description]
228 rows = [dict(zip(labels, row)) for row in rows]
230 if key_field is not None and key_field in labels:
231 # Return rows as a dictionary keyed on the specified field
232 # (like DBI selectall_hashref()).
233 return dict([(row[key_field], row) for row in rows])
237 def fields(self, table, notnull = None, hasdef = None):
239 Return the names of the fields of the specified table.
242 if hasattr(self, 'fields_cache'):
243 if self.fields_cache.has_key((table, notnull, hasdef)):
244 return self.fields_cache[(table, notnull, hasdef)]
246 self.fields_cache = {}
248 sql = "SELECT attname FROM pg_attribute, pg_class" \
249 " WHERE pg_class.oid = attrelid" \
250 " AND attnum > 0 AND relname = %(table)s"
252 if notnull is not None:
253 sql += " AND attnotnull is %(notnull)s"
255 if hasdef is not None:
256 sql += " AND atthasdef is %(hasdef)s"
258 rows = self.selectall(sql, locals(), hashref = False)
260 self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
262 return self.fields_cache[(table, notnull, hasdef)]