[Sqlalchemy-tickets] Issue #4241: selectin loading in Single Table Inheritance produces cross join
Brought to you by:
zzzeek
From: Tim C. <iss...@bi...> - 2018-04-19 18:48:12
|
New issue 4241: selectin loading in Single Table Inheritance produces cross join https://bitbucket.org/zzzeek/sqlalchemy/issues/4241/selectin-loading-in-single-table Tim Chen: ``` #!python from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import event Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) type = Column(String) __mapper_args__ = { 'polymorphic_on': type, } class EmployerUser(User): # __tablename__ = 'employer_user' # id = Column(Integer, ForeignKey('user.id'), primary_key=True) roles = relationship('Role', lazy='selectin') __mapper_args__ = { 'polymorphic_identity': 'employer', } class Role(Base): __tablename__ = 'role' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user.id')) e = create_engine("sqlite://", echo=True) Base.metadata.create_all(e) s = Session(e) user = EmployerUser(roles=[Role(), Role(), Role()]) s.add(user) s.commit() s.query(EmployerUser).all() ``` The generated selectin load SQL looks like this: ``` #!sql SELECT user_1.id AS user_1_id, role.id AS role_id, role.user_id AS role_user_id FROM user, user AS user_1 JOIN role ON user_1.id = role.user_id WHERE user_1.id IN (?) AND user.type IN (?) AND user_1.type IN (?) ORDER BY user_1.id ``` You can see that user gets cross joined to itself, blowing up the result set unnecessarily. This becomes a huge problem for large tables. |