I have a class inheritance scheme as layed out in http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance and I'd like to define a constraint that uses columns from both the parent and child classes.
from sqlalchemy import (
create_engine, Column, Integer, String, ForeignKey, CheckConstraint
)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
type = Column(String)
name = Column(String)
__mapper_args__ = {'polymorphic_on': type}
class Child(Parent):
__tablename__ = 'child'
id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_name = Column(String)
__mapper_args__ = {'polymorphic_identity': 'child'}
__table_args__ = (CheckConstraint('name != child_name'),)
engine = create_engine(...)
Base.metadata.create_all(engine)
This doesn't work because name
isn't a column in child
; I get the error
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "name" does not exist
[SQL: '\nCREATE TABLE child (\n\tid INTEGER NOT NULL, \n\tPRIMARY KEY (id), \n\tCHECK (name="something"), \n\tFOREIGN KEY(id) REFERENCES parent (id)\n)\n\n']
So how can I define such a constraint?
After some tinkering I came up with a solution: create a "copy"
parent_name
column inChild
that referencesname
inParent
. It wastes some storage space, but that's probably unavoidable in order to have a realCHECK CONSTRAINT
.Here is the code:
The output of this script is