Skip to content

Commit

Permalink
Demo Pydantic validation
Browse files Browse the repository at this point in the history
  • Loading branch information
sayanarijit committed Dec 28, 2023
1 parent 6090d51 commit 618e70a
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

SQLAlchemy core, but fancier.

### Basic Usage

```python
import sqlalchemy as sa

Expand Down Expand Up @@ -62,3 +64,27 @@ with engine.connect() as conn:
result = conn.execute(qry).fetchall()
assert result == [("John Doe", "My Book")], result
```

### With Pydantic Validation

```python

from pydantic import BaseModel, Field

from sqla_fancy_core import TableFactory

tf = TableFactory()

# Define a table
class User:
name = tf.string("name", info={"field": Field(..., max_length=5)})
Table = tf("author")

# Define a pydantic schema
class CreateUser(BaseModel):
name: str = User.name.info["field"]

assert CreateUser(name="John").model_dump() == {"name": "John"}
with pytest.raises(ValueError):
CreateUser(name="John Doe")
```
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ classifiers = [ # Optional
dependencies = ["sqlalchemy"]

[project.optional-dependencies]
test = ["pytest", "flake8"]
test = ["pytest", "flake8", "pydantic"]

[project.urls]
"Homepage" = "https://github.com/sayanarijit/sqla-fancy-core"
Expand Down
24 changes: 24 additions & 0 deletions tests/test_table_factory.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import pytest


def test_table_factory():
import sqlalchemy as sa

Expand Down Expand Up @@ -55,3 +58,24 @@ class Book:
)
result = conn.execute(qry).fetchall()
assert result == [("John Doe", "My Book")], result


def test_field():
from pydantic import BaseModel, Field

from sqla_fancy_core import TableFactory

tf = TableFactory()

# Define a table
class User:
name = tf.string("name", info={"field": Field(..., max_length=5)})
Table = tf("author")

# Define a pydantic schema
class CreateUser(BaseModel):
name: str = User.name.info["field"]

assert CreateUser(name="John").model_dump() == {"name": "John"}
with pytest.raises(ValueError):
CreateUser(name="John Doe")

0 comments on commit 618e70a

Please sign in to comment.