Skip to content

Add support for polymorphism models#1894

Open
viet-hung-ng wants to merge 3 commits intofastapi:mainfrom
qube-rt:feat/polymorphic-inheritance
Open

Add support for polymorphism models#1894
viet-hung-ng wants to merge 3 commits intofastapi:mainfrom
qube-rt:feat/polymorphic-inheritance

Conversation

@viet-hung-ng
Copy link
Copy Markdown

This PR builds on top of #1226 and completes support for SQLAlchemy single-table and joined-table polymorphic inheritance in SQLModel.

#1226 had some problems:

  • inherited relationships passed as constructor kwargs were silently dropped
  • assigning inherited relationships doesn't work
  • merge conflicts

We fix these issues in this PR and add a more complete test suite.

Commit structure

This PR is quite large (mainly due to tests), so the commits are split to make review easier.

1. Add metaclass support for SQLAlchemy polymorphic models

Adds support for both joined-table and single-table inheritance.

This commit:

  • merges base-class fields into the subclass namespace
  • auto-sets __tablename__
  • skips already-instrumented attributes
  • sets the polymorphic discriminator to polymorphic_identity on __init__

2. Fix inherited relationship resolution in polymorphic subclasses

sqlmodel_table_construct and sqlmodel_validate previously iterated only over __sqlmodel_relationships__, which missed relationships inherited from polymorphic base classes.

This commit replaces that logic with _relationship_keys(), which falls back to the SQLAlchemy mapper when available.

It also fixes SQLModel.__setattr__, which now detects mapper-owned relationships with _is_sqlmodel_relationship() and lets SQLAlchemy handle the assignment instead of forwarding the inherited relationship assignments to Pydantic.

3. Add polymorphic inheritance test suite

Adds a large test suite under tests/test_polymorphic/.

Most tests are ported from SQLAlchemy's own inheritance test suite, test/orm/inheritance/, and adapted to SQLModel's API.

The suite also covers issues raised in #1226 comments:

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.

3 participants