-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
with.go
213 lines (187 loc) · 7.4 KB
/
with.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package optbuilder
import (
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/errors"
)
func (b *Builder) buildCTE(
cte *tree.CTE, inScope *scope, isRecursive bool,
) (memo.RelExpr, physical.Presentation) {
if !isRecursive {
cteScope := b.buildStmt(cte.Stmt, nil /* desiredTypes */, inScope)
cteScope.removeHiddenCols()
b.dropOrderingAndExtraCols(cteScope)
return cteScope.expr, b.getCTECols(cteScope, cte.Name)
}
// WITH RECURSIVE queries are always of the form:
//
// WITH RECURSIVE name(cols) AS (
// initial_query
// UNION ALL
// recursive_query
// )
//
// Recursive CTE evaluation (paraphrased from postgres docs):
// 1. Evaluate the initial query; emit the results and also save them in
// a "working" table.
// 2. So long as the working table is not empty:
// - evaluate the recursive query, substituting the current contents of
// the working table for the recursive self-reference. Emit all
// resulting rows, and save them into the next iteration's working
// table.
//
// Note however, that a non-recursive CTE can be used even when RECURSIVE is
// specified (particularly useful when there are multiple CTEs defined).
// Handling this while having decent error messages is tricky.
// Generate an id for the recursive CTE reference. This is the id through
// which the recursive expression refers to the current working table
// (via WithScan).
withID := b.factory.Memo().NextWithID()
// cteScope allows recursive references to this CTE.
cteScope := inScope.push()
cteSrc := &cteSource{
id: withID,
name: cte.Name,
}
cteScope.ctes = map[string]*cteSource{cte.Name.Alias.String(): cteSrc}
initial, recursive, ok := b.splitRecursiveCTE(cte.Stmt)
if !ok {
// Build this as a non-recursive CTE, but throw a proper error message if it
// does have a recursive reference.
cteSrc.onRef = func() {
panic(pgerror.Newf(
pgcode.Syntax,
"recursive query %q does not have the form non-recursive-term UNION ALL recursive-term",
cte.Name.Alias,
))
}
return b.buildCTE(cte, cteScope, false /* recursive */)
}
// Set up an error if the initial part has a recursive reference.
cteSrc.onRef = func() {
panic(pgerror.Newf(
pgcode.Syntax,
"recursive reference to query %q must not appear within its non-recursive term",
cte.Name.Alias,
))
}
initialScope := b.buildStmt(initial, nil /* desiredTypes */, cteScope)
initialScope.removeHiddenCols()
b.dropOrderingAndExtraCols(initialScope)
// The properties of the binding tricky: the recursive expression is invoked
// repeatedly and these must hold each time. We can't use the initial
// expression's properties directly, as those only hold the first time the
// recursive query is executed. We can't really say too much about what the
// working table contains, except that it has at least one row (the
// recursive query is never invoked with an empty working table).
bindingProps := &props.Relational{}
bindingProps.OutputCols = initialScope.colSet()
bindingProps.Cardinality = props.AnyCardinality.AtLeast(props.OneCardinality)
// We don't really know the input row count, except for the first time we run
// the recursive query. We don't have anything better though.
bindingProps.Stats.RowCount = initialScope.expr.Relational().Stats.RowCount
cteSrc.bindingProps = bindingProps
cteSrc.cols = b.getCTECols(initialScope, cte.Name)
outScope := inScope.push()
initialTypes := initialScope.makeColumnTypes()
// Synthesize new output columns (because they contain values from both the
// initial and the recursive relations). These columns will also be used to
// refer to the working table (from the recursive query); we can't use the
// initial columns directly because they might contain duplicate IDs (e.g.
// consider initial query SELECT 0, 0).
for i, c := range cteSrc.cols {
newCol := b.synthesizeColumn(outScope, c.Alias, initialTypes[i], nil /* expr */, nil /* scalar */)
cteSrc.cols[i].ID = newCol.id
}
// We want to check if the recursive query is actually recursive. This is for
// annoying cases like `SELECT 1 UNION ALL SELECT 2`.
referenced := false
cteSrc.onRef = func() {
referenced = true
}
recursiveScope := b.buildSelect(recursive, initialTypes /* desiredTypes */, cteScope)
if !referenced {
// Build this as a non-recursive CTE.
cteScope := b.buildSetOp(tree.UnionOp, false /* all */, inScope, initialScope, recursiveScope)
return cteScope.expr, b.getCTECols(cteScope, cte.Name)
}
recursiveScope.removeHiddenCols()
b.dropOrderingAndExtraCols(recursiveScope)
// We allow propagation of types from the initial query to the recursive
// query.
_, propagateToRight := b.checkTypesMatch(initialScope, recursiveScope,
false, /* tolerateUnknownLeft */
true, /* tolerateUnknownRight */
"UNION",
)
if propagateToRight {
recursiveScope = b.propagateTypes(recursiveScope /* dst */, initialScope /* src */)
}
private := memo.RecursiveCTEPrivate{
Name: string(cte.Name.Alias),
WithID: withID,
InitialCols: colsToColList(initialScope.cols),
RecursiveCols: colsToColList(recursiveScope.cols),
OutCols: colsToColList(outScope.cols),
}
expr := b.factory.ConstructRecursiveCTE(initialScope.expr, recursiveScope.expr, &private)
return expr, cteSrc.cols
}
// getCTECols renames a presentation for the scope, renaming the columns to
// those provided in the AliasClause (if any). Throws an error if there is a
// mistmatch in the number of columns.
func (b *Builder) getCTECols(cteScope *scope, name tree.AliasClause) physical.Presentation {
presentation := cteScope.makePresentation()
if len(presentation) == 0 {
err := pgerror.Newf(
pgcode.FeatureNotSupported,
"WITH clause %q does not return any columns",
tree.ErrString(&name),
)
panic(errors.WithHint(err, "missing RETURNING clause?"))
}
if name.Cols == nil {
return presentation
}
if len(presentation) != len(name.Cols) {
panic(pgerror.Newf(
pgcode.InvalidColumnReference,
"source %q has %d columns available but %d columns specified",
name.Alias, len(presentation), len(name.Cols),
))
}
for i := range presentation {
presentation[i].Alias = string(name.Cols[i])
}
return presentation
}
// splitRecursiveCTE splits a CTE statement of the form
// initial_query UNION ALL recursive_query
// into the initial and recursive parts. If the statement is not of this form,
// returns ok=false.
func (b *Builder) splitRecursiveCTE(
stmt tree.Statement,
) (initial, recursive *tree.Select, ok bool) {
sel, ok := stmt.(*tree.Select)
if !ok || sel.With != nil || sel.OrderBy != nil || sel.Limit != nil {
return nil, nil, false
}
union, ok := sel.Select.(*tree.UnionClause)
if !ok || union.Type != tree.UnionOp || !union.All {
return nil, nil, false
}
return union.Left, union.Right, true
}