add_entity and before_compile event

Issue #3387 resolved
Jared created an issue

When adding an entity to a query "before_compile" the query is correctly executed but the row processor(s) used in orm.loading.instances still refer to the original query object - specifically the _entities list.

So if you had say related User and Address models and some query,

q = sess.query(User).filter_by(first_name='John')

and a listener,

@event.listens_for(SomeQuery, 'before_compile', retval=True)
def change_query(query):
    return query.add_entity(Address).join(Address)

You would expect the query to yield KeyedTuple but instead User entity is used.

A potential solution would be to change Query._execute_and_instances to return,

loading.instances(querycontext.query, result, query context)

instead of,

loading.instances(self, result, querycontext)

But this change may have other side-effects?

Comments (4)

  1. Mike Bayer repo owner

    kudos for using the new feature so quickly! I think your solution is correct:

    diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py
    index 2bd6889..c3638f6 100644
    --- a/lib/sqlalchemy/orm/query.py
    +++ b/lib/sqlalchemy/orm/query.py
    @@ -2528,7 +2528,7 @@ class Query(object):
                 close_with_result=True)
    
             result = conn.execute(querycontext.statement, self._params)
    -        return loading.instances(self, result, querycontext)
    +        return loading.instances(querycontext.query, result, querycontext)
    
         @property
         def column_descriptions(self):
    

    all tests pass with that and the change seems like it should be appropriate.

    tagging this for 1.0.3 and I'll see if i can test more fully. the feature is very new so only has one test so far :)

  2. Mike Bayer repo owner
    • Fixed issue in new :meth:.QueryEvents.before_compile event where changes made to the :class:.Query object's collection of entities to load within the event would render in the SQL, but would not be reflected during the loading process. fixes #3387

    → <<cset d48acff23bc0>>

  3. Log in to comment