|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + sqlalchemy_django_query |
| 4 | + ~~~~~~~~~~~~~~~~~~~~~~~ |
| 5 | +
|
| 6 | + A module that implements a more Django like interface for SQLAlchemy |
| 7 | + query objects. It's still API compatible with the regular one but |
| 8 | + extends it with Djangoisms. |
| 9 | +
|
| 10 | + :copyright: 2011 by Armin Ronacher, Mike Bayer. |
| 11 | + license: BSD, see LICENSE for more details. |
| 12 | +""" |
| 13 | +from sqlalchemy.orm.query import Query |
| 14 | +from sqlalchemy.orm.util import _entity_descriptor |
| 15 | +from sqlalchemy.util import to_list |
| 16 | +from sqlalchemy.sql import operators, extract |
| 17 | + |
| 18 | + |
| 19 | +class DjangoQuery(Query): |
| 20 | + """A subclass of a regular SQLAlchemy query object that implements |
| 21 | + more Django like behavior: |
| 22 | +
|
| 23 | + - `filter_by` supports implicit joining and subitem accessing with |
| 24 | + double underscores. |
| 25 | + - `exclude_by` works like `filter_by` just that every expression is |
| 26 | + automatically negated. |
| 27 | + - `order_by` supports ordering by field name with an optional `-` |
| 28 | + in front. |
| 29 | + """ |
| 30 | + _underscore_operators = { |
| 31 | + 'gt': operators.gt, |
| 32 | + 'lte': operators.lt, |
| 33 | + 'gte': operators.ge, |
| 34 | + 'le': operators.le, |
| 35 | + 'contains': operators.contains_op, |
| 36 | + 'in': operators.in_op, |
| 37 | + 'exact': operators.eq, |
| 38 | + 'iexact': operators.ilike_op, |
| 39 | + 'startswith': operators.startswith_op, |
| 40 | + 'istartswith': lambda c, x: c.ilike(x.replace('%', '%%') + '%'), |
| 41 | + 'iendswith': lambda c, x: c.ilike('%' + x.replace('%', '%%')), |
| 42 | + 'endswith': operators.endswith_op, |
| 43 | + 'isnull': lambda c, x: x and c != None or c == None, |
| 44 | + 'range': operators.between_op, |
| 45 | + 'year': lambda c, x: extract('year', c) == x, |
| 46 | + 'month': lambda c, x: extract('month', c) == x, |
| 47 | + 'day': lambda c, x: extract('day', c) == x |
| 48 | + } |
| 49 | + |
| 50 | + def filter_by(self, **kwargs): |
| 51 | + return self._filter_or_exclude(False, kwargs) |
| 52 | + |
| 53 | + def exclude_by(self, **kwargs): |
| 54 | + return self._filter_or_exclude(True, kwargs) |
| 55 | + |
| 56 | + def order_by(self, *args): |
| 57 | + args = list(args) |
| 58 | + joins_needed = [] |
| 59 | + for idx, arg in enumerate(args): |
| 60 | + q = self |
| 61 | + if not isinstance(arg, basestring): |
| 62 | + continue |
| 63 | + if arg[0] in '+-': |
| 64 | + desc = arg[0] == '-' |
| 65 | + arg = arg[1:] |
| 66 | + else: |
| 67 | + desc = False |
| 68 | + q = self |
| 69 | + column = None |
| 70 | + for token in arg.split('__'): |
| 71 | + column = _entity_descriptor(q._joinpoint_zero(), token) |
| 72 | + if column.impl.uses_objects: |
| 73 | + q = q.join(column) |
| 74 | + joins_needed.append(column) |
| 75 | + column = None |
| 76 | + if column is None: |
| 77 | + raise ValueError('Tried to order by table, column expected') |
| 78 | + if desc: |
| 79 | + column = column.desc() |
| 80 | + args[idx] = column |
| 81 | + |
| 82 | + q = Query.order_by(self, *args) |
| 83 | + for join in joins_needed: |
| 84 | + q = q.join(join) |
| 85 | + return q |
| 86 | + |
| 87 | + def _filter_or_exclude(self, negate, kwargs): |
| 88 | + q = self |
| 89 | + negate_if = lambda expr: expr if not negate else ~expr |
| 90 | + column = None |
| 91 | + |
| 92 | + for arg, value in kwargs.iteritems(): |
| 93 | + for token in arg.split('__'): |
| 94 | + if column is None: |
| 95 | + column = _entity_descriptor(q._joinpoint_zero(), token) |
| 96 | + if column.impl.uses_objects: |
| 97 | + q = q.join(column) |
| 98 | + column = None |
| 99 | + elif token in self._underscore_operators: |
| 100 | + op = self._underscore_operators[token] |
| 101 | + q = q.filter(negate_if(op(column, *to_list(value)))) |
| 102 | + column = None |
| 103 | + else: |
| 104 | + raise ValueError('No idea what to do with %r' % token) |
| 105 | + if column is not None: |
| 106 | + q = q.filter(negate_if(column == value)) |
| 107 | + column = None |
| 108 | + q = q.reset_joinpoint() |
| 109 | + return q |
0 commit comments