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.3 2006/10/03 19:27:07 mlhuang Exp $
12 from types import StringTypes, NoneType
15 from pprint import pformat
17 from PLC.Debug import profile, log
18 from PLC.Faults import *
21 def __init__(self, api):
24 # Initialize database connection
25 self.db = pgdb.connect(user = api.config.PLC_DB_USER,
26 password = api.config.PLC_DB_PASSWORD,
27 host = "%s:%d" % (api.config.PLC_DB_HOST, api.config.PLC_DB_PORT),
28 database = api.config.PLC_DB_NAME)
29 self.cursor = self.db.cursor()
31 (self.rowcount, self.description, self.lastrowid) = \
34 def quote(self, params):
36 Returns quoted version(s) of the specified parameter(s).
39 # pgdb._quote functions are good enough for general SQL quoting
40 if hasattr(params, 'has_key'):
41 params = pgdb._quoteitem(params)
42 elif isinstance(params, list) or isinstance(params, tuple):
43 params = map(pgdb._quote, params)
45 params = pgdb._quote(params)
49 quote = classmethod(quote)
51 def param(self, name, value):
52 # None is converted to the unquoted string NULL
53 if isinstance(value, NoneType):
55 # True and False are also converted to unquoted strings
56 elif isinstance(value, bool):
58 elif isinstance(value, float):
60 elif not isinstance(value, StringTypes):
65 return '%(' + name + ')' + conversion
67 param = classmethod(param)
70 # Implicit in pgdb.connect()
79 def do(self, query, params = None):
80 self.execute(query, params)
83 def last_insert_id(self, table_name, primary_key):
84 if isinstance(self.lastrowid, int):
85 sql = "SELECT %s FROM %s WHERE oid = %d" % \
86 (primary_key, table_name, self.lastrowid)
87 rows = self.selectall(sql, hashref = False)
93 def execute(self, query, params = None):
94 self.execute_array(query, (params,))
96 def execute_array(self, query, param_seq):
99 cursor.executemany(query, param_seq)
100 (self.rowcount, self.description, self.lastrowid) = \
101 (cursor.rowcount, cursor.description, cursor.lastrowid)
102 except pgdb.DatabaseError, e:
105 uuid = commands.getoutput("uuidgen")
106 print >> log, "Database error %s:" % uuid
108 print >> log, "Query:"
110 print >> log, "Params:"
111 print >> log, pformat(param_seq[0])
112 raise PLCDBError("Please contact " + \
113 self.api.config.PLC_NAME + " Support " + \
114 "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
115 " and reference " + uuid)
117 def selectall(self, query, params = None, hashref = True, key_field = None):
119 Return each row as a dictionary keyed on field name (like DBI
120 selectrow_hashref()). If key_field is specified, return rows
121 as a dictionary keyed on the specified field (like DBI
122 selectall_hashref()).
124 If params is specified, the specified parameters will be bound
125 to the query (see PLC.DB.parameterize() and
126 pgdb.cursor.execute()).
129 self.execute(query, params)
130 rows = self.cursor.fetchall()
133 # Return each row as a dictionary keyed on field name
134 # (like DBI selectrow_hashref()).
135 labels = [column[0] for column in self.description]
136 rows = [dict(zip(labels, row)) for row in rows]
138 if key_field is not None and key_field in labels:
139 # Return rows as a dictionary keyed on the specified field
140 # (like DBI selectall_hashref()).
141 return dict([(row[key_field], row) for row in rows])
145 def fields(self, table, notnull = None, hasdef = None):
147 Return the names of the fields of the specified table.
150 sql = "SELECT attname FROM pg_attribute, pg_class" \
151 " WHERE pg_class.oid = attrelid" \
152 " AND attnum > 0 AND relname = %(table)s"
154 if notnull is not None:
155 sql += " AND attnotnull is %(notnull)s"
157 if hasdef is not None:
158 sql += " AND atthasdef is %(hasdef)s"
160 rows = self.selectall(sql, locals(), hashref = False)
162 return [row[0] for row in rows]