eager aliasing should not dig into scalar or labeled selects (just like aliased selects)

Issue #947 resolved
Mike Bayer repo owner created an issue
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy import exceptions
import datetime

meta = MetaData(create_engine('sqlite://', echo=True))


users = Table('users', meta,
    Column('id', Integer, primary_key=True),
    Column('name', String(50))
    )

stuff = Table('stuff', meta,
    Column('id', Integer, primary_key=True),
    Column('date', Date),
    Column('user_id', Integer, ForeignKey('users.id')))


meta.create_all()

users.insert().execute(
    {'id':1, 'name':'user1'},
    {'id':2, 'name':'user2'},
    {'id':3, 'name':'user3'},
)

stuff.insert().execute(
    {'id':1, 'user_id':1, 'date':datetime.date(2007, 10, 15)},
    {'id':2, 'user_id':1, 'date':datetime.date(2007, 12, 15)},
    {'id':3, 'user_id':1, 'date':datetime.date(2007, 11, 15)},
    {'id':4, 'user_id':2, 'date':datetime.date(2008, 1, 15)},
    {'id':5, 'user_id':3, 'date':datetime.date(2007, 6, 15)},
)

class User(object):
    def __repr__(self):
        return "User %r, stuff: %r" % (self.id, self.stuff)

class Stuff(object):
    def __repr__(self):
        return "Stuff %r" % self.id

mapper(Stuff, stuff)


# salias = stuff # doesn't work; aliases half of the query but not the "func" part; eager aliasing should probably not dig into scalar selects
salias = stuff.alias() # works

stuff_view = select([func.max(salias.c.date).label('max_date')](func.max(salias.c.date).label('max_date'))).where(salias.c.user_id==users.c.id).correlate(users)

mapper(User, users, properties={
    'stuff':relation(Stuff, primaryjoin=and_(users.c.id==stuff.c.user_id, stuff.c.date==(stuff_view.as_scalar())))
})

sess = create_session()

print sess.query(User).options(eagerload('stuff')).all()

Comments (5)

  1. Mike Bayer reporter

    except, the "users" table does need to be aliased inside the selectable. also im not finding any code stating that aliased selects don't get dug into. its possible here that maybe also search-n-replacing the func would fix the issue, by just having the aliasing change everything to stuff_1 universally. im not seeing a way that aliasing would know to alias the "users" table, needed as per #948, but not the "stuff" table, inside the subquery.

  2. Log in to comment