Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

expressions.py 61KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  1. import copy
  2. import datetime
  3. import functools
  4. import inspect
  5. import warnings
  6. from collections import defaultdict
  7. from decimal import Decimal
  8. from uuid import UUID
  9. from django.core.exceptions import EmptyResultSet, FieldError
  10. from django.db import DatabaseError, NotSupportedError, connection
  11. from django.db.models import fields
  12. from django.db.models.constants import LOOKUP_SEP
  13. from django.db.models.query_utils import Q
  14. from django.utils.deconstruct import deconstructible
  15. from django.utils.deprecation import RemovedInDjango50Warning
  16. from django.utils.functional import cached_property
  17. from django.utils.hashable import make_hashable
  18. class SQLiteNumericMixin:
  19. """
  20. Some expressions with output_field=DecimalField() must be cast to
  21. numeric to be properly filtered.
  22. """
  23. def as_sqlite(self, compiler, connection, **extra_context):
  24. sql, params = self.as_sql(compiler, connection, **extra_context)
  25. try:
  26. if self.output_field.get_internal_type() == "DecimalField":
  27. sql = "CAST(%s AS NUMERIC)" % sql
  28. except FieldError:
  29. pass
  30. return sql, params
  31. class Combinable:
  32. """
  33. Provide the ability to combine one or two objects with
  34. some connector. For example F('foo') + F('bar').
  35. """
  36. # Arithmetic connectors
  37. ADD = "+"
  38. SUB = "-"
  39. MUL = "*"
  40. DIV = "/"
  41. POW = "^"
  42. # The following is a quoted % operator - it is quoted because it can be
  43. # used in strings that also have parameter substitution.
  44. MOD = "%%"
  45. # Bitwise operators - note that these are generated by .bitand()
  46. # and .bitor(), the '&' and '|' are reserved for boolean operator
  47. # usage.
  48. BITAND = "&"
  49. BITOR = "|"
  50. BITLEFTSHIFT = "<<"
  51. BITRIGHTSHIFT = ">>"
  52. BITXOR = "#"
  53. def _combine(self, other, connector, reversed):
  54. if not hasattr(other, "resolve_expression"):
  55. # everything must be resolvable to an expression
  56. other = Value(other)
  57. if reversed:
  58. return CombinedExpression(other, connector, self)
  59. return CombinedExpression(self, connector, other)
  60. #############
  61. # OPERATORS #
  62. #############
  63. def __neg__(self):
  64. return self._combine(-1, self.MUL, False)
  65. def __add__(self, other):
  66. return self._combine(other, self.ADD, False)
  67. def __sub__(self, other):
  68. return self._combine(other, self.SUB, False)
  69. def __mul__(self, other):
  70. return self._combine(other, self.MUL, False)
  71. def __truediv__(self, other):
  72. return self._combine(other, self.DIV, False)
  73. def __mod__(self, other):
  74. return self._combine(other, self.MOD, False)
  75. def __pow__(self, other):
  76. return self._combine(other, self.POW, False)
  77. def __and__(self, other):
  78. if getattr(self, "conditional", False) and getattr(other, "conditional", False):
  79. return Q(self) & Q(other)
  80. raise NotImplementedError(
  81. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  82. )
  83. def bitand(self, other):
  84. return self._combine(other, self.BITAND, False)
  85. def bitleftshift(self, other):
  86. return self._combine(other, self.BITLEFTSHIFT, False)
  87. def bitrightshift(self, other):
  88. return self._combine(other, self.BITRIGHTSHIFT, False)
  89. def __xor__(self, other):
  90. if getattr(self, "conditional", False) and getattr(other, "conditional", False):
  91. return Q(self) ^ Q(other)
  92. raise NotImplementedError(
  93. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  94. )
  95. def bitxor(self, other):
  96. return self._combine(other, self.BITXOR, False)
  97. def __or__(self, other):
  98. if getattr(self, "conditional", False) and getattr(other, "conditional", False):
  99. return Q(self) | Q(other)
  100. raise NotImplementedError(
  101. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  102. )
  103. def bitor(self, other):
  104. return self._combine(other, self.BITOR, False)
  105. def __radd__(self, other):
  106. return self._combine(other, self.ADD, True)
  107. def __rsub__(self, other):
  108. return self._combine(other, self.SUB, True)
  109. def __rmul__(self, other):
  110. return self._combine(other, self.MUL, True)
  111. def __rtruediv__(self, other):
  112. return self._combine(other, self.DIV, True)
  113. def __rmod__(self, other):
  114. return self._combine(other, self.MOD, True)
  115. def __rpow__(self, other):
  116. return self._combine(other, self.POW, True)
  117. def __rand__(self, other):
  118. raise NotImplementedError(
  119. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  120. )
  121. def __ror__(self, other):
  122. raise NotImplementedError(
  123. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  124. )
  125. def __rxor__(self, other):
  126. raise NotImplementedError(
  127. "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
  128. )
  129. class BaseExpression:
  130. """Base class for all query expressions."""
  131. empty_result_set_value = NotImplemented
  132. # aggregate specific fields
  133. is_summary = False
  134. _output_field_resolved_to_none = False
  135. # Can the expression be used in a WHERE clause?
  136. filterable = True
  137. # Can the expression can be used as a source expression in Window?
  138. window_compatible = False
  139. def __init__(self, output_field=None):
  140. if output_field is not None:
  141. self.output_field = output_field
  142. def __getstate__(self):
  143. state = self.__dict__.copy()
  144. state.pop("convert_value", None)
  145. return state
  146. def get_db_converters(self, connection):
  147. return (
  148. []
  149. if self.convert_value is self._convert_value_noop
  150. else [self.convert_value]
  151. ) + self.output_field.get_db_converters(connection)
  152. def get_source_expressions(self):
  153. return []
  154. def set_source_expressions(self, exprs):
  155. assert not exprs
  156. def _parse_expressions(self, *expressions):
  157. return [
  158. arg
  159. if hasattr(arg, "resolve_expression")
  160. else (F(arg) if isinstance(arg, str) else Value(arg))
  161. for arg in expressions
  162. ]
  163. def as_sql(self, compiler, connection):
  164. """
  165. Responsible for returning a (sql, [params]) tuple to be included
  166. in the current query.
  167. Different backends can provide their own implementation, by
  168. providing an `as_{vendor}` method and patching the Expression:
  169. ```
  170. def override_as_sql(self, compiler, connection):
  171. # custom logic
  172. return super().as_sql(compiler, connection)
  173. setattr(Expression, 'as_' + connection.vendor, override_as_sql)
  174. ```
  175. Arguments:
  176. * compiler: the query compiler responsible for generating the query.
  177. Must have a compile method, returning a (sql, [params]) tuple.
  178. Calling compiler(value) will return a quoted `value`.
  179. * connection: the database connection used for the current query.
  180. Return: (sql, params)
  181. Where `sql` is a string containing ordered sql parameters to be
  182. replaced with the elements of the list `params`.
  183. """
  184. raise NotImplementedError("Subclasses must implement as_sql()")
  185. @cached_property
  186. def contains_aggregate(self):
  187. return any(
  188. expr and expr.contains_aggregate for expr in self.get_source_expressions()
  189. )
  190. @cached_property
  191. def contains_over_clause(self):
  192. return any(
  193. expr and expr.contains_over_clause for expr in self.get_source_expressions()
  194. )
  195. @cached_property
  196. def contains_column_references(self):
  197. return any(
  198. expr and expr.contains_column_references
  199. for expr in self.get_source_expressions()
  200. )
  201. def resolve_expression(
  202. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  203. ):
  204. """
  205. Provide the chance to do any preprocessing or validation before being
  206. added to the query.
  207. Arguments:
  208. * query: the backend query implementation
  209. * allow_joins: boolean allowing or denying use of joins
  210. in this query
  211. * reuse: a set of reusable joins for multijoins
  212. * summarize: a terminal aggregate clause
  213. * for_save: whether this expression about to be used in a save or update
  214. Return: an Expression to be added to the query.
  215. """
  216. c = self.copy()
  217. c.is_summary = summarize
  218. c.set_source_expressions(
  219. [
  220. expr.resolve_expression(query, allow_joins, reuse, summarize)
  221. if expr
  222. else None
  223. for expr in c.get_source_expressions()
  224. ]
  225. )
  226. return c
  227. @property
  228. def conditional(self):
  229. return isinstance(self.output_field, fields.BooleanField)
  230. @property
  231. def field(self):
  232. return self.output_field
  233. @cached_property
  234. def output_field(self):
  235. """Return the output type of this expressions."""
  236. output_field = self._resolve_output_field()
  237. if output_field is None:
  238. self._output_field_resolved_to_none = True
  239. raise FieldError("Cannot resolve expression type, unknown output_field")
  240. return output_field
  241. @cached_property
  242. def _output_field_or_none(self):
  243. """
  244. Return the output field of this expression, or None if
  245. _resolve_output_field() didn't return an output type.
  246. """
  247. try:
  248. return self.output_field
  249. except FieldError:
  250. if not self._output_field_resolved_to_none:
  251. raise
  252. def _resolve_output_field(self):
  253. """
  254. Attempt to infer the output type of the expression.
  255. As a guess, if the output fields of all source fields match then simply
  256. infer the same type here.
  257. If a source's output field resolves to None, exclude it from this check.
  258. If all sources are None, then an error is raised higher up the stack in
  259. the output_field property.
  260. """
  261. # This guess is mostly a bad idea, but there is quite a lot of code
  262. # (especially 3rd party Func subclasses) that depend on it, we'd need a
  263. # deprecation path to fix it.
  264. sources_iter = (
  265. source for source in self.get_source_fields() if source is not None
  266. )
  267. for output_field in sources_iter:
  268. for source in sources_iter:
  269. if not isinstance(output_field, source.__class__):
  270. raise FieldError(
  271. "Expression contains mixed types: %s, %s. You must "
  272. "set output_field."
  273. % (
  274. output_field.__class__.__name__,
  275. source.__class__.__name__,
  276. )
  277. )
  278. return output_field
  279. @staticmethod
  280. def _convert_value_noop(value, expression, connection):
  281. return value
  282. @cached_property
  283. def convert_value(self):
  284. """
  285. Expressions provide their own converters because users have the option
  286. of manually specifying the output_field which may be a different type
  287. from the one the database returns.
  288. """
  289. field = self.output_field
  290. internal_type = field.get_internal_type()
  291. if internal_type == "FloatField":
  292. return (
  293. lambda value, expression, connection: None
  294. if value is None
  295. else float(value)
  296. )
  297. elif internal_type.endswith("IntegerField"):
  298. return (
  299. lambda value, expression, connection: None
  300. if value is None
  301. else int(value)
  302. )
  303. elif internal_type == "DecimalField":
  304. return (
  305. lambda value, expression, connection: None
  306. if value is None
  307. else Decimal(value)
  308. )
  309. return self._convert_value_noop
  310. def get_lookup(self, lookup):
  311. return self.output_field.get_lookup(lookup)
  312. def get_transform(self, name):
  313. return self.output_field.get_transform(name)
  314. def relabeled_clone(self, change_map):
  315. clone = self.copy()
  316. clone.set_source_expressions(
  317. [
  318. e.relabeled_clone(change_map) if e is not None else None
  319. for e in self.get_source_expressions()
  320. ]
  321. )
  322. return clone
  323. def replace_references(self, references_map):
  324. clone = self.copy()
  325. clone.set_source_expressions(
  326. [
  327. expr.replace_references(references_map)
  328. for expr in self.get_source_expressions()
  329. ]
  330. )
  331. return clone
  332. def copy(self):
  333. return copy.copy(self)
  334. def prefix_references(self, prefix):
  335. clone = self.copy()
  336. clone.set_source_expressions(
  337. [
  338. F(f"{prefix}{expr.name}")
  339. if isinstance(expr, F)
  340. else expr.prefix_references(prefix)
  341. for expr in self.get_source_expressions()
  342. ]
  343. )
  344. return clone
  345. def get_group_by_cols(self, alias=None):
  346. if not self.contains_aggregate:
  347. return [self]
  348. cols = []
  349. for source in self.get_source_expressions():
  350. cols.extend(source.get_group_by_cols())
  351. return cols
  352. def get_source_fields(self):
  353. """Return the underlying field types used by this aggregate."""
  354. return [e._output_field_or_none for e in self.get_source_expressions()]
  355. def asc(self, **kwargs):
  356. return OrderBy(self, **kwargs)
  357. def desc(self, **kwargs):
  358. return OrderBy(self, descending=True, **kwargs)
  359. def reverse_ordering(self):
  360. return self
  361. def flatten(self):
  362. """
  363. Recursively yield this expression and all subexpressions, in
  364. depth-first order.
  365. """
  366. yield self
  367. for expr in self.get_source_expressions():
  368. if expr:
  369. if hasattr(expr, "flatten"):
  370. yield from expr.flatten()
  371. else:
  372. yield expr
  373. def select_format(self, compiler, sql, params):
  374. """
  375. Custom format for select clauses. For example, EXISTS expressions need
  376. to be wrapped in CASE WHEN on Oracle.
  377. """
  378. if hasattr(self.output_field, "select_format"):
  379. return self.output_field.select_format(compiler, sql, params)
  380. return sql, params
  381. @deconstructible
  382. class Expression(BaseExpression, Combinable):
  383. """An expression that can be combined with other expressions."""
  384. @cached_property
  385. def identity(self):
  386. constructor_signature = inspect.signature(self.__init__)
  387. args, kwargs = self._constructor_args
  388. signature = constructor_signature.bind_partial(*args, **kwargs)
  389. signature.apply_defaults()
  390. arguments = signature.arguments.items()
  391. identity = [self.__class__]
  392. for arg, value in arguments:
  393. if isinstance(value, fields.Field):
  394. if value.name and value.model:
  395. value = (value.model._meta.label, value.name)
  396. else:
  397. value = type(value)
  398. else:
  399. value = make_hashable(value)
  400. identity.append((arg, value))
  401. return tuple(identity)
  402. def __eq__(self, other):
  403. if not isinstance(other, Expression):
  404. return NotImplemented
  405. return other.identity == self.identity
  406. def __hash__(self):
  407. return hash(self.identity)
  408. # Type inference for CombinedExpression.output_field.
  409. # Missing items will result in FieldError, by design.
  410. #
  411. # The current approach for NULL is based on lowest common denominator behavior
  412. # i.e. if one of the supported databases is raising an error (rather than
  413. # return NULL) for `val <op> NULL`, then Django raises FieldError.
  414. NoneType = type(None)
  415. _connector_combinations = [
  416. # Numeric operations - operands of same type.
  417. {
  418. connector: [
  419. (fields.IntegerField, fields.IntegerField, fields.IntegerField),
  420. (fields.FloatField, fields.FloatField, fields.FloatField),
  421. (fields.DecimalField, fields.DecimalField, fields.DecimalField),
  422. ]
  423. for connector in (
  424. Combinable.ADD,
  425. Combinable.SUB,
  426. Combinable.MUL,
  427. # Behavior for DIV with integer arguments follows Postgres/SQLite,
  428. # not MySQL/Oracle.
  429. Combinable.DIV,
  430. Combinable.MOD,
  431. Combinable.POW,
  432. )
  433. },
  434. # Numeric operations - operands of different type.
  435. {
  436. connector: [
  437. (fields.IntegerField, fields.DecimalField, fields.DecimalField),
  438. (fields.DecimalField, fields.IntegerField, fields.DecimalField),
  439. (fields.IntegerField, fields.FloatField, fields.FloatField),
  440. (fields.FloatField, fields.IntegerField, fields.FloatField),
  441. ]
  442. for connector in (
  443. Combinable.ADD,
  444. Combinable.SUB,
  445. Combinable.MUL,
  446. Combinable.DIV,
  447. )
  448. },
  449. # Bitwise operators.
  450. {
  451. connector: [
  452. (fields.IntegerField, fields.IntegerField, fields.IntegerField),
  453. ]
  454. for connector in (
  455. Combinable.BITAND,
  456. Combinable.BITOR,
  457. Combinable.BITLEFTSHIFT,
  458. Combinable.BITRIGHTSHIFT,
  459. Combinable.BITXOR,
  460. )
  461. },
  462. # Numeric with NULL.
  463. {
  464. connector: [
  465. (field_type, NoneType, field_type),
  466. (NoneType, field_type, field_type),
  467. ]
  468. for connector in (
  469. Combinable.ADD,
  470. Combinable.SUB,
  471. Combinable.MUL,
  472. Combinable.DIV,
  473. Combinable.MOD,
  474. Combinable.POW,
  475. )
  476. for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField)
  477. },
  478. # Date/DateTimeField/DurationField/TimeField.
  479. {
  480. Combinable.ADD: [
  481. # Date/DateTimeField.
  482. (fields.DateField, fields.DurationField, fields.DateTimeField),
  483. (fields.DateTimeField, fields.DurationField, fields.DateTimeField),
  484. (fields.DurationField, fields.DateField, fields.DateTimeField),
  485. (fields.DurationField, fields.DateTimeField, fields.DateTimeField),
  486. # DurationField.
  487. (fields.DurationField, fields.DurationField, fields.DurationField),
  488. # TimeField.
  489. (fields.TimeField, fields.DurationField, fields.TimeField),
  490. (fields.DurationField, fields.TimeField, fields.TimeField),
  491. ],
  492. },
  493. {
  494. Combinable.SUB: [
  495. # Date/DateTimeField.
  496. (fields.DateField, fields.DurationField, fields.DateTimeField),
  497. (fields.DateTimeField, fields.DurationField, fields.DateTimeField),
  498. (fields.DateField, fields.DateField, fields.DurationField),
  499. (fields.DateField, fields.DateTimeField, fields.DurationField),
  500. (fields.DateTimeField, fields.DateField, fields.DurationField),
  501. (fields.DateTimeField, fields.DateTimeField, fields.DurationField),
  502. # DurationField.
  503. (fields.DurationField, fields.DurationField, fields.DurationField),
  504. # TimeField.
  505. (fields.TimeField, fields.DurationField, fields.TimeField),
  506. (fields.TimeField, fields.TimeField, fields.DurationField),
  507. ],
  508. },
  509. ]
  510. _connector_combinators = defaultdict(list)
  511. def register_combinable_fields(lhs, connector, rhs, result):
  512. """
  513. Register combinable types:
  514. lhs <connector> rhs -> result
  515. e.g.
  516. register_combinable_fields(
  517. IntegerField, Combinable.ADD, FloatField, FloatField
  518. )
  519. """
  520. _connector_combinators[connector].append((lhs, rhs, result))
  521. for d in _connector_combinations:
  522. for connector, field_types in d.items():
  523. for lhs, rhs, result in field_types:
  524. register_combinable_fields(lhs, connector, rhs, result)
  525. @functools.lru_cache(maxsize=128)
  526. def _resolve_combined_type(connector, lhs_type, rhs_type):
  527. combinators = _connector_combinators.get(connector, ())
  528. for combinator_lhs_type, combinator_rhs_type, combined_type in combinators:
  529. if issubclass(lhs_type, combinator_lhs_type) and issubclass(
  530. rhs_type, combinator_rhs_type
  531. ):
  532. return combined_type
  533. class CombinedExpression(SQLiteNumericMixin, Expression):
  534. def __init__(self, lhs, connector, rhs, output_field=None):
  535. super().__init__(output_field=output_field)
  536. self.connector = connector
  537. self.lhs = lhs
  538. self.rhs = rhs
  539. def __repr__(self):
  540. return "<{}: {}>".format(self.__class__.__name__, self)
  541. def __str__(self):
  542. return "{} {} {}".format(self.lhs, self.connector, self.rhs)
  543. def get_source_expressions(self):
  544. return [self.lhs, self.rhs]
  545. def set_source_expressions(self, exprs):
  546. self.lhs, self.rhs = exprs
  547. def _resolve_output_field(self):
  548. # We avoid using super() here for reasons given in
  549. # Expression._resolve_output_field()
  550. combined_type = _resolve_combined_type(
  551. self.connector,
  552. type(self.lhs._output_field_or_none),
  553. type(self.rhs._output_field_or_none),
  554. )
  555. if combined_type is None:
  556. raise FieldError(
  557. f"Cannot infer type of {self.connector!r} expression involving these "
  558. f"types: {self.lhs.output_field.__class__.__name__}, "
  559. f"{self.rhs.output_field.__class__.__name__}. You must set "
  560. f"output_field."
  561. )
  562. return combined_type()
  563. def as_sql(self, compiler, connection):
  564. expressions = []
  565. expression_params = []
  566. sql, params = compiler.compile(self.lhs)
  567. expressions.append(sql)
  568. expression_params.extend(params)
  569. sql, params = compiler.compile(self.rhs)
  570. expressions.append(sql)
  571. expression_params.extend(params)
  572. # order of precedence
  573. expression_wrapper = "(%s)"
  574. sql = connection.ops.combine_expression(self.connector, expressions)
  575. return expression_wrapper % sql, expression_params
  576. def resolve_expression(
  577. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  578. ):
  579. lhs = self.lhs.resolve_expression(
  580. query, allow_joins, reuse, summarize, for_save
  581. )
  582. rhs = self.rhs.resolve_expression(
  583. query, allow_joins, reuse, summarize, for_save
  584. )
  585. if not isinstance(self, (DurationExpression, TemporalSubtraction)):
  586. try:
  587. lhs_type = lhs.output_field.get_internal_type()
  588. except (AttributeError, FieldError):
  589. lhs_type = None
  590. try:
  591. rhs_type = rhs.output_field.get_internal_type()
  592. except (AttributeError, FieldError):
  593. rhs_type = None
  594. if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type:
  595. return DurationExpression(
  596. self.lhs, self.connector, self.rhs
  597. ).resolve_expression(
  598. query,
  599. allow_joins,
  600. reuse,
  601. summarize,
  602. for_save,
  603. )
  604. datetime_fields = {"DateField", "DateTimeField", "TimeField"}
  605. if (
  606. self.connector == self.SUB
  607. and lhs_type in datetime_fields
  608. and lhs_type == rhs_type
  609. ):
  610. return TemporalSubtraction(self.lhs, self.rhs).resolve_expression(
  611. query,
  612. allow_joins,
  613. reuse,
  614. summarize,
  615. for_save,
  616. )
  617. c = self.copy()
  618. c.is_summary = summarize
  619. c.lhs = lhs
  620. c.rhs = rhs
  621. return c
  622. class DurationExpression(CombinedExpression):
  623. def compile(self, side, compiler, connection):
  624. try:
  625. output = side.output_field
  626. except FieldError:
  627. pass
  628. else:
  629. if output.get_internal_type() == "DurationField":
  630. sql, params = compiler.compile(side)
  631. return connection.ops.format_for_duration_arithmetic(sql), params
  632. return compiler.compile(side)
  633. def as_sql(self, compiler, connection):
  634. if connection.features.has_native_duration_field:
  635. return super().as_sql(compiler, connection)
  636. connection.ops.check_expression_support(self)
  637. expressions = []
  638. expression_params = []
  639. sql, params = self.compile(self.lhs, compiler, connection)
  640. expressions.append(sql)
  641. expression_params.extend(params)
  642. sql, params = self.compile(self.rhs, compiler, connection)
  643. expressions.append(sql)
  644. expression_params.extend(params)
  645. # order of precedence
  646. expression_wrapper = "(%s)"
  647. sql = connection.ops.combine_duration_expression(self.connector, expressions)
  648. return expression_wrapper % sql, expression_params
  649. def as_sqlite(self, compiler, connection, **extra_context):
  650. sql, params = self.as_sql(compiler, connection, **extra_context)
  651. if self.connector in {Combinable.MUL, Combinable.DIV}:
  652. try:
  653. lhs_type = self.lhs.output_field.get_internal_type()
  654. rhs_type = self.rhs.output_field.get_internal_type()
  655. except (AttributeError, FieldError):
  656. pass
  657. else:
  658. allowed_fields = {
  659. "DecimalField",
  660. "DurationField",
  661. "FloatField",
  662. "IntegerField",
  663. }
  664. if lhs_type not in allowed_fields or rhs_type not in allowed_fields:
  665. raise DatabaseError(
  666. f"Invalid arguments for operator {self.connector}."
  667. )
  668. return sql, params
  669. class TemporalSubtraction(CombinedExpression):
  670. output_field = fields.DurationField()
  671. def __init__(self, lhs, rhs):
  672. super().__init__(lhs, self.SUB, rhs)
  673. def as_sql(self, compiler, connection):
  674. connection.ops.check_expression_support(self)
  675. lhs = compiler.compile(self.lhs)
  676. rhs = compiler.compile(self.rhs)
  677. return connection.ops.subtract_temporals(
  678. self.lhs.output_field.get_internal_type(), lhs, rhs
  679. )
  680. @deconstructible(path="django.db.models.F")
  681. class F(Combinable):
  682. """An object capable of resolving references to existing query objects."""
  683. def __init__(self, name):
  684. """
  685. Arguments:
  686. * name: the name of the field this expression references
  687. """
  688. self.name = name
  689. def __repr__(self):
  690. return "{}({})".format(self.__class__.__name__, self.name)
  691. def resolve_expression(
  692. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  693. ):
  694. return query.resolve_ref(self.name, allow_joins, reuse, summarize)
  695. def replace_references(self, references_map):
  696. return references_map.get(self.name, self)
  697. def asc(self, **kwargs):
  698. return OrderBy(self, **kwargs)
  699. def desc(self, **kwargs):
  700. return OrderBy(self, descending=True, **kwargs)
  701. def __eq__(self, other):
  702. return self.__class__ == other.__class__ and self.name == other.name
  703. def __hash__(self):
  704. return hash(self.name)
  705. class ResolvedOuterRef(F):
  706. """
  707. An object that contains a reference to an outer query.
  708. In this case, the reference to the outer query has been resolved because
  709. the inner query has been used as a subquery.
  710. """
  711. contains_aggregate = False
  712. def as_sql(self, *args, **kwargs):
  713. raise ValueError(
  714. "This queryset contains a reference to an outer query and may "
  715. "only be used in a subquery."
  716. )
  717. def resolve_expression(self, *args, **kwargs):
  718. col = super().resolve_expression(*args, **kwargs)
  719. # FIXME: Rename possibly_multivalued to multivalued and fix detection
  720. # for non-multivalued JOINs (e.g. foreign key fields). This should take
  721. # into account only many-to-many and one-to-many relationships.
  722. col.possibly_multivalued = LOOKUP_SEP in self.name
  723. return col
  724. def relabeled_clone(self, relabels):
  725. return self
  726. def get_group_by_cols(self, alias=None):
  727. return []
  728. class OuterRef(F):
  729. contains_aggregate = False
  730. def resolve_expression(self, *args, **kwargs):
  731. if isinstance(self.name, self.__class__):
  732. return self.name
  733. return ResolvedOuterRef(self.name)
  734. def relabeled_clone(self, relabels):
  735. return self
  736. @deconstructible(path="django.db.models.Func")
  737. class Func(SQLiteNumericMixin, Expression):
  738. """An SQL function call."""
  739. function = None
  740. template = "%(function)s(%(expressions)s)"
  741. arg_joiner = ", "
  742. arity = None # The number of arguments the function accepts.
  743. def __init__(self, *expressions, output_field=None, **extra):
  744. if self.arity is not None and len(expressions) != self.arity:
  745. raise TypeError(
  746. "'%s' takes exactly %s %s (%s given)"
  747. % (
  748. self.__class__.__name__,
  749. self.arity,
  750. "argument" if self.arity == 1 else "arguments",
  751. len(expressions),
  752. )
  753. )
  754. super().__init__(output_field=output_field)
  755. self.source_expressions = self._parse_expressions(*expressions)
  756. self.extra = extra
  757. def __repr__(self):
  758. args = self.arg_joiner.join(str(arg) for arg in self.source_expressions)
  759. extra = {**self.extra, **self._get_repr_options()}
  760. if extra:
  761. extra = ", ".join(
  762. str(key) + "=" + str(val) for key, val in sorted(extra.items())
  763. )
  764. return "{}({}, {})".format(self.__class__.__name__, args, extra)
  765. return "{}({})".format(self.__class__.__name__, args)
  766. def _get_repr_options(self):
  767. """Return a dict of extra __init__() options to include in the repr."""
  768. return {}
  769. def get_source_expressions(self):
  770. return self.source_expressions
  771. def set_source_expressions(self, exprs):
  772. self.source_expressions = exprs
  773. def resolve_expression(
  774. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  775. ):
  776. c = self.copy()
  777. c.is_summary = summarize
  778. for pos, arg in enumerate(c.source_expressions):
  779. c.source_expressions[pos] = arg.resolve_expression(
  780. query, allow_joins, reuse, summarize, for_save
  781. )
  782. return c
  783. def as_sql(
  784. self,
  785. compiler,
  786. connection,
  787. function=None,
  788. template=None,
  789. arg_joiner=None,
  790. **extra_context,
  791. ):
  792. connection.ops.check_expression_support(self)
  793. sql_parts = []
  794. params = []
  795. for arg in self.source_expressions:
  796. try:
  797. arg_sql, arg_params = compiler.compile(arg)
  798. except EmptyResultSet:
  799. empty_result_set_value = getattr(
  800. arg, "empty_result_set_value", NotImplemented
  801. )
  802. if empty_result_set_value is NotImplemented:
  803. raise
  804. arg_sql, arg_params = compiler.compile(Value(empty_result_set_value))
  805. sql_parts.append(arg_sql)
  806. params.extend(arg_params)
  807. data = {**self.extra, **extra_context}
  808. # Use the first supplied value in this order: the parameter to this
  809. # method, a value supplied in __init__()'s **extra (the value in
  810. # `data`), or the value defined on the class.
  811. if function is not None:
  812. data["function"] = function
  813. else:
  814. data.setdefault("function", self.function)
  815. template = template or data.get("template", self.template)
  816. arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner)
  817. data["expressions"] = data["field"] = arg_joiner.join(sql_parts)
  818. return template % data, params
  819. def copy(self):
  820. copy = super().copy()
  821. copy.source_expressions = self.source_expressions[:]
  822. copy.extra = self.extra.copy()
  823. return copy
  824. @deconstructible(path="django.db.models.Value")
  825. class Value(SQLiteNumericMixin, Expression):
  826. """Represent a wrapped value as a node within an expression."""
  827. # Provide a default value for `for_save` in order to allow unresolved
  828. # instances to be compiled until a decision is taken in #25425.
  829. for_save = False
  830. def __init__(self, value, output_field=None):
  831. """
  832. Arguments:
  833. * value: the value this expression represents. The value will be
  834. added into the sql parameter list and properly quoted.
  835. * output_field: an instance of the model field type that this
  836. expression will return, such as IntegerField() or CharField().
  837. """
  838. super().__init__(output_field=output_field)
  839. self.value = value
  840. def __repr__(self):
  841. return f"{self.__class__.__name__}({self.value!r})"
  842. def as_sql(self, compiler, connection):
  843. connection.ops.check_expression_support(self)
  844. val = self.value
  845. output_field = self._output_field_or_none
  846. if output_field is not None:
  847. if self.for_save:
  848. val = output_field.get_db_prep_save(val, connection=connection)
  849. else:
  850. val = output_field.get_db_prep_value(val, connection=connection)
  851. if hasattr(output_field, "get_placeholder"):
  852. return output_field.get_placeholder(val, compiler, connection), [val]
  853. if val is None:
  854. # cx_Oracle does not always convert None to the appropriate
  855. # NULL type (like in case expressions using numbers), so we
  856. # use a literal SQL NULL
  857. return "NULL", []
  858. return "%s", [val]
  859. def resolve_expression(
  860. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  861. ):
  862. c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
  863. c.for_save = for_save
  864. return c
  865. def get_group_by_cols(self, alias=None):
  866. return []
  867. def _resolve_output_field(self):
  868. if isinstance(self.value, str):
  869. return fields.CharField()
  870. if isinstance(self.value, bool):
  871. return fields.BooleanField()
  872. if isinstance(self.value, int):
  873. return fields.IntegerField()
  874. if isinstance(self.value, float):
  875. return fields.FloatField()
  876. if isinstance(self.value, datetime.datetime):
  877. return fields.DateTimeField()
  878. if isinstance(self.value, datetime.date):
  879. return fields.DateField()
  880. if isinstance(self.value, datetime.time):
  881. return fields.TimeField()
  882. if isinstance(self.value, datetime.timedelta):
  883. return fields.DurationField()
  884. if isinstance(self.value, Decimal):
  885. return fields.DecimalField()
  886. if isinstance(self.value, bytes):
  887. return fields.BinaryField()
  888. if isinstance(self.value, UUID):
  889. return fields.UUIDField()
  890. @property
  891. def empty_result_set_value(self):
  892. return self.value
  893. class RawSQL(Expression):
  894. def __init__(self, sql, params, output_field=None):
  895. if output_field is None:
  896. output_field = fields.Field()
  897. self.sql, self.params = sql, params
  898. super().__init__(output_field=output_field)
  899. def __repr__(self):
  900. return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params)
  901. def as_sql(self, compiler, connection):
  902. return "(%s)" % self.sql, self.params
  903. def get_group_by_cols(self, alias=None):
  904. return [self]
  905. def resolve_expression(
  906. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  907. ):
  908. # Resolve parents fields used in raw SQL.
  909. if query.model:
  910. for parent in query.model._meta.get_parent_list():
  911. for parent_field in parent._meta.local_fields:
  912. _, column_name = parent_field.get_attname_column()
  913. if column_name.lower() in self.sql.lower():
  914. query.resolve_ref(
  915. parent_field.name, allow_joins, reuse, summarize
  916. )
  917. break
  918. return super().resolve_expression(
  919. query, allow_joins, reuse, summarize, for_save
  920. )
  921. class Star(Expression):
  922. def __repr__(self):
  923. return "'*'"
  924. def as_sql(self, compiler, connection):
  925. return "*", []
  926. class Col(Expression):
  927. contains_column_references = True
  928. possibly_multivalued = False
  929. def __init__(self, alias, target, output_field=None):
  930. if output_field is None:
  931. output_field = target
  932. super().__init__(output_field=output_field)
  933. self.alias, self.target = alias, target
  934. def __repr__(self):
  935. alias, target = self.alias, self.target
  936. identifiers = (alias, str(target)) if alias else (str(target),)
  937. return "{}({})".format(self.__class__.__name__, ", ".join(identifiers))
  938. def as_sql(self, compiler, connection):
  939. alias, column = self.alias, self.target.column
  940. identifiers = (alias, column) if alias else (column,)
  941. sql = ".".join(map(compiler.quote_name_unless_alias, identifiers))
  942. return sql, []
  943. def relabeled_clone(self, relabels):
  944. if self.alias is None:
  945. return self
  946. return self.__class__(
  947. relabels.get(self.alias, self.alias), self.target, self.output_field
  948. )
  949. def get_group_by_cols(self, alias=None):
  950. return [self]
  951. def get_db_converters(self, connection):
  952. if self.target == self.output_field:
  953. return self.output_field.get_db_converters(connection)
  954. return self.output_field.get_db_converters(
  955. connection
  956. ) + self.target.get_db_converters(connection)
  957. class Ref(Expression):
  958. """
  959. Reference to column alias of the query. For example, Ref('sum_cost') in
  960. qs.annotate(sum_cost=Sum('cost')) query.
  961. """
  962. def __init__(self, refs, source):
  963. super().__init__()
  964. self.refs, self.source = refs, source
  965. def __repr__(self):
  966. return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source)
  967. def get_source_expressions(self):
  968. return [self.source]
  969. def set_source_expressions(self, exprs):
  970. (self.source,) = exprs
  971. def resolve_expression(
  972. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  973. ):
  974. # The sub-expression `source` has already been resolved, as this is
  975. # just a reference to the name of `source`.
  976. return self
  977. def relabeled_clone(self, relabels):
  978. return self
  979. def as_sql(self, compiler, connection):
  980. return connection.ops.quote_name(self.refs), []
  981. def get_group_by_cols(self, alias=None):
  982. return [self]
  983. class ExpressionList(Func):
  984. """
  985. An expression containing multiple expressions. Can be used to provide a
  986. list of expressions as an argument to another expression, like a partition
  987. clause.
  988. """
  989. template = "%(expressions)s"
  990. def __init__(self, *expressions, **extra):
  991. if not expressions:
  992. raise ValueError(
  993. "%s requires at least one expression." % self.__class__.__name__
  994. )
  995. super().__init__(*expressions, **extra)
  996. def __str__(self):
  997. return self.arg_joiner.join(str(arg) for arg in self.source_expressions)
  998. def as_sqlite(self, compiler, connection, **extra_context):
  999. # Casting to numeric is unnecessary.
  1000. return self.as_sql(compiler, connection, **extra_context)
  1001. class OrderByList(Func):
  1002. template = "ORDER BY %(expressions)s"
  1003. def __init__(self, *expressions, **extra):
  1004. expressions = (
  1005. (
  1006. OrderBy(F(expr[1:]), descending=True)
  1007. if isinstance(expr, str) and expr[0] == "-"
  1008. else expr
  1009. )
  1010. for expr in expressions
  1011. )
  1012. super().__init__(*expressions, **extra)
  1013. def as_sql(self, *args, **kwargs):
  1014. if not self.source_expressions:
  1015. return "", ()
  1016. return super().as_sql(*args, **kwargs)
  1017. @deconstructible(path="django.db.models.ExpressionWrapper")
  1018. class ExpressionWrapper(SQLiteNumericMixin, Expression):
  1019. """
  1020. An expression that can wrap another expression so that it can provide
  1021. extra context to the inner expression, such as the output_field.
  1022. """
  1023. def __init__(self, expression, output_field):
  1024. super().__init__(output_field=output_field)
  1025. self.expression = expression
  1026. def set_source_expressions(self, exprs):
  1027. self.expression = exprs[0]
  1028. def get_source_expressions(self):
  1029. return [self.expression]
  1030. def get_group_by_cols(self, alias=None):
  1031. if isinstance(self.expression, Expression):
  1032. expression = self.expression.copy()
  1033. expression.output_field = self.output_field
  1034. return expression.get_group_by_cols(alias=alias)
  1035. # For non-expressions e.g. an SQL WHERE clause, the entire
  1036. # `expression` must be included in the GROUP BY clause.
  1037. return super().get_group_by_cols()
  1038. def as_sql(self, compiler, connection):
  1039. return compiler.compile(self.expression)
  1040. def __repr__(self):
  1041. return "{}({})".format(self.__class__.__name__, self.expression)
  1042. @deconstructible(path="django.db.models.When")
  1043. class When(Expression):
  1044. template = "WHEN %(condition)s THEN %(result)s"
  1045. # This isn't a complete conditional expression, must be used in Case().
  1046. conditional = False
  1047. def __init__(self, condition=None, then=None, **lookups):
  1048. if lookups:
  1049. if condition is None:
  1050. condition, lookups = Q(**lookups), None
  1051. elif getattr(condition, "conditional", False):
  1052. condition, lookups = Q(condition, **lookups), None
  1053. if condition is None or not getattr(condition, "conditional", False) or lookups:
  1054. raise TypeError(
  1055. "When() supports a Q object, a boolean expression, or lookups "
  1056. "as a condition."
  1057. )
  1058. if isinstance(condition, Q) and not condition:
  1059. raise ValueError("An empty Q() can't be used as a When() condition.")
  1060. super().__init__(output_field=None)
  1061. self.condition = condition
  1062. self.result = self._parse_expressions(then)[0]
  1063. def __str__(self):
  1064. return "WHEN %r THEN %r" % (self.condition, self.result)
  1065. def __repr__(self):
  1066. return "<%s: %s>" % (self.__class__.__name__, self)
  1067. def get_source_expressions(self):
  1068. return [self.condition, self.result]
  1069. def set_source_expressions(self, exprs):
  1070. self.condition, self.result = exprs
  1071. def get_source_fields(self):
  1072. # We're only interested in the fields of the result expressions.
  1073. return [self.result._output_field_or_none]
  1074. def resolve_expression(
  1075. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  1076. ):
  1077. c = self.copy()
  1078. c.is_summary = summarize
  1079. if hasattr(c.condition, "resolve_expression"):
  1080. c.condition = c.condition.resolve_expression(
  1081. query, allow_joins, reuse, summarize, False
  1082. )
  1083. c.result = c.result.resolve_expression(
  1084. query, allow_joins, reuse, summarize, for_save
  1085. )
  1086. return c
  1087. def as_sql(self, compiler, connection, template=None, **extra_context):
  1088. connection.ops.check_expression_support(self)
  1089. template_params = extra_context
  1090. sql_params = []
  1091. condition_sql, condition_params = compiler.compile(self.condition)
  1092. template_params["condition"] = condition_sql
  1093. sql_params.extend(condition_params)
  1094. result_sql, result_params = compiler.compile(self.result)
  1095. template_params["result"] = result_sql
  1096. sql_params.extend(result_params)
  1097. template = template or self.template
  1098. return template % template_params, sql_params
  1099. def get_group_by_cols(self, alias=None):
  1100. # This is not a complete expression and cannot be used in GROUP BY.
  1101. cols = []
  1102. for source in self.get_source_expressions():
  1103. cols.extend(source.get_group_by_cols())
  1104. return cols
  1105. @deconstructible(path="django.db.models.Case")
  1106. class Case(SQLiteNumericMixin, Expression):
  1107. """
  1108. An SQL searched CASE expression:
  1109. CASE
  1110. WHEN n > 0
  1111. THEN 'positive'
  1112. WHEN n < 0
  1113. THEN 'negative'
  1114. ELSE 'zero'
  1115. END
  1116. """
  1117. template = "CASE %(cases)s ELSE %(default)s END"
  1118. case_joiner = " "
  1119. def __init__(self, *cases, default=None, output_field=None, **extra):
  1120. if not all(isinstance(case, When) for case in cases):
  1121. raise TypeError("Positional arguments must all be When objects.")
  1122. super().__init__(output_field)
  1123. self.cases = list(cases)
  1124. self.default = self._parse_expressions(default)[0]
  1125. self.extra = extra
  1126. def __str__(self):
  1127. return "CASE %s, ELSE %r" % (
  1128. ", ".join(str(c) for c in self.cases),
  1129. self.default,
  1130. )
  1131. def __repr__(self):
  1132. return "<%s: %s>" % (self.__class__.__name__, self)
  1133. def get_source_expressions(self):
  1134. return self.cases + [self.default]
  1135. def set_source_expressions(self, exprs):
  1136. *self.cases, self.default = exprs
  1137. def resolve_expression(
  1138. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  1139. ):
  1140. c = self.copy()
  1141. c.is_summary = summarize
  1142. for pos, case in enumerate(c.cases):
  1143. c.cases[pos] = case.resolve_expression(
  1144. query, allow_joins, reuse, summarize, for_save
  1145. )
  1146. c.default = c.default.resolve_expression(
  1147. query, allow_joins, reuse, summarize, for_save
  1148. )
  1149. return c
  1150. def copy(self):
  1151. c = super().copy()
  1152. c.cases = c.cases[:]
  1153. return c
  1154. def as_sql(
  1155. self, compiler, connection, template=None, case_joiner=None, **extra_context
  1156. ):
  1157. connection.ops.check_expression_support(self)
  1158. if not self.cases:
  1159. return compiler.compile(self.default)
  1160. template_params = {**self.extra, **extra_context}
  1161. case_parts = []
  1162. sql_params = []
  1163. for case in self.cases:
  1164. try:
  1165. case_sql, case_params = compiler.compile(case)
  1166. except EmptyResultSet:
  1167. continue
  1168. case_parts.append(case_sql)
  1169. sql_params.extend(case_params)
  1170. default_sql, default_params = compiler.compile(self.default)
  1171. if not case_parts:
  1172. return default_sql, default_params
  1173. case_joiner = case_joiner or self.case_joiner
  1174. template_params["cases"] = case_joiner.join(case_parts)
  1175. template_params["default"] = default_sql
  1176. sql_params.extend(default_params)
  1177. template = template or template_params.get("template", self.template)
  1178. sql = template % template_params
  1179. if self._output_field_or_none is not None:
  1180. sql = connection.ops.unification_cast_sql(self.output_field) % sql
  1181. return sql, sql_params
  1182. def get_group_by_cols(self, alias=None):
  1183. if not self.cases:
  1184. return self.default.get_group_by_cols(alias)
  1185. return super().get_group_by_cols(alias)
  1186. class Subquery(BaseExpression, Combinable):
  1187. """
  1188. An explicit subquery. It may contain OuterRef() references to the outer
  1189. query which will be resolved when it is applied to that query.
  1190. """
  1191. template = "(%(subquery)s)"
  1192. contains_aggregate = False
  1193. empty_result_set_value = None
  1194. def __init__(self, queryset, output_field=None, **extra):
  1195. # Allow the usage of both QuerySet and sql.Query objects.
  1196. self.query = getattr(queryset, "query", queryset).clone()
  1197. self.query.subquery = True
  1198. self.extra = extra
  1199. super().__init__(output_field)
  1200. def get_source_expressions(self):
  1201. return [self.query]
  1202. def set_source_expressions(self, exprs):
  1203. self.query = exprs[0]
  1204. def _resolve_output_field(self):
  1205. return self.query.output_field
  1206. def copy(self):
  1207. clone = super().copy()
  1208. clone.query = clone.query.clone()
  1209. return clone
  1210. @property
  1211. def external_aliases(self):
  1212. return self.query.external_aliases
  1213. def get_external_cols(self):
  1214. return self.query.get_external_cols()
  1215. def as_sql(self, compiler, connection, template=None, query=None, **extra_context):
  1216. connection.ops.check_expression_support(self)
  1217. template_params = {**self.extra, **extra_context}
  1218. query = query or self.query
  1219. subquery_sql, sql_params = query.as_sql(compiler, connection)
  1220. template_params["subquery"] = subquery_sql[1:-1]
  1221. template = template or template_params.get("template", self.template)
  1222. sql = template % template_params
  1223. return sql, sql_params
  1224. def get_group_by_cols(self, alias=None):
  1225. # If this expression is referenced by an alias for an explicit GROUP BY
  1226. # through values() a reference to this expression and not the
  1227. # underlying .query must be returned to ensure external column
  1228. # references are not grouped against as well.
  1229. if alias:
  1230. return [Ref(alias, self)]
  1231. return self.query.get_group_by_cols()
  1232. class Exists(Subquery):
  1233. template = "EXISTS(%(subquery)s)"
  1234. output_field = fields.BooleanField()
  1235. def __init__(self, queryset, negated=False, **kwargs):
  1236. self.negated = negated
  1237. super().__init__(queryset, **kwargs)
  1238. def __invert__(self):
  1239. clone = self.copy()
  1240. clone.negated = not self.negated
  1241. return clone
  1242. def get_group_by_cols(self, alias=None):
  1243. # self.query only gets limited to a single row in the .exists() call
  1244. # from self.as_sql() so deferring to Query.get_group_by_cols() is
  1245. # inappropriate.
  1246. if alias is None:
  1247. return [self]
  1248. return super().get_group_by_cols(alias)
  1249. def as_sql(self, compiler, connection, template=None, **extra_context):
  1250. query = self.query.exists(using=connection.alias)
  1251. try:
  1252. sql, params = super().as_sql(
  1253. compiler,
  1254. connection,
  1255. template=template,
  1256. query=query,
  1257. **extra_context,
  1258. )
  1259. except EmptyResultSet:
  1260. if self.negated:
  1261. features = compiler.connection.features
  1262. if not features.supports_boolean_expr_in_select_clause:
  1263. return "1=1", ()
  1264. return compiler.compile(Value(True))
  1265. raise
  1266. if self.negated:
  1267. sql = "NOT {}".format(sql)
  1268. return sql, params
  1269. def select_format(self, compiler, sql, params):
  1270. # Wrap EXISTS() with a CASE WHEN expression if a database backend
  1271. # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
  1272. # BY list.
  1273. if not compiler.connection.features.supports_boolean_expr_in_select_clause:
  1274. sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
  1275. return sql, params
  1276. @deconstructible(path="django.db.models.OrderBy")
  1277. class OrderBy(Expression):
  1278. template = "%(expression)s %(ordering)s"
  1279. conditional = False
  1280. def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None):
  1281. if nulls_first and nulls_last:
  1282. raise ValueError("nulls_first and nulls_last are mutually exclusive")
  1283. if nulls_first is False or nulls_last is False:
  1284. # When the deprecation ends, replace with:
  1285. # raise ValueError(
  1286. # "nulls_first and nulls_last values must be True or None."
  1287. # )
  1288. warnings.warn(
  1289. "Passing nulls_first=False or nulls_last=False is deprecated, use None "
  1290. "instead.",
  1291. RemovedInDjango50Warning,
  1292. stacklevel=2,
  1293. )
  1294. self.nulls_first = nulls_first
  1295. self.nulls_last = nulls_last
  1296. self.descending = descending
  1297. if not hasattr(expression, "resolve_expression"):
  1298. raise ValueError("expression must be an expression type")
  1299. self.expression = expression
  1300. def __repr__(self):
  1301. return "{}({}, descending={})".format(
  1302. self.__class__.__name__, self.expression, self.descending
  1303. )
  1304. def set_source_expressions(self, exprs):
  1305. self.expression = exprs[0]
  1306. def get_source_expressions(self):
  1307. return [self.expression]
  1308. def as_sql(self, compiler, connection, template=None, **extra_context):
  1309. template = template or self.template
  1310. if connection.features.supports_order_by_nulls_modifier:
  1311. if self.nulls_last:
  1312. template = "%s NULLS LAST" % template
  1313. elif self.nulls_first:
  1314. template = "%s NULLS FIRST" % template
  1315. else:
  1316. if self.nulls_last and not (
  1317. self.descending and connection.features.order_by_nulls_first
  1318. ):
  1319. template = "%%(expression)s IS NULL, %s" % template
  1320. elif self.nulls_first and not (
  1321. not self.descending and connection.features.order_by_nulls_first
  1322. ):
  1323. template = "%%(expression)s IS NOT NULL, %s" % template
  1324. connection.ops.check_expression_support(self)
  1325. expression_sql, params = compiler.compile(self.expression)
  1326. placeholders = {
  1327. "expression": expression_sql,
  1328. "ordering": "DESC" if self.descending else "ASC",
  1329. **extra_context,
  1330. }
  1331. params *= template.count("%(expression)s")
  1332. return (template % placeholders).rstrip(), params
  1333. def as_oracle(self, compiler, connection):
  1334. # Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped
  1335. # in a CASE WHEN.
  1336. if connection.ops.conditional_expression_supported_in_where_clause(
  1337. self.expression
  1338. ):
  1339. copy = self.copy()
  1340. copy.expression = Case(
  1341. When(self.expression, then=True),
  1342. default=False,
  1343. )
  1344. return copy.as_sql(compiler, connection)
  1345. return self.as_sql(compiler, connection)
  1346. def get_group_by_cols(self, alias=None):
  1347. cols = []
  1348. for source in self.get_source_expressions():
  1349. cols.extend(source.get_group_by_cols())
  1350. return cols
  1351. def reverse_ordering(self):
  1352. self.descending = not self.descending
  1353. if self.nulls_first:
  1354. self.nulls_last = True
  1355. self.nulls_first = None
  1356. elif self.nulls_last:
  1357. self.nulls_first = True
  1358. self.nulls_last = None
  1359. return self
  1360. def asc(self):
  1361. self.descending = False
  1362. def desc(self):
  1363. self.descending = True
  1364. class Window(SQLiteNumericMixin, Expression):
  1365. template = "%(expression)s OVER (%(window)s)"
  1366. # Although the main expression may either be an aggregate or an
  1367. # expression with an aggregate function, the GROUP BY that will
  1368. # be introduced in the query as a result is not desired.
  1369. contains_aggregate = False
  1370. contains_over_clause = True
  1371. filterable = False
  1372. def __init__(
  1373. self,
  1374. expression,
  1375. partition_by=None,
  1376. order_by=None,
  1377. frame=None,
  1378. output_field=None,
  1379. ):
  1380. self.partition_by = partition_by
  1381. self.order_by = order_by
  1382. self.frame = frame
  1383. if not getattr(expression, "window_compatible", False):
  1384. raise ValueError(
  1385. "Expression '%s' isn't compatible with OVER clauses."
  1386. % expression.__class__.__name__
  1387. )
  1388. if self.partition_by is not None:
  1389. if not isinstance(self.partition_by, (tuple, list)):
  1390. self.partition_by = (self.partition_by,)
  1391. self.partition_by = ExpressionList(*self.partition_by)
  1392. if self.order_by is not None:
  1393. if isinstance(self.order_by, (list, tuple)):
  1394. self.order_by = OrderByList(*self.order_by)
  1395. elif isinstance(self.order_by, (BaseExpression, str)):
  1396. self.order_by = OrderByList(self.order_by)
  1397. else:
  1398. raise ValueError(
  1399. "Window.order_by must be either a string reference to a "
  1400. "field, an expression, or a list or tuple of them."
  1401. )
  1402. super().__init__(output_field=output_field)
  1403. self.source_expression = self._parse_expressions(expression)[0]
  1404. def _resolve_output_field(self):
  1405. return self.source_expression.output_field
  1406. def get_source_expressions(self):
  1407. return [self.source_expression, self.partition_by, self.order_by, self.frame]
  1408. def set_source_expressions(self, exprs):
  1409. self.source_expression, self.partition_by, self.order_by, self.frame = exprs
  1410. def as_sql(self, compiler, connection, template=None):
  1411. connection.ops.check_expression_support(self)
  1412. if not connection.features.supports_over_clause:
  1413. raise NotSupportedError("This backend does not support window expressions.")
  1414. expr_sql, params = compiler.compile(self.source_expression)
  1415. window_sql, window_params = [], ()
  1416. if self.partition_by is not None:
  1417. sql_expr, sql_params = self.partition_by.as_sql(
  1418. compiler=compiler,
  1419. connection=connection,
  1420. template="PARTITION BY %(expressions)s",
  1421. )
  1422. window_sql.append(sql_expr)
  1423. window_params += tuple(sql_params)
  1424. if self.order_by is not None:
  1425. order_sql, order_params = compiler.compile(self.order_by)
  1426. window_sql.append(order_sql)
  1427. window_params += tuple(order_params)
  1428. if self.frame:
  1429. frame_sql, frame_params = compiler.compile(self.frame)
  1430. window_sql.append(frame_sql)
  1431. window_params += tuple(frame_params)
  1432. template = template or self.template
  1433. return (
  1434. template % {"expression": expr_sql, "window": " ".join(window_sql).strip()},
  1435. (*params, *window_params),
  1436. )
  1437. def as_sqlite(self, compiler, connection):
  1438. if isinstance(self.output_field, fields.DecimalField):
  1439. # Casting to numeric must be outside of the window expression.
  1440. copy = self.copy()
  1441. source_expressions = copy.get_source_expressions()
  1442. source_expressions[0].output_field = fields.FloatField()
  1443. copy.set_source_expressions(source_expressions)
  1444. return super(Window, copy).as_sqlite(compiler, connection)
  1445. return self.as_sql(compiler, connection)
  1446. def __str__(self):
  1447. return "{} OVER ({}{}{})".format(
  1448. str(self.source_expression),
  1449. "PARTITION BY " + str(self.partition_by) if self.partition_by else "",
  1450. str(self.order_by or ""),
  1451. str(self.frame or ""),
  1452. )
  1453. def __repr__(self):
  1454. return "<%s: %s>" % (self.__class__.__name__, self)
  1455. def get_group_by_cols(self, alias=None):
  1456. return []
  1457. class WindowFrame(Expression):
  1458. """
  1459. Model the frame clause in window expressions. There are two types of frame
  1460. clauses which are subclasses, however, all processing and validation (by no
  1461. means intended to be complete) is done here. Thus, providing an end for a
  1462. frame is optional (the default is UNBOUNDED FOLLOWING, which is the last
  1463. row in the frame).
  1464. """
  1465. template = "%(frame_type)s BETWEEN %(start)s AND %(end)s"
  1466. def __init__(self, start=None, end=None):
  1467. self.start = Value(start)
  1468. self.end = Value(end)
  1469. def set_source_expressions(self, exprs):
  1470. self.start, self.end = exprs
  1471. def get_source_expressions(self):
  1472. return [self.start, self.end]
  1473. def as_sql(self, compiler, connection):
  1474. connection.ops.check_expression_support(self)
  1475. start, end = self.window_frame_start_end(
  1476. connection, self.start.value, self.end.value
  1477. )
  1478. return (
  1479. self.template
  1480. % {
  1481. "frame_type": self.frame_type,
  1482. "start": start,
  1483. "end": end,
  1484. },
  1485. [],
  1486. )
  1487. def __repr__(self):
  1488. return "<%s: %s>" % (self.__class__.__name__, self)
  1489. def get_group_by_cols(self, alias=None):
  1490. return []
  1491. def __str__(self):
  1492. if self.start.value is not None and self.start.value < 0:
  1493. start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING)
  1494. elif self.start.value is not None and self.start.value == 0:
  1495. start = connection.ops.CURRENT_ROW
  1496. else:
  1497. start = connection.ops.UNBOUNDED_PRECEDING
  1498. if self.end.value is not None and self.end.value > 0:
  1499. end = "%d %s" % (self.end.value, connection.ops.FOLLOWING)
  1500. elif self.end.value is not None and self.end.value == 0:
  1501. end = connection.ops.CURRENT_ROW
  1502. else:
  1503. end = connection.ops.UNBOUNDED_FOLLOWING
  1504. return self.template % {
  1505. "frame_type": self.frame_type,
  1506. "start": start,
  1507. "end": end,
  1508. }
  1509. def window_frame_start_end(self, connection, start, end):
  1510. raise NotImplementedError("Subclasses must implement window_frame_start_end().")
  1511. class RowRange(WindowFrame):
  1512. frame_type = "ROWS"
  1513. def window_frame_start_end(self, connection, start, end):
  1514. return connection.ops.window_frame_rows_start_end(start, end)
  1515. class ValueRange(WindowFrame):
  1516. frame_type = "RANGE"
  1517. def window_frame_start_end(self, connection, start, end):
  1518. return connection.ops.window_frame_range_start_end(start, end)