mapper._optimized_get needs to take column property expressions into account

Issue #1480 resolved
Mike Bayer repo owner created an issue

fix:

Index: lib/sqlalchemy/orm/mapper.py
===================================================================
--- lib/sqlalchemy/orm/mapper.py    (revision 6121)
+++ lib/sqlalchemy/orm/mapper.py    (working copy)
@@ -1138,7 +1138,7 @@
             return None

         cond = sql.and_(*allconds)
-        return sql.select(tables, cond, use_labels=True)
+        return sql.select([props[key](props[key).columns[0](0) for key in attribute_names], cond, use_labels=True)

     def cascade_iterator(self, type_, state, halt_on=None):
         """Iterate each element and its mapper in an object graph,

test, please adapt:

from sqlalchemy import *
from sqlalchemy.orm import *

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

parties=Table('parties', metadata,
              Column('id', Integer, primary_key=True),
              Column('type', String(1), nullable=False) 
              )

class Party(object):
    pass

persons=Table('persons', metadata,
              Column('id', Integer, ForeignKey('parties.id'),primary_key=True), 
              Column('first_name', String(50)),
              Column('last_name', String(50))
              )

class Person(Party):
    def __init__(self, first_name, last_name):
        self.first_name=first_name
        self.last_name=last_name

mapper(Party, parties, polymorphic_on=parties.c.type,polymorphic_identity='T')
mapper(Person, persons, inherits=Party, polymorphic_identity='P',
properties={
    'full_name': column_property((persons.c.first_name + ' ' +persons.c.last_name).label('full_name'))
})

metadata.create_all(db_engine)
s=sessionmaker(bind=db_engine)()
s.add(Person('John', 'Smith'))
s.commit()
all_parties=s.query(Party).all()
assert all_parties[0](0).full_name=='John Smith', all_parties[0](0).full_name

also include a test for a ColumnExpression that builds on the base table + the subclass table. This will probably end up requiring that the scan for tables in the method needs to do a full search for tables among column expressions, rather than just looking at "parent".

Comments (3)

  1. Log in to comment