fastapi / sqlmodel

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

SQLModel inheritance breaks sqlalchemy mutation tracking #468

Open jtpavlock opened 2 years ago

jtpavlock commented 2 years ago

First Check

Commit to Help

Example Code

#!/usr/bin/env python3

from typing import Optional, Any

import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import MutableDict, MutableSet
from sqlalchemy.orm import sessionmaker
from sqlalchemy import JSON, Column
from sqlmodel import SQLModel, Field, create_engine

Session = sessionmaker()
Base = declarative_base()

class BadTrackBase(SQLModel):
    custom: dict[str, Any] = Field(
        sa_column=Column(MutableDict.as_mutable(JSON(none_as_null=True))), default={}
    )

class BadTrack(BadTrackBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)

class Track(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    custom: dict[str, Any] = Field(
        sa_column=Column(MutableDict.as_mutable(JSON(none_as_null=True))), default={}
    )

engine = create_engine("sqlite:///:memory:")
Session.configure(bind=engine)
SQLModel.metadata.create_all(engine)
session = Session()

good_track = Track(id=1, custom={"test": "good"})
bad_track = BadTrack(id=1, custom={"test": "bad"})

session.add(good_track)
session.add(bad_track)
session.commit()

good_track.custom["test"] = "changed"
bad_track.custom["test"] = "changed"

assert good_track in session.dirty
assert bad_track in session.dirty

Description

When setting a field to one of the fields supported by sqlalchemy mutation tracking, it seems the mutation tracking isn't working as intended. I attached the above code sample to illustrate what I mean. The assertions on the bottom of the script should pass under normal circumstance.

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.08

Python Version

3.9.13

Additional Context

No response

blerrgh commented 1 year ago

I have the same issue in SQLModel 0.08 and it's kind of a big deal. Is there a workaround for this besides re-assigning the entire dict i.e. good_track.custom = {"test": changed"} ?

jyotirmay123 commented 11 months ago

Any update here, A big blocker before I can migrate from sqlalchemy+pydantic to sqlmodel.

alexpotv commented 4 months ago

Also a blocker here, commenting to stay in the loop!

pwinged commented 2 months ago

yep, same here, blocker.