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 48KB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  1. import copy
  2. import datetime
  3. import inspect
  4. from decimal import Decimal
  5. from django.core.exceptions import EmptyResultSet, FieldError
  6. from django.db import connection
  7. from django.db.models import fields
  8. from django.db.models.query_utils import Q
  9. from django.utils.deconstruct import deconstructible
  10. from django.utils.functional import cached_property
  11. from django.utils.hashable import make_hashable
  12. class SQLiteNumericMixin:
  13. """
  14. Some expressions with output_field=DecimalField() must be cast to
  15. numeric to be properly filtered.
  16. """
  17. def as_sqlite(self, compiler, connection, **extra_context):
  18. sql, params = self.as_sql(compiler, connection, **extra_context)
  19. try:
  20. if self.output_field.get_internal_type() == 'DecimalField':
  21. sql = 'CAST(%s AS NUMERIC)' % sql
  22. except FieldError:
  23. pass
  24. return sql, params
  25. class Combinable:
  26. """
  27. Provide the ability to combine one or two objects with
  28. some connector. For example F('foo') + F('bar').
  29. """
  30. # Arithmetic connectors
  31. ADD = '+'
  32. SUB = '-'
  33. MUL = '*'
  34. DIV = '/'
  35. POW = '^'
  36. # The following is a quoted % operator - it is quoted because it can be
  37. # used in strings that also have parameter substitution.
  38. MOD = '%%'
  39. # Bitwise operators - note that these are generated by .bitand()
  40. # and .bitor(), the '&' and '|' are reserved for boolean operator
  41. # usage.
  42. BITAND = '&'
  43. BITOR = '|'
  44. BITLEFTSHIFT = '<<'
  45. BITRIGHTSHIFT = '>>'
  46. def _combine(self, other, connector, reversed):
  47. if not hasattr(other, 'resolve_expression'):
  48. # everything must be resolvable to an expression
  49. if isinstance(other, datetime.timedelta):
  50. other = DurationValue(other, output_field=fields.DurationField())
  51. else:
  52. other = Value(other)
  53. if reversed:
  54. return CombinedExpression(other, connector, self)
  55. return CombinedExpression(self, connector, other)
  56. #############
  57. # OPERATORS #
  58. #############
  59. def __neg__(self):
  60. return self._combine(-1, self.MUL, False)
  61. def __add__(self, other):
  62. return self._combine(other, self.ADD, False)
  63. def __sub__(self, other):
  64. return self._combine(other, self.SUB, False)
  65. def __mul__(self, other):
  66. return self._combine(other, self.MUL, False)
  67. def __truediv__(self, other):
  68. return self._combine(other, self.DIV, False)
  69. def __mod__(self, other):
  70. return self._combine(other, self.MOD, False)
  71. def __pow__(self, other):
  72. return self._combine(other, self.POW, False)
  73. def __and__(self, other):
  74. raise NotImplementedError(
  75. "Use .bitand() and .bitor() for bitwise logical operations."
  76. )
  77. def bitand(self, other):
  78. return self._combine(other, self.BITAND, False)
  79. def bitleftshift(self, other):
  80. return self._combine(other, self.BITLEFTSHIFT, False)
  81. def bitrightshift(self, other):
  82. return self._combine(other, self.BITRIGHTSHIFT, False)
  83. def __or__(self, other):
  84. raise NotImplementedError(
  85. "Use .bitand() and .bitor() for bitwise logical operations."
  86. )
  87. def bitor(self, other):
  88. return self._combine(other, self.BITOR, False)
  89. def __radd__(self, other):
  90. return self._combine(other, self.ADD, True)
  91. def __rsub__(self, other):
  92. return self._combine(other, self.SUB, True)
  93. def __rmul__(self, other):
  94. return self._combine(other, self.MUL, True)
  95. def __rtruediv__(self, other):
  96. return self._combine(other, self.DIV, True)
  97. def __rmod__(self, other):
  98. return self._combine(other, self.MOD, True)
  99. def __rpow__(self, other):
  100. return self._combine(other, self.POW, True)
  101. def __rand__(self, other):
  102. raise NotImplementedError(
  103. "Use .bitand() and .bitor() for bitwise logical operations."
  104. )
  105. def __ror__(self, other):
  106. raise NotImplementedError(
  107. "Use .bitand() and .bitor() for bitwise logical operations."
  108. )
  109. @deconstructible
  110. class BaseExpression:
  111. """Base class for all query expressions."""
  112. # aggregate specific fields
  113. is_summary = False
  114. _output_field_resolved_to_none = False
  115. # Can the expression be used in a WHERE clause?
  116. filterable = True
  117. # Can the expression can be used as a source expression in Window?
  118. window_compatible = False
  119. def __init__(self, output_field=None):
  120. if output_field is not None:
  121. self.output_field = output_field
  122. def __getstate__(self):
  123. state = self.__dict__.copy()
  124. state.pop('convert_value', None)
  125. return state
  126. def get_db_converters(self, connection):
  127. return (
  128. []
  129. if self.convert_value is self._convert_value_noop else
  130. [self.convert_value]
  131. ) + self.output_field.get_db_converters(connection)
  132. def get_source_expressions(self):
  133. return []
  134. def set_source_expressions(self, exprs):
  135. assert not exprs
  136. def _parse_expressions(self, *expressions):
  137. return [
  138. arg if hasattr(arg, 'resolve_expression') else (
  139. F(arg) if isinstance(arg, str) else Value(arg)
  140. ) for arg in expressions
  141. ]
  142. def as_sql(self, compiler, connection):
  143. """
  144. Responsible for returning a (sql, [params]) tuple to be included
  145. in the current query.
  146. Different backends can provide their own implementation, by
  147. providing an `as_{vendor}` method and patching the Expression:
  148. ```
  149. def override_as_sql(self, compiler, connection):
  150. # custom logic
  151. return super().as_sql(compiler, connection)
  152. setattr(Expression, 'as_' + connection.vendor, override_as_sql)
  153. ```
  154. Arguments:
  155. * compiler: the query compiler responsible for generating the query.
  156. Must have a compile method, returning a (sql, [params]) tuple.
  157. Calling compiler(value) will return a quoted `value`.
  158. * connection: the database connection used for the current query.
  159. Return: (sql, params)
  160. Where `sql` is a string containing ordered sql parameters to be
  161. replaced with the elements of the list `params`.
  162. """
  163. raise NotImplementedError("Subclasses must implement as_sql()")
  164. @cached_property
  165. def contains_aggregate(self):
  166. return any(expr and expr.contains_aggregate for expr in self.get_source_expressions())
  167. @cached_property
  168. def contains_over_clause(self):
  169. return any(expr and expr.contains_over_clause for expr in self.get_source_expressions())
  170. @cached_property
  171. def contains_column_references(self):
  172. return any(expr and expr.contains_column_references for expr in self.get_source_expressions())
  173. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  174. """
  175. Provide the chance to do any preprocessing or validation before being
  176. added to the query.
  177. Arguments:
  178. * query: the backend query implementation
  179. * allow_joins: boolean allowing or denying use of joins
  180. in this query
  181. * reuse: a set of reusable joins for multijoins
  182. * summarize: a terminal aggregate clause
  183. * for_save: whether this expression about to be used in a save or update
  184. Return: an Expression to be added to the query.
  185. """
  186. c = self.copy()
  187. c.is_summary = summarize
  188. c.set_source_expressions([
  189. expr.resolve_expression(query, allow_joins, reuse, summarize)
  190. if expr else None
  191. for expr in c.get_source_expressions()
  192. ])
  193. return c
  194. def _prepare(self, field):
  195. """Hook used by Lookup.get_prep_lookup() to do custom preparation."""
  196. return self
  197. @property
  198. def field(self):
  199. return self.output_field
  200. @cached_property
  201. def output_field(self):
  202. """Return the output type of this expressions."""
  203. output_field = self._resolve_output_field()
  204. if output_field is None:
  205. self._output_field_resolved_to_none = True
  206. raise FieldError('Cannot resolve expression type, unknown output_field')
  207. return output_field
  208. @cached_property
  209. def _output_field_or_none(self):
  210. """
  211. Return the output field of this expression, or None if
  212. _resolve_output_field() didn't return an output type.
  213. """
  214. try:
  215. return self.output_field
  216. except FieldError:
  217. if not self._output_field_resolved_to_none:
  218. raise
  219. def _resolve_output_field(self):
  220. """
  221. Attempt to infer the output type of the expression. If the output
  222. fields of all source fields match then, simply infer the same type
  223. here. This isn't always correct, but it makes sense most of the time.
  224. Consider the difference between `2 + 2` and `2 / 3`. Inferring
  225. the type here is a convenience for the common case. The user should
  226. supply their own output_field with more complex computations.
  227. If a source's output field resolves to None, exclude it from this check.
  228. If all sources are None, then an error is raised higher up the stack in
  229. the output_field property.
  230. """
  231. sources_iter = (source for source in self.get_source_fields() if source is not None)
  232. for output_field in sources_iter:
  233. if any(not isinstance(output_field, source.__class__) for source in sources_iter):
  234. raise FieldError('Expression contains mixed types. You must set output_field.')
  235. return output_field
  236. @staticmethod
  237. def _convert_value_noop(value, expression, connection):
  238. return value
  239. @cached_property
  240. def convert_value(self):
  241. """
  242. Expressions provide their own converters because users have the option
  243. of manually specifying the output_field which may be a different type
  244. from the one the database returns.
  245. """
  246. field = self.output_field
  247. internal_type = field.get_internal_type()
  248. if internal_type == 'FloatField':
  249. return lambda value, expression, connection: None if value is None else float(value)
  250. elif internal_type.endswith('IntegerField'):
  251. return lambda value, expression, connection: None if value is None else int(value)
  252. elif internal_type == 'DecimalField':
  253. return lambda value, expression, connection: None if value is None else Decimal(value)
  254. return self._convert_value_noop
  255. def get_lookup(self, lookup):
  256. return self.output_field.get_lookup(lookup)
  257. def get_transform(self, name):
  258. return self.output_field.get_transform(name)
  259. def relabeled_clone(self, change_map):
  260. clone = self.copy()
  261. clone.set_source_expressions([
  262. e.relabeled_clone(change_map) if e is not None else None
  263. for e in self.get_source_expressions()
  264. ])
  265. return clone
  266. def copy(self):
  267. return copy.copy(self)
  268. def get_group_by_cols(self):
  269. if not self.contains_aggregate:
  270. return [self]
  271. cols = []
  272. for source in self.get_source_expressions():
  273. cols.extend(source.get_group_by_cols())
  274. return cols
  275. def get_source_fields(self):
  276. """Return the underlying field types used by this aggregate."""
  277. return [e._output_field_or_none for e in self.get_source_expressions()]
  278. def asc(self, **kwargs):
  279. return OrderBy(self, **kwargs)
  280. def desc(self, **kwargs):
  281. return OrderBy(self, descending=True, **kwargs)
  282. def reverse_ordering(self):
  283. return self
  284. def flatten(self):
  285. """
  286. Recursively yield this expression and all subexpressions, in
  287. depth-first order.
  288. """
  289. yield self
  290. for expr in self.get_source_expressions():
  291. if expr:
  292. yield from expr.flatten()
  293. @cached_property
  294. def identity(self):
  295. constructor_signature = inspect.signature(self.__init__)
  296. args, kwargs = self._constructor_args
  297. signature = constructor_signature.bind_partial(*args, **kwargs)
  298. signature.apply_defaults()
  299. arguments = signature.arguments.items()
  300. identity = [self.__class__]
  301. for arg, value in arguments:
  302. if isinstance(value, fields.Field):
  303. if value.name and value.model:
  304. value = (value.model._meta.label, value.name)
  305. else:
  306. value = type(value)
  307. else:
  308. value = make_hashable(value)
  309. identity.append((arg, value))
  310. return tuple(identity)
  311. def __eq__(self, other):
  312. return isinstance(other, BaseExpression) and other.identity == self.identity
  313. def __hash__(self):
  314. return hash(self.identity)
  315. class Expression(BaseExpression, Combinable):
  316. """An expression that can be combined with other expressions."""
  317. pass
  318. class CombinedExpression(SQLiteNumericMixin, Expression):
  319. def __init__(self, lhs, connector, rhs, output_field=None):
  320. super().__init__(output_field=output_field)
  321. self.connector = connector
  322. self.lhs = lhs
  323. self.rhs = rhs
  324. def __repr__(self):
  325. return "<{}: {}>".format(self.__class__.__name__, self)
  326. def __str__(self):
  327. return "{} {} {}".format(self.lhs, self.connector, self.rhs)
  328. def get_source_expressions(self):
  329. return [self.lhs, self.rhs]
  330. def set_source_expressions(self, exprs):
  331. self.lhs, self.rhs = exprs
  332. def as_sql(self, compiler, connection):
  333. try:
  334. lhs_output = self.lhs.output_field
  335. except FieldError:
  336. lhs_output = None
  337. try:
  338. rhs_output = self.rhs.output_field
  339. except FieldError:
  340. rhs_output = None
  341. if (not connection.features.has_native_duration_field and
  342. ((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
  343. (rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
  344. return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
  345. if (lhs_output and rhs_output and self.connector == self.SUB and
  346. lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
  347. lhs_output.get_internal_type() == rhs_output.get_internal_type()):
  348. return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
  349. expressions = []
  350. expression_params = []
  351. sql, params = compiler.compile(self.lhs)
  352. expressions.append(sql)
  353. expression_params.extend(params)
  354. sql, params = compiler.compile(self.rhs)
  355. expressions.append(sql)
  356. expression_params.extend(params)
  357. # order of precedence
  358. expression_wrapper = '(%s)'
  359. sql = connection.ops.combine_expression(self.connector, expressions)
  360. return expression_wrapper % sql, expression_params
  361. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  362. c = self.copy()
  363. c.is_summary = summarize
  364. c.lhs = c.lhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  365. c.rhs = c.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  366. return c
  367. class DurationExpression(CombinedExpression):
  368. def compile(self, side, compiler, connection):
  369. if not isinstance(side, DurationValue):
  370. try:
  371. output = side.output_field
  372. except FieldError:
  373. pass
  374. else:
  375. if output.get_internal_type() == 'DurationField':
  376. sql, params = compiler.compile(side)
  377. return connection.ops.format_for_duration_arithmetic(sql), params
  378. return compiler.compile(side)
  379. def as_sql(self, compiler, connection):
  380. connection.ops.check_expression_support(self)
  381. expressions = []
  382. expression_params = []
  383. sql, params = self.compile(self.lhs, compiler, connection)
  384. expressions.append(sql)
  385. expression_params.extend(params)
  386. sql, params = self.compile(self.rhs, compiler, connection)
  387. expressions.append(sql)
  388. expression_params.extend(params)
  389. # order of precedence
  390. expression_wrapper = '(%s)'
  391. sql = connection.ops.combine_duration_expression(self.connector, expressions)
  392. return expression_wrapper % sql, expression_params
  393. class TemporalSubtraction(CombinedExpression):
  394. output_field = fields.DurationField()
  395. def __init__(self, lhs, rhs):
  396. super().__init__(lhs, self.SUB, rhs)
  397. def as_sql(self, compiler, connection):
  398. connection.ops.check_expression_support(self)
  399. lhs = compiler.compile(self.lhs, connection)
  400. rhs = compiler.compile(self.rhs, connection)
  401. return connection.ops.subtract_temporals(self.lhs.output_field.get_internal_type(), lhs, rhs)
  402. @deconstructible
  403. class F(Combinable):
  404. """An object capable of resolving references to existing query objects."""
  405. # Can the expression be used in a WHERE clause?
  406. filterable = True
  407. def __init__(self, name):
  408. """
  409. Arguments:
  410. * name: the name of the field this expression references
  411. """
  412. self.name = name
  413. def __repr__(self):
  414. return "{}({})".format(self.__class__.__name__, self.name)
  415. def resolve_expression(self, query=None, allow_joins=True, reuse=None,
  416. summarize=False, for_save=False, simple_col=False):
  417. return query.resolve_ref(self.name, allow_joins, reuse, summarize, simple_col)
  418. def asc(self, **kwargs):
  419. return OrderBy(self, **kwargs)
  420. def desc(self, **kwargs):
  421. return OrderBy(self, descending=True, **kwargs)
  422. def __eq__(self, other):
  423. return self.__class__ == other.__class__ and self.name == other.name
  424. def __hash__(self):
  425. return hash(self.name)
  426. class ResolvedOuterRef(F):
  427. """
  428. An object that contains a reference to an outer query.
  429. In this case, the reference to the outer query has been resolved because
  430. the inner query has been used as a subquery.
  431. """
  432. def as_sql(self, *args, **kwargs):
  433. raise ValueError(
  434. 'This queryset contains a reference to an outer query and may '
  435. 'only be used in a subquery.'
  436. )
  437. def _prepare(self, output_field=None):
  438. return self
  439. def relabeled_clone(self, relabels):
  440. return self
  441. class OuterRef(F):
  442. def resolve_expression(self, query=None, allow_joins=True, reuse=None,
  443. summarize=False, for_save=False, simple_col=False):
  444. if isinstance(self.name, self.__class__):
  445. return self.name
  446. return ResolvedOuterRef(self.name)
  447. def _prepare(self, output_field=None):
  448. return self
  449. class Func(SQLiteNumericMixin, Expression):
  450. """An SQL function call."""
  451. function = None
  452. template = '%(function)s(%(expressions)s)'
  453. arg_joiner = ', '
  454. arity = None # The number of arguments the function accepts.
  455. def __init__(self, *expressions, output_field=None, **extra):
  456. if self.arity is not None and len(expressions) != self.arity:
  457. raise TypeError(
  458. "'%s' takes exactly %s %s (%s given)" % (
  459. self.__class__.__name__,
  460. self.arity,
  461. "argument" if self.arity == 1 else "arguments",
  462. len(expressions),
  463. )
  464. )
  465. super().__init__(output_field=output_field)
  466. self.source_expressions = self._parse_expressions(*expressions)
  467. self.extra = extra
  468. def __repr__(self):
  469. args = self.arg_joiner.join(str(arg) for arg in self.source_expressions)
  470. extra = {**self.extra, **self._get_repr_options()}
  471. if extra:
  472. extra = ', '.join(str(key) + '=' + str(val) for key, val in sorted(extra.items()))
  473. return "{}({}, {})".format(self.__class__.__name__, args, extra)
  474. return "{}({})".format(self.__class__.__name__, args)
  475. def _get_repr_options(self):
  476. """Return a dict of extra __init__() options to include in the repr."""
  477. return {}
  478. def get_source_expressions(self):
  479. return self.source_expressions
  480. def set_source_expressions(self, exprs):
  481. self.source_expressions = exprs
  482. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  483. c = self.copy()
  484. c.is_summary = summarize
  485. for pos, arg in enumerate(c.source_expressions):
  486. c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  487. return c
  488. def as_sql(self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context):
  489. connection.ops.check_expression_support(self)
  490. sql_parts = []
  491. params = []
  492. for arg in self.source_expressions:
  493. arg_sql, arg_params = compiler.compile(arg)
  494. sql_parts.append(arg_sql)
  495. params.extend(arg_params)
  496. data = {**self.extra, **extra_context}
  497. # Use the first supplied value in this order: the parameter to this
  498. # method, a value supplied in __init__()'s **extra (the value in
  499. # `data`), or the value defined on the class.
  500. if function is not None:
  501. data['function'] = function
  502. else:
  503. data.setdefault('function', self.function)
  504. template = template or data.get('template', self.template)
  505. arg_joiner = arg_joiner or data.get('arg_joiner', self.arg_joiner)
  506. data['expressions'] = data['field'] = arg_joiner.join(sql_parts)
  507. return template % data, params
  508. def copy(self):
  509. copy = super().copy()
  510. copy.source_expressions = self.source_expressions[:]
  511. copy.extra = self.extra.copy()
  512. return copy
  513. class Value(Expression):
  514. """Represent a wrapped value as a node within an expression."""
  515. def __init__(self, value, output_field=None):
  516. """
  517. Arguments:
  518. * value: the value this expression represents. The value will be
  519. added into the sql parameter list and properly quoted.
  520. * output_field: an instance of the model field type that this
  521. expression will return, such as IntegerField() or CharField().
  522. """
  523. super().__init__(output_field=output_field)
  524. self.value = value
  525. def __repr__(self):
  526. return "{}({})".format(self.__class__.__name__, self.value)
  527. def as_sql(self, compiler, connection):
  528. connection.ops.check_expression_support(self)
  529. val = self.value
  530. output_field = self._output_field_or_none
  531. if output_field is not None:
  532. if self.for_save:
  533. val = output_field.get_db_prep_save(val, connection=connection)
  534. else:
  535. val = output_field.get_db_prep_value(val, connection=connection)
  536. if hasattr(output_field, 'get_placeholder'):
  537. return output_field.get_placeholder(val, compiler, connection), [val]
  538. if val is None:
  539. # cx_Oracle does not always convert None to the appropriate
  540. # NULL type (like in case expressions using numbers), so we
  541. # use a literal SQL NULL
  542. return 'NULL', []
  543. return '%s', [val]
  544. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  545. c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
  546. c.for_save = for_save
  547. return c
  548. def get_group_by_cols(self):
  549. return []
  550. class DurationValue(Value):
  551. def as_sql(self, compiler, connection):
  552. connection.ops.check_expression_support(self)
  553. if connection.features.has_native_duration_field:
  554. return super().as_sql(compiler, connection)
  555. return connection.ops.date_interval_sql(self.value), []
  556. class RawSQL(Expression):
  557. def __init__(self, sql, params, output_field=None):
  558. if output_field is None:
  559. output_field = fields.Field()
  560. self.sql, self.params = sql, params
  561. super().__init__(output_field=output_field)
  562. def __repr__(self):
  563. return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params)
  564. def as_sql(self, compiler, connection):
  565. return '(%s)' % self.sql, self.params
  566. def get_group_by_cols(self):
  567. return [self]
  568. class Star(Expression):
  569. def __repr__(self):
  570. return "'*'"
  571. def as_sql(self, compiler, connection):
  572. return '*', []
  573. class Random(Expression):
  574. output_field = fields.FloatField()
  575. def __repr__(self):
  576. return "Random()"
  577. def as_sql(self, compiler, connection):
  578. return connection.ops.random_function_sql(), []
  579. class Col(Expression):
  580. contains_column_references = True
  581. def __init__(self, alias, target, output_field=None):
  582. if output_field is None:
  583. output_field = target
  584. super().__init__(output_field=output_field)
  585. self.alias, self.target = alias, target
  586. def __repr__(self):
  587. return "{}({}, {})".format(
  588. self.__class__.__name__, self.alias, self.target)
  589. def as_sql(self, compiler, connection):
  590. qn = compiler.quote_name_unless_alias
  591. return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
  592. def relabeled_clone(self, relabels):
  593. return self.__class__(relabels.get(self.alias, self.alias), self.target, self.output_field)
  594. def get_group_by_cols(self):
  595. return [self]
  596. def get_db_converters(self, connection):
  597. if self.target == self.output_field:
  598. return self.output_field.get_db_converters(connection)
  599. return (self.output_field.get_db_converters(connection) +
  600. self.target.get_db_converters(connection))
  601. class SimpleCol(Expression):
  602. """
  603. Represents the SQL of a column name without the table name.
  604. This variant of Col doesn't include the table name (or an alias) to
  605. avoid a syntax error in check constraints.
  606. """
  607. contains_column_references = True
  608. def __init__(self, target, output_field=None):
  609. if output_field is None:
  610. output_field = target
  611. super().__init__(output_field=output_field)
  612. self.target = target
  613. def __repr__(self):
  614. return '{}({})'.format(self.__class__.__name__, self.target)
  615. def as_sql(self, compiler, connection):
  616. qn = compiler.quote_name_unless_alias
  617. return qn(self.target.column), []
  618. def get_group_by_cols(self):
  619. return [self]
  620. def get_db_converters(self, connection):
  621. if self.target == self.output_field:
  622. return self.output_field.get_db_converters(connection)
  623. return (
  624. self.output_field.get_db_converters(connection) +
  625. self.target.get_db_converters(connection)
  626. )
  627. class Ref(Expression):
  628. """
  629. Reference to column alias of the query. For example, Ref('sum_cost') in
  630. qs.annotate(sum_cost=Sum('cost')) query.
  631. """
  632. def __init__(self, refs, source):
  633. super().__init__()
  634. self.refs, self.source = refs, source
  635. def __repr__(self):
  636. return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source)
  637. def get_source_expressions(self):
  638. return [self.source]
  639. def set_source_expressions(self, exprs):
  640. self.source, = exprs
  641. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  642. # The sub-expression `source` has already been resolved, as this is
  643. # just a reference to the name of `source`.
  644. return self
  645. def relabeled_clone(self, relabels):
  646. return self
  647. def as_sql(self, compiler, connection):
  648. return connection.ops.quote_name(self.refs), []
  649. def get_group_by_cols(self):
  650. return [self]
  651. class ExpressionList(Func):
  652. """
  653. An expression containing multiple expressions. Can be used to provide a
  654. list of expressions as an argument to another expression, like an
  655. ordering clause.
  656. """
  657. template = '%(expressions)s'
  658. def __init__(self, *expressions, **extra):
  659. if not expressions:
  660. raise ValueError('%s requires at least one expression.' % self.__class__.__name__)
  661. super().__init__(*expressions, **extra)
  662. def __str__(self):
  663. return self.arg_joiner.join(str(arg) for arg in self.source_expressions)
  664. class ExpressionWrapper(Expression):
  665. """
  666. An expression that can wrap another expression so that it can provide
  667. extra context to the inner expression, such as the output_field.
  668. """
  669. def __init__(self, expression, output_field):
  670. super().__init__(output_field=output_field)
  671. self.expression = expression
  672. def set_source_expressions(self, exprs):
  673. self.expression = exprs[0]
  674. def get_source_expressions(self):
  675. return [self.expression]
  676. def as_sql(self, compiler, connection):
  677. return self.expression.as_sql(compiler, connection)
  678. def __repr__(self):
  679. return "{}({})".format(self.__class__.__name__, self.expression)
  680. class When(Expression):
  681. template = 'WHEN %(condition)s THEN %(result)s'
  682. def __init__(self, condition=None, then=None, **lookups):
  683. if lookups and condition is None:
  684. condition, lookups = Q(**lookups), None
  685. if condition is None or not getattr(condition, 'conditional', False) or lookups:
  686. raise TypeError("__init__() takes either a Q object or lookups as keyword arguments")
  687. if isinstance(condition, Q) and not condition:
  688. raise ValueError("An empty Q() can't be used as a When() condition.")
  689. super().__init__(output_field=None)
  690. self.condition = condition
  691. self.result = self._parse_expressions(then)[0]
  692. def __str__(self):
  693. return "WHEN %r THEN %r" % (self.condition, self.result)
  694. def __repr__(self):
  695. return "<%s: %s>" % (self.__class__.__name__, self)
  696. def get_source_expressions(self):
  697. return [self.condition, self.result]
  698. def set_source_expressions(self, exprs):
  699. self.condition, self.result = exprs
  700. def get_source_fields(self):
  701. # We're only interested in the fields of the result expressions.
  702. return [self.result._output_field_or_none]
  703. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  704. c = self.copy()
  705. c.is_summary = summarize
  706. if hasattr(c.condition, 'resolve_expression'):
  707. c.condition = c.condition.resolve_expression(query, allow_joins, reuse, summarize, False)
  708. c.result = c.result.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  709. return c
  710. def as_sql(self, compiler, connection, template=None, **extra_context):
  711. connection.ops.check_expression_support(self)
  712. template_params = extra_context
  713. sql_params = []
  714. condition_sql, condition_params = compiler.compile(self.condition)
  715. template_params['condition'] = condition_sql
  716. sql_params.extend(condition_params)
  717. result_sql, result_params = compiler.compile(self.result)
  718. template_params['result'] = result_sql
  719. sql_params.extend(result_params)
  720. template = template or self.template
  721. return template % template_params, sql_params
  722. def get_group_by_cols(self):
  723. # This is not a complete expression and cannot be used in GROUP BY.
  724. cols = []
  725. for source in self.get_source_expressions():
  726. cols.extend(source.get_group_by_cols())
  727. return cols
  728. class Case(Expression):
  729. """
  730. An SQL searched CASE expression:
  731. CASE
  732. WHEN n > 0
  733. THEN 'positive'
  734. WHEN n < 0
  735. THEN 'negative'
  736. ELSE 'zero'
  737. END
  738. """
  739. template = 'CASE %(cases)s ELSE %(default)s END'
  740. case_joiner = ' '
  741. def __init__(self, *cases, default=None, output_field=None, **extra):
  742. if not all(isinstance(case, When) for case in cases):
  743. raise TypeError("Positional arguments must all be When objects.")
  744. super().__init__(output_field)
  745. self.cases = list(cases)
  746. self.default = self._parse_expressions(default)[0]
  747. self.extra = extra
  748. def __str__(self):
  749. return "CASE %s, ELSE %r" % (', '.join(str(c) for c in self.cases), self.default)
  750. def __repr__(self):
  751. return "<%s: %s>" % (self.__class__.__name__, self)
  752. def get_source_expressions(self):
  753. return self.cases + [self.default]
  754. def set_source_expressions(self, exprs):
  755. *self.cases, self.default = exprs
  756. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  757. c = self.copy()
  758. c.is_summary = summarize
  759. for pos, case in enumerate(c.cases):
  760. c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  761. c.default = c.default.resolve_expression(query, allow_joins, reuse, summarize, for_save)
  762. return c
  763. def copy(self):
  764. c = super().copy()
  765. c.cases = c.cases[:]
  766. return c
  767. def as_sql(self, compiler, connection, template=None, case_joiner=None, **extra_context):
  768. connection.ops.check_expression_support(self)
  769. if not self.cases:
  770. return compiler.compile(self.default)
  771. template_params = {**self.extra, **extra_context}
  772. case_parts = []
  773. sql_params = []
  774. for case in self.cases:
  775. try:
  776. case_sql, case_params = compiler.compile(case)
  777. except EmptyResultSet:
  778. continue
  779. case_parts.append(case_sql)
  780. sql_params.extend(case_params)
  781. default_sql, default_params = compiler.compile(self.default)
  782. if not case_parts:
  783. return default_sql, default_params
  784. case_joiner = case_joiner or self.case_joiner
  785. template_params['cases'] = case_joiner.join(case_parts)
  786. template_params['default'] = default_sql
  787. sql_params.extend(default_params)
  788. template = template or template_params.get('template', self.template)
  789. sql = template % template_params
  790. if self._output_field_or_none is not None:
  791. sql = connection.ops.unification_cast_sql(self.output_field) % sql
  792. return sql, sql_params
  793. class Subquery(Expression):
  794. """
  795. An explicit subquery. It may contain OuterRef() references to the outer
  796. query which will be resolved when it is applied to that query.
  797. """
  798. template = '(%(subquery)s)'
  799. contains_aggregate = False
  800. def __init__(self, queryset, output_field=None, **extra):
  801. self.queryset = queryset
  802. self.extra = extra
  803. super().__init__(output_field)
  804. def _resolve_output_field(self):
  805. if len(self.queryset.query.select) == 1:
  806. return self.queryset.query.select[0].field
  807. return super()._resolve_output_field()
  808. def copy(self):
  809. clone = super().copy()
  810. clone.queryset = clone.queryset.all()
  811. return clone
  812. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  813. clone = self.copy()
  814. clone.is_summary = summarize
  815. clone.queryset.query.bump_prefix(query)
  816. # Need to recursively resolve these.
  817. def resolve_all(child):
  818. if hasattr(child, 'children'):
  819. [resolve_all(_child) for _child in child.children]
  820. if hasattr(child, 'rhs'):
  821. child.rhs = resolve(child.rhs)
  822. def resolve(child):
  823. if hasattr(child, 'resolve_expression'):
  824. resolved = child.resolve_expression(
  825. query=query, allow_joins=allow_joins, reuse=reuse,
  826. summarize=summarize, for_save=for_save,
  827. )
  828. # Add table alias to the parent query's aliases to prevent
  829. # quoting.
  830. if hasattr(resolved, 'alias') and resolved.alias != resolved.target.model._meta.db_table:
  831. clone.queryset.query.external_aliases.add(resolved.alias)
  832. return resolved
  833. return child
  834. resolve_all(clone.queryset.query.where)
  835. for key, value in clone.queryset.query.annotations.items():
  836. if isinstance(value, Subquery):
  837. clone.queryset.query.annotations[key] = resolve(value)
  838. return clone
  839. def get_source_expressions(self):
  840. return [
  841. x for x in [
  842. getattr(expr, 'lhs', None)
  843. for expr in self.queryset.query.where.children
  844. ] if x
  845. ]
  846. def relabeled_clone(self, change_map):
  847. clone = self.copy()
  848. clone.queryset.query = clone.queryset.query.relabeled_clone(change_map)
  849. clone.queryset.query.external_aliases.update(
  850. alias for alias in change_map.values()
  851. if alias not in clone.queryset.query.alias_map
  852. )
  853. return clone
  854. def as_sql(self, compiler, connection, template=None, **extra_context):
  855. connection.ops.check_expression_support(self)
  856. template_params = {**self.extra, **extra_context}
  857. template_params['subquery'], sql_params = self.queryset.query.get_compiler(connection=connection).as_sql()
  858. template = template or template_params.get('template', self.template)
  859. sql = template % template_params
  860. return sql, sql_params
  861. def _prepare(self, output_field):
  862. # This method will only be called if this instance is the "rhs" in an
  863. # expression: the wrapping () must be removed (as the expression that
  864. # contains this will provide them). SQLite evaluates ((subquery))
  865. # differently than the other databases.
  866. if self.template == '(%(subquery)s)':
  867. clone = self.copy()
  868. clone.template = '%(subquery)s'
  869. return clone
  870. return self
  871. class Exists(Subquery):
  872. template = 'EXISTS(%(subquery)s)'
  873. output_field = fields.BooleanField()
  874. def __init__(self, *args, negated=False, **kwargs):
  875. self.negated = negated
  876. super().__init__(*args, **kwargs)
  877. def __invert__(self):
  878. return type(self)(self.queryset, negated=(not self.negated), **self.extra)
  879. def resolve_expression(self, query=None, *args, **kwargs):
  880. # As a performance optimization, remove ordering since EXISTS doesn't
  881. # care about it, just whether or not a row matches.
  882. self.queryset = self.queryset.order_by()
  883. return super().resolve_expression(query, *args, **kwargs)
  884. def as_sql(self, compiler, connection, template=None, **extra_context):
  885. sql, params = super().as_sql(compiler, connection, template, **extra_context)
  886. if self.negated:
  887. sql = 'NOT {}'.format(sql)
  888. return sql, params
  889. def as_oracle(self, compiler, connection, template=None, **extra_context):
  890. # Oracle doesn't allow EXISTS() in the SELECT list, so wrap it with a
  891. # CASE WHEN expression. Change the template since the When expression
  892. # requires a left hand side (column) to compare against.
  893. sql, params = self.as_sql(compiler, connection, template, **extra_context)
  894. sql = 'CASE WHEN {} THEN 1 ELSE 0 END'.format(sql)
  895. return sql, params
  896. class OrderBy(BaseExpression):
  897. template = '%(expression)s %(ordering)s'
  898. def __init__(self, expression, descending=False, nulls_first=False, nulls_last=False):
  899. if nulls_first and nulls_last:
  900. raise ValueError('nulls_first and nulls_last are mutually exclusive')
  901. self.nulls_first = nulls_first
  902. self.nulls_last = nulls_last
  903. self.descending = descending
  904. if not hasattr(expression, 'resolve_expression'):
  905. raise ValueError('expression must be an expression type')
  906. self.expression = expression
  907. def __repr__(self):
  908. return "{}({}, descending={})".format(
  909. self.__class__.__name__, self.expression, self.descending)
  910. def set_source_expressions(self, exprs):
  911. self.expression = exprs[0]
  912. def get_source_expressions(self):
  913. return [self.expression]
  914. def as_sql(self, compiler, connection, template=None, **extra_context):
  915. if not template:
  916. if self.nulls_last:
  917. template = '%s NULLS LAST' % self.template
  918. elif self.nulls_first:
  919. template = '%s NULLS FIRST' % self.template
  920. connection.ops.check_expression_support(self)
  921. expression_sql, params = compiler.compile(self.expression)
  922. placeholders = {
  923. 'expression': expression_sql,
  924. 'ordering': 'DESC' if self.descending else 'ASC',
  925. **extra_context,
  926. }
  927. template = template or self.template
  928. params *= template.count('%(expression)s')
  929. return (template % placeholders).rstrip(), params
  930. def as_sqlite(self, compiler, connection):
  931. template = None
  932. if self.nulls_last:
  933. template = '%(expression)s IS NULL, %(expression)s %(ordering)s'
  934. elif self.nulls_first:
  935. template = '%(expression)s IS NOT NULL, %(expression)s %(ordering)s'
  936. return self.as_sql(compiler, connection, template=template)
  937. def as_mysql(self, compiler, connection):
  938. template = None
  939. if self.nulls_last:
  940. template = 'IF(ISNULL(%(expression)s),1,0), %(expression)s %(ordering)s '
  941. elif self.nulls_first:
  942. template = 'IF(ISNULL(%(expression)s),0,1), %(expression)s %(ordering)s '
  943. return self.as_sql(compiler, connection, template=template)
  944. def get_group_by_cols(self):
  945. cols = []
  946. for source in self.get_source_expressions():
  947. cols.extend(source.get_group_by_cols())
  948. return cols
  949. def reverse_ordering(self):
  950. self.descending = not self.descending
  951. if self.nulls_first or self.nulls_last:
  952. self.nulls_first = not self.nulls_first
  953. self.nulls_last = not self.nulls_last
  954. return self
  955. def asc(self):
  956. self.descending = False
  957. def desc(self):
  958. self.descending = True
  959. class Window(Expression):
  960. template = '%(expression)s OVER (%(window)s)'
  961. # Although the main expression may either be an aggregate or an
  962. # expression with an aggregate function, the GROUP BY that will
  963. # be introduced in the query as a result is not desired.
  964. contains_aggregate = False
  965. contains_over_clause = True
  966. filterable = False
  967. def __init__(self, expression, partition_by=None, order_by=None, frame=None, output_field=None):
  968. self.partition_by = partition_by
  969. self.order_by = order_by
  970. self.frame = frame
  971. if not getattr(expression, 'window_compatible', False):
  972. raise ValueError(
  973. "Expression '%s' isn't compatible with OVER clauses." %
  974. expression.__class__.__name__
  975. )
  976. if self.partition_by is not None:
  977. if not isinstance(self.partition_by, (tuple, list)):
  978. self.partition_by = (self.partition_by,)
  979. self.partition_by = ExpressionList(*self.partition_by)
  980. if self.order_by is not None:
  981. if isinstance(self.order_by, (list, tuple)):
  982. self.order_by = ExpressionList(*self.order_by)
  983. elif not isinstance(self.order_by, BaseExpression):
  984. raise ValueError(
  985. 'order_by must be either an Expression or a sequence of '
  986. 'expressions.'
  987. )
  988. super().__init__(output_field=output_field)
  989. self.source_expression = self._parse_expressions(expression)[0]
  990. def _resolve_output_field(self):
  991. return self.source_expression.output_field
  992. def get_source_expressions(self):
  993. return [self.source_expression, self.partition_by, self.order_by, self.frame]
  994. def set_source_expressions(self, exprs):
  995. self.source_expression, self.partition_by, self.order_by, self.frame = exprs
  996. def as_sql(self, compiler, connection, template=None):
  997. connection.ops.check_expression_support(self)
  998. expr_sql, params = compiler.compile(self.source_expression)
  999. window_sql, window_params = [], []
  1000. if self.partition_by is not None:
  1001. sql_expr, sql_params = self.partition_by.as_sql(
  1002. compiler=compiler, connection=connection,
  1003. template='PARTITION BY %(expressions)s',
  1004. )
  1005. window_sql.extend(sql_expr)
  1006. window_params.extend(sql_params)
  1007. if self.order_by is not None:
  1008. window_sql.append(' ORDER BY ')
  1009. order_sql, order_params = compiler.compile(self.order_by)
  1010. window_sql.extend(''.join(order_sql))
  1011. window_params.extend(order_params)
  1012. if self.frame:
  1013. frame_sql, frame_params = compiler.compile(self.frame)
  1014. window_sql.extend(' ' + frame_sql)
  1015. window_params.extend(frame_params)
  1016. params.extend(window_params)
  1017. template = template or self.template
  1018. return template % {
  1019. 'expression': expr_sql,
  1020. 'window': ''.join(window_sql).strip()
  1021. }, params
  1022. def __str__(self):
  1023. return '{} OVER ({}{}{})'.format(
  1024. str(self.source_expression),
  1025. 'PARTITION BY ' + str(self.partition_by) if self.partition_by else '',
  1026. 'ORDER BY ' + str(self.order_by) if self.order_by else '',
  1027. str(self.frame or ''),
  1028. )
  1029. def __repr__(self):
  1030. return '<%s: %s>' % (self.__class__.__name__, self)
  1031. def get_group_by_cols(self):
  1032. return []
  1033. class WindowFrame(Expression):
  1034. """
  1035. Model the frame clause in window expressions. There are two types of frame
  1036. clauses which are subclasses, however, all processing and validation (by no
  1037. means intended to be complete) is done here. Thus, providing an end for a
  1038. frame is optional (the default is UNBOUNDED FOLLOWING, which is the last
  1039. row in the frame).
  1040. """
  1041. template = '%(frame_type)s BETWEEN %(start)s AND %(end)s'
  1042. def __init__(self, start=None, end=None):
  1043. self.start = Value(start)
  1044. self.end = Value(end)
  1045. def set_source_expressions(self, exprs):
  1046. self.start, self.end = exprs
  1047. def get_source_expressions(self):
  1048. return [self.start, self.end]
  1049. def as_sql(self, compiler, connection):
  1050. connection.ops.check_expression_support(self)
  1051. start, end = self.window_frame_start_end(connection, self.start.value, self.end.value)
  1052. return self.template % {
  1053. 'frame_type': self.frame_type,
  1054. 'start': start,
  1055. 'end': end,
  1056. }, []
  1057. def __repr__(self):
  1058. return '<%s: %s>' % (self.__class__.__name__, self)
  1059. def get_group_by_cols(self):
  1060. return []
  1061. def __str__(self):
  1062. if self.start.value is not None and self.start.value < 0:
  1063. start = '%d %s' % (abs(self.start.value), connection.ops.PRECEDING)
  1064. elif self.start.value is not None and self.start.value == 0:
  1065. start = connection.ops.CURRENT_ROW
  1066. else:
  1067. start = connection.ops.UNBOUNDED_PRECEDING
  1068. if self.end.value is not None and self.end.value > 0:
  1069. end = '%d %s' % (self.end.value, connection.ops.FOLLOWING)
  1070. elif self.end.value is not None and self.end.value == 0:
  1071. end = connection.ops.CURRENT_ROW
  1072. else:
  1073. end = connection.ops.UNBOUNDED_FOLLOWING
  1074. return self.template % {
  1075. 'frame_type': self.frame_type,
  1076. 'start': start,
  1077. 'end': end,
  1078. }
  1079. def window_frame_start_end(self, connection, start, end):
  1080. raise NotImplementedError('Subclasses must implement window_frame_start_end().')
  1081. class RowRange(WindowFrame):
  1082. frame_type = 'ROWS'
  1083. def window_frame_start_end(self, connection, start, end):
  1084. return connection.ops.window_frame_rows_start_end(start, end)
  1085. class ValueRange(WindowFrame):
  1086. frame_type = 'RANGE'
  1087. def window_frame_start_end(self, connection, start, end):
  1088. return connection.ops.window_frame_range_start_end(start, end)