Skip to content

Commit

Permalink
Merge pull request #176 from cs50/create-view
Browse files Browse the repository at this point in the history
Adds support for 'CREATE VIEW' statement
  • Loading branch information
rongxin-liu authored Sep 29, 2023
2 parents 464f237 + 4424e65 commit 955637c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
package_dir={"": "src"},
packages=["cs50"],
url="https://github.com/cs50/python-cs50",
version="9.2.5"
version="9.2.6"
)
24 changes: 14 additions & 10 deletions src/cs50/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __init__(self, url, **kwargs):
import sqlalchemy
import sqlalchemy.orm
import threading

# Temporary fix for missing sqlite3 module on the buildpack stack
try:
import sqlite3
Expand Down Expand Up @@ -149,15 +149,15 @@ def execute(self, sql, *args, **kwargs):
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]:
token_value = token.value.upper()
if token_value in ["BEGIN", "DELETE", "INSERT", "SELECT", "START", "UPDATE"]:
command = token_value
break
else:
command = None
# 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])
full_statement = full_statement.upper()

# set of possible commands
commands = {"BEGIN", "CREATE VIEW", "DELETE", "INSERT", "SELECT", "START", "UPDATE"}

# check if the full_statement starts with any command
command = next((cmd for cmd in commands if full_statement.startswith(cmd)), None)

# Flatten statement
tokens = list(statements[0].flatten())
Expand Down Expand Up @@ -393,6 +393,10 @@ def teardown_appcontext(exception):
elif command in ["DELETE", "UPDATE"]:
ret = result.rowcount

# If CREATE VIEW, return True
elif command == "CREATE VIEW":
ret = True

# If constraint violated
except sqlalchemy.exc.IntegrityError as e:
self._logger.error(termcolor.colored(_statement, "red"))
Expand Down

0 comments on commit 955637c

Please sign in to comment.