Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SQL improvements #28

Merged
merged 3 commits into from
Jul 8, 2017
Merged
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
19 changes: 13 additions & 6 deletions src/cs50/sql.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import decimal
import importlib
import logging
import re
@@ -31,7 +32,6 @@ def execute(self, text, **params):
"""
Execute a SQL statement.
"""

class UserDefinedType(sqlalchemy.TypeDecorator):
"""
Add support for expandable values, a la https://bitbucket.org/zzzeek/sqlalchemy/issues/3953/expanding-parameter.
@@ -122,20 +122,27 @@ def process(value):
self.logger.debug(statement)

# if SELECT (or INSERT with RETURNING), return result set as list of dict objects
if re.search(r"^\s*SELECT\s+", statement, re.I):
rows = result.fetchall()
return [dict(row) for row in rows]
if re.search(r"^\s*SELECT", statement, re.I):

# coerce any decimal.Decimal objects to float objects
# https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
rows = [dict(row) for row in result.fetchall()]
for row in rows:
for column in row:
if isinstance(row[column], decimal.Decimal):
row[column] = float(row[column])
return rows

# if INSERT, return primary key value for a newly inserted row
elif re.search(r"^\s*INSERT\s+", statement, re.I):
elif re.search(r"^\s*INSERT", statement, re.I):
if self.engine.url.get_backend_name() in ["postgres", "postgresql"]:
result = self.engine.execute(sqlalchemy.text("SELECT LASTVAL()"))
return result.first()[0]
else:
return result.lastrowid

# if DELETE or UPDATE, return number of rows matched
elif re.search(r"^\s*(?:DELETE|UPDATE)\s+", statement, re.I):
elif re.search(r"^\s*(?:DELETE|UPDATE)", statement, re.I):
return result.rowcount

# if some other statement, return True unless exception