Skip to content

Commit 6b15a87

Browse files
authored
Fixes support for comments above and below statements and for semicolons at end of single statements (#98)
* fixes bug whereby comments before query yielded wrong return value * tolerates semicolon at end of single statement * removed whitespace * fixed comment * added test * added test for semicolon
1 parent af8dd92 commit 6b15a87

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,5 @@
1616
package_dir={"": "src"},
1717
packages=["cs50"],
1818
url="https://github.com/cs50/python-cs50",
19-
version="4.0.3"
19+
version="4.0.4"
2020
)

src/cs50/sql.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,11 @@ def execute(self, sql, *args, **kwargs):
7575
import termcolor
7676
import warnings
7777

78+
# Parse statement, stripping comments and then leading/trailing whitespace
79+
statements = sqlparse.parse(sqlparse.format(sql, strip_comments=True).strip())
80+
7881
# Allow only one statement at a time, since SQLite doesn't support multiple
7982
# https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute
80-
statements = sqlparse.parse(sql)
8183
if len(statements) > 1:
8284
raise RuntimeError("too many statements at once")
8385
elif len(statements) == 0:

tests/sql.py

+6
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ def test_select_where(self):
6363

6464
self.assertEqual(self.db.execute("SELECT * FROM cs50 WHERE id = :id OR val = :val", id=rows[1]["id"], val=rows[2]["val"]), rows[1:3])
6565

66+
def test_select_with_comments(self):
67+
self.assertEqual(self.db.execute("--comment\nSELECT * FROM cs50;\n--comment"), [])
68+
69+
def test_select_with_semicolon(self):
70+
self.assertEqual(self.db.execute("SELECT * FROM cs50;\n--comment"), [])
71+
6672
def test_update_returns_affected_rows(self):
6773
rows = [
6874
{"id": 1, "val": "foo"},

0 commit comments

Comments
 (0)