MCPcopy
hub / github.com/django/django / as_sql

Method as_sql

django/db/models/sql/datastructures.py:76–133  ·  view source on GitHub ↗

Generate the full LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params clause for this join.

(self, compiler, connection)

Source from the content-addressed store, hash-verified

74 self.filtered_relation = filtered_relation
75
76 def as_sql(self, compiler, connection):
77 """
78 Generate the full
79 LEFT OUTER JOIN sometable
80 ON sometable.somecol = othertable.othercol, params
81 clause for this join.
82 """
83 join_conditions = []
84 params = []
85 qn = compiler.quote_name
86 # Add a join condition for each pair of joining columns.
87 for lhs, rhs in self.join_fields:
88 lhs, rhs = connection.ops.prepare_join_on_clause(
89 self.parent_alias, lhs, self.table_alias, rhs
90 )
91 lhs_sql, lhs_params = compiler.compile(lhs)
92 lhs_full_name = lhs_sql % lhs_params
93 rhs_sql, rhs_params = compiler.compile(rhs)
94 rhs_full_name = rhs_sql % rhs_params
95 join_conditions.append(f"{lhs_full_name} = {rhs_full_name}")
96
97 # Add a single condition inside parentheses for whatever
98 # get_extra_restriction() returns.
99 extra_cond = self.join_field.get_extra_restriction(
100 self.table_alias, self.parent_alias
101 )
102 if extra_cond:
103 extra_sql, extra_params = compiler.compile(extra_cond)
104 join_conditions.append("(%s)" % extra_sql)
105 params.extend(extra_params)
106 if self.filtered_relation:
107 try:
108 extra_sql, extra_params = compiler.compile(self.filtered_relation)
109 except FullResultSet:
110 pass
111 else:
112 join_conditions.append("(%s)" % extra_sql)
113 params.extend(extra_params)
114 if not join_conditions:
115 # This might be a rel on the other end of an actual declared field.
116 declared_field = getattr(self.join_field, "field", self.join_field)
117 raise ValueError(
118 "Join generated an empty ON clause. %s did not yield either "
119 "joining columns or extra restrictions." % declared_field.__class__
120 )
121 on_clause_sql = " AND ".join(join_conditions)
122 alias_str = (
123 ""
124 if self.table_alias == self.table_name
125 else (" %s" % qn(self.table_alias))
126 )
127 sql = "%s %s%s ON (%s)" % (
128 self.join_type,
129 qn(self.table_name),
130 alias_str,
131 on_clause_sql,
132 )
133 return sql, params

Callers

nothing calls this directly

Calls 6

extendMethod · 0.80
compileMethod · 0.45
appendMethod · 0.45
get_extra_restrictionMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected