forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select_name_resolution.go
235 lines (209 loc) · 7.45 KB
/
select_name_resolution.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright 2016 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// This file implements the select code that deals with column references
// and resolving column names in expressions.
package sql
import (
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
)
// invalidSrcIdx is the srcIdx value returned by findColumn() when there is no match.
const invalidSrcIdx = -1
// invalidColIdx is the colIdx value returned by findColumn() when there is no match.
// We reuse the value from parser.InvalidColIdx because its meaning is the same.
const invalidColIdx = parser.InvalidColIdx
// nameResolutionVisitor is a parser.Visitor implementation used to
// resolve the column names in an expression.
type nameResolutionVisitor struct {
err error
sources multiSourceInfo
colOffsets []int
iVarHelper parser.IndexedVarHelper
searchPath parser.SearchPath
// foundDependentVars is set to true during the analysis if an
// expression was found which can change values between rows of the
// same data source, for example IndexedVars and calls to the
// random() function.
foundDependentVars bool
// foundStars is set to true if a star is expanded during name
// resolution, e.g. in SELECT (kv.*) FROM kv.
foundStars bool
}
var _ parser.Visitor = &nameResolutionVisitor{}
func makeUntypedTuple(texprs []parser.TypedExpr) *parser.Tuple {
exprs := make(parser.Exprs, len(texprs))
for i, e := range texprs {
exprs[i] = e
}
return &parser.Tuple{Exprs: exprs}
}
func (v *nameResolutionVisitor) VisitPre(expr parser.Expr) (recurse bool, newNode parser.Expr) {
if v.err != nil {
return false, expr
}
switch t := expr.(type) {
case parser.UnqualifiedStar:
v.foundDependentVars = true
case *parser.AllColumnsSelector:
v.foundStars = true
// AllColumnsSelector at the top level of a SELECT clause are
// replaced when the select's renders are prepared. If we
// encounter one here during expression analysis, it's being used
// as an argument to an inner expression/function. In that case,
// treat it as a tuple of the expanded columns.
//
// Hence:
// SELECT kv.* FROM kv -> SELECT k, v FROM kv
// SELECT (kv.*) FROM kv -> SELECT (k, v) FROM kv
// SELECT COUNT(DISTINCT kv.*) FROM kv -> SELECT COUNT(DISTINCT (k, v)) FROM kv
//
_, exprs, err := v.sources[0].expandStar(t, v.iVarHelper)
if err != nil {
v.err = err
return false, expr
}
if len(exprs) > 0 {
// If the star expanded to more than one column, then there are
// dependent vars.
v.foundDependentVars = true
}
// We return an untyped tuple because name resolution occurs
// before type checking, and type checking will resolve the
// tuple's type.
return false, makeUntypedTuple(exprs)
case *parser.IndexedVar:
// If the indexed var is a standalone ordinal reference, ensure it
// becomes a fully bound indexed var.
t, v.err = v.iVarHelper.BindIfUnbound(t)
if v.err != nil {
return false, expr
}
v.foundDependentVars = true
return false, t
case parser.UnresolvedName:
vn, err := t.NormalizeVarName()
if err != nil {
v.err = err
return false, expr
}
return v.VisitPre(vn)
case *parser.ColumnItem:
srcIdx, colIdx, err := v.sources.findColumn(t)
if err != nil {
v.err = err
return false, expr
}
ivar := v.iVarHelper.IndexedVar(v.colOffsets[srcIdx] + colIdx)
v.foundDependentVars = true
return true, ivar
case *parser.FuncExpr:
fd, err := t.Func.Resolve(v.searchPath)
if err != nil {
v.err = err
return false, expr
}
if fd.HasOverloadsNeedingRepeatedEvaluation {
// TODO(knz): this property should really be an attribute of the
// individual overloads. By looking at the name-level property
// indicator, we are marking a function as row-dependent as
// soon as one overload is, even if the particular overload
// that would be selected by type checking for this FuncExpr
// is constant. This could be more fine-grained.
v.foundDependentVars = true
}
// Check for invalid use of *, which, if it is an argument, is the only argument.
if len(t.Exprs) != 1 {
break
}
vn, ok := t.Exprs[0].(parser.VarName)
if !ok {
break
}
vn, v.err = vn.NormalizeVarName()
if v.err != nil {
return false, expr
}
// Save back to avoid re-doing the work later.
t.Exprs[0] = vn
if strings.EqualFold(fd.Name, "count") && t.Type == 0 {
if _, ok := vn.(parser.UnqualifiedStar); ok {
// Special case handling for COUNT(*). This is a special construct to
// count the number of rows; in this case * does NOT refer to a set of
// columns. A * is invalid elsewhere (and will be caught by TypeCheck()).
// Replace the function with COUNT_ROWS (which doesn't take any
// arguments).
e := &parser.FuncExpr{
Func: parser.ResolvableFunctionReference{
FunctionReference: parser.UnresolvedName{parser.Name("COUNT_ROWS")},
},
}
// We call TypeCheck to fill in FuncExpr internals. This is a fixed
// expression; we should not hit an error here.
if _, err := e.TypeCheck(&parser.SemaContext{}, parser.TypeAny); err != nil {
panic(err)
}
e.Filter = t.Filter
e.WindowDef = t.WindowDef
return true, e
}
}
// TODO(#15750): support additional forms:
//
// COUNT(t.*): looks like this behaves the same as COUNT(*) in PG (perhaps
// t.* becomes a tuple and the tuple itself is never NULL?)
//
// COUNT(DISTINCT t.*): this deduplicates between the tuples. Note that
// this can be part of a join:
// SELECT COUNT(DISTINCT t.*) FROM t, u
return true, t
case *parser.Subquery:
// Do not recurse into subqueries.
return false, expr
}
return true, expr
}
func (*nameResolutionVisitor) VisitPost(expr parser.Expr) parser.Expr { return expr }
func (s *renderNode) resolveNames(expr parser.Expr) (parser.Expr, bool, bool, error) {
return s.planner.resolveNames(expr, s.sourceInfo, s.ivarHelper)
}
// resolveNames walks the provided expression and resolves all names
// using the tableInfo and iVarHelper.
// If anything that looks like a column reference (indexed vars, star,
// etc) is encountered, or a function that may change value for every
// row in a table, the 2nd return value is true.
// If any star is expanded, the 3rd return value is true.
func (p *planner) resolveNames(
expr parser.Expr, sources multiSourceInfo, ivarHelper parser.IndexedVarHelper,
) (parser.Expr, bool, bool, error) {
if expr == nil {
return nil, false, false, nil
}
v := &p.nameResolutionVisitor
*v = nameResolutionVisitor{
err: nil,
sources: sources,
colOffsets: make([]int, len(sources)),
iVarHelper: ivarHelper,
searchPath: p.session.SearchPath,
foundDependentVars: false,
}
colOffset := 0
for i, s := range sources {
v.colOffsets[i] = colOffset
colOffset += len(s.sourceColumns)
}
expr, _ = parser.WalkExpr(v, expr)
return expr, v.foundDependentVars, v.foundStars, v.err
}