Skip to content

Commit dc148b4

Browse files
committed
coercing decimal.Decimal objects to float objects for PostgreSQL
1 parent c6c114b commit dc148b4

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/cs50/sql.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime
2+
import decimal
23
import importlib
34
import logging
45
import re
@@ -31,7 +32,6 @@ def execute(self, text, **params):
3132
"""
3233
Execute a SQL statement.
3334
"""
34-
3535
class UserDefinedType(sqlalchemy.TypeDecorator):
3636
"""
3737
Add support for expandable values, a la https://bitbucket.org/zzzeek/sqlalchemy/issues/3953/expanding-parameter.
@@ -123,8 +123,14 @@ def process(value):
123123

124124
# if SELECT (or INSERT with RETURNING), return result set as list of dict objects
125125
if re.search(r"^\s*SELECT", statement, re.I):
126-
rows = result.fetchall()
127-
return [dict(row) for row in rows]
126+
127+
# coerce any decimal.Decimal objects to float objects
128+
rows = [dict(row) for row in result.fetchall()]
129+
for row in rows:
130+
for column in row:
131+
if isinstance(row[column], decimal.Decimal):
132+
row[column] = float(row[column])
133+
return rows
128134

129135
# if INSERT, return primary key value for a newly inserted row
130136
elif re.search(r"^\s*INSERT", statement, re.I):

0 commit comments

Comments
 (0)