Debian Codegraph @

bitfield/models.py

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