1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125 |
- import collections
- import json
- import re
- from functools import partial
- from itertools import chain
- from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet
- from django.db import DatabaseError, NotSupportedError
- from django.db.models.constants import LOOKUP_SEP
- from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value
- from django.db.models.functions import Cast, Random
- from django.db.models.lookups import Lookup
- from django.db.models.query_utils import select_related_descend
- from django.db.models.sql.constants import (
- CURSOR,
- GET_ITERATOR_CHUNK_SIZE,
- MULTI,
- NO_RESULTS,
- ORDER_DIR,
- SINGLE,
- )
- from django.db.models.sql.query import Query, get_order_dir
- from django.db.models.sql.where import AND
- from django.db.transaction import TransactionManagementError
- from django.utils.functional import cached_property
- from django.utils.hashable import make_hashable
- from django.utils.regex_helper import _lazy_re_compile
- class PositionRef(Ref):
- def __init__(self, ordinal, refs, source):
- self.ordinal = ordinal
- super().__init__(refs, source)
- def as_sql(self, compiler, connection):
- return str(self.ordinal), ()
- class SQLCompiler:
-
- ordering_parts = _lazy_re_compile(
- r"^(.*)\s(?:ASC|DESC).*",
- re.MULTILINE | re.DOTALL,
- )
- def __init__(self, query, connection, using, elide_empty=True):
- self.query = query
- self.connection = connection
- self.using = using
-
-
- self.elide_empty = elide_empty
- self.quote_cache = {"*": "*"}
-
-
-
-
- self.select = None
- self.annotation_col_map = None
- self.klass_info = None
- self._meta_ordering = None
- def __repr__(self):
- return (
- f"<{self.__class__.__qualname__} "
- f"model={self.query.model.__qualname__} "
- f"connection={self.connection!r} using={self.using!r}>"
- )
- def setup_query(self, with_col_aliases=False):
- if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
- self.query.get_initial_alias()
- self.select, self.klass_info, self.annotation_col_map = self.get_select(
- with_col_aliases=with_col_aliases,
- )
- self.col_count = len(self.select)
- def pre_sql_setup(self, with_col_aliases=False):
- """
- Do any necessary class setup immediately prior to producing SQL. This
- is for things that can't necessarily be done in __init__ because we
- might not have all the pieces in place at that time.
- """
- self.setup_query(with_col_aliases=with_col_aliases)
- order_by = self.get_order_by()
- self.where, self.having, self.qualify = self.query.where.split_having_qualify(
- must_group_by=self.query.group_by is not None
- )
- extra_select = self.get_extra_select(order_by, self.select)
- self.has_extra_select = bool(extra_select)
- group_by = self.get_group_by(self.select + extra_select, order_by)
- return extra_select, order_by, group_by
- def get_group_by(self, select, order_by):
- """
- Return a list of 2-tuples of form (sql, params).
- The logic of what exactly the GROUP BY clause contains is hard
- to describe in other words than "if it passes the test suite,
- then it is correct".
- """
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if self.query.group_by is None:
- return []
- expressions = []
- group_by_refs = set()
- if self.query.group_by is not True:
-
-
-
-
-
- for expr in self.query.group_by:
- if not hasattr(expr, "as_sql"):
- expr = self.query.resolve_ref(expr)
- if isinstance(expr, Ref):
- if expr.refs not in group_by_refs:
- group_by_refs.add(expr.refs)
- expressions.append(expr.source)
- else:
- expressions.append(expr)
-
-
-
- selected_expr_positions = {}
- for ordinal, (expr, _, alias) in enumerate(select, start=1):
- if alias:
- selected_expr_positions[expr] = ordinal
-
-
- if alias in group_by_refs:
- continue
- expressions.extend(expr.get_group_by_cols())
- if not self._meta_ordering:
- for expr, (sql, params, is_ref) in order_by:
-
-
- if not is_ref:
- expressions.extend(expr.get_group_by_cols())
- having_group_by = self.having.get_group_by_cols() if self.having else ()
- for expr in having_group_by:
- expressions.append(expr)
- result = []
- seen = set()
- expressions = self.collapse_group_by(expressions, having_group_by)
- allows_group_by_select_index = (
- self.connection.features.allows_group_by_select_index
- )
- for expr in expressions:
- try:
- sql, params = self.compile(expr)
- except (EmptyResultSet, FullResultSet):
- continue
- if (
- allows_group_by_select_index
- and (position := selected_expr_positions.get(expr)) is not None
- ):
- sql, params = str(position), ()
- else:
- sql, params = expr.select_format(self, sql, params)
- params_hash = make_hashable(params)
- if (sql, params_hash) not in seen:
- result.append((sql, params))
- seen.add((sql, params_hash))
- return result
- def collapse_group_by(self, expressions, having):
-
-
-
- if self.connection.features.allows_group_by_selected_pks:
-
-
-
-
-
-
- pks = {
- expr
- for expr in expressions
- if (
- hasattr(expr, "target")
- and expr.target.primary_key
- and self.connection.features.allows_group_by_selected_pks_on_model(
- expr.target.model
- )
- )
- }
- aliases = {expr.alias for expr in pks}
- expressions = [
- expr
- for expr in expressions
- if expr in pks
- or expr in having
- or getattr(expr, "alias", None) not in aliases
- ]
- return expressions
- def get_select(self, with_col_aliases=False):
- """
- Return three values:
- - a list of 3-tuples of (expression, (sql, params), alias)
- - a klass_info structure,
- - a dictionary of annotations
- The (sql, params) is what the expression will produce, and alias is the
- "AS alias" for the column (possibly None).
- The klass_info structure contains the following information:
- - The base model of the query.
- - Which columns for that model are present in the query (by
- position of the select clause).
- - related_klass_infos: [f, klass_info] to descent into
- The annotations is a dictionary of {'attname': column position} values.
- """
- select = []
- klass_info = None
- annotations = {}
- assert not (self.query.select and self.query.default_cols)
- select_mask = self.query.get_select_mask()
- if self.query.default_cols:
- cols = self.get_default_columns(select_mask)
- else:
-
-
- cols = self.query.select
- if cols:
- klass_info = {
- "model": self.query.model,
- "select_fields": list(
- range(
- len(self.query.extra_select),
- len(self.query.extra_select) + len(cols),
- )
- ),
- }
- selected = []
- if self.query.selected is None:
- selected = [
- *(
- (alias, RawSQL(*args))
- for alias, args in self.query.extra_select.items()
- ),
- *((None, col) for col in cols),
- *self.query.annotation_select.items(),
- ]
- else:
- for alias, expression in self.query.selected.items():
-
- if isinstance(expression, str):
- expression = self.query.annotations[expression]
-
- elif isinstance(expression, int):
- expression = cols[expression]
- selected.append((alias, expression))
- for select_idx, (alias, expression) in enumerate(selected):
- if alias:
- annotations[alias] = select_idx
- select.append((expression, alias))
- if self.query.select_related:
- related_klass_infos = self.get_related_selections(select, select_mask)
- klass_info["related_klass_infos"] = related_klass_infos
- def get_select_from_parent(klass_info):
- for ki in klass_info["related_klass_infos"]:
- if ki["from_parent"]:
- ki["select_fields"] = (
- klass_info["select_fields"] + ki["select_fields"]
- )
- get_select_from_parent(ki)
- get_select_from_parent(klass_info)
- ret = []
- col_idx = 1
- for col, alias in select:
- try:
- sql, params = self.compile(col)
- except EmptyResultSet:
- empty_result_set_value = getattr(
- col, "empty_result_set_value", NotImplemented
- )
- if empty_result_set_value is NotImplemented:
-
- sql, params = "0", ()
- else:
- sql, params = self.compile(Value(empty_result_set_value))
- except FullResultSet:
- sql, params = self.compile(Value(True))
- else:
- sql, params = col.select_format(self, sql, params)
- if alias is None and with_col_aliases:
- alias = f"col{col_idx}"
- col_idx += 1
- ret.append((col, (sql, params), alias))
- return ret, klass_info, annotations
- def _order_by_pairs(self):
- if self.query.extra_order_by:
- ordering = self.query.extra_order_by
- elif not self.query.default_ordering:
- ordering = self.query.order_by
- elif self.query.order_by:
- ordering = self.query.order_by
- elif (meta := self.query.get_meta()) and meta.ordering:
- ordering = meta.ordering
- self._meta_ordering = ordering
- else:
- ordering = []
- if self.query.standard_ordering:
- default_order, _ = ORDER_DIR["ASC"]
- else:
- default_order, _ = ORDER_DIR["DESC"]
- selected_exprs = {}
-
-
- if ordering and (select := self.select):
- for ordinal, (expr, _, alias) in enumerate(select, start=1):
- pos_expr = PositionRef(ordinal, alias, expr)
- if alias:
- selected_exprs[alias] = pos_expr
- selected_exprs[expr] = pos_expr
- for field in ordering:
- if hasattr(field, "resolve_expression"):
- if isinstance(field, Value):
-
- field = Cast(field, field.output_field)
- if not isinstance(field, OrderBy):
- field = field.asc()
- if not self.query.standard_ordering:
- field = field.copy()
- field.reverse_ordering()
- select_ref = selected_exprs.get(field.expression)
- if select_ref or (
- isinstance(field.expression, F)
- and (select_ref := selected_exprs.get(field.expression.name))
- ):
-
-
- if (
- field.nulls_first is None and field.nulls_last is None
- ) or self.connection.features.supports_order_by_nulls_modifier:
- field = field.copy()
- field.expression = select_ref
-
-
-
- elif self.query.combinator:
- field = field.copy()
- field.expression = Ref(select_ref.refs, select_ref.source)
- yield field, select_ref is not None
- continue
- if field == "?":
- yield OrderBy(Random()), False
- continue
- col, order = get_order_dir(field, default_order)
- descending = order == "DESC"
- if select_ref := selected_exprs.get(col):
-
- yield (
- OrderBy(
- select_ref,
- descending=descending,
- ),
- True,
- )
- continue
- ref, *transforms = col.split(LOOKUP_SEP)
- if expr := self.query.annotations.get(ref):
- if self.query.combinator and self.select:
- if transforms:
- raise NotImplementedError(
- "Ordering combined queries by transforms is not "
- "implemented."
- )
-
-
- expr = F(ref)
- if transforms:
- for name in transforms:
- expr = self.query.try_transform(expr, name)
- if isinstance(expr, Value):
-
- expr = Cast(expr, expr.output_field)
- yield OrderBy(expr, descending=descending), False
- continue
- if "." in field:
-
-
- table, col = col.split(".", 1)
- yield (
- OrderBy(
- RawSQL(
- "%s.%s" % (self.quote_name_unless_alias(table), col), []
- ),
- descending=descending,
- ),
- False,
- )
- continue
- if self.query.extra and col in self.query.extra:
- if col in self.query.extra_select:
- yield (
- OrderBy(
- Ref(col, RawSQL(*self.query.extra[col])),
- descending=descending,
- ),
- True,
- )
- else:
- yield (
- OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
- False,
- )
- else:
- if self.query.combinator and self.select:
-
-
- yield OrderBy(F(col), descending=descending), False
- else:
-
-
- yield from self.find_ordering_name(
- field,
- self.query.get_meta(),
- default_order=default_order,
- )
- def get_order_by(self):
- """
- Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for
- the ORDER BY clause.
- The order_by clause can alter the select clause (for example it can add
- aliases to clauses that do not yet have one, or it can add totally new
- select clauses).
- """
- result = []
- seen = set()
- for expr, is_ref in self._order_by_pairs():
- resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
- if not is_ref and self.query.combinator and self.select:
- src = resolved.expression
- expr_src = expr.expression
- for sel_expr, _, col_alias in self.select:
- if src == sel_expr:
-
-
- if (
- self.query.has_select_fields
- and col_alias in self.query.annotation_select
- and not (
- isinstance(expr_src, F) and col_alias == expr_src.name
- )
- ):
- continue
- resolved.set_source_expressions(
- [Ref(col_alias if col_alias else src.target.column, src)]
- )
- break
- else:
-
-
- order_by_idx = len(self.query.select) + 1
- col_alias = f"__orderbycol{order_by_idx}"
- for q in self.query.combined_queries:
-
-
- if q.has_select_fields:
- raise DatabaseError(
- "ORDER BY term does not match any column in "
- "the result set."
- )
- q.add_annotation(expr_src, col_alias)
- self.query.add_select_col(resolved, col_alias)
- resolved.set_source_expressions([Ref(col_alias, src)])
- sql, params = self.compile(resolved)
-
-
-
-
- without_ordering = self.ordering_parts.search(sql)[1]
- params_hash = make_hashable(params)
- if (without_ordering, params_hash) in seen:
- continue
- seen.add((without_ordering, params_hash))
- result.append((resolved, (sql, params, is_ref)))
- return result
- def get_extra_select(self, order_by, select):
- extra_select = []
- if self.query.distinct and not self.query.distinct_fields:
- select_sql = [t[1] for t in select]
- for expr, (sql, params, is_ref) in order_by:
- without_ordering = self.ordering_parts.search(sql)[1]
- if not is_ref and (without_ordering, params) not in select_sql:
- extra_select.append((expr, (without_ordering, params), None))
- return extra_select
- def quote_name_unless_alias(self, name):
- """
- A wrapper around connection.ops.quote_name that doesn't quote aliases
- for table names. This avoids problems with some SQL dialects that treat
- quoted strings specially (e.g. PostgreSQL).
- """
- if name in self.quote_cache:
- return self.quote_cache[name]
- if (
- (name in self.query.alias_map and name not in self.query.table_map)
- or name in self.query.extra_select
- or (
- self.query.external_aliases.get(name)
- and name not in self.query.table_map
- )
- ):
- self.quote_cache[name] = name
- return name
- r = self.connection.ops.quote_name(name)
- self.quote_cache[name] = r
- return r
- def compile(self, node):
- vendor_impl = getattr(node, "as_" + self.connection.vendor, None)
- if vendor_impl:
- sql, params = vendor_impl(self, self.connection)
- else:
- sql, params = node.as_sql(self, self.connection)
- return sql, params
- def get_combinator_sql(self, combinator, all):
- features = self.connection.features
- compilers = [
- query.get_compiler(self.using, self.connection, self.elide_empty)
- for query in self.query.combined_queries
- ]
- if not features.supports_slicing_ordering_in_compound:
- for compiler in compilers:
- if compiler.query.is_sliced:
- raise DatabaseError(
- "LIMIT/OFFSET not allowed in subqueries of compound statements."
- )
- if compiler.get_order_by():
- raise DatabaseError(
- "ORDER BY not allowed in subqueries of compound statements."
- )
- elif self.query.is_sliced and combinator == "union":
- for compiler in compilers:
-
-
-
-
- compiler.elide_empty = False
- parts = ()
- for compiler in compilers:
- try:
-
-
-
- if not compiler.query.values_select and self.query.values_select:
- compiler.query = compiler.query.clone()
- compiler.query.set_values(
- (
- *self.query.extra_select,
- *self.query.values_select,
- *self.query.annotation_select,
- )
- )
- part_sql, part_args = compiler.as_sql(with_col_aliases=True)
- if compiler.query.combinator:
-
-
- if not features.supports_parentheses_in_compound:
- part_sql = "SELECT * FROM ({})".format(part_sql)
-
-
- elif (
- self.query.subquery
- or not features.supports_slicing_ordering_in_compound
- ):
- part_sql = "({})".format(part_sql)
- elif (
- self.query.subquery
- and features.supports_slicing_ordering_in_compound
- ):
- part_sql = "({})".format(part_sql)
- parts += ((part_sql, part_args),)
- except EmptyResultSet:
-
-
- if combinator == "union" or (combinator == "difference" and parts):
- continue
- raise
- if not parts:
- raise EmptyResultSet
- combinator_sql = self.connection.ops.set_operators[combinator]
- if all and combinator == "union":
- combinator_sql += " ALL"
- braces = "{}"
- if not self.query.subquery and features.supports_slicing_ordering_in_compound:
- braces = "({})"
- sql_parts, args_parts = zip(
- *((braces.format(sql), args) for sql, args in parts)
- )
- result = [" {} ".format(combinator_sql).join(sql_parts)]
- params = []
- for part in args_parts:
- params.extend(part)
- return result, params
- def get_qualify_sql(self):
- where_parts = []
- if self.where:
- where_parts.append(self.where)
- if self.having:
- where_parts.append(self.having)
- inner_query = self.query.clone()
- inner_query.subquery = True
- inner_query.where = inner_query.where.__class__(where_parts)
-
-
-
-
- select = {
- expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0]
- }
- select_aliases = set(select.values())
- qual_aliases = set()
- replacements = {}
- def collect_replacements(expressions):
- while expressions:
- expr = expressions.pop()
- if expr in replacements:
- continue
- elif select_alias := select.get(expr):
- replacements[expr] = select_alias
- elif isinstance(expr, Lookup):
- expressions.extend(expr.get_source_expressions())
- elif isinstance(expr, Ref):
- if expr.refs not in select_aliases:
- expressions.extend(expr.get_source_expressions())
- else:
- num_qual_alias = len(qual_aliases)
- select_alias = f"qual{num_qual_alias}"
- qual_aliases.add(select_alias)
- inner_query.add_annotation(expr, select_alias)
- replacements[expr] = select_alias
- collect_replacements(list(self.qualify.leaves()))
- self.qualify = self.qualify.replace_expressions(
- {expr: Ref(alias, expr) for expr, alias in replacements.items()}
- )
- order_by = []
- for order_by_expr, *_ in self.get_order_by():
- collect_replacements(order_by_expr.get_source_expressions())
- order_by.append(
- order_by_expr.replace_expressions(
- {expr: Ref(alias, expr) for expr, alias in replacements.items()}
- )
- )
- inner_query_compiler = inner_query.get_compiler(
- self.using, connection=self.connection, elide_empty=self.elide_empty
- )
- inner_sql, inner_params = inner_query_compiler.as_sql(
-
-
- with_limits=False,
-
-
- with_col_aliases=True,
- )
- qualify_sql, qualify_params = self.compile(self.qualify)
- result = [
- "SELECT * FROM (",
- inner_sql,
- ")",
- self.connection.ops.quote_name("qualify"),
- "WHERE",
- qualify_sql,
- ]
- if qual_aliases:
-
-
- cols = [self.connection.ops.quote_name(alias) for alias in select.values()]
- result = [
- "SELECT",
- ", ".join(cols),
- "FROM (",
- *result,
- ")",
- self.connection.ops.quote_name("qualify_mask"),
- ]
- params = list(inner_params) + qualify_params
-
-
-
- if order_by:
- ordering_sqls = []
- for ordering in order_by:
- ordering_sql, ordering_params = self.compile(ordering)
- ordering_sqls.append(ordering_sql)
- params.extend(ordering_params)
- result.extend(["ORDER BY", ", ".join(ordering_sqls)])
- return result, params
- def as_sql(self, with_limits=True, with_col_aliases=False):
- """
- Create the SQL for this query. Return the SQL string and list of
- parameters.
- If 'with_limits' is False, any limit/offset information is not included
- in the query.
- """
- refcounts_before = self.query.alias_refcount.copy()
- try:
- combinator = self.query.combinator
- extra_select, order_by, group_by = self.pre_sql_setup(
- with_col_aliases=with_col_aliases or bool(combinator),
- )
- for_update_part = None
-
- with_limit_offset = with_limits and self.query.is_sliced
- combinator = self.query.combinator
- features = self.connection.features
- if combinator:
- if not getattr(features, "supports_select_{}".format(combinator)):
- raise NotSupportedError(
- "{} is not supported on this database backend.".format(
- combinator
- )
- )
- result, params = self.get_combinator_sql(
- combinator, self.query.combinator_all
- )
- elif self.qualify:
- result, params = self.get_qualify_sql()
- order_by = None
- else:
- distinct_fields, distinct_params = self.get_distinct()
-
-
- from_, f_params = self.get_from_clause()
- try:
- where, w_params = (
- self.compile(self.where) if self.where is not None else ("", [])
- )
- except EmptyResultSet:
- if self.elide_empty:
- raise
-
- where, w_params = "0 = 1", []
- except FullResultSet:
- where, w_params = "", []
- try:
- having, h_params = (
- self.compile(self.having)
- if self.having is not None
- else ("", [])
- )
- except FullResultSet:
- having, h_params = "", []
- result = ["SELECT"]
- params = []
- if self.query.distinct:
- distinct_result, distinct_params = self.connection.ops.distinct_sql(
- distinct_fields,
- distinct_params,
- )
- result += distinct_result
- params += distinct_params
- out_cols = []
- for _, (s_sql, s_params), alias in self.select + extra_select:
- if alias:
- s_sql = "%s AS %s" % (
- s_sql,
- self.connection.ops.quote_name(alias),
- )
- params.extend(s_params)
- out_cols.append(s_sql)
- result += [", ".join(out_cols)]
- if from_:
- result += ["FROM", *from_]
- elif self.connection.features.bare_select_suffix:
- result += [self.connection.features.bare_select_suffix]
- params.extend(f_params)
- if self.query.select_for_update and features.has_select_for_update:
- if (
- self.connection.get_autocommit()
-
-
- and features.supports_transactions
- ):
- raise TransactionManagementError(
- "select_for_update cannot be used outside of a transaction."
- )
- if (
- with_limit_offset
- and not features.supports_select_for_update_with_limit
- ):
- raise NotSupportedError(
- "LIMIT/OFFSET is not supported with "
- "select_for_update on this database backend."
- )
- nowait = self.query.select_for_update_nowait
- skip_locked = self.query.select_for_update_skip_locked
- of = self.query.select_for_update_of
- no_key = self.query.select_for_no_key_update
-
-
-
- if nowait and not features.has_select_for_update_nowait:
- raise NotSupportedError(
- "NOWAIT is not supported on this database backend."
- )
- elif skip_locked and not features.has_select_for_update_skip_locked:
- raise NotSupportedError(
- "SKIP LOCKED is not supported on this database backend."
- )
- elif of and not features.has_select_for_update_of:
- raise NotSupportedError(
- "FOR UPDATE OF is not supported on this database backend."
- )
- elif no_key and not features.has_select_for_no_key_update:
- raise NotSupportedError(
- "FOR NO KEY UPDATE is not supported on this "
- "database backend."
- )
- for_update_part = self.connection.ops.for_update_sql(
- nowait=nowait,
- skip_locked=skip_locked,
- of=self.get_select_for_update_of_arguments(),
- no_key=no_key,
- )
- if for_update_part and features.for_update_after_from:
- result.append(for_update_part)
- if where:
- result.append("WHERE %s" % where)
- params.extend(w_params)
- grouping = []
- for g_sql, g_params in group_by:
- grouping.append(g_sql)
- params.extend(g_params)
- if grouping:
- if distinct_fields:
- raise NotImplementedError(
- "annotate() + distinct(fields) is not implemented."
- )
- order_by = order_by or self.connection.ops.force_no_ordering()
- result.append("GROUP BY %s" % ", ".join(grouping))
- if self._meta_ordering:
- order_by = None
- if having:
- if not grouping:
- result.extend(self.connection.ops.force_group_by())
- result.append("HAVING %s" % having)
- params.extend(h_params)
- if self.query.explain_info:
- result.insert(
- 0,
- self.connection.ops.explain_query_prefix(
- self.query.explain_info.format,
- **self.query.explain_info.options,
- ),
- )
- if order_by:
- ordering = []
- for _, (o_sql, o_params, _) in order_by:
- ordering.append(o_sql)
- params.extend(o_params)
- order_by_sql = "ORDER BY %s" % ", ".join(ordering)
- if combinator and features.requires_compound_order_by_subquery:
- result = ["SELECT * FROM (", *result, ")", order_by_sql]
- else:
- result.append(order_by_sql)
- if with_limit_offset:
- result.append(
- self.connection.ops.limit_offset_sql(
- self.query.low_mark, self.query.high_mark
- )
- )
- if for_update_part and not features.for_update_after_from:
- result.append(for_update_part)
- if self.query.subquery and extra_select:
-
-
-
-
-
-
- sub_selects = []
- sub_params = []
- for index, (select, _, alias) in enumerate(self.select, start=1):
- if alias:
- sub_selects.append(
- "%s.%s"
- % (
- self.connection.ops.quote_name("subquery"),
- self.connection.ops.quote_name(alias),
- )
- )
- else:
- select_clone = select.relabeled_clone(
- {select.alias: "subquery"}
- )
- subselect, subparams = select_clone.as_sql(
- self, self.connection
- )
- sub_selects.append(subselect)
- sub_params.extend(subparams)
- return "SELECT %s FROM (%s) subquery" % (
- ", ".join(sub_selects),
- " ".join(result),
- ), tuple(sub_params + params)
- return " ".join(result), tuple(params)
- finally:
-
- self.query.reset_refcounts(refcounts_before)
- def get_default_columns(
- self, select_mask, start_alias=None, opts=None, from_parent=None
- ):
- """
- Compute the default columns for selecting every field in the base
- model. Will sometimes be called to pull in related models (e.g. via
- select_related), in which case "opts" and "start_alias" will be given
- to provide a starting point for the traversal.
- Return a list of strings, quoted appropriately for use in SQL
- directly, as well as a set of aliases used in the select statement (if
- 'as_pairs' is True, return a list of (alias, col_name) pairs instead
- of strings as the first component and None as the second component).
- """
- result = []
- if opts is None:
- if (opts := self.query.get_meta()) is None:
- return result
- start_alias = start_alias or self.query.get_initial_alias()
-
-
-
- seen_models = {None: start_alias}
- for field in opts.concrete_fields:
- model = field.model._meta.concrete_model
-
-
- if model == opts.model:
- model = None
- if (
- from_parent
- and model is not None
- and issubclass(
- from_parent._meta.concrete_model, model._meta.concrete_model
- )
- ):
-
-
-
-
-
- continue
- if select_mask and field not in select_mask:
- continue
- alias = self.query.join_parent_model(opts, model, start_alias, seen_models)
- column = field.get_col(alias)
- result.append(column)
- return result
- def get_distinct(self):
- """
- Return a quoted list of fields to use in DISTINCT ON part of the query.
- This method can alter the tables in the query, and thus it must be
- called before get_from_clause().
- """
- result = []
- params = []
- opts = self.query.get_meta()
- for name in self.query.distinct_fields:
- parts = name.split(LOOKUP_SEP)
- _, targets, alias, joins, path, _, transform_function = self._setup_joins(
- parts, opts, None
- )
- targets, alias, _ = self.query.trim_joins(targets, joins, path)
- for target in targets:
- if name in self.query.annotation_select:
- result.append(self.connection.ops.quote_name(name))
- else:
- r, p = self.compile(transform_function(target, alias))
- result.append(r)
- params.append(p)
- return result, params
- def find_ordering_name(
- self, name, opts, alias=None, default_order="ASC", already_seen=None
- ):
- """
- Return the table alias (the name might be ambiguous, the alias will
- not be) and column name for ordering by the given 'name' parameter.
- The 'name' is of the form 'field1__field2__...__fieldN'.
- """
- name, order = get_order_dir(name, default_order)
- descending = order == "DESC"
- pieces = name.split(LOOKUP_SEP)
- (
- field,
- targets,
- alias,
- joins,
- path,
- opts,
- transform_function,
- ) = self._setup_joins(pieces, opts, alias)
-
-
-
-
- if (
- field.is_relation
- and opts.ordering
- and getattr(field, "attname", None) != pieces[-1]
- and name != "pk"
- and not getattr(transform_function, "has_transforms", False)
- ):
-
- already_seen = already_seen or set()
- join_tuple = tuple(
- getattr(self.query.alias_map[j], "join_cols", None) for j in joins
- )
- if join_tuple in already_seen:
- raise FieldError("Infinite loop caused by ordering.")
- already_seen.add(join_tuple)
- results = []
- for item in opts.ordering:
- if hasattr(item, "resolve_expression") and not isinstance(
- item, OrderBy
- ):
- item = item.desc() if descending else item.asc()
- if isinstance(item, OrderBy):
- results.append(
- (item.prefix_references(f"{name}{LOOKUP_SEP}"), False)
- )
- continue
- results.extend(
- (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref)
- for expr, is_ref in self.find_ordering_name(
- item, opts, alias, order, already_seen
- )
- )
- return results
- targets, alias, _ = self.query.trim_joins(targets, joins, path)
- return [
- (OrderBy(transform_function(t, alias), descending=descending), False)
- for t in targets
- ]
- def _setup_joins(self, pieces, opts, alias):
- """
- Helper method for get_order_by() and get_distinct().
- get_ordering() and get_distinct() must produce same target columns on
- same input, as the prefixes of get_ordering() and get_distinct() must
- match. Executing SQL where this is not true is an error.
- """
- alias = alias or self.query.get_initial_alias()
- field, targets, opts, joins, path, transform_function = self.query.setup_joins(
- pieces, opts, alias
- )
- alias = joins[-1]
- return field, targets, alias, joins, path, opts, transform_function
- def get_from_clause(self):
- """
- Return a list of strings that are joined together to go after the
- "FROM" part of the query, as well as a list any extra parameters that
- need to be included. Subclasses, can override this to create a
- from-clause via a "select".
- This should only be called after any SQL construction methods that
- might change the tables that are needed. This means the select columns,
- ordering, and distinct must be done first.
- """
- result = []
- params = []
- for alias in tuple(self.query.alias_map):
- if not self.query.alias_refcount[alias]:
- continue
- try:
- from_clause = self.query.alias_map[alias]
- except KeyError:
-
-
- continue
- clause_sql, clause_params = self.compile(from_clause)
- result.append(clause_sql)
- params.extend(clause_params)
- for t in self.query.extra_tables:
- alias, _ = self.query.table_alias(t)
-
-
-
- if (
- alias not in self.query.alias_map
- or self.query.alias_refcount[alias] == 1
- ):
- result.append(", %s" % self.quote_name_unless_alias(alias))
- return result, params
- def get_related_selections(
- self,
- select,
- select_mask,
- opts=None,
- root_alias=None,
- cur_depth=1,
- requested=None,
- restricted=None,
- ):
- """
- Fill in the information needed for a select_related query. The current
- depth is measured as the number of connections away from the root model
- (for example, cur_depth=1 means we are looking at models with direct
- connections to the root model).
- """
- def _get_field_choices():
- direct_choices = (f.name for f in opts.fields if f.is_relation)
- reverse_choices = (
- f.field.related_query_name()
- for f in opts.related_objects
- if f.field.unique
- )
- return chain(
- direct_choices, reverse_choices, self.query._filtered_relations
- )
- related_klass_infos = []
- if not restricted and cur_depth > self.query.max_depth:
-
- return related_klass_infos
- if not opts:
- opts = self.query.get_meta()
- root_alias = self.query.get_initial_alias()
-
-
- fields_found = set()
- if requested is None:
- restricted = isinstance(self.query.select_related, dict)
- if restricted:
- requested = self.query.select_related
- def get_related_klass_infos(klass_info, related_klass_infos):
- klass_info["related_klass_infos"] = related_klass_infos
- for f in opts.fields:
- fields_found.add(f.name)
- if restricted:
- next = requested.get(f.name, {})
- if not f.is_relation:
-
-
- if next or f.name in requested:
- raise FieldError(
- "Non-relational field given in select_related: '%s'. "
- "Choices are: %s"
- % (
- f.name,
- ", ".join(_get_field_choices()) or "(none)",
- )
- )
- else:
- next = False
- if not select_related_descend(f, restricted, requested, select_mask):
- continue
- related_select_mask = select_mask.get(f) or {}
- klass_info = {
- "model": f.remote_field.model,
- "field": f,
- "reverse": False,
- "local_setter": f.set_cached_value,
- "remote_setter": (
- f.remote_field.set_cached_value if f.unique else lambda x, y: None
- ),
- "from_parent": False,
- }
- related_klass_infos.append(klass_info)
- select_fields = []
- _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias)
- alias = joins[-1]
- columns = self.get_default_columns(
- related_select_mask, start_alias=alias, opts=f.remote_field.model._meta
- )
- for col in columns:
- select_fields.append(len(select))
- select.append((col, None))
- klass_info["select_fields"] = select_fields
- next_klass_infos = self.get_related_selections(
- select,
- related_select_mask,
- f.remote_field.model._meta,
- alias,
- cur_depth + 1,
- next,
- restricted,
- )
- get_related_klass_infos(klass_info, next_klass_infos)
- if restricted:
- related_fields = [
- (o, o.field, o.related_model)
- for o in opts.related_objects
- if o.field.unique and not o.many_to_many
- ]
- for related_object, related_field, model in related_fields:
- if not select_related_descend(
- related_object,
- restricted,
- requested,
- select_mask,
- ):
- continue
- related_select_mask = select_mask.get(related_object) or {}
- related_field_name = related_field.related_query_name()
- fields_found.add(related_field_name)
- join_info = self.query.setup_joins(
- [related_field_name], opts, root_alias
- )
- alias = join_info.joins[-1]
- from_parent = issubclass(model, opts.model) and model is not opts.model
- klass_info = {
- "model": model,
- "field": related_field,
- "reverse": True,
- "local_setter": related_object.set_cached_value,
- "remote_setter": related_field.set_cached_value,
- "from_parent": from_parent,
- }
- related_klass_infos.append(klass_info)
- select_fields = []
- columns = self.get_default_columns(
- related_select_mask,
- start_alias=alias,
- opts=model._meta,
- from_parent=opts.model,
- )
- for col in columns:
- select_fields.append(len(select))
- select.append((col, None))
- klass_info["select_fields"] = select_fields
- next = requested.get(related_field_name, {})
- next_klass_infos = self.get_related_selections(
- select,
- related_select_mask,
- model._meta,
- alias,
- cur_depth + 1,
- next,
- restricted,
- )
- get_related_klass_infos(klass_info, next_klass_infos)
- def local_setter(final_field, obj, from_obj):
-
- if from_obj:
- final_field.remote_field.set_cached_value(from_obj, obj)
- def local_setter_noop(obj, from_obj):
- pass
- def remote_setter(name, obj, from_obj):
- setattr(from_obj, name, obj)
- for name in list(requested):
-
- if cur_depth > 1:
- break
- if name in self.query._filtered_relations:
- fields_found.add(name)
- final_field, _, join_opts, joins, _, _ = self.query.setup_joins(
- [name], opts, root_alias
- )
- model = join_opts.model
- alias = joins[-1]
- from_parent = (
- issubclass(model, opts.model) and model is not opts.model
- )
- klass_info = {
- "model": model,
- "field": final_field,
- "reverse": True,
- "local_setter": (
- partial(local_setter, final_field)
- if len(joins) <= 2
- else local_setter_noop
- ),
- "remote_setter": partial(remote_setter, name),
- "from_parent": from_parent,
- }
- related_klass_infos.append(klass_info)
- select_fields = []
- field_select_mask = select_mask.get((name, final_field)) or {}
- columns = self.get_default_columns(
- field_select_mask,
- start_alias=alias,
- opts=model._meta,
- from_parent=opts.model,
- )
- for col in columns:
- select_fields.append(len(select))
- select.append((col, None))
- klass_info["select_fields"] = select_fields
- next_requested = requested.get(name, {})
- next_klass_infos = self.get_related_selections(
- select,
- field_select_mask,
- opts=model._meta,
- root_alias=alias,
- cur_depth=cur_depth + 1,
- requested=next_requested,
- restricted=restricted,
- )
- get_related_klass_infos(klass_info, next_klass_infos)
- fields_not_found = set(requested).difference(fields_found)
- if fields_not_found:
- invalid_fields = ("'%s'" % s for s in fields_not_found)
- raise FieldError(
- "Invalid field name(s) given in select_related: %s. "
- "Choices are: %s"
- % (
- ", ".join(invalid_fields),
- ", ".join(_get_field_choices()) or "(none)",
- )
- )
- return related_klass_infos
- def get_select_for_update_of_arguments(self):
- """
- Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
- the query.
- """
- def _get_parent_klass_info(klass_info):
- concrete_model = klass_info["model"]._meta.concrete_model
- for parent_model, parent_link in concrete_model._meta.parents.items():
- all_parents = parent_model._meta.all_parents
- yield {
- "model": parent_model,
- "field": parent_link,
- "reverse": False,
- "select_fields": [
- select_index
- for select_index in klass_info["select_fields"]
-
- if (
- self.select[select_index][0].target.model == parent_model
- or self.select[select_index][0].target.model in all_parents
- )
- ],
- }
- def _get_first_selected_col_from_model(klass_info):
- """
- Find the first selected column from a model. If it doesn't exist,
- don't lock a model.
- select_fields is filled recursively, so it also contains fields
- from the parent models.
- """
- concrete_model = klass_info["model"]._meta.concrete_model
- for select_index in klass_info["select_fields"]:
- if self.select[select_index][0].target.model == concrete_model:
- return self.select[select_index][0]
- def _get_field_choices():
- """Yield all allowed field paths in breadth-first search order."""
- queue = collections.deque([(None, self.klass_info)])
- while queue:
- parent_path, klass_info = queue.popleft()
- if parent_path is None:
- path = []
- yield "self"
- else:
- field = klass_info["field"]
- if klass_info["reverse"]:
- field = field.remote_field
- path = parent_path + [field.name]
- yield LOOKUP_SEP.join(path)
- queue.extend(
- (path, klass_info)
- for klass_info in _get_parent_klass_info(klass_info)
- )
- queue.extend(
- (path, klass_info)
- for klass_info in klass_info.get("related_klass_infos", [])
- )
- if not self.klass_info:
- return []
- result = []
- invalid_names = []
- for name in self.query.select_for_update_of:
- klass_info = self.klass_info
- if name == "self":
- col = _get_first_selected_col_from_model(klass_info)
- else:
- for part in name.split(LOOKUP_SEP):
- klass_infos = (
- *klass_info.get("related_klass_infos", []),
- *_get_parent_klass_info(klass_info),
- )
- for related_klass_info in klass_infos:
- field = related_klass_info["field"]
- if related_klass_info["reverse"]:
- field = field.remote_field
- if field.name == part:
- klass_info = related_klass_info
- break
- else:
- klass_info = None
- break
- if klass_info is None:
- invalid_names.append(name)
- continue
- col = _get_first_selected_col_from_model(klass_info)
- if col is not None:
- if self.connection.features.select_for_update_of_column:
- result.append(self.compile(col)[0])
- else:
- result.append(self.quote_name_unless_alias(col.alias))
- if invalid_names:
- raise FieldError(
- "Invalid field name(s) given in select_for_update(of=(...)): %s. "
- "Only relational fields followed in the query are allowed. "
- "Choices are: %s."
- % (
- ", ".join(invalid_names),
- ", ".join(_get_field_choices()),
- )
- )
- return result
- def get_converters(self, expressions):
- converters = {}
- for i, expression in enumerate(expressions):
- if expression:
- backend_converters = self.connection.ops.get_db_converters(expression)
- field_converters = expression.get_db_converters(self.connection)
- if backend_converters or field_converters:
- converters[i] = (backend_converters + field_converters, expression)
- return converters
- def apply_converters(self, rows, converters):
- connection = self.connection
- converters = list(converters.items())
- for row in map(list, rows):
- for pos, (convs, expression) in converters:
- value = row[pos]
- for converter in convs:
- value = converter(value, expression, connection)
- row[pos] = value
- yield row
- def results_iter(
- self,
- results=None,
- tuple_expected=False,
- chunked_fetch=False,
- chunk_size=GET_ITERATOR_CHUNK_SIZE,
- ):
- """Return an iterator over the results from executing this query."""
- if results is None:
- results = self.execute_sql(
- MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size
- )
- fields = [s[0] for s in self.select[0 : self.col_count]]
- converters = self.get_converters(fields)
- rows = chain.from_iterable(results)
- if converters:
- rows = self.apply_converters(rows, converters)
- if tuple_expected:
- rows = map(tuple, rows)
- return rows
- def has_results(self):
- """
- Backends (e.g. NoSQL) can override this in order to use optimized
- versions of "query has any results."
- """
- return bool(self.execute_sql(SINGLE))
- def execute_sql(
- self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
- ):
- """
- Run the query against the database and return the result(s). The
- return value is a single data item if result_type is SINGLE, or an
- iterator over the results if the result_type is MULTI.
- result_type is either MULTI (use fetchmany() to retrieve all rows),
- SINGLE (only retrieve a single row), or None. In this last case, the
- cursor is returned if any query is executed, since it's used by
- subclasses such as InsertQuery). It's possible, however, that no query
- is needed, as the filters describe an empty set. In that case, None is
- returned, to avoid any unnecessary database interaction.
- """
- result_type = result_type or NO_RESULTS
- try:
- sql, params = self.as_sql()
- if not sql:
- raise EmptyResultSet
- except EmptyResultSet:
- if result_type == MULTI:
- return iter([])
- else:
- return
- if chunked_fetch:
- cursor = self.connection.chunked_cursor()
- else:
- cursor = self.connection.cursor()
- try:
- cursor.execute(sql, params)
- except Exception:
-
- cursor.close()
- raise
- if result_type == CURSOR:
-
- return cursor
- if result_type == SINGLE:
- try:
- val = cursor.fetchone()
- if val:
- return val[0 : self.col_count]
- return val
- finally:
-
- cursor.close()
- if result_type == NO_RESULTS:
- cursor.close()
- return
- result = cursor_iter(
- cursor,
- self.connection.features.empty_fetchmany_value,
- self.col_count if self.has_extra_select else None,
- chunk_size,
- )
- if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
-
-
-
-
- return list(result)
- return result
- def as_subquery_condition(self, alias, columns, compiler):
- qn = compiler.quote_name_unless_alias
- qn2 = self.connection.ops.quote_name
- for index, select_col in enumerate(self.query.select):
- lhs_sql, lhs_params = self.compile(select_col)
- rhs = "%s.%s" % (qn(alias), qn2(columns[index]))
- self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND)
- sql, params = self.as_sql()
- return "EXISTS (%s)" % sql, params
- def explain_query(self):
- result = list(self.execute_sql())
-
-
- format_ = self.query.explain_info.format
- output_formatter = json.dumps if format_ and format_.lower() == "json" else str
- for row in result:
- for value in row:
- if not isinstance(value, str):
- yield " ".join([output_formatter(c) for c in value])
- else:
- yield value
- class SQLInsertCompiler(SQLCompiler):
- returning_fields = None
- returning_params = ()
- def field_as_sql(self, field, val):
- """
- Take a field and a value intended to be saved on that field, and
- return placeholder SQL and accompanying params. Check for raw values,
- expressions, and fields with get_placeholder() defined in that order.
- When field is None, consider the value raw and use it as the
- placeholder, with no corresponding parameters returned.
- """
- if field is None:
-
- sql, params = val, []
- elif hasattr(val, "as_sql"):
-
- sql, params = self.compile(val)
- elif hasattr(field, "get_placeholder"):
-
-
- sql, params = field.get_placeholder(val, self, self.connection), [val]
- else:
-
- sql, params = "%s", [val]
-
-
-
-
-
- params = self.connection.ops.modify_insert_params(sql, params)
- return sql, params
- def prepare_value(self, field, value):
- """
- Prepare a value to be used in a query by resolving it if it is an
- expression and otherwise calling the field's get_db_prep_save().
- """
- if hasattr(value, "resolve_expression"):
- value = value.resolve_expression(
- self.query, allow_joins=False, for_save=True
- )
-
-
-
- if value.contains_column_references:
- raise ValueError(
- 'Failed to insert expression "%s" on %s. F() expressions '
- "can only be used to update, not to insert." % (value, field)
- )
- if value.contains_aggregate:
- raise FieldError(
- "Aggregate functions are not allowed in this query "
- "(%s=%r)." % (field.name, value)
- )
- if value.contains_over_clause:
- raise FieldError(
- "Window expressions are not allowed in this query (%s=%r)."
- % (field.name, value)
- )
- return field.get_db_prep_save(value, connection=self.connection)
- def pre_save_val(self, field, obj):
- """
- Get the given field's value off the given obj. pre_save() is used for
- things like auto_now on DateTimeField. Skip it if this is a raw query.
- """
- if self.query.raw:
- return getattr(obj, field.attname)
- return field.pre_save(obj, add=True)
- def assemble_as_sql(self, fields, value_rows):
- """
- Take a sequence of N fields and a sequence of M rows of values, and
- generate placeholder SQL and parameters for each field and value.
- Return a pair containing:
- * a sequence of M rows of N SQL placeholder strings, and
- * a sequence of M rows of corresponding parameter values.
- Each placeholder string may contain any number of '%s' interpolation
- strings, and each parameter row will contain exactly as many params
- as the total number of '%s's in the corresponding placeholder row.
- """
- if not value_rows:
- return [], []
-
-
- rows_of_fields_as_sql = (
- (self.field_as_sql(field, v) for field, v in zip(fields, row))
- for row in value_rows
- )
-
-
- sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
-
-
- placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
-
- param_rows = [[p for ps in row for p in ps] for row in param_rows]
- return placeholder_rows, param_rows
- def as_sql(self):
-
-
- qn = self.connection.ops.quote_name
- opts = self.query.get_meta()
- insert_statement = self.connection.ops.insert_statement(
- on_conflict=self.query.on_conflict,
- )
- result = ["%s %s" % (insert_statement, qn(opts.db_table))]
- fields = self.query.fields or [opts.pk]
- result.append("(%s)" % ", ".join(qn(f.column) for f in fields))
- if self.query.fields:
- value_rows = [
- [
- self.prepare_value(field, self.pre_save_val(field, obj))
- for field in fields
- ]
- for obj in self.query.objs
- ]
- else:
-
- value_rows = [
- [self.connection.ops.pk_default_value()] for _ in self.query.objs
- ]
- fields = [None]
-
-
-
-
- can_bulk = (
- not self.returning_fields and self.connection.features.has_bulk_insert
- )
- placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
- on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql(
- fields,
- self.query.on_conflict,
- (f.column for f in self.query.update_fields),
- (f.column for f in self.query.unique_fields),
- )
- if (
- self.returning_fields
- and self.connection.features.can_return_columns_from_insert
- ):
- if self.connection.features.can_return_rows_from_bulk_insert:
- result.append(
- self.connection.ops.bulk_insert_sql(fields, placeholder_rows)
- )
- params = param_rows
- else:
- result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
- params = [param_rows[0]]
- if on_conflict_suffix_sql:
- result.append(on_conflict_suffix_sql)
-
-
- r_sql, self.returning_params = self.connection.ops.return_insert_columns(
- self.returning_fields
- )
- if r_sql:
- result.append(r_sql)
- params += [self.returning_params]
- return [(" ".join(result), tuple(chain.from_iterable(params)))]
- if can_bulk:
- result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
- if on_conflict_suffix_sql:
- result.append(on_conflict_suffix_sql)
- return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
- else:
- if on_conflict_suffix_sql:
- result.append(on_conflict_suffix_sql)
- return [
- (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
- for p, vals in zip(placeholder_rows, param_rows)
- ]
- def execute_sql(self, returning_fields=None):
- assert not (
- returning_fields
- and len(self.query.objs) != 1
- and not self.connection.features.can_return_rows_from_bulk_insert
- )
- opts = self.query.get_meta()
- self.returning_fields = returning_fields
- cols = []
- with self.connection.cursor() as cursor:
- for sql, params in self.as_sql():
- cursor.execute(sql, params)
- if not self.returning_fields:
- return []
- if (
- self.connection.features.can_return_rows_from_bulk_insert
- and len(self.query.objs) > 1
- ):
- rows = self.connection.ops.fetch_returned_insert_rows(cursor)
- cols = [field.get_col(opts.db_table) for field in self.returning_fields]
- elif self.connection.features.can_return_columns_from_insert:
- assert len(self.query.objs) == 1
- rows = [
- self.connection.ops.fetch_returned_insert_columns(
- cursor,
- self.returning_params,
- )
- ]
- cols = [field.get_col(opts.db_table) for field in self.returning_fields]
- else:
- cols = [opts.pk.get_col(opts.db_table)]
- rows = [
- (
- self.connection.ops.last_insert_id(
- cursor,
- opts.db_table,
- opts.pk.column,
- ),
- )
- ]
- converters = self.get_converters(cols)
- if converters:
- rows = list(self.apply_converters(rows, converters))
- return rows
- class SQLDeleteCompiler(SQLCompiler):
- @cached_property
- def single_alias(self):
-
- self.query.get_initial_alias()
- return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1
- @classmethod
- def _expr_refs_base_model(cls, expr, base_model):
- if isinstance(expr, Query):
- return expr.model == base_model
- if not hasattr(expr, "get_source_expressions"):
- return False
- return any(
- cls._expr_refs_base_model(source_expr, base_model)
- for source_expr in expr.get_source_expressions()
- )
- @cached_property
- def contains_self_reference_subquery(self):
- return any(
- self._expr_refs_base_model(expr, self.query.model)
- for expr in chain(
- self.query.annotations.values(), self.query.where.children
- )
- )
- def _as_sql(self, query):
- delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table)
- try:
- where, params = self.compile(query.where)
- except FullResultSet:
- return delete, ()
- return f"{delete} WHERE {where}", tuple(params)
- def as_sql(self):
- """
- Create the SQL for this query. Return the SQL string and list of
- parameters.
- """
- if self.single_alias and (
- self.connection.features.delete_can_self_reference_subquery
- or not self.contains_self_reference_subquery
- ):
- return self._as_sql(self.query)
- innerq = self.query.clone()
- innerq.__class__ = Query
- innerq.clear_select_clause()
- pk = self.query.model._meta.pk
- innerq.select = [pk.get_col(self.query.get_initial_alias())]
- outerq = Query(self.query.model)
- if not self.connection.features.update_can_self_select:
-
-
- sql, params = innerq.get_compiler(connection=self.connection).as_sql()
- innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params)
- outerq.add_filter("pk__in", innerq)
- return self._as_sql(outerq)
- class SQLUpdateCompiler(SQLCompiler):
- def as_sql(self):
- """
- Create the SQL for this query. Return the SQL string and list of
- parameters.
- """
- self.pre_sql_setup()
- if not self.query.values:
- return "", ()
- qn = self.quote_name_unless_alias
- values, update_params = [], []
- for field, model, val in self.query.values:
- if hasattr(val, "resolve_expression"):
- val = val.resolve_expression(
- self.query, allow_joins=False, for_save=True
- )
- if val.contains_aggregate:
- raise FieldError(
- "Aggregate functions are not allowed in this query "
- "(%s=%r)." % (field.name, val)
- )
- if val.contains_over_clause:
- raise FieldError(
- "Window expressions are not allowed in this query "
- "(%s=%r)." % (field.name, val)
- )
- elif hasattr(val, "prepare_database_save"):
- if field.remote_field:
- val = val.prepare_database_save(field)
- else:
- raise TypeError(
- "Tried to update field %s with a model instance, %r. "
- "Use a value compatible with %s."
- % (field, val, field.__class__.__name__)
- )
- val = field.get_db_prep_save(val, connection=self.connection)
-
- if hasattr(field, "get_placeholder"):
- placeholder = field.get_placeholder(val, self, self.connection)
- else:
- placeholder = "%s"
- name = field.column
- if hasattr(val, "as_sql"):
- sql, params = self.compile(val)
- values.append("%s = %s" % (qn(name), placeholder % sql))
- update_params.extend(params)
- elif val is not None:
- values.append("%s = %s" % (qn(name), placeholder))
- update_params.append(val)
- else:
- values.append("%s = NULL" % qn(name))
- table = self.query.base_table
- result = [
- "UPDATE %s SET" % qn(table),
- ", ".join(values),
- ]
- try:
- where, params = self.compile(self.query.where)
- except FullResultSet:
- params = []
- else:
- result.append("WHERE %s" % where)
- return " ".join(result), tuple(update_params + params)
- def execute_sql(self, result_type):
- """
- Execute the specified update. Return the number of rows affected by
- the primary update query. The "primary update query" is the first
- non-empty query that is executed. Row counts for any subsequent,
- related queries are not available.
- """
- cursor = super().execute_sql(result_type)
- try:
- rows = cursor.rowcount if cursor else 0
- is_empty = cursor is None
- finally:
- if cursor:
- cursor.close()
- for query in self.query.get_related_updates():
- aux_rows = query.get_compiler(self.using).execute_sql(result_type)
- if is_empty and aux_rows:
- rows = aux_rows
- is_empty = False
- return rows
- def pre_sql_setup(self):
- """
- If the update depends on results from other tables, munge the "where"
- conditions to match the format required for (portable) SQL updates.
- If multiple updates are required, pull out the id values to update at
- this point so that they don't change as a result of the progressive
- updates.
- """
- refcounts_before = self.query.alias_refcount.copy()
-
- self.query.get_initial_alias()
- count = self.query.count_active_tables()
- if not self.query.related_updates and count == 1:
- return
- query = self.query.chain(klass=Query)
- query.select_related = False
- query.clear_ordering(force=True)
- query.extra = {}
- query.select = []
- meta = query.get_meta()
- fields = [meta.pk.name]
- related_ids_index = []
- for related in self.query.related_updates:
- if all(
- path.join_field.primary_key for path in meta.get_path_to_parent(related)
- ):
-
-
- related_ids_index.append((related, 0))
- else:
-
-
-
- related_ids_index.append((related, len(fields)))
- fields.append(related._meta.pk.name)
- query.add_fields(fields)
- super().pre_sql_setup()
- must_pre_select = (
- count > 1 and not self.connection.features.update_can_self_select
- )
-
-
- self.query.clear_where()
- if self.query.related_updates or must_pre_select:
-
-
-
- idents = []
- related_ids = collections.defaultdict(list)
- for rows in query.get_compiler(self.using).execute_sql(MULTI):
- idents.extend(r[0] for r in rows)
- for parent, index in related_ids_index:
- related_ids[parent].extend(r[index] for r in rows)
- self.query.add_filter("pk__in", idents)
- self.query.related_ids = related_ids
- else:
-
- self.query.add_filter("pk__in", query)
- self.query.reset_refcounts(refcounts_before)
- class SQLAggregateCompiler(SQLCompiler):
- def as_sql(self):
- """
- Create the SQL for this query. Return the SQL string and list of
- parameters.
- """
- sql, params = [], []
- for annotation in self.query.annotation_select.values():
- ann_sql, ann_params = self.compile(annotation)
- ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
- sql.append(ann_sql)
- params.extend(ann_params)
- self.col_count = len(self.query.annotation_select)
- sql = ", ".join(sql)
- params = tuple(params)
- inner_query_sql, inner_query_params = self.query.inner_query.get_compiler(
- self.using,
- elide_empty=self.elide_empty,
- ).as_sql(with_col_aliases=True)
- sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql)
- params += inner_query_params
- return sql, params
- def cursor_iter(cursor, sentinel, col_count, itersize):
- """
- Yield blocks of rows from a cursor and ensure the cursor is closed when
- done.
- """
- try:
- for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
- yield rows if col_count is None else [r[:col_count] for r in rows]
- finally:
- cursor.close()
|