Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: SQLModel table model not validated #1696

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

AlpAribal
Copy link

When using a SQLModel class with table=True as dtype, schema is not validated. This is because such SQLModel classes do not validate data at init time (see here). This PR solves this by explicitly calling model_validate/parse_obj instead of instantiating the class.

Minimal example (python=3.8 sqlmodel=0.0.19 pandera=0.19.3):

# example.py
import pandas as pd
import pandera as pa
from pandera.engines.pandas_engine import PydanticModel
from sqlmodel import SQLModel, Field

class Record(SQLModel, table=True):
    name: str = Field(primary_key=True)

class PydanticSchema(pa.DataFrameModel):
    class Config:
        dtype = PydanticModel(Record)

df = pd.DataFrame({"name": [3]})
PydanticSchema.validate(df)

Without the fix, validation succeeds while only emitting a warning from model_dump():

$ python example.py 
UserWarning: Pydantic serializer warnings:
  Expected `str` but got `int` - serialized value may not be as expected

With the fix, a SchemaError is raised:

$ python example.py 
...
pandera.errors.SchemaError: Error while coercing 'PydanticSchema' to type <class '__main__.Record'>: Could not coerce <class 'pandas.core.frame.DataFrame'> data_container into type <class '__main__.Record'>
   index failure_case
0      0  {'name': 1}

Signed-off-by: Alp Aribal <alparbal@gmail.com>
@AlpAribal AlpAribal force-pushed the bugfix/sqlmodel-table-not-validated branch from ce0553f to 9935ffe Compare June 19, 2024 22:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant