This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathvalidation_rules.go
359 lines (306 loc) · 9.5 KB
/
validation_rules.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package analyzer
import (
"strings"
"github.com/src-d/go-mysql-server/sql"
"github.com/src-d/go-mysql-server/sql/expression"
"github.com/src-d/go-mysql-server/sql/expression/function"
"github.com/src-d/go-mysql-server/sql/plan"
"gopkg.in/src-d/go-errors.v1"
)
const (
validateResolvedRule = "validate_resolved"
validateOrderByRule = "validate_order_by"
validateGroupByRule = "validate_group_by"
validateSchemaSourceRule = "validate_schema_source"
validateProjectTuplesRule = "validate_project_tuples"
validateIndexCreationRule = "validate_index_creation"
validateCaseResultTypesRule = "validate_case_result_types"
validateIntervalUsageRule = "validate_interval_usage"
validateExplodeUsageRule = "validate_explode_usage"
validateSubqueryColumnsRule = "validate_subquery_columns"
)
var (
// ErrValidationResolved is returned when the plan can not be resolved.
ErrValidationResolved = errors.NewKind("plan is not resolved because of node '%T'")
// ErrValidationOrderBy is returned when the order by contains aggregation
// expressions.
ErrValidationOrderBy = errors.NewKind("OrderBy does not support aggregation expressions")
// ErrValidationGroupBy is returned when the aggregation expression does not
// appear in the grouping columns.
ErrValidationGroupBy = errors.NewKind("GroupBy aggregate expression '%v' doesn't appear in the grouping columns")
// ErrValidationSchemaSource is returned when there is any column source
// that does not match the table name.
ErrValidationSchemaSource = errors.NewKind("one or more schema sources are empty")
// ErrProjectTuple is returned when there is a tuple of more than 1 column
// inside a projection.
ErrProjectTuple = errors.NewKind("selected field %d should have 1 column, but has %d")
// ErrUnknownIndexColumns is returned when there are columns in the expr
// to index that are unknown in the table.
ErrUnknownIndexColumns = errors.NewKind("unknown columns to index for table %q: %s")
// ErrCaseResultType is returned when one or more of the types of the values in
// a case expression don't match.
ErrCaseResultType = errors.NewKind(
"expecting all case branches to return values of type %s, " +
"but found value %q of type %s on %s",
)
// ErrIntervalInvalidUse is returned when an interval expression is not
// correctly used.
ErrIntervalInvalidUse = errors.NewKind(
"invalid use of an interval, which can only be used with DATE_ADD, " +
"DATE_SUB and +/- operators to subtract from or add to a date",
)
// ErrExplodeInvalidUse is returned when an EXPLODE function is used
// outside a Project node.
ErrExplodeInvalidUse = errors.NewKind(
"using EXPLODE is not supported outside a Project node",
)
// ErrSubqueryColumns is returned when an expression subquery returns
// more than a single column.
ErrSubqueryColumns = errors.NewKind(
"subquery expressions can only return a single column",
)
)
// DefaultValidationRules to apply while analyzing nodes.
var DefaultValidationRules = []Rule{
{validateResolvedRule, validateIsResolved},
{validateOrderByRule, validateOrderBy},
{validateGroupByRule, validateGroupBy},
{validateSchemaSourceRule, validateSchemaSource},
{validateProjectTuplesRule, validateProjectTuples},
{validateIndexCreationRule, validateIndexCreation},
{validateCaseResultTypesRule, validateCaseResultTypes},
{validateIntervalUsageRule, validateIntervalUsage},
{validateExplodeUsageRule, validateExplodeUsage},
{validateSubqueryColumnsRule, validateSubqueryColumns},
}
func validateIsResolved(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_is_resolved")
defer span.Finish()
if !n.Resolved() {
return nil, ErrValidationResolved.New(n)
}
return n, nil
}
func validateOrderBy(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_order_by")
defer span.Finish()
switch n := n.(type) {
case *plan.Sort:
for _, field := range n.SortFields {
switch field.Column.(type) {
case sql.Aggregation:
return nil, ErrValidationOrderBy.New()
}
}
}
return n, nil
}
func validateGroupBy(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_group_by")
defer span.Finish()
switch n := n.(type) {
case *plan.GroupBy:
// Allow the parser use the GroupBy node to eval the aggregation functions
// for sql statementes that don't make use of the GROUP BY expression.
if len(n.Grouping) == 0 {
return n, nil
}
var validAggs []string
for _, expr := range n.Grouping {
validAggs = append(validAggs, expr.String())
}
// TODO: validate columns inside aggregations
// and allow any kind of expression that make use of the grouping
// columns.
for _, expr := range n.Aggregate {
if _, ok := expr.(sql.Aggregation); !ok {
if !isValidAgg(validAggs, expr) {
return nil, ErrValidationGroupBy.New(expr.String())
}
}
}
return n, nil
}
return n, nil
}
func isValidAgg(validAggs []string, expr sql.Expression) bool {
switch expr := expr.(type) {
case sql.Aggregation:
return true
case *expression.Alias:
return isValidAgg(validAggs, expr.Child)
default:
return stringContains(validAggs, expr.String())
}
}
func validateSchemaSource(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_schema_source")
defer span.Finish()
switch n := n.(type) {
case *plan.TableAlias:
// table aliases should not be validated
if child, ok := n.Child.(*plan.ResolvedTable); ok {
return n, validateSchema(child)
}
case *plan.ResolvedTable:
return n, validateSchema(n)
}
return n, nil
}
func validateIndexCreation(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_index_creation")
defer span.Finish()
ci, ok := n.(*plan.CreateIndex)
if !ok {
return n, nil
}
schema := ci.Table.Schema()
table := schema[0].Source
var unknownColumns []string
for _, expr := range ci.Exprs {
expression.Inspect(expr, func(e sql.Expression) bool {
gf, ok := e.(*expression.GetField)
if ok {
if gf.Table() != table || !schema.Contains(gf.Name(), gf.Table()) {
unknownColumns = append(unknownColumns, gf.Name())
}
}
return true
})
}
if len(unknownColumns) > 0 {
return nil, ErrUnknownIndexColumns.New(table, strings.Join(unknownColumns, ", "))
}
return n, nil
}
func validateSchema(t *plan.ResolvedTable) error {
for _, col := range t.Schema() {
if col.Source == "" {
return ErrValidationSchemaSource.New()
}
}
return nil
}
func findProjectTuples(n sql.Node) (sql.Node, error) {
if n == nil {
return n, nil
}
switch n := n.(type) {
case *plan.Project, *plan.GroupBy:
for i, e := range n.(sql.Expressioner).Expressions() {
if sql.IsTuple(e.Type()) {
return nil, ErrProjectTuple.New(i+1, sql.NumColumns(e.Type()))
}
}
default:
for _, ch := range n.Children() {
_, err := findProjectTuples(ch)
if err != nil {
return nil, err
}
}
}
return n, nil
}
func validateProjectTuples(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, _ := ctx.Span("validate_project_tuples")
defer span.Finish()
return findProjectTuples(n)
}
func validateCaseResultTypes(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
span, ctx := ctx.Span("validate_case_result_types")
defer span.Finish()
var err error
plan.InspectExpressions(n, func(e sql.Expression) bool {
switch e := e.(type) {
case *expression.Case:
typ := e.Type()
for _, b := range e.Branches {
if b.Value.Type() != typ && b.Value.Type() != sql.Null {
err = ErrCaseResultType.New(typ, b.Value, b.Value.Type(), e)
return false
}
}
if e.Else != nil {
if e.Else.Type() != typ && e.Else.Type() != sql.Null {
err = ErrCaseResultType.New(typ, e.Else, e.Else.Type(), e)
return false
}
}
return false
default:
return true
}
})
if err != nil {
return nil, err
}
return n, nil
}
func validateIntervalUsage(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
var invalid bool
plan.InspectExpressions(n, func(e sql.Expression) bool {
// If it's already invalid just skip everything else.
if invalid {
return false
}
switch e := e.(type) {
case *function.DateAdd, *function.DateSub:
return false
case *expression.Arithmetic:
if e.Op == "+" || e.Op == "-" {
return false
}
case *expression.Interval:
invalid = true
}
return true
})
if invalid {
return nil, ErrIntervalInvalidUse.New()
}
return n, nil
}
func validateExplodeUsage(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
var invalid bool
plan.InspectExpressions(n, func(e sql.Expression) bool {
// If it's already invalid just skip everything else.
if invalid {
return false
}
// All usage of Explode will be incorrect because the ones in projects
// would have already been converted to Generate, so we only have to
// look for those.
if _, ok := e.(*function.Explode); ok {
invalid = true
}
return true
})
if invalid {
return nil, ErrExplodeInvalidUse.New()
}
return n, nil
}
func validateSubqueryColumns(ctx *sql.Context, a *Analyzer, n sql.Node) (sql.Node, error) {
valid := true
plan.InspectExpressions(n, func(e sql.Expression) bool {
s, ok := e.(*expression.Subquery)
if ok && len(s.Query.Schema()) != 1 {
valid = false
return false
}
return true
})
if !valid {
return nil, ErrSubqueryColumns.New()
}
return n, nil
}
func stringContains(strs []string, target string) bool {
for _, s := range strs {
if s == target {
return true
}
}
return false
}