Skip to content

Commit e1b8e1d

Browse files
committed
add validation sqlmodel helpers
1 parent 176e715 commit e1b8e1d

File tree

3 files changed

+68
-1
lines changed

3 files changed

+68
-1
lines changed

ecodev_core/sqlmodel_utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
module implementing SQLModel related helper methods. Related to validation
3+
"""
4+
from sqlmodel import SQLModel
5+
6+
7+
class SQLModelWithVal(SQLModel):
8+
"""
9+
Helper class to ease validation in SQLModel classes with table=True
10+
"""
11+
@classmethod
12+
def create(cls, **kwargs):
13+
"""
14+
Forces validation to take place, even for SQLModel classes with table=True
15+
"""
16+
return cls(**cls.__bases__[0](**kwargs).model_dump())

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "ecodev-core"
3-
version = "0.0.32"
3+
version = "0.0.33"
44
description = "Low level sqlmodel/fastapi/pydantic building blocks"
55
authors = ["Thomas Epelbaum <[email protected]>",
66
"Olivier Gabriel <[email protected]>",

tests/unitary/test_sqlmodel_utils.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Module testing SQLModel helpers
3+
"""
4+
from typing import Optional
5+
6+
from pydantic import field_validator
7+
from sqlmodel import Field
8+
9+
from ecodev_core import SafeTestCase
10+
from ecodev_core.sqlmodel_utils import SQLModelWithVal
11+
12+
13+
class FooBase(SQLModelWithVal):
14+
"""
15+
Example base class to illustrate the table validation behaviour of SQLModelWithVal
16+
"""
17+
bar: int
18+
19+
@field_validator('bar', mode='before')
20+
def convert_bar(cls, bar):
21+
"""
22+
Example validation
23+
"""
24+
return int(bar / 1_000_000)
25+
26+
27+
class Foo(FooBase, table=True): # type: ignore
28+
"""
29+
Example class to illustrate the table validation behaviour of SQLModelWithVal
30+
"""
31+
id: Optional[int] = Field(default=None, primary_key=True)
32+
33+
34+
class SQLModelTest(SafeTestCase):
35+
"""
36+
Class testing validation behaviour of SQLModelWithVal
37+
"""
38+
39+
def test_init_without_validation(self):
40+
"""
41+
Test creation without validation
42+
"""
43+
foo = Foo(bar=3_000_000)
44+
self.assertEqual(foo.bar, 3_000_000)
45+
46+
def test_init_with_validation(self):
47+
"""
48+
Test creation with validation
49+
"""
50+
foo = Foo.create(bar=3_000_000)
51+
self.assertEqual(foo.bar, 3)

0 commit comments

Comments
 (0)