Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 39 additions & 19 deletions src/cs50/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,24 +156,42 @@ def execute(self, sql, *args, **kwargs):
raise RuntimeError("cannot pass both positional and named parameters")

# Infer command from flattened statement to a single string separated by spaces
full_statement = " ".join(
str(token)
for token in statements[0].tokens
if token.ttype
in [
sqlparse.tokens.Keyword,
sqlparse.tokens.Keyword.DDL,
sqlparse.tokens.Keyword.DML,
]
first_token = next(
(
t
for t in statements[0].flatten()
if not t.is_whitespace
and t.ttype
not in [
sqlparse.tokens.Comment,
sqlparse.tokens.Comment.Single,
sqlparse.tokens.Comment.Multiline,
]
),
None,
)
full_statement = full_statement.upper()
if first_token and first_token.value.upper() == "PRAGMA":
full_statement = "PRAGMA"
else:
full_statement = " ".join(
str(token)
for token in statements[0].tokens
if token.ttype
in [
sqlparse.tokens.Keyword,
sqlparse.tokens.Keyword.DDL,
sqlparse.tokens.Keyword.DML,
]
)
full_statement = full_statement.upper()

# Set of possible commands
commands = {
"BEGIN",
"CREATE VIEW",
"DELETE",
"INSERT",
"PRAGMA",
"SELECT",
"START",
"UPDATE",
Expand Down Expand Up @@ -383,21 +401,16 @@ def teardown_appcontext(exception):
self._autocommit = False

# Execute statement
if self._autocommit:
autocommit = self._autocommit and command != "PRAGMA"
if autocommit:
connection.execute(sqlalchemy.text("BEGIN"))
result = connection.execute(sqlalchemy.text(statement))
if self._autocommit:
connection.execute(sqlalchemy.text("COMMIT"))

# Check for end of transaction
if command in ["COMMIT", "ROLLBACK", "VACUUM"]: # cannot VACUUM from within a transaction
self._autocommit = True

# Return value
ret = True

# If SELECT, return result set as list of dict objects
if command == "SELECT":
# If SELECT or PRAGMA that returns rows, return result set as list of dict objects
if command == "SELECT" or (command == "PRAGMA" and result.returns_rows):
# Coerce types
rows = [dict(row) for row in result.mappings().all()]
for row in rows:
Expand All @@ -414,6 +427,13 @@ def teardown_appcontext(exception):
# Rows to be returned
ret = rows

if autocommit:
connection.execute(sqlalchemy.text("COMMIT"))

# Check for end of transaction
if command in ["COMMIT", "ROLLBACK", "VACUUM"]: # cannot VACUUM from within a transaction
self._autocommit = True

# If INSERT, return primary key value for a newly inserted row (or None if none)
elif command == "INSERT":
# If PostgreSQL
Expand Down
21 changes: 21 additions & 0 deletions tests/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,27 @@ def test_foreign_key_support(self):
self.db.execute("CREATE TABLE bar(foo_id INTEGER, FOREIGN KEY (foo_id) REFERENCES foo(id))")
self.assertRaises(ValueError, self.db.execute, "INSERT INTO bar VALUES(50)")

def test_pragma(self):
rows = self.db.execute("PRAGMA journal_mode")
self.assertIsInstance(rows, list)
self.assertTrue(len(rows) > 0)
self.assertIn("journal_mode", rows[0])

ret = self.db.execute("PRAGMA foreign_keys = ON")
self.assertTrue(ret)

fk_rows = self.db.execute("PRAGMA foreign_keys")
self.assertEqual(fk_rows, [{"foreign_keys": 1}])

table_info = self.db.execute("PRAGMA table_info(cs50)")
self.assertIsInstance(table_info, list)
col_names = [col["name"] for col in table_info]
self.assertIn("id", col_names)
self.assertIn("val", col_names)

comment_pragma = self.db.execute("-- check foreign keys\npragma foreign_keys;")
self.assertEqual(comment_pragma, [{"foreign_keys": 1}])

def test_qmark(self):
self.db.execute("CREATE TABLE foo (firstname STRING, lastname STRING)")

Expand Down