From 019b47d36e42abd88f4d58de1485d63cefce0954 Mon Sep 17 00:00:00 2001 From: Rajnish Singh Date: Tue, 24 Nov 2026 12:49:20 +0530 Subject: [PATCH] sql.py: support PRAGMA statements and consume results before commit Resolves #199 by: - Recognizing PRAGMA statements during command parsing (sqlparse parses PRAGMA as an Identifier rather than a generic SQL keyword). - Adding PRAGMA to supported commands. - Bypassing autocommit transaction wrapping for PRAGMA statements (some PRAGMAs cannot be executed inside transactions, e.g., WAL mode). - Consuming statement results before committing when results return rows, preventing 'cannot commit transaction - SQL statements in progress'. - Returning formatted list-of-dicts result rows for querying PRAGMAs (e.g., journal_mode, table_info, foreign_keys) and True for configuration PRAGMAs. - Adding comprehensive test_pragma coverage in SQLiteTests. Signed-off-by: Rajnish Singh --- src/cs50/sql.py | 58 +++++++++++++++++++++++++++++++++---------------- tests/sql.py | 21 ++++++++++++++++++ 2 files changed, 60 insertions(+), 19 deletions(-) diff --git a/src/cs50/sql.py b/src/cs50/sql.py index 81905bc..3283e17 100644 --- a/src/cs50/sql.py +++ b/src/cs50/sql.py @@ -156,17 +156,34 @@ 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 = { @@ -174,6 +191,7 @@ def execute(self, sql, *args, **kwargs): "CREATE VIEW", "DELETE", "INSERT", + "PRAGMA", "SELECT", "START", "UPDATE", @@ -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: @@ -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 diff --git a/tests/sql.py b/tests/sql.py index bb37fd9..dd95723 100644 --- a/tests/sql.py +++ b/tests/sql.py @@ -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)")