Skip to content
Navigation Menu
{{ message }}
forked from cs50/python-cs50
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.py
More file actions
544 lines (422 loc) · 19.5 KB
/
Copy pathsql.py
File metadata and controls
544 lines (422 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def _enable_logging(f):
"""Enable logging of SQL statements when Flask is in use."""
import logging
import functools
@functools.wraps(f)
def decorator(*args, **kwargs):
# Infer whether Flask is installed
try:
import flask
except ModuleNotFoundError:
return f(*args, **kwargs)
# Enable logging
disabled = logging.getLogger("cs50").disabled
if flask.current_app:
logging.getLogger("cs50").disabled = False
try:
return f(*args, **kwargs)
finally:
logging.getLogger("cs50").disabled = disabled
return decorator
class SQL(object):
"""Wrap SQLAlchemy to provide a simple SQL API."""
def __init__(self, url, **kwargs):
"""
Create instance of sqlalchemy.engine.Engine.
URL should be a string that indicates database dialect and connection arguments.
http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
http://docs.sqlalchemy.org/en/latest/dialects/index.html
"""
# Lazily import
import logging
import os
import re
import sqlalchemy
import sqlalchemy.orm
import sqlite3
# Require that file already exist for SQLite
matches = re.search(r"^sqlite:///(.+)$", url)
if matches:
if not os.path.exists(matches.group(1)):
raise RuntimeError("does not exist: {}".format(matches.group(1)))
if not os.path.isfile(matches.group(1)):
raise RuntimeError("not a file: {}".format(matches.group(1)))
# Create engine, disabling SQLAlchemy's own autocommit mode, raising exception if back end's module not installed
self._engine = sqlalchemy.create_engine(url, **kwargs).execution_options(autocommit=False)
# Get logger
self._logger = logging.getLogger("cs50")
# Listener for connections
def connect(dbapi_connection, connection_record):
# Disable underlying API's own emitting of BEGIN and COMMIT so we can ourselves
# https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl
dbapi_connection.isolation_level = None
# Enable foreign key constraints
if type(dbapi_connection) is sqlite3.Connection: # If back end is sqlite
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
# Register listener
sqlalchemy.event.listen(self._engine, "connect", connect)
# Autocommit by default
self._autocommit = True
# Test database
disabled = self._logger.disabled
self._logger.disabled = True
try:
self.execute("SELECT 1")
except sqlalchemy.exc.OperationalError as e:
e = RuntimeError(_parse_exception(e))
e.__cause__ = None
raise e
finally:
self._logger.disabled = disabled
def __del__(self):
"""Disconnect from database."""
self._disconnect()
def _disconnect(self):
"""Close database connection."""
if hasattr(self, "_session"):
self._session.remove()
delattr(self, "_session")
@_enable_logging
def execute(self, sql, *args, **kwargs):
"""Execute a SQL statement."""
# Lazily import
import decimal
import re
import sqlalchemy
import sqlparse
import termcolor
import warnings
# Parse statement, stripping comments and then leading/trailing whitespace
statements = sqlparse.parse(sqlparse.format(sql, keyword_case="upper", strip_comments=True).strip())
# Allow only one statement at a time, since SQLite doesn't support multiple
# https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute
if len(statements) > 1:
raise RuntimeError("too many statements at once")
elif len(statements) == 0:
raise RuntimeError("missing statement")
# Ensure named and positional parameters are mutually exclusive
if len(args) > 0 and len(kwargs) > 0:
raise RuntimeError("cannot pass both positional and named parameters")
# Infer command from (unflattened) statement
for token in statements[0]:
if token.ttype in [sqlparse.tokens.Keyword, sqlparse.tokens.Keyword.DDL, sqlparse.tokens.Keyword.DML]:
if token.value in ["BEGIN", "DELETE", "INSERT", "SELECT", "START", "UPDATE"]:
command = token.value
break
else:
command = None
# Flatten statement
tokens = list(statements[0].flatten())
# Validate paramstyle
placeholders = {}
paramstyle = None
for index, token in enumerate(tokens):
# If token is a placeholder
if token.ttype == sqlparse.tokens.Name.Placeholder:
# Determine paramstyle, name
_paramstyle, name = _parse_placeholder(token)
# Remember paramstyle
if not paramstyle:
paramstyle = _paramstyle
# Ensure paramstyle is consistent
elif _paramstyle != paramstyle:
raise RuntimeError("inconsistent paramstyle")
# Remember placeholder's index, name
placeholders[index] = name
# If no placeholders
if not paramstyle:
# Error-check like qmark if args
if args:
paramstyle = "qmark"
# Error-check like named if kwargs
elif kwargs:
paramstyle = "named"
# In case of errors
_placeholders = ", ".join([str(tokens[index]) for index in placeholders])
_args = ", ".join([str(self._escape(arg)) for arg in args])
# qmark
if paramstyle == "qmark":
# Validate number of placeholders
if len(placeholders) != len(args):
if len(placeholders) < len(args):
raise RuntimeError("fewer placeholders ({}) than values ({})".format(_placeholders, _args))
else:
raise RuntimeError("more placeholders ({}) than values ({})".format(_placeholders, _args))
# Escape values
for i, index in enumerate(placeholders.keys()):
tokens[index] = self._escape(args[i])
# numeric
elif paramstyle == "numeric":
# Escape values
for index, i in placeholders.items():
if i >= len(args):
raise RuntimeError("missing value for placeholder (:{})".format(i + 1, len(args)))
tokens[index] = self._escape(args[i])
# Check if any values unused
indices = set(range(len(args))) - set(placeholders.values())
if indices:
raise RuntimeError("unused {} ({})".format(
"value" if len(indices) == 1 else "values",
", ".join([str(self._escape(args[index])) for index in indices])))
# named
elif paramstyle == "named":
# Escape values
for index, name in placeholders.items():
if name not in kwargs:
raise RuntimeError("missing value for placeholder (:{})".format(name))
tokens[index] = self._escape(kwargs[name])
# Check if any keys unused
keys = kwargs.keys() - placeholders.values()
if keys:
raise RuntimeError("unused values ({})".format(", ".join(keys)))
# format
elif paramstyle == "format":
# Validate number of placeholders
if len(placeholders) != len(args):
if len(placeholders) < len(args):
raise RuntimeError("fewer placeholders ({}) than values ({})".format(_placeholders, _args))
else:
raise RuntimeError("more placeholders ({}) than values ({})".format(_placeholders, _args))
# Escape values
for i, index in enumerate(placeholders.keys()):
tokens[index] = self._escape(args[i])
# pyformat
elif paramstyle == "pyformat":
# Escape values
for index, name in placeholders.items():
if name not in kwargs:
raise RuntimeError("missing value for placeholder (%{}s)".format(name))
tokens[index] = self._escape(kwargs[name])
# Check if any keys unused
keys = kwargs.keys() - placeholders.values()
if keys:
raise RuntimeError("unused {} ({})".format(
"value" if len(keys) == 1 else "values",
", ".join(keys)))
# For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape
# https://docs.sqlalchemy.org/en/13/core/sqlelement.html?highlight=text#sqlalchemy.sql.expression.text
for index, token in enumerate(tokens):
# In string literal
# https://www.sqlite.org/lang_keywords.html
if token.ttype in [sqlparse.tokens.Literal.String, sqlparse.tokens.Literal.String.Single]:
token.value = re.sub("(^'|\s+):", r"\1\:", token.value)
# In identifier
# https://www.sqlite.org/lang_keywords.html
elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
token.value = re.sub("(^\"|\s+):", r"\1\:", token.value)
# Join tokens into statement
statement = "".join([str(token) for token in tokens])
# Connect to database
try:
# Infer whether Flask is installed
import flask
# Infer whether app is defined
assert flask.current_app
# If no sessions for any databases yet
if not hasattr(flask.g, "_sessions"):
setattr(flask.g, "_sessions", {})
sessions = getattr(flask.g, "_sessions")
# If no session yet for this database
# https://flask.palletsprojects.com/en/1.1.x/appcontext/#storing-data
# https://stackoverflow.com/a/34010159
if self not in sessions:
# Connect to database
sessions[self] = sqlalchemy.orm.scoping.scoped_session(sqlalchemy.orm.sessionmaker(bind=self._engine))
# Remove session later
if _teardown_appcontext not in flask.current_app.teardown_appcontext_funcs:
flask.current_app.teardown_appcontext(_teardown_appcontext)
# Use this session
session = sessions[self]
except (ModuleNotFoundError, AssertionError):
# If no connection yet
if not hasattr(self, "_session"):
self._session = sqlalchemy.orm.scoping.scoped_session(sqlalchemy.orm.sessionmaker(bind=self._engine))
# Use this session
session = self._session
# Catch SQLAlchemy warnings
with warnings.catch_warnings():
# Raise exceptions for warnings
warnings.simplefilter("error")
# Prepare, execute statement
try:
# Join tokens into statement, abbreviating binary data as <class 'bytes'>
_statement = "".join([str(bytes) if token.ttype == sqlparse.tokens.Other else str(token) for token in tokens])
# Check for start of transaction
if command in ["BEGIN", "START"]:
self._autocommit = False
# Execute statement
if self._autocommit:
session.execute(sqlalchemy.text("BEGIN"))
result = session.execute(sqlalchemy.text(statement))
if self._autocommit:
session.execute(sqlalchemy.text("COMMIT"))
# Check for end of transaction
if command in ["COMMIT", "ROLLBACK"]:
self._autocommit = True
# Return value
ret = True
# If SELECT, return result set as list of dict objects
if command == "SELECT":
# Coerce types
rows = [dict(row) for row in result.fetchall()]
for row in rows:
for column in row:
# Coerce decimal.Decimal objects to float objects
# https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
if type(row[column]) is decimal.Decimal:
row[column] = float(row[column])
# Coerce memoryview objects (as from PostgreSQL's bytea columns) to bytes
elif type(row[column]) is memoryview:
row[column] = bytes(row[column])
# Rows to be returned
ret = rows
# If INSERT, return primary key value for a newly inserted row (or None if none)
elif command == "INSERT":
if self._engine.url.get_backend_name() in ["postgres", "postgresql"]:
try:
result = session.execute("SELECT LASTVAL()")
ret = result.first()[0]
except sqlalchemy.exc.OperationalError: # If lastval is not yet defined in this session
ret = None
else:
ret = result.lastrowid if result.rowcount == 1 else None
# If DELETE or UPDATE, return number of rows matched
elif command in ["DELETE", "UPDATE"]:
ret = result.rowcount
# If constraint violated, return None
except sqlalchemy.exc.IntegrityError as e:
self._logger.debug(termcolor.colored(statement, "yellow"))
e = ValueError(e.orig)
e.__cause__ = None
raise e
# If user error
except (sqlalchemy.exc.OperationalError, sqlalchemy.exc.ProgrammingError) as e:
self._disconnect()
self._logger.debug(termcolor.colored(statement, "red"))
e = RuntimeError(e.orig)
e.__cause__ = None
raise e
# Return value
else:
self._logger.debug(termcolor.colored(_statement, "green"))
return ret
def _escape(self, value):
"""
Escapes value using engine's conversion function.
https://docs.sqlalchemy.org/en/latest/core/type_api.html#sqlalchemy.types.TypeEngine.literal_processor
"""
# Lazily import
import sqlparse
def __escape(value):
# Lazily import
import datetime
import sqlalchemy
# bool
if type(value) is bool:
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Boolean().literal_processor(self._engine.dialect)(value))
# bytes
elif type(value) is bytes:
if self._engine.url.get_backend_name() in ["mysql", "sqlite"]:
return sqlparse.sql.Token(sqlparse.tokens.Other, f"x'{value.hex()}'") # https://dev.mysql.com/doc/refman/8.0/en/hexadecimal-literals.html
elif self._engine.url.get_backend_name() == "postgresql":
return sqlparse.sql.Token(sqlparse.tokens.Other, f"'\\x{value.hex()}'") # https://dba.stackexchange.com/a/203359
else:
raise RuntimeError("unsupported value: {}".format(value))
# datetime.date
elif type(value) is datetime.date:
return sqlparse.sql.Token(
sqlparse.tokens.String,
sqlalchemy.types.String().literal_processor(self._engine.dialect)(value.strftime("%Y-%m-%d")))
# datetime.datetime
elif type(value) is datetime.datetime:
return sqlparse.sql.Token(
sqlparse.tokens.String,
sqlalchemy.types.String().literal_processor(self._engine.dialect)(value.strftime("%Y-%m-%d %H:%M:%S")))
# datetime.time
elif type(value) is datetime.time:
return sqlparse.sql.Token(
sqlparse.tokens.String,
sqlalchemy.types.String().literal_processor(self._engine.dialect)(value.strftime("%H:%M:%S")))
# float
elif type(value) is float:
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Float().literal_processor(self._engine.dialect)(value))
# int
elif type(value) is int:
return sqlparse.sql.Token(
sqlparse.tokens.Number,
sqlalchemy.types.Integer().literal_processor(self._engine.dialect)(value))
# str
elif type(value) is str:
return sqlparse.sql.Token(
sqlparse.tokens.String,
sqlalchemy.types.String().literal_processor(self._engine.dialect)(value))
# None
elif value is None:
return sqlparse.sql.Token(
sqlparse.tokens.Keyword,
sqlalchemy.types.NullType().literal_processor(self._engine.dialect)(value))
# Unsupported value
else:
raise RuntimeError("unsupported value: {}".format(value))
# Escape value(s), separating with commas as needed
if type(value) in [list, tuple]:
return sqlparse.sql.TokenList(sqlparse.parse(", ".join([str(__escape(v)) for v in value])))
else:
return __escape(value)
def _parse_exception(e):
"""Parses an exception, returns its message."""
# Lazily import
import re
# MySQL
matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
if matches:
return matches.group(1)
# PostgreSQL
matches = re.search(r"^\(psycopg2\.OperationalError\) (.+)$", str(e))
if matches:
return matches.group(1)
# SQLite
matches = re.search(r"^\(sqlite3\.OperationalError\) (.+)$", str(e))
if matches:
return matches.group(1)
# Default
return str(e)
def _parse_placeholder(token):
"""Infers paramstyle, name from sqlparse.tokens.Name.Placeholder."""
# Lazily load
import re
import sqlparse
# Validate token
if not isinstance(token, sqlparse.sql.Token) or token.ttype != sqlparse.tokens.Name.Placeholder:
raise TypeError()
# qmark
if token.value == "?":
return "qmark", None
# numeric
matches = re.search(r"^:([1-9]\d*)$", token.value)
if matches:
return "numeric", int(matches.group(1)) - 1
# named
matches = re.search(r"^:([a-zA-Z]\w*)$", token.value)
if matches:
return "named", matches.group(1)
# format
if token.value == "%s":
return "format", None
# pyformat
matches = re.search(r"%\((\w+)\)s$", token.value)
if matches:
return "pyformat", matches.group(1)
# Invalid
raise RuntimeError("{}: invalid placeholder".format(token.value))
def _teardown_appcontext(exception=None):
"""Closes context's database connection, if any."""
import flask
for session in flask.g.pop("_sessions", {}).values():
session.remove()
You can’t perform that action at this time.
