lookups.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import itertools
  2. import math
  3. import warnings
  4. from django.core.exceptions import EmptyResultSet, FullResultSet
  5. from django.db.backends.base.operations import BaseDatabaseOperations
  6. from django.db.models.expressions import Case, Expression, Func, Value, When
  7. from django.db.models.fields import (
  8. BooleanField,
  9. CharField,
  10. DateTimeField,
  11. Field,
  12. IntegerField,
  13. UUIDField,
  14. )
  15. from django.db.models.query_utils import RegisterLookupMixin
  16. from django.utils.datastructures import OrderedSet
  17. from django.utils.deprecation import RemovedInDjango60Warning
  18. from django.utils.functional import cached_property
  19. from django.utils.hashable import make_hashable
  20. class Lookup(Expression):
  21. lookup_name = None
  22. prepare_rhs = True
  23. can_use_none_as_rhs = False
  24. def __init__(self, lhs, rhs):
  25. self.lhs, self.rhs = lhs, rhs
  26. self.rhs = self.get_prep_lookup()
  27. self.lhs = self.get_prep_lhs()
  28. if hasattr(self.lhs, "get_bilateral_transforms"):
  29. bilateral_transforms = self.lhs.get_bilateral_transforms()
  30. else:
  31. bilateral_transforms = []
  32. if bilateral_transforms:
  33. # Warn the user as soon as possible if they are trying to apply
  34. # a bilateral transformation on a nested QuerySet: that won't work.
  35. from django.db.models.sql.query import Query # avoid circular import
  36. if isinstance(rhs, Query):
  37. raise NotImplementedError(
  38. "Bilateral transformations on nested querysets are not implemented."
  39. )
  40. self.bilateral_transforms = bilateral_transforms
  41. def apply_bilateral_transforms(self, value):
  42. for transform in self.bilateral_transforms:
  43. value = transform(value)
  44. return value
  45. def __repr__(self):
  46. return f"{self.__class__.__name__}({self.lhs!r}, {self.rhs!r})"
  47. def batch_process_rhs(self, compiler, connection, rhs=None):
  48. if rhs is None:
  49. rhs = self.rhs
  50. if self.bilateral_transforms:
  51. sqls, sqls_params = [], []
  52. for p in rhs:
  53. value = Value(p, output_field=self.lhs.output_field)
  54. value = self.apply_bilateral_transforms(value)
  55. value = value.resolve_expression(compiler.query)
  56. sql, sql_params = compiler.compile(value)
  57. sqls.append(sql)
  58. sqls_params.extend(sql_params)
  59. else:
  60. _, params = self.get_db_prep_lookup(rhs, connection)
  61. sqls, sqls_params = ["%s"] * len(params), params
  62. return sqls, sqls_params
  63. def get_source_expressions(self):
  64. if self.rhs_is_direct_value():
  65. return [self.lhs]
  66. return [self.lhs, self.rhs]
  67. def set_source_expressions(self, new_exprs):
  68. if len(new_exprs) == 1:
  69. self.lhs = new_exprs[0]
  70. else:
  71. self.lhs, self.rhs = new_exprs
  72. def get_prep_lookup(self):
  73. if not self.prepare_rhs or hasattr(self.rhs, "resolve_expression"):
  74. return self.rhs
  75. if hasattr(self.lhs, "output_field"):
  76. if hasattr(self.lhs.output_field, "get_prep_value"):
  77. return self.lhs.output_field.get_prep_value(self.rhs)
  78. elif self.rhs_is_direct_value():
  79. return Value(self.rhs)
  80. return self.rhs
  81. def get_prep_lhs(self):
  82. if hasattr(self.lhs, "resolve_expression"):
  83. return self.lhs
  84. return Value(self.lhs)
  85. def get_db_prep_lookup(self, value, connection):
  86. return ("%s", [value])
  87. def process_lhs(self, compiler, connection, lhs=None):
  88. lhs = lhs or self.lhs
  89. if hasattr(lhs, "resolve_expression"):
  90. lhs = lhs.resolve_expression(compiler.query)
  91. sql, params = compiler.compile(lhs)
  92. if isinstance(lhs, Lookup):
  93. # Wrapped in parentheses to respect operator precedence.
  94. sql = f"({sql})"
  95. return sql, params
  96. def process_rhs(self, compiler, connection):
  97. value = self.rhs
  98. if self.bilateral_transforms:
  99. if self.rhs_is_direct_value():
  100. # Do not call get_db_prep_lookup here as the value will be
  101. # transformed before being used for lookup
  102. value = Value(value, output_field=self.lhs.output_field)
  103. value = self.apply_bilateral_transforms(value)
  104. value = value.resolve_expression(compiler.query)
  105. if hasattr(value, "as_sql"):
  106. sql, params = compiler.compile(value)
  107. # Ensure expression is wrapped in parentheses to respect operator
  108. # precedence but avoid double wrapping as it can be misinterpreted
  109. # on some backends (e.g. subqueries on SQLite).
  110. if sql and sql[0] != "(":
  111. sql = "(%s)" % sql
  112. return sql, params
  113. else:
  114. return self.get_db_prep_lookup(value, connection)
  115. def rhs_is_direct_value(self):
  116. return not hasattr(self.rhs, "as_sql")
  117. def get_group_by_cols(self):
  118. cols = []
  119. for source in self.get_source_expressions():
  120. cols.extend(source.get_group_by_cols())
  121. return cols
  122. def as_oracle(self, compiler, connection):
  123. # Oracle doesn't allow EXISTS() and filters to be compared to another
  124. # expression unless they're wrapped in a CASE WHEN.
  125. wrapped = False
  126. exprs = []
  127. for expr in (self.lhs, self.rhs):
  128. if connection.ops.conditional_expression_supported_in_where_clause(expr):
  129. expr = Case(When(expr, then=True), default=False)
  130. wrapped = True
  131. exprs.append(expr)
  132. lookup = type(self)(*exprs) if wrapped else self
  133. return lookup.as_sql(compiler, connection)
  134. @cached_property
  135. def output_field(self):
  136. return BooleanField()
  137. @property
  138. def identity(self):
  139. return self.__class__, self.lhs, self.rhs
  140. def __eq__(self, other):
  141. if not isinstance(other, Lookup):
  142. return NotImplemented
  143. return self.identity == other.identity
  144. def __hash__(self):
  145. return hash(make_hashable(self.identity))
  146. def resolve_expression(
  147. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  148. ):
  149. c = self.copy()
  150. c.is_summary = summarize
  151. c.lhs = self.lhs.resolve_expression(
  152. query, allow_joins, reuse, summarize, for_save
  153. )
  154. if hasattr(self.rhs, "resolve_expression"):
  155. c.rhs = self.rhs.resolve_expression(
  156. query, allow_joins, reuse, summarize, for_save
  157. )
  158. return c
  159. def select_format(self, compiler, sql, params):
  160. # Wrap filters with a CASE WHEN expression if a database backend
  161. # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
  162. # BY list.
  163. if not compiler.connection.features.supports_boolean_expr_in_select_clause:
  164. sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END"
  165. return sql, params
  166. @cached_property
  167. def allowed_default(self):
  168. return self.lhs.allowed_default and self.rhs.allowed_default
  169. class Transform(RegisterLookupMixin, Func):
  170. """
  171. RegisterLookupMixin() is first so that get_lookup() and get_transform()
  172. first examine self and then check output_field.
  173. """
  174. bilateral = False
  175. arity = 1
  176. @property
  177. def lhs(self):
  178. return self.get_source_expressions()[0]
  179. def get_bilateral_transforms(self):
  180. if hasattr(self.lhs, "get_bilateral_transforms"):
  181. bilateral_transforms = self.lhs.get_bilateral_transforms()
  182. else:
  183. bilateral_transforms = []
  184. if self.bilateral:
  185. bilateral_transforms.append(self.__class__)
  186. return bilateral_transforms
  187. class BuiltinLookup(Lookup):
  188. def process_lhs(self, compiler, connection, lhs=None):
  189. lhs_sql, params = super().process_lhs(compiler, connection, lhs)
  190. field_internal_type = self.lhs.output_field.get_internal_type()
  191. if (
  192. hasattr(connection.ops.__class__, "field_cast_sql")
  193. and connection.ops.__class__.field_cast_sql
  194. is not BaseDatabaseOperations.field_cast_sql
  195. ):
  196. warnings.warn(
  197. (
  198. "The usage of DatabaseOperations.field_cast_sql() is deprecated. "
  199. "Implement DatabaseOperations.lookup_cast() instead."
  200. ),
  201. RemovedInDjango60Warning,
  202. )
  203. db_type = self.lhs.output_field.db_type(connection=connection)
  204. lhs_sql = (
  205. connection.ops.field_cast_sql(db_type, field_internal_type) % lhs_sql
  206. )
  207. lhs_sql = (
  208. connection.ops.lookup_cast(self.lookup_name, field_internal_type) % lhs_sql
  209. )
  210. return lhs_sql, list(params)
  211. def as_sql(self, compiler, connection):
  212. lhs_sql, params = self.process_lhs(compiler, connection)
  213. rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  214. params.extend(rhs_params)
  215. rhs_sql = self.get_rhs_op(connection, rhs_sql)
  216. return "%s %s" % (lhs_sql, rhs_sql), params
  217. def get_rhs_op(self, connection, rhs):
  218. return connection.operators[self.lookup_name] % rhs
  219. class FieldGetDbPrepValueMixin:
  220. """
  221. Some lookups require Field.get_db_prep_value() to be called on their
  222. inputs.
  223. """
  224. get_db_prep_lookup_value_is_iterable = False
  225. def get_db_prep_lookup(self, value, connection):
  226. # For relational fields, use the 'target_field' attribute of the
  227. # output_field.
  228. field = getattr(self.lhs.output_field, "target_field", None)
  229. get_db_prep_value = (
  230. getattr(field, "get_db_prep_value", None)
  231. or self.lhs.output_field.get_db_prep_value
  232. )
  233. return (
  234. "%s",
  235. [get_db_prep_value(v, connection, prepared=True) for v in value]
  236. if self.get_db_prep_lookup_value_is_iterable
  237. else [get_db_prep_value(value, connection, prepared=True)],
  238. )
  239. class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin):
  240. """
  241. Some lookups require Field.get_db_prep_value() to be called on each value
  242. in an iterable.
  243. """
  244. get_db_prep_lookup_value_is_iterable = True
  245. def get_prep_lookup(self):
  246. if hasattr(self.rhs, "resolve_expression"):
  247. return self.rhs
  248. prepared_values = []
  249. for rhs_value in self.rhs:
  250. if hasattr(rhs_value, "resolve_expression"):
  251. # An expression will be handled by the database but can coexist
  252. # alongside real values.
  253. pass
  254. elif self.prepare_rhs and hasattr(self.lhs.output_field, "get_prep_value"):
  255. rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
  256. prepared_values.append(rhs_value)
  257. return prepared_values
  258. def process_rhs(self, compiler, connection):
  259. if self.rhs_is_direct_value():
  260. # rhs should be an iterable of values. Use batch_process_rhs()
  261. # to prepare/transform those values.
  262. return self.batch_process_rhs(compiler, connection)
  263. else:
  264. return super().process_rhs(compiler, connection)
  265. def resolve_expression_parameter(self, compiler, connection, sql, param):
  266. params = [param]
  267. if hasattr(param, "resolve_expression"):
  268. param = param.resolve_expression(compiler.query)
  269. if hasattr(param, "as_sql"):
  270. sql, params = compiler.compile(param)
  271. return sql, params
  272. def batch_process_rhs(self, compiler, connection, rhs=None):
  273. pre_processed = super().batch_process_rhs(compiler, connection, rhs)
  274. # The params list may contain expressions which compile to a
  275. # sql/param pair. Zip them to get sql and param pairs that refer to the
  276. # same argument and attempt to replace them with the result of
  277. # compiling the param step.
  278. sql, params = zip(
  279. *(
  280. self.resolve_expression_parameter(compiler, connection, sql, param)
  281. for sql, param in zip(*pre_processed)
  282. )
  283. )
  284. params = itertools.chain.from_iterable(params)
  285. return sql, tuple(params)
  286. class PostgresOperatorLookup(Lookup):
  287. """Lookup defined by operators on PostgreSQL."""
  288. postgres_operator = None
  289. def as_postgresql(self, compiler, connection):
  290. lhs, lhs_params = self.process_lhs(compiler, connection)
  291. rhs, rhs_params = self.process_rhs(compiler, connection)
  292. params = tuple(lhs_params) + tuple(rhs_params)
  293. return "%s %s %s" % (lhs, self.postgres_operator, rhs), params
  294. @Field.register_lookup
  295. class Exact(FieldGetDbPrepValueMixin, BuiltinLookup):
  296. lookup_name = "exact"
  297. def get_prep_lookup(self):
  298. from django.db.models.sql.query import Query # avoid circular import
  299. if isinstance(self.rhs, Query):
  300. if self.rhs.has_limit_one():
  301. if not self.rhs.has_select_fields:
  302. self.rhs.clear_select_clause()
  303. self.rhs.add_fields(["pk"])
  304. else:
  305. raise ValueError(
  306. "The QuerySet value for an exact lookup must be limited to "
  307. "one result using slicing."
  308. )
  309. return super().get_prep_lookup()
  310. def as_sql(self, compiler, connection):
  311. # Avoid comparison against direct rhs if lhs is a boolean value. That
  312. # turns "boolfield__exact=True" into "WHERE boolean_field" instead of
  313. # "WHERE boolean_field = True" when allowed.
  314. if (
  315. isinstance(self.rhs, bool)
  316. and getattr(self.lhs, "conditional", False)
  317. and connection.ops.conditional_expression_supported_in_where_clause(
  318. self.lhs
  319. )
  320. ):
  321. lhs_sql, params = self.process_lhs(compiler, connection)
  322. template = "%s" if self.rhs else "NOT %s"
  323. return template % lhs_sql, params
  324. return super().as_sql(compiler, connection)
  325. @Field.register_lookup
  326. class IExact(BuiltinLookup):
  327. lookup_name = "iexact"
  328. prepare_rhs = False
  329. def process_rhs(self, qn, connection):
  330. rhs, params = super().process_rhs(qn, connection)
  331. if params:
  332. params[0] = connection.ops.prep_for_iexact_query(params[0])
  333. return rhs, params
  334. @Field.register_lookup
  335. class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup):
  336. lookup_name = "gt"
  337. @Field.register_lookup
  338. class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup):
  339. lookup_name = "gte"
  340. @Field.register_lookup
  341. class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup):
  342. lookup_name = "lt"
  343. @Field.register_lookup
  344. class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup):
  345. lookup_name = "lte"
  346. class IntegerFieldOverflow:
  347. underflow_exception = EmptyResultSet
  348. overflow_exception = EmptyResultSet
  349. def process_rhs(self, compiler, connection):
  350. rhs = self.rhs
  351. if isinstance(rhs, int):
  352. field_internal_type = self.lhs.output_field.get_internal_type()
  353. min_value, max_value = connection.ops.integer_field_range(
  354. field_internal_type
  355. )
  356. if min_value is not None and rhs < min_value:
  357. raise self.underflow_exception
  358. if max_value is not None and rhs > max_value:
  359. raise self.overflow_exception
  360. return super().process_rhs(compiler, connection)
  361. class IntegerFieldFloatRounding:
  362. """
  363. Allow floats to work as query values for IntegerField. Without this, the
  364. decimal portion of the float would always be discarded.
  365. """
  366. def get_prep_lookup(self):
  367. if isinstance(self.rhs, float):
  368. self.rhs = math.ceil(self.rhs)
  369. return super().get_prep_lookup()
  370. @IntegerField.register_lookup
  371. class IntegerFieldExact(IntegerFieldOverflow, Exact):
  372. pass
  373. @IntegerField.register_lookup
  374. class IntegerGreaterThan(IntegerFieldOverflow, GreaterThan):
  375. underflow_exception = FullResultSet
  376. @IntegerField.register_lookup
  377. class IntegerGreaterThanOrEqual(
  378. IntegerFieldOverflow, IntegerFieldFloatRounding, GreaterThanOrEqual
  379. ):
  380. underflow_exception = FullResultSet
  381. @IntegerField.register_lookup
  382. class IntegerLessThan(IntegerFieldOverflow, IntegerFieldFloatRounding, LessThan):
  383. overflow_exception = FullResultSet
  384. @IntegerField.register_lookup
  385. class IntegerLessThanOrEqual(IntegerFieldOverflow, LessThanOrEqual):
  386. overflow_exception = FullResultSet
  387. @Field.register_lookup
  388. class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup):
  389. lookup_name = "in"
  390. def get_prep_lookup(self):
  391. from django.db.models.sql.query import Query # avoid circular import
  392. if isinstance(self.rhs, Query):
  393. self.rhs.clear_ordering(clear_default=True)
  394. if not self.rhs.has_select_fields:
  395. self.rhs.clear_select_clause()
  396. self.rhs.add_fields(["pk"])
  397. return super().get_prep_lookup()
  398. def process_rhs(self, compiler, connection):
  399. db_rhs = getattr(self.rhs, "_db", None)
  400. if db_rhs is not None and db_rhs != connection.alias:
  401. raise ValueError(
  402. "Subqueries aren't allowed across different databases. Force "
  403. "the inner query to be evaluated using `list(inner_query)`."
  404. )
  405. if self.rhs_is_direct_value():
  406. # Remove None from the list as NULL is never equal to anything.
  407. try:
  408. rhs = OrderedSet(self.rhs)
  409. rhs.discard(None)
  410. except TypeError: # Unhashable items in self.rhs
  411. rhs = [r for r in self.rhs if r is not None]
  412. if not rhs:
  413. raise EmptyResultSet
  414. # rhs should be an iterable; use batch_process_rhs() to
  415. # prepare/transform those values.
  416. sqls, sqls_params = self.batch_process_rhs(compiler, connection, rhs)
  417. placeholder = "(" + ", ".join(sqls) + ")"
  418. return (placeholder, sqls_params)
  419. return super().process_rhs(compiler, connection)
  420. def get_rhs_op(self, connection, rhs):
  421. return "IN %s" % rhs
  422. def as_sql(self, compiler, connection):
  423. max_in_list_size = connection.ops.max_in_list_size()
  424. if (
  425. self.rhs_is_direct_value()
  426. and max_in_list_size
  427. and len(self.rhs) > max_in_list_size
  428. ):
  429. return self.split_parameter_list_as_sql(compiler, connection)
  430. return super().as_sql(compiler, connection)
  431. def split_parameter_list_as_sql(self, compiler, connection):
  432. # This is a special case for databases which limit the number of
  433. # elements which can appear in an 'IN' clause.
  434. max_in_list_size = connection.ops.max_in_list_size()
  435. lhs, lhs_params = self.process_lhs(compiler, connection)
  436. rhs, rhs_params = self.batch_process_rhs(compiler, connection)
  437. in_clause_elements = ["("]
  438. params = []
  439. for offset in range(0, len(rhs_params), max_in_list_size):
  440. if offset > 0:
  441. in_clause_elements.append(" OR ")
  442. in_clause_elements.append("%s IN (" % lhs)
  443. params.extend(lhs_params)
  444. sqls = rhs[offset : offset + max_in_list_size]
  445. sqls_params = rhs_params[offset : offset + max_in_list_size]
  446. param_group = ", ".join(sqls)
  447. in_clause_elements.append(param_group)
  448. in_clause_elements.append(")")
  449. params.extend(sqls_params)
  450. in_clause_elements.append(")")
  451. return "".join(in_clause_elements), params
  452. class PatternLookup(BuiltinLookup):
  453. param_pattern = "%%%s%%"
  454. prepare_rhs = False
  455. def get_rhs_op(self, connection, rhs):
  456. # Assume we are in startswith. We need to produce SQL like:
  457. # col LIKE %s, ['thevalue%']
  458. # For python values we can (and should) do that directly in Python,
  459. # but if the value is for example reference to other column, then
  460. # we need to add the % pattern match to the lookup by something like
  461. # col LIKE othercol || '%%'
  462. # So, for Python values we don't need any special pattern, but for
  463. # SQL reference values or SQL transformations we need the correct
  464. # pattern added.
  465. if hasattr(self.rhs, "as_sql") or self.bilateral_transforms:
  466. pattern = connection.pattern_ops[self.lookup_name].format(
  467. connection.pattern_esc
  468. )
  469. return pattern.format(rhs)
  470. else:
  471. return super().get_rhs_op(connection, rhs)
  472. def process_rhs(self, qn, connection):
  473. rhs, params = super().process_rhs(qn, connection)
  474. if self.rhs_is_direct_value() and params and not self.bilateral_transforms:
  475. params[0] = self.param_pattern % connection.ops.prep_for_like_query(
  476. params[0]
  477. )
  478. return rhs, params
  479. @Field.register_lookup
  480. class Contains(PatternLookup):
  481. lookup_name = "contains"
  482. @Field.register_lookup
  483. class IContains(Contains):
  484. lookup_name = "icontains"
  485. @Field.register_lookup
  486. class StartsWith(PatternLookup):
  487. lookup_name = "startswith"
  488. param_pattern = "%s%%"
  489. @Field.register_lookup
  490. class IStartsWith(StartsWith):
  491. lookup_name = "istartswith"
  492. @Field.register_lookup
  493. class EndsWith(PatternLookup):
  494. lookup_name = "endswith"
  495. param_pattern = "%%%s"
  496. @Field.register_lookup
  497. class IEndsWith(EndsWith):
  498. lookup_name = "iendswith"
  499. @Field.register_lookup
  500. class Range(FieldGetDbPrepValueIterableMixin, BuiltinLookup):
  501. lookup_name = "range"
  502. def get_rhs_op(self, connection, rhs):
  503. return "BETWEEN %s AND %s" % (rhs[0], rhs[1])
  504. @Field.register_lookup
  505. class IsNull(BuiltinLookup):
  506. lookup_name = "isnull"
  507. prepare_rhs = False
  508. def as_sql(self, compiler, connection):
  509. if not isinstance(self.rhs, bool):
  510. raise ValueError(
  511. "The QuerySet value for an isnull lookup must be True or False."
  512. )
  513. if isinstance(self.lhs, Value):
  514. if self.lhs.value is None or (
  515. self.lhs.value == ""
  516. and connection.features.interprets_empty_strings_as_nulls
  517. ):
  518. result_exception = FullResultSet if self.rhs else EmptyResultSet
  519. else:
  520. result_exception = EmptyResultSet if self.rhs else FullResultSet
  521. raise result_exception
  522. sql, params = self.process_lhs(compiler, connection)
  523. if self.rhs:
  524. return "%s IS NULL" % sql, params
  525. else:
  526. return "%s IS NOT NULL" % sql, params
  527. @Field.register_lookup
  528. class Regex(BuiltinLookup):
  529. lookup_name = "regex"
  530. prepare_rhs = False
  531. def as_sql(self, compiler, connection):
  532. if self.lookup_name in connection.operators:
  533. return super().as_sql(compiler, connection)
  534. else:
  535. lhs, lhs_params = self.process_lhs(compiler, connection)
  536. rhs, rhs_params = self.process_rhs(compiler, connection)
  537. sql_template = connection.ops.regex_lookup(self.lookup_name)
  538. return sql_template % (lhs, rhs), lhs_params + rhs_params
  539. @Field.register_lookup
  540. class IRegex(Regex):
  541. lookup_name = "iregex"
  542. class YearLookup(Lookup):
  543. def year_lookup_bounds(self, connection, year):
  544. from django.db.models.functions import ExtractIsoYear
  545. iso_year = isinstance(self.lhs, ExtractIsoYear)
  546. output_field = self.lhs.lhs.output_field
  547. if isinstance(output_field, DateTimeField):
  548. bounds = connection.ops.year_lookup_bounds_for_datetime_field(
  549. year,
  550. iso_year=iso_year,
  551. )
  552. else:
  553. bounds = connection.ops.year_lookup_bounds_for_date_field(
  554. year,
  555. iso_year=iso_year,
  556. )
  557. return bounds
  558. def as_sql(self, compiler, connection):
  559. # Avoid the extract operation if the rhs is a direct value to allow
  560. # indexes to be used.
  561. if self.rhs_is_direct_value():
  562. # Skip the extract part by directly using the originating field,
  563. # that is self.lhs.lhs.
  564. lhs_sql, params = self.process_lhs(compiler, connection, self.lhs.lhs)
  565. rhs_sql, _ = self.process_rhs(compiler, connection)
  566. rhs_sql = self.get_direct_rhs_sql(connection, rhs_sql)
  567. start, finish = self.year_lookup_bounds(connection, self.rhs)
  568. params.extend(self.get_bound_params(start, finish))
  569. return "%s %s" % (lhs_sql, rhs_sql), params
  570. return super().as_sql(compiler, connection)
  571. def get_direct_rhs_sql(self, connection, rhs):
  572. return connection.operators[self.lookup_name] % rhs
  573. def get_bound_params(self, start, finish):
  574. raise NotImplementedError(
  575. "subclasses of YearLookup must provide a get_bound_params() method"
  576. )
  577. class YearExact(YearLookup, Exact):
  578. def get_direct_rhs_sql(self, connection, rhs):
  579. return "BETWEEN %s AND %s"
  580. def get_bound_params(self, start, finish):
  581. return (start, finish)
  582. class YearGt(YearLookup, GreaterThan):
  583. def get_bound_params(self, start, finish):
  584. return (finish,)
  585. class YearGte(YearLookup, GreaterThanOrEqual):
  586. def get_bound_params(self, start, finish):
  587. return (start,)
  588. class YearLt(YearLookup, LessThan):
  589. def get_bound_params(self, start, finish):
  590. return (start,)
  591. class YearLte(YearLookup, LessThanOrEqual):
  592. def get_bound_params(self, start, finish):
  593. return (finish,)
  594. class UUIDTextMixin:
  595. """
  596. Strip hyphens from a value when filtering a UUIDField on backends without
  597. a native datatype for UUID.
  598. """
  599. def process_rhs(self, qn, connection):
  600. if not connection.features.has_native_uuid_field:
  601. from django.db.models.functions import Replace
  602. if self.rhs_is_direct_value():
  603. self.rhs = Value(self.rhs)
  604. self.rhs = Replace(
  605. self.rhs, Value("-"), Value(""), output_field=CharField()
  606. )
  607. rhs, params = super().process_rhs(qn, connection)
  608. return rhs, params
  609. @UUIDField.register_lookup
  610. class UUIDIExact(UUIDTextMixin, IExact):
  611. pass
  612. @UUIDField.register_lookup
  613. class UUIDContains(UUIDTextMixin, Contains):
  614. pass
  615. @UUIDField.register_lookup
  616. class UUIDIContains(UUIDTextMixin, IContains):
  617. pass
  618. @UUIDField.register_lookup
  619. class UUIDStartsWith(UUIDTextMixin, StartsWith):
  620. pass
  621. @UUIDField.register_lookup
  622. class UUIDIStartsWith(UUIDTextMixin, IStartsWith):
  623. pass
  624. @UUIDField.register_lookup
  625. class UUIDEndsWith(UUIDTextMixin, EndsWith):
  626. pass
  627. @UUIDField.register_lookup
  628. class UUIDIEndsWith(UUIDTextMixin, IEndsWith):
  629. pass