| 1 |
import datetime |
| 2 |
import json |
| 3 |
|
| 4 |
from django.contrib.postgres import forms, lookups |
| 5 |
from django.db import models |
| 6 |
from django.db.backends.postgresql.psycopg_any import ( |
| 7 |
DateRange, |
| 8 |
DateTimeTZRange, |
| 9 |
NumericRange, |
| 10 |
Range, |
| 11 |
) |
| 12 |
from django.db.models.functions import Cast |
| 13 |
from django.db.models.lookups import PostgresOperatorLookup |
| 14 |
|
| 15 |
from .utils import AttributeSetter |
| 16 |
|
| 17 |
__all__ = [ |
| 18 |
"RangeField", |
| 19 |
"IntegerRangeField", |
| 20 |
"BigIntegerRangeField", |
| 21 |
"DecimalRangeField", |
| 22 |
"DateTimeRangeField", |
| 23 |
"DateRangeField", |
| 24 |
"RangeBoundary", |
| 25 |
"RangeOperators", |
| 26 |
] |
| 27 |
|
| 28 |
|
| 29 |
class RangeBoundary(models.Expression): |
| 30 |
"""A class that represents range boundaries.""" |
| 31 |
|
| 32 |
def __init__(self, inclusive_lower=True, inclusive_upper=False): |
| 33 |
self.lower = "[" if inclusive_lower else "(" |
| 34 |
self.upper = "]" if inclusive_upper else ")" |
| 35 |
|
| 36 |
def as_sql(self, compiler, connection): |
| 37 |
return "'%s%s'" % (self.lower, self.upper), [] |
| 38 |
|
| 39 |
|
| 40 |
class RangeOperators: |
| 41 |
# https://www.postgresql.org/docs/current/functions-range.html#RANGE-OPERATORS-TABLE |
| 42 |
EQUAL = "=" |
| 43 |
NOT_EQUAL = "<>" |
| 44 |
CONTAINS = "@>" |
| 45 |
CONTAINED_BY = "<@" |
| 46 |
OVERLAPS = "&&" |
| 47 |
FULLY_LT = "<<" |
| 48 |
FULLY_GT = ">>" |
| 49 |
NOT_LT = "&>" |
| 50 |
NOT_GT = "&<" |
| 51 |
ADJACENT_TO = "-|-" |
| 52 |
|
| 53 |
|
| 54 |
class RangeField(models.Field): |
| 55 |
empty_strings_allowed = False |
| 56 |
|
| 57 |
def __init__(self, *args, **kwargs): |
| 58 |
if "default_bounds" in kwargs: |
| 59 |
raise TypeError( |
| 60 |
f"Cannot use 'default_bounds' with {self.__class__.__name__}." |
| 61 |
) |
| 62 |
# Initializing base_field here ensures that its model matches the model |
| 63 |
# for self. |
| 64 |
if hasattr(self, "base_field"): |
| 65 |
self.base_field = self.base_field() |
| 66 |
super().__init__(*args, **kwargs) |
| 67 |
|
| 68 |
@property |
| 69 |
def model(self): |
| 70 |
try: |
| 71 |
return self.__dict__["model"] |
| 72 |
except KeyError: |
| 73 |
raise AttributeError( |
| 74 |
"'%s' object has no attribute 'model'" % self.__class__.__name__ |
| 75 |
) |
| 76 |
|
| 77 |
@model.setter |
| 78 |
def model(self, model): |
| 79 |
self.__dict__["model"] = model |
| 80 |
self.base_field.model = model |
| 81 |
|
| 82 |
@classmethod |
| 83 |
def _choices_is_value(cls, value): |
| 84 |
return isinstance(value, (list, tuple)) or super()._choices_is_value(value) |
| 85 |
|
| 86 |
def get_placeholder(self, value, compiler, connection): |
| 87 |
return "%s::{}".format(self.db_type(connection)) |
| 88 |
|
| 89 |
def get_prep_value(self, value): |
| 90 |
if value is None: |
| 91 |
return None |
| 92 |
elif isinstance(value, Range): |
| 93 |
return value |
| 94 |
elif isinstance(value, (list, tuple)): |
| 95 |
return self.range_type(value[0], value[1]) |
| 96 |
return value |
| 97 |
|
| 98 |
def to_python(self, value): |
| 99 |
if isinstance(value, str): |
| 100 |
# Assume we're deserializing |
| 101 |
vals = json.loads(value) |
| 102 |
for end in ("lower", "upper"): |
| 103 |
if end in vals: |
| 104 |
vals[end] = self.base_field.to_python(vals[end]) |
| 105 |
value = self.range_type(**vals) |
| 106 |
elif isinstance(value, (list, tuple)): |
| 107 |
value = self.range_type(value[0], value[1]) |
| 108 |
return value |
| 109 |
|
| 110 |
def set_attributes_from_name(self, name): |
| 111 |
super().set_attributes_from_name(name) |
| 112 |
self.base_field.set_attributes_from_name(name) |
| 113 |
|
| 114 |
def value_to_string(self, obj): |
| 115 |
value = self.value_from_object(obj) |
| 116 |
if value is None: |
| 117 |
return None |
| 118 |
if value.isempty: |
| 119 |
return json.dumps({"empty": True}) |
| 120 |
base_field = self.base_field |
| 121 |
result = {"bounds": value._bounds} |
| 122 |
for end in ("lower", "upper"): |
| 123 |
val = getattr(value, end) |
| 124 |
if val is None: |
| 125 |
result[end] = None |
| 126 |
else: |
| 127 |
obj = AttributeSetter(base_field.attname, val) |
| 128 |
result[end] = base_field.value_to_string(obj) |
| 129 |
return json.dumps(result) |
| 130 |
|
| 131 |
def formfield(self, **kwargs): |
| 132 |
kwargs.setdefault("form_class", self.form_field) |
| 133 |
return super().formfield(**kwargs) |
| 134 |
|
| 135 |
|
| 136 |
CANONICAL_RANGE_BOUNDS = "[)" |
| 137 |
|
| 138 |
|
| 139 |
class ContinuousRangeField(RangeField): |
| 140 |
""" |
| 141 |
Continuous range field. It allows specifying default bounds for list and |
| 142 |
tuple inputs. |
| 143 |
""" |
| 144 |
|
| 145 |
def __init__(self, *args, default_bounds=CANONICAL_RANGE_BOUNDS, **kwargs): |
| 146 |
if default_bounds not in ("[)", "(]", "()", "[]"): |
| 147 |
raise ValueError("default_bounds must be one of '[)', '(]', '()', or '[]'.") |
| 148 |
self.default_bounds = default_bounds |
| 149 |
super().__init__(*args, **kwargs) |
| 150 |
|
| 151 |
def get_prep_value(self, value): |
| 152 |
if isinstance(value, (list, tuple)): |
| 153 |
return self.range_type(value[0], value[1], self.default_bounds) |
| 154 |
return super().get_prep_value(value) |
| 155 |
|
| 156 |
def formfield(self, **kwargs): |
| 157 |
kwargs.setdefault("default_bounds", self.default_bounds) |
| 158 |
return super().formfield(**kwargs) |
| 159 |
|
| 160 |
def deconstruct(self): |
| 161 |
name, path, args, kwargs = super().deconstruct() |
| 162 |
if self.default_bounds and self.default_bounds != CANONICAL_RANGE_BOUNDS: |
| 163 |
kwargs["default_bounds"] = self.default_bounds |
| 164 |
return name, path, args, kwargs |
| 165 |
|
| 166 |
|
| 167 |
class IntegerRangeField(RangeField): |
| 168 |
base_field = models.IntegerField |
| 169 |
range_type = NumericRange |
| 170 |
form_field = forms.IntegerRangeField |
| 171 |
|
| 172 |
def db_type(self, connection): |
| 173 |
return "int4range" |
| 174 |
|
| 175 |
|
| 176 |
class BigIntegerRangeField(RangeField): |
| 177 |
base_field = models.BigIntegerField |
| 178 |
range_type = NumericRange |
| 179 |
form_field = forms.IntegerRangeField |
| 180 |
|
| 181 |
def db_type(self, connection): |
| 182 |
return "int8range" |
| 183 |
|
| 184 |
|
| 185 |
class DecimalRangeField(ContinuousRangeField): |
| 186 |
base_field = models.DecimalField |
| 187 |
range_type = NumericRange |
| 188 |
form_field = forms.DecimalRangeField |
| 189 |
|
| 190 |
def db_type(self, connection): |
| 191 |
return "numrange" |
| 192 |
|
| 193 |
|
| 194 |
class DateTimeRangeField(ContinuousRangeField): |
| 195 |
base_field = models.DateTimeField |
| 196 |
range_type = DateTimeTZRange |
| 197 |
form_field = forms.DateTimeRangeField |
| 198 |
|
| 199 |
def db_type(self, connection): |
| 200 |
return "tstzrange" |
| 201 |
|
| 202 |
|
| 203 |
class DateRangeField(RangeField): |
| 204 |
base_field = models.DateField |
| 205 |
range_type = DateRange |
| 206 |
form_field = forms.DateRangeField |
| 207 |
|
| 208 |
def db_type(self, connection): |
| 209 |
return "daterange" |
| 210 |
|
| 211 |
|
| 212 |
class RangeContains(lookups.DataContains): |
| 213 |
def get_prep_lookup(self): |
| 214 |
if not isinstance(self.rhs, (list, tuple, Range)): |
| 215 |
return Cast(self.rhs, self.lhs.field.base_field) |
| 216 |
return super().get_prep_lookup() |
| 217 |
|
| 218 |
|
| 219 |
RangeField.register_lookup(RangeContains) |
| 220 |
RangeField.register_lookup(lookups.ContainedBy) |
| 221 |
RangeField.register_lookup(lookups.Overlap) |
| 222 |
|
| 223 |
|
| 224 |
class DateTimeRangeContains(PostgresOperatorLookup): |
| 225 |
""" |
| 226 |
Lookup for Date/DateTimeRange containment to cast the rhs to the correct |
| 227 |
type. |
| 228 |
""" |
| 229 |
|
| 230 |
lookup_name = "contains" |
| 231 |
postgres_operator = RangeOperators.CONTAINS |
| 232 |
|
| 233 |
def process_rhs(self, compiler, connection): |
| 234 |
# Transform rhs value for db lookup. |
| 235 |
if isinstance(self.rhs, datetime.date): |
| 236 |
value = models.Value(self.rhs) |
| 237 |
self.rhs = value.resolve_expression(compiler.query) |
| 238 |
return super().process_rhs(compiler, connection) |
| 239 |
|
| 240 |
def as_postgresql(self, compiler, connection): |
| 241 |
sql, params = super().as_postgresql(compiler, connection) |
| 242 |
# Cast the rhs if needed. |
| 243 |
cast_sql = "" |
| 244 |
if ( |
| 245 |
isinstance(self.rhs, models.Expression) |
| 246 |
and self.rhs._output_field_or_none |
| 247 |
and |
| 248 |
# Skip cast if rhs has a matching range type. |
| 249 |
not isinstance( |
| 250 |
self.rhs._output_field_or_none, self.lhs.output_field.__class__ |
| 251 |
) |
| 252 |
): |
| 253 |
cast_internal_type = self.lhs.output_field.base_field.get_internal_type() |
| 254 |
cast_sql = "::{}".format(connection.data_types.get(cast_internal_type)) |
| 255 |
return "%s%s" % (sql, cast_sql), params |
| 256 |
|
| 257 |
|
| 258 |
DateRangeField.register_lookup(DateTimeRangeContains) |
| 259 |
DateTimeRangeField.register_lookup(DateTimeRangeContains) |
| 260 |
|
| 261 |
|
| 262 |
class RangeContainedBy(PostgresOperatorLookup): |
| 263 |
lookup_name = "contained_by" |
| 264 |
type_mapping = { |
| 265 |
"smallint": "int4range", |
| 266 |
"integer": "int4range", |
| 267 |
"bigint": "int8range", |
| 268 |
"double precision": "numrange", |
| 269 |
"numeric": "numrange", |
| 270 |
"date": "daterange", |
| 271 |
"timestamp with time zone": "tstzrange", |
| 272 |
} |
| 273 |
postgres_operator = RangeOperators.CONTAINED_BY |
| 274 |
|
| 275 |
def process_rhs(self, compiler, connection): |
| 276 |
rhs, rhs_params = super().process_rhs(compiler, connection) |
| 277 |
# Ignore precision for DecimalFields. |
| 278 |
db_type = self.lhs.output_field.cast_db_type(connection).split("(")[0] |
| 279 |
cast_type = self.type_mapping[db_type] |
| 280 |
return "%s::%s" % (rhs, cast_type), rhs_params |
| 281 |
|
| 282 |
def process_lhs(self, compiler, connection): |
| 283 |
lhs, lhs_params = super().process_lhs(compiler, connection) |
| 284 |
if isinstance(self.lhs.output_field, models.FloatField): |
| 285 |
lhs = "%s::numeric" % lhs |
| 286 |
elif isinstance(self.lhs.output_field, models.SmallIntegerField): |
| 287 |
lhs = "%s::integer" % lhs |
| 288 |
return lhs, lhs_params |
| 289 |
|
| 290 |
def get_prep_lookup(self): |
| 291 |
return RangeField().get_prep_value(self.rhs) |
| 292 |
|
| 293 |
|
| 294 |
models.DateField.register_lookup(RangeContainedBy) |
| 295 |
models.DateTimeField.register_lookup(RangeContainedBy) |
| 296 |
models.IntegerField.register_lookup(RangeContainedBy) |
| 297 |
models.FloatField.register_lookup(RangeContainedBy) |
| 298 |
models.DecimalField.register_lookup(RangeContainedBy) |
| 299 |
|
| 300 |
|
| 301 |
@RangeField.register_lookup |
| 302 |
class FullyLessThan(PostgresOperatorLookup): |
| 303 |
lookup_name = "fully_lt" |
| 304 |
postgres_operator = RangeOperators.FULLY_LT |
| 305 |
|
| 306 |
|
| 307 |
@RangeField.register_lookup |
| 308 |
class FullGreaterThan(PostgresOperatorLookup): |
| 309 |
lookup_name = "fully_gt" |
| 310 |
postgres_operator = RangeOperators.FULLY_GT |
| 311 |
|
| 312 |
|
| 313 |
@RangeField.register_lookup |
| 314 |
class NotLessThan(PostgresOperatorLookup): |
| 315 |
lookup_name = "not_lt" |
| 316 |
postgres_operator = RangeOperators.NOT_LT |
| 317 |
|
| 318 |
|
| 319 |
@RangeField.register_lookup |
| 320 |
class NotGreaterThan(PostgresOperatorLookup): |
| 321 |
lookup_name = "not_gt" |
| 322 |
postgres_operator = RangeOperators.NOT_GT |
| 323 |
|
| 324 |
|
| 325 |
@RangeField.register_lookup |
| 326 |
class AdjacentToLookup(PostgresOperatorLookup): |
| 327 |
lookup_name = "adjacent_to" |
| 328 |
postgres_operator = RangeOperators.ADJACENT_TO |
| 329 |
|
| 330 |
|
| 331 |
@RangeField.register_lookup |
| 332 |
class RangeStartsWith(models.Transform): |
| 333 |
lookup_name = "startswith" |
| 334 |
function = "lower" |
| 335 |
|
| 336 |
@property |
| 337 |
def output_field(self): |
| 338 |
return self.lhs.output_field.base_field |
| 339 |
|
| 340 |
|
| 341 |
@RangeField.register_lookup |
| 342 |
class RangeEndsWith(models.Transform): |
| 343 |
lookup_name = "endswith" |
| 344 |
function = "upper" |
| 345 |
|
| 346 |
@property |
| 347 |
def output_field(self): |
| 348 |
return self.lhs.output_field.base_field |
| 349 |
|
| 350 |
|
| 351 |
@RangeField.register_lookup |
| 352 |
class IsEmpty(models.Transform): |
| 353 |
lookup_name = "isempty" |
| 354 |
function = "isempty" |
| 355 |
output_field = models.BooleanField() |
| 356 |
|
| 357 |
|
| 358 |
@RangeField.register_lookup |
| 359 |
class LowerInclusive(models.Transform): |
| 360 |
lookup_name = "lower_inc" |
| 361 |
function = "LOWER_INC" |
| 362 |
output_field = models.BooleanField() |
| 363 |
|
| 364 |
|
| 365 |
@RangeField.register_lookup |
| 366 |
class LowerInfinite(models.Transform): |
| 367 |
lookup_name = "lower_inf" |
| 368 |
function = "LOWER_INF" |
| 369 |
output_field = models.BooleanField() |
| 370 |
|
| 371 |
|
| 372 |
@RangeField.register_lookup |
| 373 |
class UpperInclusive(models.Transform): |
| 374 |
lookup_name = "upper_inc" |
| 375 |
function = "UPPER_INC" |
| 376 |
output_field = models.BooleanField() |
| 377 |
|
| 378 |
|
| 379 |
@RangeField.register_lookup |
| 380 |
class UpperInfinite(models.Transform): |
| 381 |
lookup_name = "upper_inf" |
| 382 |
function = "UPPER_INF" |
| 383 |
output_field = models.BooleanField() |