From 618e70af79eacd8fb8924c356b676ac9c6626c7a Mon Sep 17 00:00:00 2001 From: Arijit Basu Date: Thu, 28 Dec 2023 22:22:53 +0530 Subject: [PATCH] Demo Pydantic validation --- README.md | 26 ++++++++++++++++++++++++++ pyproject.toml | 2 +- tests/test_table_factory.py | 24 ++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1aedc1f..b4bec30 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ SQLAlchemy core, but fancier. +### Basic Usage + ```python import sqlalchemy as sa @@ -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") +``` diff --git a/pyproject.toml b/pyproject.toml index 63c9c79..a95d7d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/tests/test_table_factory.py b/tests/test_table_factory.py index 3600b26..9cbe770 100644 --- a/tests/test_table_factory.py +++ b/tests/test_table_factory.py @@ -1,3 +1,6 @@ +import pytest + + def test_table_factory(): import sqlalchemy as sa @@ -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")