Last active
August 29, 2015 14:07
-
-
Save nickretallack/b808ebb7c330d699321d to your computer and use it in GitHub Desktop.
This should work, right? This demonstrates an issue I'm having with composite primary keys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy import Column, ForeignKey, Integer, String, ForeignKeyConstraint | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import sessionmaker, relationship | |
Base = declarative_base() | |
class Tenant(Base): | |
__tablename__ = 'tenant' | |
id = Column(Integer, primary_key=True) | |
name = Column(String) | |
class Friend(Base): | |
__tablename__ = 'friend' | |
id = Column(Integer, primary_key=True) | |
tenant_id = Column(ForeignKey('tenant.id'), primary_key=True) | |
name = Column(String) | |
tenant = relationship(Tenant) | |
class Parent(Base): | |
__tablename__ = 'parent' | |
id = Column(Integer, primary_key=True) | |
tenant_id = Column(ForeignKey('tenant.id'), primary_key=True) | |
tenant = relationship(Tenant) | |
class Child(Parent): | |
__tablename__ = 'child' | |
id = Column(Integer, primary_key=True) | |
tenant_id = Column(ForeignKey('tenant.id'), primary_key=True) | |
friend_id = Column(Integer) | |
name = Column(String) | |
__table_args__ = ( | |
# superclass relationship | |
ForeignKeyConstraint( | |
(id, tenant_id), | |
('parent.id','parent.tenant_id'), | |
), | |
# friend relationship | |
ForeignKeyConstraint( | |
(friend_id, tenant_id), | |
('friend.id','friend.tenant_id'), | |
), | |
) | |
parent = relationship(Parent) | |
friend = relationship(Friend) | |
engine = create_engine('sqlite:///:memory:', echo=True) | |
Session = sessionmaker(bind=engine) | |
def run(): | |
# Basic Setup | |
Base.metadata.create_all(engine) | |
session = Session() | |
# Make a child with a friend | |
tenant = Tenant(name="testing", id=1) | |
child = Child(name="Bob", tenant=tenant, id=1) | |
friend = Friend(name="George", tenant=tenant, id=1) | |
child.friend = friend | |
session.add_all([tenant, child, friend]) | |
session.commit() | |
# Take away the friend | |
child = session.query(Child).first() | |
child.friend = None | |
session.commit() | |
if __name__ == '__main__': | |
run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AssertionError: Dependency rule tried to blank-out primary key column 'child.tenant_id' on instance '<Child at 0x10c8719d0>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment