accept sets when quoting
[plcapi.git] / PLC / PostgreSQL.py
1 #
2 # PostgreSQL database interface. Sort of like DBI(3) (Database
3 # independent interface for Perl).
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: PostgreSQL.py,v 1.6 2006/10/20 17:53:42 mlhuang Exp $
9 #
10
11 import pgdb
12 from types import StringTypes, NoneType
13 import traceback
14 import commands
15 from pprint import pformat
16
17 from PLC.Debug import profile, log
18 from PLC.Faults import *
19
20 class PostgreSQL:
21     def __init__(self, api):
22         self.api = api
23
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 = "planetlab4") # XXX api.config.PLC_DB_NAME)
29         self.cursor = self.db.cursor()
30
31         (self.rowcount, self.description, self.lastrowid) = \
32                         (None, None, None)
33
34     def quote(self, params):
35         """
36         Returns quoted version(s) of the specified parameter(s).
37         """
38
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) or isinstance(params, set):
43             params = map(pgdb._quote, params)
44         else:
45             params = pgdb._quote(params)
46
47         return params
48
49     quote = classmethod(quote)
50
51     def param(self, name, value):
52         # None is converted to the unquoted string NULL
53         if isinstance(value, NoneType):
54             conversion = "s"
55         # True and False are also converted to unquoted strings
56         elif isinstance(value, bool):
57             conversion = "s"
58         elif isinstance(value, float):
59             conversion = "f"
60         elif not isinstance(value, StringTypes):
61             conversion = "d"
62         else:
63             conversion = "s"
64
65         return '%(' + name + ')' + conversion
66
67     param = classmethod(param)
68
69     def begin_work(self):
70         # Implicit in pgdb.connect()
71         pass
72
73     def commit(self):
74         self.db.commit()
75
76     def rollback(self):
77         self.db.rollback()
78
79     def do(self, query, params = None):
80         self.execute(query, params)
81         return self.rowcount
82
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)
88             if rows:
89                 return rows[0][0]
90
91         return None
92
93     def execute(self, query, params = None):
94         self.execute_array(query, (params,))
95
96     def execute_array(self, query, param_seq):
97         cursor = self.cursor
98         try:
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:
103             try:
104                 self.rollback()
105             except:
106                 pass
107             uuid = commands.getoutput("uuidgen")
108             print >> log, "Database error %s:" % uuid
109             print >> log, e
110             print >> log, "Query:"
111             print >> log, query
112             print >> log, "Params:"
113             print >> log, pformat(param_seq[0])
114             raise PLCDBError("Please contact " + \
115                              self.api.config.PLC_NAME + " Support " + \
116                              "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
117                              " and reference " + uuid)
118
119     def selectall(self, query, params = None, hashref = True, key_field = None):
120         """
121         Return each row as a dictionary keyed on field name (like DBI
122         selectrow_hashref()). If key_field is specified, return rows
123         as a dictionary keyed on the specified field (like DBI
124         selectall_hashref()).
125
126         If params is specified, the specified parameters will be bound
127         to the query (see PLC.DB.parameterize() and
128         pgdb.cursor.execute()).
129         """
130
131         self.execute(query, params)
132         rows = self.cursor.fetchall()
133
134         if hashref:
135             # Return each row as a dictionary keyed on field name
136             # (like DBI selectrow_hashref()).
137             labels = [column[0] for column in self.description]
138             rows = [dict(zip(labels, row)) for row in rows]
139
140         if key_field is not None and key_field in labels:
141             # Return rows as a dictionary keyed on the specified field
142             # (like DBI selectall_hashref()).
143             return dict([(row[key_field], row) for row in rows])
144         else:
145             return rows
146
147     def fields(self, table, notnull = None, hasdef = None):
148         """
149         Return the names of the fields of the specified table.
150         """
151
152         sql = "SELECT attname FROM pg_attribute, pg_class" \
153               " WHERE pg_class.oid = attrelid" \
154               " AND attnum > 0 AND relname = %(table)s"
155
156         if notnull is not None:
157             sql += " AND attnotnull is %(notnull)s"
158
159         if hasdef is not None:
160             sql += " AND atthasdef is %(hasdef)s"
161
162         rows = self.selectall(sql, locals(), hashref = False)
163
164         return [row[0] for row in rows]