-
Notifications
You must be signed in to change notification settings - Fork 0
/
inserts.go
executable file
·236 lines (209 loc) · 6.36 KB
/
inserts.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
// Copyright 2020-2021 Dolthub, Inc.
//
// 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.
package analyzer
import (
"strings"
"github.com/Rock-liyi/p2pdb-store/sql"
"github.com/Rock-liyi/p2pdb-store/sql/expression"
"github.com/Rock-liyi/p2pdb-store/sql/plan"
)
func resolveInsertRows(ctx *sql.Context, a *Analyzer, n sql.Node, scope *Scope) (sql.Node, error) {
if _, ok := n.(*plan.TriggerExecutor); ok {
return n, nil
} else if _, ok := n.(*plan.CreateProcedure); ok {
return n, nil
}
// We capture all INSERTs along the tree, such as those inside of block statements.
return plan.TransformUp(n, func(n sql.Node) (sql.Node, error) {
insert, ok := n.(*plan.InsertInto)
if !ok {
return n, nil
}
insertable, err := plan.GetInsertable(insert.Destination)
if err != nil {
return nil, err
}
if insert.IsReplace {
var ok bool
_, ok = insertable.(sql.ReplaceableTable)
if !ok {
return nil, plan.ErrReplaceIntoNotSupported.New()
}
}
if len(insert.OnDupExprs) > 0 {
var ok bool
_, ok = insertable.(sql.UpdatableTable)
if !ok {
return nil, plan.ErrOnDuplicateKeyUpdateNotSupported.New()
}
}
source := insert.Source
// TriggerExecutor has already been analyzed
if _, ok := insert.Source.(*plan.TriggerExecutor); !ok {
// Analyze the source of the insert independently
source, err = a.Analyze(ctx, insert.Source, scope)
if err != nil {
return nil, err
}
source = StripQueryProcess(source)
}
dstSchema := insertable.Schema()
// normalize the column name
columnNames := make([]string, len(insert.ColumnNames))
for i, name := range insert.ColumnNames {
columnNames[i] = strings.ToLower(name)
}
// If no columns are given and value tuples are not all empty, use the full schema
if len(columnNames) == 0 && existsNonZeroValueCount(source) {
columnNames = make([]string, len(dstSchema))
for i, f := range dstSchema {
columnNames[i] = f.Name
}
} else {
err = validateColumns(columnNames, dstSchema)
if err != nil {
return nil, err
}
}
err = validateValueCount(columnNames, source)
if err != nil {
return nil, err
}
project, err := wrapRowSource(ctx, source, insertable, columnNames)
if err != nil {
return nil, err
}
return insert.WithSource(project), nil
})
}
// Ensures that the number of elements in each Value tuple is empty
func existsNonZeroValueCount(values sql.Node) bool {
switch node := values.(type) {
case *plan.Values:
for _, exprTuple := range node.ExpressionTuples {
if len(exprTuple) != 0 {
return true
}
}
default:
return true
}
return false
}
// wrapRowSource wraps the original row source in a projection so that its schema matches the full schema of the
// underlying table, in the same order.
func wrapRowSource(ctx *sql.Context, insertSource sql.Node, destTbl sql.Table, columnNames []string) (sql.Node, error) {
projExprs := make([]sql.Expression, len(destTbl.Schema()))
for i, f := range destTbl.Schema() {
found := false
for j, col := range columnNames {
if strings.EqualFold(f.Name, col) {
projExprs[i] = expression.NewGetField(j, f.Type, f.Name, f.Nullable)
found = true
break
}
}
if !found {
if !f.Nullable && f.Default == nil && !f.AutoIncrement {
return nil, sql.ErrInsertIntoNonNullableDefaultNullColumn.New(f.Name)
}
projExprs[i] = f.Default
}
if f.AutoIncrement {
ai, err := expression.NewAutoIncrement(ctx, destTbl, projExprs[i])
if err != nil {
return nil, err
}
projExprs[i] = ai
}
}
err := validateRowSource(insertSource, projExprs)
if err != nil {
return nil, err
}
return plan.NewProject(projExprs, insertSource), nil
}
func validateColumns(columnNames []string, dstSchema sql.Schema) error {
dstColNames := make(map[string]struct{})
for _, dstCol := range dstSchema {
dstColNames[strings.ToLower(dstCol.Name)] = struct{}{}
}
usedNames := make(map[string]struct{})
for _, columnName := range columnNames {
if _, exists := dstColNames[columnName]; !exists {
return plan.ErrInsertIntoNonexistentColumn.New(columnName)
}
if _, exists := usedNames[columnName]; !exists {
usedNames[columnName] = struct{}{}
} else {
return plan.ErrInsertIntoDuplicateColumn.New(columnName)
}
}
return nil
}
func validateValueCount(columnNames []string, values sql.Node) error {
if exchange, ok := values.(*plan.Exchange); ok {
values = exchange.Child
}
switch node := values.(type) {
case *plan.Values:
for _, exprTuple := range node.ExpressionTuples {
if len(exprTuple) != len(columnNames) {
return plan.ErrInsertIntoMismatchValueCount.New()
}
}
default:
// Parser assures us that this will be some form of SelectStatement, so no need to type check it
if len(columnNames) != len(values.Schema()) {
return plan.ErrInsertIntoMismatchValueCount.New()
}
}
return nil
}
func assertCompatibleSchemas(projExprs []sql.Expression, schema sql.Schema) error {
for _, expr := range projExprs {
switch e := expr.(type) {
case *expression.Literal,
*expression.AutoIncrement,
*sql.ColumnDefaultValue:
continue
case *expression.GetField:
otherCol := schema[e.Index()]
// special case: null field type, will get checked at execution time
if otherCol.Type == sql.Null {
continue
}
_, err := expr.Type().Convert(otherCol.Type.Zero())
if err != nil {
return plan.ErrInsertIntoIncompatibleTypes.New(otherCol.Type.String(), expr.Type().String())
}
default:
return plan.ErrInsertIntoUnsupportedValues.New(expr)
}
}
return nil
}
func validateRowSource(values sql.Node, projExprs []sql.Expression) error {
if exchange, ok := values.(*plan.Exchange); ok {
values = exchange.Child
}
switch n := values.(type) {
case *plan.Values:
// already verified
return nil
default:
// Parser assures us that this will be some form of SelectStatement, so no need to type check it
return assertCompatibleSchemas(projExprs, n.Schema())
}
}