fastapi / sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
https://sqlmodel.tiangolo.com/
MIT License
14.44k stars 657 forks source link

Switch from `str` to `EmailStr` errors `alembic revision --autogenerate` with exit code 1 and no stack trace #289

Open Cielquan opened 2 years ago

Cielquan commented 2 years ago

First Check

Commit to Help

Example Code

from pydantic import EmailStr
from sqlmodel import AutoString, Column, Field, SQLModel

class User(SQLModel, table=True):
    """User database model."""

    __tablename__ = "users"

    id: int | None = Field(default=None, primary_key=True)
    email: str
    email2: str = Field(sa_column=Column("email2", AutoString, nullable=False))

Description

When I use the str type alembic runs just fine. But when I change the type to pydantic's EmailStr type alembic errors somehow.

As the type annotation, coming from pydantic, in a SQLModel causes an error with alembic I guess that there is somehow a communication / translation error from SQLModel to alembic.

I looked into the code of sqlmodel and here are my findings:

Maybe it is somehow related to #212.

Reproduction steps

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

3.10.1

Additional Context

No response

Cielquan commented 2 years ago

I somehow get the same error result, when I use a base class and overwrite the type for the Read-Model, which does not make any sense to me.

from pydantic import BaseModel, EmailStr
from sqlmodel import Field, SQLModel

class _UserBase(BaseModel):
    """Base model for User database and data models."""

    email: str

class User(_UserBase, SQLModel, table=True):
    """User database model."""

    __tablename__ = "users"

    id: int | None = Field(default=None, primary_key=True)

class UserRead(_UserBase):
    """User data model for reading database entries."""

    id: int
    email: EmailStr

EDIT: remove noqa comment EDIT2: remove unnecessary foreign key

sashkent3 commented 6 months ago

EmailStr is actually NOT a subclass of str thus the check fails. SQLAlchemy type checks for such types as EmailStr should be added to SQLModel similar to IPV4Address. I can submit a PR if that's ok by maintainers.

sashkent3 commented 6 months ago

Nevermind, I found a draft PR #762, which should probably be linked here.