that one was hard to pinpoint: we DON'T want to convert str to bytes, when normalizin...
[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             x = x.replace("\\", "\\\\").replace("'", "''")
72             x = f"'{x}'"
73         elif isinstance(x, (int, float)):
74             pass
75         elif x is None:
76             x = 'NULL'
77         elif isinstance(x, (list, tuple, set)):
78             x = 'ARRAY[%s]' % ', '.join([str(PostgreSQL._quote(x)) for x in x])
79         elif hasattr(x, '__pg_repr__'):
80             x = x.__pg_repr__()
81         else:
82             raise PLCDBError('Cannot quote type %s' % type(x))
83         return x
84
85
86     def quote(self, value):
87         """
88         Returns quoted version of the specified value.
89         """
90         return PostgreSQL._quote(value)
91
92 # following is an unsuccessful attempt to re-use lib code as much as possible
93 #    def quote(self, value):
94 #        # The pgdb._quote function is good enough for general SQL
95 #        # quoting, except for array types.
96 #        if isinstance (value, (types.ListType, types.TupleType, set)):
97 #            'ARRAY[%s]' % ', '.join( [ str(self.quote(x)) for x in value ] )
98 #        else:
99 #            try:
100 #                # up to PyGreSQL-3.x, function was pgdb._quote
101 #                import pgdb
102 #                return pgdb._quote(value)
103 #            except:
104 #                # with PyGreSQL-4.x, use psycopg2's adapt
105 #                from psycopg2.extensions import adapt
106 #                return adapt (value)
107
108     @classmethod
109     def param(cls, name, value):
110         # None is converted to the unquoted string NULL
111         if isinstance(value, type(None)):
112             conversion = "s"
113         # True and False are also converted to unquoted strings
114         elif isinstance(value, bool):
115             conversion = "s"
116         elif isinstance(value, float):
117             conversion = "f"
118         elif not isinstance(value, str):
119             conversion = "d"
120         else:
121             conversion = "s"
122
123         return '%(' + name + ')' + conversion
124
125     def begin_work(self):
126         # Implicit in pgdb.connect()
127         pass
128
129     def commit(self):
130         self.connection.commit()
131
132     def rollback(self):
133         self.connection.rollback()
134
135     def do(self, query, params=None):
136         cursor = self.execute(query, params)
137         cursor.close()
138         return self.rowcount
139
140     def next_id(self, table_name, primary_key):
141         sequence = "{}_{}_seq".format(table_name, primary_key)
142         sql = "SELECT nextval('{}')".format(sequence)
143         rows = self.selectall(sql, hashref=False)
144         if rows:
145             return rows[0][0]
146         return None
147
148     def last_insert_id(self, table_name, primary_key):
149         if isinstance(self.lastrowid, int):
150             sql = "SELECT %s FROM %s WHERE oid = %d" % \
151                   (primary_key, table_name, self.lastrowid)
152             rows = self.selectall(sql, hashref=False)
153             if rows:
154                 return rows[0][0]
155
156         return None
157
158     # modified for psycopg2-2.0.7
159     # executemany is undefined for SELECT's
160     # see http://www.python.org/dev/peps/pep-0249/
161     # accepts either None, a single dict, a tuple of single dict - in which case it execute's
162     # or a tuple of several dicts, in which case it executemany's
163     def execute(self, query, params=None):
164
165         cursor = self.cursor()
166         try:
167
168             # psycopg2 requires %()s format for all parameters,
169             # regardless of type.
170             # this needs to be done carefully though as with pattern-based filters
171             # we might have percents embedded in the query
172             # so e.g. GetPersons({'email':'*fake*'}) was resulting in .. LIKE '%sake%'
173             if psycopg2:
174                 query = re.sub(r'(%\([^)]*\)|%)[df]', r'\1s', query)
175             # rewrite wildcards set by Filter.py as '***' into '%'
176             query = query.replace('***', '%')
177
178             if not params:
179                 if self.debug:
180                     logger.debug('execute0: {}'.format(query))
181                 cursor.execute(query)
182             elif isinstance(params, dict):
183                 if self.debug:
184                     logger.debug('execute-dict: params {} query {}'
185                                  .format(params, query%params))
186                 cursor.execute(query, params)
187             elif isinstance(params, tuple) and len(params) == 1:
188                 if self.debug:
189                     logger.debug('execute-tuple {}'.format(query%params[0]))
190                 cursor.execute(query, params[0])
191             else:
192                 param_seq = (params,)
193                 if self.debug:
194                     for params in param_seq:
195                         logger.debug('executemany {}'.format(query%params))
196                 cursor.executemany(query, param_seq)
197             (self.rowcount, self.description, self.lastrowid) = \
198                             (cursor.rowcount, cursor.description, cursor.lastrowid)
199         except Exception as e:
200             try:
201                 self.rollback()
202             except:
203                 pass
204             uuid = subprocess.getoutput("uuidgen")
205             message = "Database error {}: - Query {} - Params {}".format(uuid, query, pformat(params))
206             logger.exception(message)
207             raise PLCDBError("Please contact " + \
208                              self.api.config.PLC_NAME + " Support " + \
209                              "<" + self.api.config.PLC_MAIL_SUPPORT_ADDRESS + ">" + \
210                              " and reference " + uuid)
211
212         return cursor
213
214     def selectall(self, query, params=None, hashref=True, key_field=None):
215         """
216         Return each row as a dictionary keyed on field name (like DBI
217         selectrow_hashref()). If key_field is specified, return rows
218         as a dictionary keyed on the specified field (like DBI
219         selectall_hashref()).
220
221         If params is specified, the specified parameters will be bound
222         to the query.
223         """
224
225         cursor = self.execute(query, params)
226         rows = cursor.fetchall()
227         cursor.close()
228         self.commit()
229         if hashref or key_field is not None:
230             # Return each row as a dictionary keyed on field name
231             # (like DBI selectrow_hashref()).
232             labels = [column[0] for column in self.description]
233             rows = [dict(list(zip(labels, row))) for row in rows]
234
235         if key_field is not None and key_field in labels:
236             # Return rows as a dictionary keyed on the specified field
237             # (like DBI selectall_hashref()).
238             return {row[key_field]: row for row in rows}
239         else:
240             return rows
241
242     def fields(self, table, notnull=None, hasdef=None):
243         """
244         Return the names of the fields of the specified table.
245         """
246
247         if hasattr(self, 'fields_cache'):
248             if (table, notnull, hasdef) in self.fields_cache:
249                 return self.fields_cache[(table, notnull, hasdef)]
250         else:
251             self.fields_cache = {}
252
253         sql = "SELECT attname FROM pg_attribute, pg_class" \
254               " WHERE pg_class.oid = attrelid" \
255               " AND attnum > 0 AND relname = %(table)s"
256
257         if notnull is not None:
258             sql += " AND attnotnull is %(notnull)s"
259
260         if hasdef is not None:
261             sql += " AND atthasdef is %(hasdef)s"
262
263         rows = self.selectall(sql, locals(), hashref=False)
264
265         self.fields_cache[(table, notnull, hasdef)] = [row[0] for row in rows]
266
267         return self.fields_cache[(table, notnull, hasdef)]