File: query.py

package info (click to toggle)
django-bitfield 1.9.6-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 180 kB
  • sloc: python: 931; makefile: 4
file content (72 lines) | stat: -rw-r--r-- 2,378 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from __future__ import absolute_import

from bitfield.types import Bit, BitHandler


class BitQueryLookupWrapper(object):
    def __init__(self, alias, column, bit):
        self.table_alias = alias
        self.column = column
        self.bit = bit

    def as_sql(self, qn, connection=None):
        """
        Create the proper SQL fragment. This inserts something like
        "(T0.flags & value) != 0".

        This will be called by Where.as_sql()
        """
        if self.bit:
            return ("(%s.%s | %d)" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                    [])
        return ("(%s.%s & %d)" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                [])


try:
    # Django 1.7+
    from django.db.models.lookups import Exact

    class BitQueryLookupWrapper(Exact):  # NOQA
        def process_lhs(self, qn, connection, lhs=None):
            lhs_sql, params = super(BitQueryLookupWrapper, self).process_lhs(
                qn, connection, lhs)
            if self.rhs:
                lhs_sql = lhs_sql + ' & %s'
            else:
                lhs_sql = lhs_sql + ' | %s'
            params.extend(self.get_db_prep_lookup(self.rhs, connection)[1])
            return lhs_sql, params

        def get_db_prep_lookup(self, value, connection, prepared=False):
            v = value.mask if isinstance(value, (BitHandler, Bit)) else value
            return super(BitQueryLookupWrapper, self).get_db_prep_lookup(v, connection)

        def get_prep_lookup(self):
            return self.rhs

except ImportError:
    pass


class BitQuerySaveWrapper(BitQueryLookupWrapper):
    def as_sql(self, qn, connection):
        """
        Create the proper SQL fragment. This inserts something like
        "(T0.flags & value) != 0".

        This will be called by Where.as_sql()
        """
        engine = connection.settings_dict['ENGINE'].rsplit('.', -1)[-1]
        if engine.startswith('postgres'):
            XOR_OPERATOR = '#'
        elif engine.startswith('sqlite'):
            raise NotImplementedError
        else:
            XOR_OPERATOR = '^'

        if self.bit:
            return ("%s.%s | %d" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                    [])
        return ("%s.%s %s %d" % (qn(self.table_alias), qn(self.column), XOR_OPERATOR, self.bit.mask),
                [])