2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
8 # $Id: PostgreSQL.py,v 1.9 2006/11/08 22:43:02 mlhuang Exp $
12 import psycopg2.extensions
13 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
16 from types import StringTypes, NoneType
20 from pprint import pformat
22 from PLC.Debug import profile, log
23 from PLC.Faults import *
26 is8bit = re.compile("[\x80-\xff]").search
28 def unicast(typecast):
30 pgdb returns raw UTF-8 strings. This function casts strings that
31 appear to contain non-ASCII characters to unicode objects.
34 def wrapper(*args, **kwds):
35 value = typecast(*args, **kwds)
37 # pgdb always encodes unicode objects as UTF-8 regardless of
38 # the DB encoding (and gives you no option for overriding
39 # the encoding), so always decode 8-bit objects as UTF-8.
40 if isinstance(value, str) and is8bit(value):
41 value = unicode(value, "utf-8")
47 pgdb.pgdbTypeCache.typecast = unicast(pgdb.pgdbTypeCache.typecast)
50 def __init__(self, api):
53 # Initialize database connection
56 # Try UNIX socket first
57 self.db = psycopg2.connect(user = api.config.PLC_DB_USER,
58 password = api.config.PLC_DB_PASSWORD,
59 database = api.config.PLC_DB_NAME)
60 except psycopg2.OperationalError:
62 self.db = psycopg2.connect(user = api.config.PLC_DB_USER,
63 password = api.config.PLC_DB_PASSWORD,
64 database = api.config.PLC_DB_NAME,
65 host = api.config.PLC_DB_HOST,
66 port = api.config.PLC_DB_PORT)
67 self.db.set_client_encoding("UNICODE")
69 self.db = pgdb.connect(user = api.config.PLC_DB_USER,
70 password = api.config.PLC_DB_PASSWORD,
71 host = "%s:%d" % (api.config.PLC_DB_HOST, api.config.PLC_DB_PORT),
72 database = api.config.PLC_DB_NAME)
74 self.cursor = self.db.cursor()
76 (self.rowcount, self.description, self.lastrowid) = \
79 def quote(self, value):
81 Returns quoted version of the specified value.
84 # The pgdb._quote function is good enough for general SQL
85 # quoting, except for array types.
86 if isinstance(value, (list, tuple, set)):
87 return "ARRAY[%s]" % ", ".join(map, self.quote, value)
89 return pgdb._quote(value)
91 quote = classmethod(quote)
93 def param(self, name, value):
94 # None is converted to the unquoted string NULL
95 if isinstance(value, NoneType):
97 # True and False are also converted to unquoted strings
98 elif isinstance(value, bool):
100 elif isinstance(value, float):
102 elif not isinstance(value, StringTypes):
107 return '%(' + name + ')' + conversion
109 param = classmethod(param)
111 def begin_work(self):
112 # Implicit in pgdb.connect()
121 def do(self, query, params = None):
122 self.execute(query, params)
125 def last_insert_id(self, table_name, primary_key):
126 if isinstance(self.lastrowid, int):
127 sql = "SELECT %s FROM %s WHERE oid = %d" % \
128 (primary_key, table_name, self.lastrowid)
129 rows = self.selectall(sql, hashref = False)
135 def execute(self, query, params = None):
136 self.execute_array(query, (params,))
138 def execute_array(self, query, param_seq):
141 # psycopg2 requires %()s format for all parameters,
142 # regardless of type.
144 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
146 cursor.executemany(query, param_seq)
147 (self.rowcount, self.description, self.lastrowid) = \
148 (cursor.rowcount, cursor.description, cursor.lastrowid)
154 uuid = commands.getoutput("uuidgen")
155 print >> log, "Database error %s:" % uuid
157 print >> log, "Query:"
159 print >> log, "Params:"
160 print >> log, pformat(param_seq[0])
161 raise PLCDBError("Please contact " + \
162 self.api.config.PLC_NAME + " Support " + \
163 "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
164 " and reference " + uuid)
166 def selectall(self, query, params = None, hashref = True, key_field = None):
168 Return each row as a dictionary keyed on field name (like DBI
169 selectrow_hashref()). If key_field is specified, return rows
170 as a dictionary keyed on the specified field (like DBI
171 selectall_hashref()).
173 If params is specified, the specified parameters will be bound
174 to the query (see PLC.DB.parameterize() and
175 pgdb.cursor.execute()).
178 self.execute(query, params)
179 rows = self.cursor.fetchall()
181 if hashref or key_field is not None:
182 # Return each row as a dictionary keyed on field name
183 # (like DBI selectrow_hashref()).
184 labels = [column[0] for column in self.description]
185 rows = [dict(zip(labels, row)) for row in rows]
187 if key_field is not None and key_field in labels:
188 # Return rows as a dictionary keyed on the specified field
189 # (like DBI selectall_hashref()).
190 return dict([(row[key_field], row) for row in rows])
194 def fields(self, table, notnull = None, hasdef = None):
196 Return the names of the fields of the specified table.
199 sql = "SELECT attname FROM pg_attribute, pg_class" \
200 " WHERE pg_class.oid = attrelid" \
201 " AND attnum > 0 AND relname = %(table)s"
203 if notnull is not None:
204 sql += " AND attnotnull is %(notnull)s"
206 if hasdef is not None:
207 sql += " AND atthasdef is %(hasdef)s"
209 rows = self.selectall(sql, locals(), hashref = False)
211 return [row[0] for row in rows]