Skip to content

Commit 580f372

Browse files
robcxyztiangolo
andauthored
✨ Add support for Decimal fields from Pydantic and SQLAlchemy (#103)
Co-authored-by: Sebastián Ramírez <[email protected]>
1 parent 1c276ef commit 580f372

File tree

10 files changed

+262
-7
lines changed

10 files changed

+262
-7
lines changed

docs/advanced/decimal.md

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# Decimal Numbers
2+
3+
In some cases you might need to be able to store decimal numbers with guarantees about the precision.
4+
5+
This is particularly important if you are storing things like **currencies**, **prices**, **accounts**, and others, as you would want to know that you wouldn't have rounding errors.
6+
7+
As an example, if you open Python and sum `1.1` + `2.2` you would expect to see `3.3`, but you will actually get `3.3000000000000003`:
8+
9+
```Python
10+
>>> 1.1 + 2.2
11+
3.3000000000000003
12+
```
13+
14+
This is because of the way numbers are stored in "ones and zeros" (binary). But Python has a module and some types to have strict decimal values. You can read more about it in the official <a href="https://docs.python.org/3/library/decimal.html" class="external-link" target="_blank">Python docs for Decimal</a>.
15+
16+
Because databases store data in the same ways as computers (in binary), they would have the same types of issues. And because of that, they also have a special **decimal** type.
17+
18+
In most cases this would probably not be a problem, for example measuring views in a video, or the life bar in a videogame. But as you can imagine, this is particularly important when dealing with **money** and **finances**.
19+
20+
## Decimal Types
21+
22+
Pydantic has special support for `Decimal` types using the <a href="https://pydantic-docs.helpmanual.io/usage/types/#arguments-to-condecimal" class="external-link" target="_blank">`condecimal()` special function</a>.
23+
24+
!!! tip
25+
Pydantic 1.9, that will be released soon, has improved support for `Decimal` types, without needing to use the `condecimal()` function.
26+
27+
But meanwhile, you can already use this feature with `condecimal()` in **SQLModel** it as it's explained here.
28+
29+
When you use `condecimal()` you can specify the number of digits and decimal places to support. They will be validated by Pydantic (for example when using FastAPI) and the same information will also be used for the database columns.
30+
31+
!!! info
32+
For the database, **SQLModel** will use <a href="https://docs.sqlalchemy.org/en/14/core/type_basics.html#sqlalchemy.types.DECIMAL" class="external-link" target="_blank">SQLAlchemy's `DECIMAL` type</a>.
33+
34+
## Decimals in SQLModel
35+
36+
Let's say that each hero in the database will have an amount of money. We could make that field a `Decimal` type using the `condecimal()` function:
37+
38+
```{.python .annotate hl_lines="12" }
39+
{!./docs_src/advanced/decimal/tutorial001.py[ln:1-12]!}
40+
41+
# More code here later 👇
42+
```
43+
44+
<details>
45+
<summary>👀 Full file preview</summary>
46+
47+
```Python
48+
{!./docs_src/advanced/decimal/tutorial001.py!}
49+
```
50+
51+
</details>
52+
53+
Here we are saying that `money` can have at most `5` digits with `max_digits`, **this includes the integers** (to the left of the decimal dot) **and the decimals** (to the right of the decimal dot).
54+
55+
We are also saying that the number of decimal places (to the right of the decimal dot) is `3`, so we can have **3 decimal digits** for these numbers in the `money` field. This means that we will have **2 digits for the integer part** and **3 digits for the decimal part**.
56+
57+
✅ So, for example, these are all valid numbers for the `money` field:
58+
59+
* `12.345`
60+
* `12.3`
61+
* `12`
62+
* `1.2`
63+
* `0.123`
64+
* `0`
65+
66+
🚫 But these are all invalid numbers for that `money` field:
67+
68+
* `1.2345`
69+
* This number has more than 3 decimal places.
70+
* `123.234`
71+
* This number has more than 5 digits in total (integer and decimal part).
72+
* `123`
73+
* Even though this number doesn't have any decimals, we still have 3 places saved for them, which means that we can **only use 2 places** for the **integer part**, and this number has 3 integer digits. So, the allowed number of integer digits is `max_digits` - `decimal_places` = 2.
74+
75+
!!! tip
76+
Make sure you adjust the number of digits and decimal places for your own needs, in your own application. 🤓
77+
78+
## Create models with Decimals
79+
80+
When creating new models you can actually pass normal (`float`) numbers, Pydantic will automatically convert them to `Decimal` types, and **SQLModel** will store them as `Decimal` types in the database (using SQLAlchemy).
81+
82+
```Python hl_lines="4-6"
83+
# Code above omitted 👆
84+
85+
{!./docs_src/advanced/decimal/tutorial001.py[ln:25-35]!}
86+
87+
# Code below omitted 👇
88+
```
89+
90+
<details>
91+
<summary>👀 Full file preview</summary>
92+
93+
```Python
94+
{!./docs_src/advanced/decimal/tutorial001.py!}
95+
```
96+
97+
</details>
98+
99+
## Select Decimal data
100+
101+
Then, when working with Decimal types, you can confirm that they indeed avoid those rounding errors from floats:
102+
103+
```Python hl_lines="15-16"
104+
# Code above omitted 👆
105+
106+
{!./docs_src/advanced/decimal/tutorial001.py[ln:38-51]!}
107+
108+
# Code below omitted 👇
109+
```
110+
111+
<details>
112+
<summary>👀 Full file preview</summary>
113+
114+
```Python
115+
{!./docs_src/advanced/decimal/tutorial001.py!}
116+
```
117+
118+
</details>
119+
120+
## Review the results
121+
122+
Now if you run this, instead of printing the unexpected number `3.3000000000000003`, it prints `3.300`:
123+
124+
<div class="termy">
125+
126+
```console
127+
$ python app.py
128+
129+
// Some boilerplate and previous output omitted 😉
130+
131+
// The type of money is Decimal('1.100')
132+
Hero 1: id=1 secret_name='Dive Wilson' age=None name='Deadpond' money=Decimal('1.100')
133+
134+
// More output omitted here 🤓
135+
136+
// The type of money is Decimal('1.100')
137+
Hero 2: id=3 secret_name='Tommy Sharp' age=48 name='Rusty-Man' money=Decimal('2.200')
138+
139+
// No rounding errors, just 3.3! 🎉
140+
Total money: 3.300
141+
```
142+
143+
</div>
144+
145+
!!! warning
146+
Although Decimal types are supported and used in the Python side, not all databases support it. In particular, SQLite doesn't support decimals, so it will convert them to the same floating `NUMERIC` type it supports.
147+
148+
But decimals are supported by most of the other SQL databases. 🎉

docs/advanced/index.md

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
# Advanced User Guide
22

3-
The **Advanced User Guide** will be coming soon to a <del>theater</del> **documentation** near you... 😅
3+
The **Advanced User Guide** is gradually growing, you can already read about some advanced topics.
44

5-
I just have to `add` it, `commit` it, and `refresh` it. 😉
5+
At some point it will include:
66

7-
It will include:
8-
9-
* How to use the `async` and `await` with the async session.
7+
* How to use `async` and `await` with the async session.
108
* How to run migrations.
119
* How to combine **SQLModel** models with SQLAlchemy.
12-
* ...and more.
10+
* ...and more. 🤓

docs_src/advanced/__init__.py

Whitespace-only changes.

docs_src/advanced/decimal/__init__.py

Whitespace-only changes.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from typing import Optional
2+
3+
from pydantic import condecimal
4+
from sqlmodel import Field, Session, SQLModel, create_engine, select
5+
6+
7+
class Hero(SQLModel, table=True):
8+
id: Optional[int] = Field(default=None, primary_key=True)
9+
name: str
10+
secret_name: str
11+
age: Optional[int] = None
12+
money: condecimal(max_digits=6, decimal_places=3) = Field(default=0)
13+
14+
15+
sqlite_file_name = "database.db"
16+
sqlite_url = f"sqlite:///{sqlite_file_name}"
17+
18+
engine = create_engine(sqlite_url, echo=True)
19+
20+
21+
def create_db_and_tables():
22+
SQLModel.metadata.create_all(engine)
23+
24+
25+
def create_heroes():
26+
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson", money=1.1)
27+
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", money=0.001)
28+
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48, money=2.2)
29+
30+
with Session(engine) as session:
31+
session.add(hero_1)
32+
session.add(hero_2)
33+
session.add(hero_3)
34+
35+
session.commit()
36+
37+
38+
def select_heroes():
39+
with Session(engine) as session:
40+
statement = select(Hero).where(Hero.name == "Deadpond")
41+
results = session.exec(statement)
42+
hero_1 = results.one()
43+
print("Hero 1:", hero_1)
44+
45+
statement = select(Hero).where(Hero.name == "Rusty-Man")
46+
results = session.exec(statement)
47+
hero_2 = results.one()
48+
print("Hero 2:", hero_2)
49+
50+
total_money = hero_1.money + hero_2.money
51+
print(f"Total money: {total_money}")
52+
53+
54+
def main():
55+
create_db_and_tables()
56+
create_heroes()
57+
select_heroes()
58+
59+
60+
if __name__ == "__main__":
61+
main()

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ nav:
8484
- tutorial/fastapi/tests.md
8585
- Advanced User Guide:
8686
- advanced/index.md
87+
- advanced/decimal.md
8788
- alternatives.md
8889
- help.md
8990
- contributing.md

sqlmodel/main.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,10 @@ def get_sqlachemy_type(field: ModelField) -> Any:
399399
if issubclass(field.type_, bytes):
400400
return LargeBinary
401401
if issubclass(field.type_, Decimal):
402-
return Numeric
402+
return Numeric(
403+
precision=getattr(field.type_, "max_digits", None),
404+
scale=getattr(field.type_, "decimal_places", None),
405+
)
403406
if issubclass(field.type_, ipaddress.IPv4Address):
404407
return AutoString
405408
if issubclass(field.type_, ipaddress.IPv4Network):

tests/test_advanced/__init__.py

Whitespace-only changes.

tests/test_advanced/test_decimal/__init__.py

Whitespace-only changes.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from decimal import Decimal
2+
from unittest.mock import patch
3+
4+
from sqlmodel import create_engine
5+
6+
from ...conftest import get_testing_print_function
7+
8+
expected_calls = [
9+
[
10+
"Hero 1:",
11+
{
12+
"name": "Deadpond",
13+
"age": None,
14+
"id": 1,
15+
"secret_name": "Dive Wilson",
16+
"money": Decimal("1.100"),
17+
},
18+
],
19+
[
20+
"Hero 2:",
21+
{
22+
"name": "Rusty-Man",
23+
"age": 48,
24+
"id": 3,
25+
"secret_name": "Tommy Sharp",
26+
"money": Decimal("2.200"),
27+
},
28+
],
29+
["Total money: 3.300"],
30+
]
31+
32+
33+
def test_tutorial(clear_sqlmodel):
34+
from docs_src.advanced.decimal import tutorial001 as mod
35+
36+
mod.sqlite_url = "sqlite://"
37+
mod.engine = create_engine(mod.sqlite_url)
38+
calls = []
39+
40+
new_print = get_testing_print_function(calls)
41+
42+
with patch("builtins.print", new=new_print):
43+
mod.main()
44+
assert calls == expected_calls

0 commit comments

Comments
 (0)