Skip to content

SQLModel inheritance breaks sqlalchemy mutation tracking #468

Description

@jtpavlock

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions