Skip to content

Conversation

@cofin
Copy link
Member

@cofin cofin commented Nov 2, 2025

Fixes automatic table name generation to support SQLAlchemy's inheritance patterns.

Changes

Implements detection and handling for:

  • Single Table Inheritance (STI) - child classes automatically use parent's table
  • Joined Table Inheritance (JTI) - separate tables with foreign key relationship
  • Concrete Table Inheritance (CTI) - independent tables with concrete=True

Implementation

  • Uses has_inherited_table() to detect STI pattern and return None for child tablenames
  • Adds __table_cls__ hook to inspect columns and prevent duplicate table creation
  • Updates __init_subclass__ to set tablename=None for STI children before SQLAlchemy processes class
  • Handles edge cases: explicit tablenames, multi-level inheritance, mixins, abstract bases

Example

class Employee(UUIDBase):
    __tablename__ = "employee"
    type: Mapped[str]
    __mapper_args__ = {
        "polymorphic_on": "type",
        "polymorphic_identity": "employee"
    }

# STI - automatically uses parent table
class Manager(Employee):
    __mapper_args__ = {"polymorphic_identity": "manager"}
    department: Mapped[str | None] = mapped_column(default=None)

@cofin cofin requested review from a team as code owners November 2, 2025 21:40
@cofin cofin changed the title Support SQLAlchemy inheritance patterns fix: Support SQLAlchemy inheritance patterns Nov 2, 2025
@cofin cofin force-pushed the feat/table-name-funk branch from 0524407 to 06f9b18 Compare November 3, 2025 00:36
Adds Single Table Inheritance (STI), Joined Table Inheritance (JTI),
and Concrete Table Inheritance (CTI) support with automatic table handling.

- Child classes without explicit __tablename__ use parent table (STI)
- Explicit __tablename__ or foreign key creates separate table (JTI)
- concrete=True creates independent table (CTI)
- Comprehensive tests for all patterns with multiple base classes
- Add automatic detection for STI/JTI/CTI using polymorphic_on check
- Capture explicit tablenames in __init_subclass__ before SQLAlchemy processes them
- Respect user's explicit tablename choices over auto-generation
- Fix test fixture to clear model caches and avoid registry disposal issues
- All STI unit tests passing (18/18)
- Integration tests fixed by not disposing registry between tests"
@cofin
Copy link
Member Author

cofin commented Nov 16, 2025

Superseded by PR #611 which provides a complete implementation with comprehensive test coverage and support for all inheritance patterns (STI, JTI, CTI).

@cofin cofin closed this Nov 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant