summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2011-09-19 16:48:39 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2011-09-19 16:48:39 -0400
commit00a2f0ef27d573066dfcaac509600876e8d71592 (patch)
treed0fef7a38eff58f36f32c3c54e1d231a68df09db /lib/sqlalchemy
parent57ae8672a6be786c32d79faca90666d5b654bce6 (diff)
downloadsqlalchemy-00a2f0ef27d573066dfcaac509600876e8d71592.tar.gz
- added "adapt_on_names" boolean flag to orm.aliased()
construct. Allows an aliased() construct to link the ORM entity to a selectable that contains aggregates or other derived forms of a particular attribute, provided the name is the same as that of the entity mapped column.
Diffstat (limited to 'lib/sqlalchemy')
-rw-r--r--lib/sqlalchemy/orm/util.py65
-rw-r--r--lib/sqlalchemy/sql/util.py6
2 files changed, 62 insertions, 9 deletions
diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py
index 4708852ea..f901d0a0b 100644
--- a/lib/sqlalchemy/orm/util.py
+++ b/lib/sqlalchemy/orm/util.py
@@ -221,15 +221,61 @@ class AliasedClass(object):
session.query(User, user_alias).\\
join((user_alias, User.id > user_alias.id)).\\
filter(User.name==user_alias.name)
-
+
+ The resulting object is an instance of :class:`.AliasedClass`, however
+ it implements a ``__getattribute__()`` scheme which will proxy attribute
+ access to that of the ORM class being aliased. All classmethods
+ on the mapped entity should also be available here, including
+ hybrids created with the :ref:`hybrids_toplevel` extension,
+ which will receive the :class:`.AliasedClass` as the "class" argument
+ when classmethods are called.
+
+ :param cls: ORM mapped entity which will be "wrapped" around an alias.
+ :param alias: a selectable, such as an :func:`.alias` or :func:`.select`
+ construct, which will be rendered in place of the mapped table of the
+ ORM entity. If left as ``None``, an ordinary :class:`.Alias` of the
+ ORM entity's mapped table will be generated.
+ :param name: A name which will be applied both to the :class:`.Alias`
+ if one is generated, as well as the name present in the "named tuple"
+ returned by the :class:`.Query` object when results are returned.
+ :param adapt_on_names: if True, more liberal "matching" will be used when
+ mapping the mapped columns of the ORM entity to those of the given selectable -
+ a name-based match will be performed if the given selectable doesn't
+ otherwise have a column that corresponds to one on the entity. The
+ use case for this is when associating an entity with some derived
+ selectable such as one that uses aggregate functions::
+
+ class UnitPrice(Base):
+ __tablename__ = 'unit_price'
+ ...
+ unit_id = Column(Integer)
+ price = Column(Numeric)
+
+ aggregated_unit_price = Session.query(
+ func.sum(UnitPrice.price).label('price')
+ ).group_by(UnitPrice.unit_id).subquery()
+
+ aggregated_unit_price = aliased(UnitPrice, alias=aggregated_unit_price, adapt_on_names=True)
+
+ Above, functions on ``aggregated_unit_price`` which
+ refer to ``.price`` will return the
+ ``fund.sum(UnitPrice.price).label('price')`` column,
+ as it is matched on the name "price". Ordinarily, the "price" function wouldn't
+ have any "column correspondence" to the actual ``UnitPrice.price`` column
+ as it is not a proxy of the original.
+
+ ``adapt_on_names`` is new in 0.7.3.
+
"""
- def __init__(self, cls, alias=None, name=None):
+ def __init__(self, cls, alias=None, name=None, adapt_on_names=False):
self.__mapper = _class_to_mapper(cls)
self.__target = self.__mapper.class_
+ self.__adapt_on_names = adapt_on_names
if alias is None:
alias = self.__mapper._with_polymorphic_selectable.alias(name=name)
self.__adapter = sql_util.ClauseAdapter(alias,
- equivalents=self.__mapper._equivalent_columns)
+ equivalents=self.__mapper._equivalent_columns,
+ adapt_on_names=self.__adapt_on_names)
self.__alias = alias
# used to assign a name to the RowTuple object
# returned by Query.
@@ -240,15 +286,18 @@ class AliasedClass(object):
return {
'mapper':self.__mapper,
'alias':self.__alias,
- 'name':self._sa_label_name
+ 'name':self._sa_label_name,
+ 'adapt_on_names':self.__adapt_on_names,
}
def __setstate__(self, state):
self.__mapper = state['mapper']
self.__target = self.__mapper.class_
+ self.__adapt_on_names = state['adapt_on_names']
alias = state['alias']
self.__adapter = sql_util.ClauseAdapter(alias,
- equivalents=self.__mapper._equivalent_columns)
+ equivalents=self.__mapper._equivalent_columns,
+ adapt_on_names=self.__adapt_on_names)
self.__alias = alias
name = state['name']
self._sa_label_name = name
@@ -300,11 +349,13 @@ class AliasedClass(object):
return '<AliasedClass at 0x%x; %s>' % (
id(self), self.__target.__name__)
-def aliased(element, alias=None, name=None):
+def aliased(element, alias=None, name=None, adapt_on_names=False):
if isinstance(element, expression.FromClause):
+ if adapt_on_names:
+ raise sa_exc.ArgumentError("adapt_on_names only applies to ORM elements")
return element.alias(name)
else:
- return AliasedClass(element, alias=alias, name=name)
+ return AliasedClass(element, alias=alias, name=name, adapt_on_names=adapt_on_names)
def _orm_annotate(element, exclude=None):
"""Deep copy the given ClauseElement, annotating each element with the
diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py
index 61a95d764..221a18e51 100644
--- a/lib/sqlalchemy/sql/util.py
+++ b/lib/sqlalchemy/sql/util.py
@@ -675,18 +675,18 @@ class ClauseAdapter(visitors.ReplacingCloningVisitor):
s.c.col1 == table2.c.col1
"""
- def __init__(self, selectable, equivalents=None, include=None, exclude=None):
+ def __init__(self, selectable, equivalents=None, include=None, exclude=None, adapt_on_names=False):
self.__traverse_options__ = {'stop_on':[selectable]}
self.selectable = selectable
self.include = include
self.exclude = exclude
self.equivalents = util.column_dict(equivalents or {})
+ self.adapt_on_names = adapt_on_names
def _corresponding_column(self, col, require_embedded, _seen=util.EMPTY_SET):
newcol = self.selectable.corresponding_column(
col,
require_embedded=require_embedded)
-
if newcol is None and col in self.equivalents and col not in _seen:
for equiv in self.equivalents[col]:
newcol = self._corresponding_column(equiv,
@@ -694,6 +694,8 @@ class ClauseAdapter(visitors.ReplacingCloningVisitor):
_seen=_seen.union([col]))
if newcol is not None:
return newcol
+ if self.adapt_on_names and newcol is None:
+ newcol = self.selectable.c.get(col.name)
return newcol
def replace(self, col):