Pydantic Dataclasses with SqlAlchemy Rasies UnmappedInstanceError

Viewed 1087

Problem

When using pydantic's dataclass class sqlalchemy mapper give an UnmappedInstanceError.

Implementation

# Create a simple user pydantic dataclass
from pydantic.dataclasses import dataclass

@dataclass
class User:
    full_name: str
    email: str

# Map sqlalchemy to the model above
import sqlalchemy as sa
from sqlalchemy.orm import mapper
import model

metadata = sa.MetaData()

user = sa.Table(
    'user', metadata,
    sa.Column("id", sa.Integer(), nullable=False, primary_key=True, autoincrement=True),
    sa.Column("full_name", sa.String(), nullable=True),
)

user_mapper = mapper(model.User, user)

# Create Sqlalchemy session
from sqlalchemy.orm import sessionmaker

engine = create_engine(database_uri)
Session = sessionmaker(bind=engine)
session = Session()

# adding user from above into the session
user = User(full_name='Hey You', email='who@me.com')
session.add(user)
session.commit()

Error

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'User' is mapped, but this instance lacks instrumentation. This occurs when the instance is created before sqlalchemy.orm.mapper(User) was called.

What in pydantic's dataclass causes this issue? Using python's base Dataclass doesn't cause an issue.

1 Answers

This is a known issue between Pydantic and SQLAlchemy that won't be fixed. This github issue has more details.

From the creator of Pydantic:

Best to use ORM mode.

I have no personal interest in ORMs or supporting them - long term they're a mistake, you'd do much better to just write SQL.

However if there's some easy way to support mapper that required a relatively small change to pydantic, I'd be happy to review a PR.

-- samuelcolvin

Related