Debian Codegraph @

bitfield/models.py

raw ◀ ▶
1 Debian patch touch this file
1 from django.db.models import signals
2 from django.db.models.fields import Field, BigIntegerField
3
4 from bitfield.forms import BitFormField
5 from bitfield.query import BitQueryLookupWrapper
6 from bitfield.types import BitHandler, Bit
7
8 # Count binary capacity. Truncate "0b" prefix from binary form.
9 # Twice faster than bin(i)[2:] or math.floor(math.log(i))
10 MAX_FLAG_COUNT = int(len(bin(BigIntegerField.MAX_BIGINT)) - 2)
11
12
13 class BitFieldFlags(object):
14 def __init__(self, flags):
15 if len(flags) > MAX_FLAG_COUNT:
16 raise ValueError('Too many flags')
17 self._flags = flags
18
19 def __repr__(self):
20 return repr(self._flags)
21
22 def __iter__(self):
23 for flag in self._flags:
24 yield flag
25
26 def __getattr__(self, key):
27 if key == '_flags':
28 # Since __getattr__ is for fallback, reaching here from Python
29 # means that there's no '_flags' attribute in this object,
30 # which may be caused by intermediate state while copying etc.
31 raise AttributeError(
32 "'%s' object has no attribute '%s'" % (self.__class__.__name__, key)
33 )
34 try:
35 flags = self._flags
36 except AttributeError:
37 raise AttributeError(
38 "'%s' object has no attribute '%s'" % (self.__class__.__name__, key)
39 )
40 try:
41 flag = flags.index(key)
42 except ValueError:
43 raise AttributeError("flag {} is not registered".format(key))
44 return Bit(flag)
45
46 def iteritems(self):
47 for flag in self._flags:
48 yield flag, Bit(self._flags.index(flag))
49
50 def iterkeys(self):
51 for flag in self._flags:
52 yield flag
53
54 def itervalues(self):
55 for flag in self._flags:
56 yield Bit(self._flags.index(flag))
57
58 def items(self):
59 return list(self.iteritems())
60
61 def keys(self):
62 return list(self.iterkeys())
63
64 def values(self):
65 return list(self.itervalues())
66
67
68 class BitFieldCreator(object):
69 """
70 A placeholder class that provides a way to set the attribute on the model.
71 Descriptor for BitFields. Checks to make sure that all flags of the
72 instance match the class. This is to handle the case when caching
73 an older version of the instance and a newer version of the class is
74 available (usually during deploys).
75 """
76 def __init__(self, field):
77 self.field = field
78
79 def __set__(self, obj, value):
80 obj.__dict__[self.field.name] = self.field.to_python(value)
81
82 def __get__(self, obj, type=None):
83 if obj is None:
84 return BitFieldFlags(self.field.flags)
85 retval = obj.__dict__[self.field.name]
86 if self.field.__class__ is BitField:
87 # Update flags from class in case they've changed.
88 retval._keys = self.field.flags
89 return retval
90
91
92 class BitField(BigIntegerField):
93
94 def contribute_to_class(self, cls, name, **kwargs):
95 super(BitField, self).contribute_to_class(cls, name, **kwargs)
96 setattr(cls, self.name, BitFieldCreator(self))
97
98 def __init__(self, flags, default=None, *args, **kwargs):
99 if isinstance(flags, dict):
100 # Get only integer keys in correct range
101 valid_keys = (k for k in flags.keys() if isinstance(k, int) and (0 <= k < MAX_FLAG_COUNT))
102 if not valid_keys:
103 raise ValueError('Wrong keys or empty dictionary')
104 # Fill list with values from dict or with empty values
105 flags = [flags.get(i, '') for i in range(max(valid_keys) + 1)]
106
107 if len(flags) > MAX_FLAG_COUNT:
108 raise ValueError('Too many flags')
109
110 self._arg_flags = flags
111 flags = list(flags)
112 labels = []
113 for num, flag in enumerate(flags):
114 if isinstance(flag, (tuple, list)):
115 flags[num] = flag[0]
116 labels.append(flag[1])
117 else:
118 labels.append(flag)
119
120 if isinstance(default, (list, tuple, set, frozenset)):
121 new_value = 0
122 for flag in default:
123 new_value |= Bit(flags.index(flag))
124 default = new_value
125
126 BigIntegerField.__init__(self, default=default, *args, **kwargs)
127 self.flags = flags
128 self.labels = labels
129
130 def formfield(self, form_class=BitFormField, **kwargs):
131 choices = [(k, self.labels[self.flags.index(k)]) for k in self.flags]
132 return Field.formfield(self, form_class, choices=choices, **kwargs)
133
134 def get_prep_value(self, value):
135 if value is None:
136 return None
137 if isinstance(value, (BitHandler, Bit)):
138 value = value.mask
139 return int(value)
140
141 # def get_db_prep_save(self, value, connection):
142 # if isinstance(value, Bit):
143 # return BitQuerySaveWrapper(self.model._meta.db_table, self.name, value)
144 # return super(BitField, self).get_db_prep_save(value, connection=connection)
145
146 def to_python(self, value):
147 if isinstance(value, Bit):
148 value = value.mask
149 if not isinstance(value, BitHandler):
150 # Regression for #1425: fix bad data that was created resulting
151 # in negative values for flags. Compute the value that would
152 # have been visible ot the application to preserve compatibility.
•153 if isinstance(value, int) and value < 0:
154 new_value = 0
155 for bit_number, _ in enumerate(self.flags):
156 new_value |= (value & (2 ** bit_number))
157 value = new_value
158
159 value = BitHandler(value, self.flags, self.labels)
160 else:
161 # Ensure flags are consistent for unpickling
162 value._keys = self.flags
163 return value
164
165 def deconstruct(self):
166 name, path, args, kwargs = super(BitField, self).deconstruct()
167 args.insert(0, self._arg_flags)
168 return name, path, args, kwargs
169
170
171 BitField.register_lookup(BitQueryLookupWrapper)
172
173
174 class CompositeBitFieldWrapper(object):
175 def __init__(self, fields):
176 self.fields = fields
177
178 def __getattr__(self, attr):
179 if attr == 'fields':
180 return super(CompositeBitFieldWrapper, self).__getattr__(attr)
181
182 for field in self.fields:
183 if hasattr(field, attr):
184 return getattr(field, attr)
185 raise AttributeError('%s is not a valid flag' % attr)
186
187 def __hasattr__(self, attr):
188 if attr == 'fields':
189 return super(CompositeBitFieldWrapper, self).__hasattr__(attr)
190
191 for field in self.fields:
192 if hasattr(field, attr):
193 return True
194 return False
195
196 def __setattr__(self, attr, value):
197 if attr == 'fields':
198 super(CompositeBitFieldWrapper, self).__setattr__(attr, value)
199 return
200
201 for field in self.fields:
202 if hasattr(field, attr):
203 setattr(field, attr, value)
204 return
205 raise AttributeError('%s is not a valid flag' % attr)
206
207
208 class CompositeBitField(object):
209 is_relation = False
210 many_to_many = False
211 concrete = False
212
213 def __init__(self, fields):
214 self.fields = fields
215
216 def contribute_to_class(self, cls, name):
217 self.name = name
218 self.model = cls
219 cls._meta.private_fields.append(self)
220
221 signals.class_prepared.connect(self.validate_fields, sender=cls)
222
223 setattr(cls, name, self)
224
225 def validate_fields(self, sender, **kwargs):
226 cls = sender
227 model_fields = dict([
228 (f.name, f) for f in cls._meta.fields if f.name in self.fields])
229 all_flags = sum([model_fields[f].flags for f in self.fields], [])
230 if len(all_flags) != len(set(all_flags)):
231 raise ValueError('BitField flags must be unique.')
232
233 def __get__(self, instance, instance_type=None):
234 fields = [getattr(instance, f) for f in self.fields]
235 return CompositeBitFieldWrapper(fields)
236
237 def __set__(self, *args, **kwargs):
238 raise NotImplementedError('CompositeBitField cannot be set.')