def _compile(self, whereclause = None, **kwargs):
order_by = kwargs.pop('order_by', False)
if order_by is False:
order_by = self.order_by
if order_by is False:
if self.table.default_order_by() is not None:
order_by = self.table.default_order_by()
if self._should_nest(**kwargs):
s2 = sql.select(self.table.primary_key, whereclause, use_labels=True, **kwargs)
if not kwargs.get('distinct', False) and order_by:
s2.order_by(*util.to_list(order_by))
s3 = s2.alias('rowcount')
crit = []
for i in range(0, len(self.table.primary_key)):
crit.append(s3.primary_key[i] == self.table.primary_key[i])
statement = sql.select([], sql.and_(*crit), from_obj=[self.table], use_labels=True)
if order_by:
statement.order_by(*util.to_list(order_by))
else:
statement = sql.select([], whereclause, from_obj=[self.table], use_labels=True, **kwargs)
if order_by:
statement.order_by(*util.to_list(order_by))
# for a DISTINCT query, you need the columns explicitly specified in order
# to use it in "order_by". insure they are in the column criterion (particularly oid).
# TODO: this should be done at the SQL level not the mapper level
if kwargs.get('distinct', False) and order_by:
statement.append_column(*util.to_list(order_by))
# plugin point
# give all the attached properties a chance to modify the query
for key, value in self.props.iteritems():
value.setup(key, statement, **kwargs)
return statement
评论列表
文章目录