Skip to content

Commit

Permalink
Store decimal.Decimal in DB as FLOAT, closes #110
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed May 11, 2020
1 parent e8c57e0 commit af3f81b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
4 changes: 4 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from .utils import sqlite3, OperationalError, suggest_column_types, column_affinity
from collections import namedtuple, OrderedDict
import datetime
import decimal
import hashlib
import itertools
import json
Expand Down Expand Up @@ -42,6 +43,7 @@
datetime.datetime: "TEXT",
datetime.date: "TEXT",
datetime.time: "TEXT",
decimal.Decimal: "FLOAT",
None.__class__: "TEXT",
# SQLite explicit types
"TEXT": "TEXT",
Expand Down Expand Up @@ -1325,6 +1327,8 @@ def chunks(sequence, size):


def jsonify_if_needed(value):
if isinstance(value, decimal.Decimal):
return float(value)
if isinstance(value, (dict, list, tuple)):
return json.dumps(value, default=repr)
elif isinstance(value, (datetime.time, datetime.date, datetime.datetime)):
Expand Down
2 changes: 2 additions & 0 deletions tests/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from sqlite_utils.utils import sqlite3
import collections
import datetime
import decimal
import json
import pathlib
import pytest
Expand Down Expand Up @@ -132,6 +133,7 @@ def test_create_table_with_not_null(fresh_db):
[{"name": "create", "type": "TEXT"}, {"name": "table", "type": "TEXT"}],
),
({"day": datetime.time(11, 0)}, [{"name": "day", "type": "TEXT"}]),
({"decimal": decimal.Decimal("1.2")}, [{"name": "decimal", "type": "FLOAT"}]),
),
)
def test_create_table_from_example(fresh_db, example, expected_columns):
Expand Down

0 comments on commit af3f81b

Please sign in to comment.