merge upstream phpxmlrpc
[plcapi.git] / PLC / PostgreSQL.py
1 #
2 # PostgreSQL database interface.
3 # Sort of like DBI(3) (Database independent interface for Perl).
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # pylint: disable=c0103, c0111
9
10 import subprocess
11 import re
12 from pprint import pformat
13 from datetime import datetime as DateTimeType
14
15 import psycopg2
16 import psycopg2.extensions
17 psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
18 # UNICODEARRAY not exported yet
19 psycopg2.extensions.register_type(psycopg2._psycopg.UNICODEARRAY)
20
21 from PLC.Logger import logger
22 #from PLC.Debug import profile
23 from PLC.Faults import *
24
25 class PostgreSQL:
26     def __init__(self, api):
27         self.api = api
28         self.debug = False
29 #        self.debug = True
30         self.connection = None
31
32     def cursor(self):
33         if self.connection is None:
34             # (Re)initialize database connection
35             try:
36                 # Try UNIX socket first
37                 self.connection = psycopg2.connect(
38                     user=self.api.config.PLC_DB_USER,
39                     password=self.api.config.PLC_DB_PASSWORD,
40                     database=self.api.config.PLC_DB_NAME)
41             except psycopg2.OperationalError:
42                 # Fall back on TCP
43                 self.connection = psycopg2.connect(
44                     user=self.api.config.PLC_DB_USER,
45                     password=self.api.config.PLC_DB_PASSWORD,
46                     database=self.api.config.PLC_DB_NAME,
47                     host=self.api.config.PLC_DB_HOST,
48                     port=self.api.config.PLC_DB_PORT)
49             self.connection.set_client_encoding("UNICODE")
50
51         (self.rowcount, self.description, self.lastrowid) = \
52                         (None, None, None)
53
54         return self.connection.cursor()
55
56     def close(self):
57         if self.connection is not None:
58             self.connection.close()
59             self.connection = None
60
61     @staticmethod
62     # From pgdb, and simplify code
63     # this is **very different** from the python2 code !
64     def _quote(x):
65         if isinstance(x, DateTimeType):
66             x = str(x)
67         elif isinstance(x, bytes):
68             x = x.decode('utf-8')
69
70         if isinstance(x, str):
71         # don't double quote backslahes, this causes failure
72         # with e.g. the SFA code when it tries to spot slices
73         # created from fed4fire, which to my knowledge is the only
74         # place where a backslash is useful
75         #    x = x.replace("\\", "\\\\")
76             x = x.replace("'", "''")
77             x = f"'{x}'"
78         elif isinstance(x, (int, float)):
79             pass
80         elif x is None:
81             x = 'NULL'
82         elif isinstance(x, (list, tuple, set)):
83             x = 'ARRAY[%s]' % ', '.join([str(PostgreSQL._quote(x)) for x in x])
84         elif hasattr(x, '__pg_repr__'):
85             x = x.__pg_repr__()
86         else:
87             raise PLCDBError('Cannot quote type %s' % type(x))
88         return x
89
90
91     def quote(self, value):
92         """
93         Returns quoted version of the specified value.
94         """
95         return PostgreSQL._quote(value)
96
97 # following is an unsuccessful attempt to re-use lib code as much as possible
98 #    def quote(self, value):
99 #        # The pgdb._quote function is good enough for general SQL
100 #        # quoting, except for array types.
101 #        if isinstance (value, (types.ListType, types.TupleType, set)):
102 #            'ARRAY[%s]' % ', '.join( [ str(self.quote(x)) for x in value ] )
103 #        else:
104 #            try:
105 #                # up to PyGreSQL-3.x, function was pgdb._quote
106 #                import pgdb
107 #                return pgdb._quote(value)
108 #            except:
109 #                # with PyGreSQL-4.x, use psycopg2's adapt
110 #                from psycopg2.extensions import adapt
111 #                return adapt (value)
112
113     @classmethod
114     def param(cls, name, value):
115         # None is converted to the unquoted string NULL
116         if isinstance(value, type(None)):
117             conversion = "s"
118         # True and False are also converted to unquoted strings
119         elif isinstance(value, bool):
120             conversion = "s"
121         elif isinstance(value, float):
122             conversion = "f"
123         elif not isinstance(value, str):
124             conversion = "d"
125         else:
126             conversion = "s"
127
128         return '%(' + name + ')' + conversion
129
130     def begin_work(self):
131         # Implicit in pgdb.connect()
132         pass
133
134     def commit(self):
135         self.connection.commit()
136
137     def rollback(self):
138         self.connection.rollback()
139
140     def do(self, query, params=None):
141         cursor = self.execute(query, params)
142         cursor.close()
143         return self.rowcount
144
145     def next_id(self, table_name, primary_key):
146         sequence = "{}_{}_seq".format(table_name, primary_key)
147         sql = "SELECT nextval('{}')".format(sequence)
148         rows = self.selectall(sql, hashref=False)
149         if rows:
150             return rows[0][0]
151         return None
152
153     def last_insert_id(self, table_name, primary_key):
154         if isinstance(self.lastrowid, int):
155             sql = "SELECT %s FROM %s WHERE oid = %d" % \
156                   (primary_key, table_name, self.lastrowid)
157             rows = self.selectall(sql, hashref=False)
158             if rows:
159                 return rows[0][0]
160
161         return None
162
163     # modified for psycopg2-2.0.7
164     # executemany is undefined for SELECT's
165     # see http://www.python.org/dev/peps/pep-0249/
166     # accepts either None, a single dict, a tuple of single dict - in which case it execute's
167     # or a tuple of several dicts, in which case it executemany's
168     def execute(self, query, params=None):
169
170         cursor = self.cursor()
171         try:
172
173             # psycopg2 requires %()s format for all parameters,
174             # regardless of type.
175             # this needs to be done carefully though as with pattern-based filters
176             # we might have percents embedded in the query
177             # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
178             if psycopg2:
179                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
180             # rewrite wildcards set by Filter.py as '***' into '%'
181             query = query.replace('***', '%')
182
183             if not params:
184                 if self.debug:
185                     logger.debug('execute0: {}'.format(query))
186                 cursor.execute(query)
187             elif isinstance(params, dict):
188                 if self.debug:
189                     logger.debug('execute-dict: params {} query {}'
190                                  .format(params, query%params))
191                 cursor.execute(query, params)
192             elif isinstance(params, tuple) and len(params) == 1:
193                 if self.debug:
194                     logger.debug('execute-tuple {}'.format(query%params[0]))
195                 cursor.execute(query, params[0])
196             else:
197                 param_seq = (params,)
198                 if self.debug:
199                     for params in param_seq:
200                         logger.debug('executemany {}'.format(query%params))
201                 cursor.executemany(query, param_seq)
202             (self.rowcount, self.description, self.lastrowid) = \
203                             (cursor.rowcount, cursor.description, cursor.lastrowid)
204         except Exception as e:
205             try:
206                 self.rollback()
207             except:
208                 pass
209             uuid = subprocess.getoutput("uuidgen")
210             message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params))
211             logger.exception(message)
212             raise PLCDBError("Please contact " + \
213                              self.api.config.PLC_NAME + " Support " + \
214                              "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
215                              " and reference " + uuid)
216
217         return cursor
218
219     def selectall(self, query, params=None, hashref=True, key_field=None):
220         """
221         Return each row as a dictionary keyed on field name (like DBI
222         selectrow_hashref()). If key_field is specified, return rows
223         as a dictionary keyed on the specified field (like DBI
224         selectall_hashref()).
225
226         If params is specified, the specified parameters will be bound
227         to the query.
228         """
229
230         cursor = self.execute(query, params)
231         rows = cursor.fetchall()
232         cursor.close()
233         self.commit()
234         if hashref or key_field is not None:
235             # Return each row as a dictionary keyed on field name
236             # (like DBI selectrow_hashref()).
237             labels = [column[0] for column in self.description]
238             rows = [dict(list(zip(labels, row))) for row in rows]
239
240         if key_field is not None and key_field in labels:
241             # Return rows as a dictionary keyed on the specified field
242             # (like DBI selectall_hashref()).
243             return {row[key_field]: row for row in rows}
244         else:
245             return rows
246
247     def fields(self, table, notnull=None, hasdef=None):
248         """
249         Return the names of the fields of the specified table.
250         """
251
252         if hasattr(self, 'fields_cache'):
253             if (table, notnull, hasdef) in self.fields_cache:
254                 return self.fields_cache[(table, notnull, hasdef)]
255         else:
256             self.fields_cache = {}
257
258         sql = "SELECT attname FROM pg_attribute, pg_class" \
259               " WHERE pg_class.oid = attrelid" \
260               " AND attnum > 0 AND relname = %(table)s"
261
262         if notnull is not None:
263             sql += " AND attnotnull is %(notnull)s"
264
265         if hasdef is not None:
266             sql += " AND atthasdef is %(hasdef)s"
267
268         rows = self.selectall(sql, locals(), hashref=False)
269
270         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
271
272         return self.fields_cache[(table, notnull, hasdef)]