Skip to content

Commit c0534e2

Browse files
author
Kareem Zidane
committed
factor out sql utility functions
1 parent 1f62283 commit c0534e2

File tree

2 files changed

+20
-18
lines changed

2 files changed

+20
-18
lines changed

src/cs50/_sql_util.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""Utility functions used by sql.py"""
2+
3+
import decimal
4+
5+
def fetch_select_result(result):
6+
rows = [dict(row) for row in result.fetchall()]
7+
for row in rows:
8+
for column in row:
9+
# Coerce decimal.Decimal objects to float objects
10+
# https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
11+
if isinstance(row[column], decimal.Decimal):
12+
row[column] = float(row[column])
13+
14+
# Coerce memoryview objects (as from PostgreSQL's bytea columns) to bytes
15+
elif isinstance(row[column], memoryview):
16+
row[column] = bytes(row[column])
17+
18+
return rows

src/cs50/sql.py

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Wraps SQLAlchemy"""
22

3-
import decimal
43
import logging
54
import warnings
65

@@ -9,6 +8,7 @@
98

109
from ._session import Session
1110
from ._statement import Statement
11+
from ._sql_util import fetch_select_result
1212

1313
_logger = logging.getLogger("cs50")
1414

@@ -43,7 +43,7 @@ def execute(self, sql, *args, **kwargs):
4343
self._session.remove()
4444

4545
if operation_keyword == "SELECT":
46-
ret = _fetch_select_result(result)
46+
ret = fetch_select_result(result)
4747
elif operation_keyword == "INSERT":
4848
ret = self._last_row_id_or_none(result)
4949
elif operation_keyword in {"DELETE", "UPDATE"}:
@@ -89,19 +89,3 @@ def _(_):
8989
self._session.remove()
9090

9191
logging.getLogger("cs50").disabled = False
92-
93-
94-
def _fetch_select_result(result):
95-
rows = [dict(row) for row in result.fetchall()]
96-
for row in rows:
97-
for column in row:
98-
# Coerce decimal.Decimal objects to float objects
99-
# https://groups.google.com/d/msg/sqlalchemy/0qXMYJvq8SA/oqtvMD9Uw-kJ
100-
if isinstance(row[column], decimal.Decimal):
101-
row[column] = float(row[column])
102-
103-
# Coerce memoryview objects (as from PostgreSQL's bytea columns) to bytes
104-
elif isinstance(row[column], memoryview):
105-
row[column] = bytes(row[column])
106-
107-
return rows

0 commit comments

Comments
 (0)