unexpected/inconsistent aliasing applied to single-table inh subclass in query.join()

Issue #3233 resolved
Mike Bayer repo owner created an issue
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)
    type = Column(String)

    __mapper_args__ = {
        'polymorphic_on': type,
        'polymorphic_identity': 'a'
    }


class ASub1(A):
    __mapper_args__ = {
        'polymorphic_identity': 'asub1'
    }


class ASub2(A):
    __mapper_args__ = {
        'polymorphic_identity': 'asub2'
    }


class B(Base):
    __tablename__ = 'b'

    id = Column(Integer, primary_key=True)

    a1_id = Column(Integer, ForeignKey("a.id"))
    a2_id = Column(Integer, ForeignKey("a.id"))

    a1 = relationship("A", primaryjoin="B.a1_id == A.id", backref='b1')
    a2 = relationship("A", primaryjoin="B.a2_id == A.id", backref='b2')

s = Session()

print s.query(ASub1).join(B, ASub1.b1).join(ASub2, B.a2)

print s.query(ASub1).join(B, ASub1.b1).join(ASub2, ASub2.id == B.a2_id)

first query:

SELECT a.id AS a_id, a.type AS a_type 
FROM a JOIN b ON b.a1_id = a.id JOIN a ON b.a2_id = a.id AND a.type IN (:type_1) 
WHERE a.type IN (:type_2)

second query, it's automatigically aliasing ASub2, bizarrely without the relationship:

SELECT a.id AS a_id, a.type AS a_type 
FROM a JOIN b ON b.a1_id = a.id JOIN a AS a_1 ON a_1.id = b.a2_id AND a_1.type IN (:type_1) 
WHERE a_1.type IN (:type_2)

this is really bad, is this happening with joined inheritance, whats the rules for the magic aliasing here? changing this is going to be really backwards incompatible.

Comments (3)

  1. Mike Bayer reporter

    with joined inh, it seems we alias the target in both cases, as that is probably a given when we join to a joined inh as a target.

  2. Mike Bayer reporter
    • Fixed bug in single table inheritance where a chain of joins that included the same single inh entity more than once (normally this should raise an error) could, in some cases depending on what was being joined "from", implicitly alias the second case of the single inh entity, producing a query that "worked". But as this implicit aliasing is not intended in the case of single table inheritance, it didn't really "work" fully and was very misleading, since it wouldn't always appear. fixes #3233

    → <<cset 445b9e2aff4e>>

  3. Log in to comment