-
Notifications
You must be signed in to change notification settings - Fork 2k
/
insert.go
261 lines (242 loc) · 8.51 KB
/
insert.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
/*
Copyright 2017 Google 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 planbuilder
import (
"errors"
"fmt"
"strconv"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vtgate/engine"
"vitess.io/vitess/go/vt/vtgate/vindexes"
)
// buildInsertPlan builds the route for an INSERT statement.
func buildInsertPlan(ins *sqlparser.Insert, vschema ContextVSchema) (*engine.Insert, error) {
pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(ins)))
aliased := &sqlparser.AliasedTableExpr{Expr: ins.Table}
if err := pb.processAliasedTable(aliased); err != nil {
return nil, err
}
rb, ok := pb.bldr.(*route)
if !ok {
// This can happen only for vindexes right now.
return nil, fmt.Errorf("inserting into a vindex not allowed: %s", sqlparser.String(ins.Table))
}
if rb.ERoute.TargetDestination != nil {
return nil, errors.New("unsupported: INSERT with a target destination")
}
var table *vindexes.Table
for _, tval := range pb.st.tables {
table = tval.vindexTable
}
if !table.Keyspace.Sharded {
if !pb.validateSubquerySamePlan(ins) {
return nil, errors.New("unsupported: sharded subquery in insert values")
}
return buildInsertUnshardedPlan(ins, table, vschema)
}
if ins.Action == sqlparser.ReplaceStr {
return nil, errors.New("unsupported: REPLACE INTO with sharded schema")
}
return buildInsertShardedPlan(ins, table)
}
func buildInsertUnshardedPlan(ins *sqlparser.Insert, table *vindexes.Table, vschema ContextVSchema) (*engine.Insert, error) {
eins := &engine.Insert{
Opcode: engine.InsertUnsharded,
Table: table,
Keyspace: table.Keyspace,
}
var rows sqlparser.Values
switch insertValues := ins.Rows.(type) {
case *sqlparser.Select, *sqlparser.Union:
if eins.Table.AutoIncrement != nil {
return nil, errors.New("unsupported: auto-inc and select in insert")
}
eins.Query = generateQuery(ins)
return eins, nil
case sqlparser.Values:
rows = insertValues
default:
panic(fmt.Sprintf("BUG: unexpected construct in insert: %T", insertValues))
}
if eins.Table.AutoIncrement == nil {
eins.Query = generateQuery(ins)
return eins, nil
}
// Table has auto-inc and has a VALUES clause.
if len(ins.Columns) == 0 {
return nil, errors.New("column list required for tables with auto-inc columns")
}
for _, row := range rows {
if len(ins.Columns) != len(row) {
return nil, errors.New("column list doesn't match values")
}
}
if err := modifyForAutoinc(ins, eins); err != nil {
return nil, err
}
eins.Query = generateQuery(ins)
return eins, nil
}
func buildInsertShardedPlan(ins *sqlparser.Insert, table *vindexes.Table) (*engine.Insert, error) {
eins := &engine.Insert{
Opcode: engine.InsertSharded,
Table: table,
Keyspace: table.Keyspace,
}
if ins.Ignore != "" {
eins.Opcode = engine.InsertShardedIgnore
}
if ins.OnDup != nil {
if isVindexChanging(sqlparser.UpdateExprs(ins.OnDup), eins.Table.ColumnVindexes) {
return nil, errors.New("unsupported: DML cannot change vindex column")
}
eins.Opcode = engine.InsertShardedIgnore
}
if len(ins.Columns) == 0 {
return nil, errors.New("no column list")
}
directives := sqlparser.ExtractCommentDirectives(ins.Comments)
if directives.IsSet(sqlparser.DirectiveMultiShardAutocommit) {
eins.MultiShardAutocommit = true
}
var rows sqlparser.Values
switch insertValues := ins.Rows.(type) {
case *sqlparser.Select, *sqlparser.Union:
return nil, errors.New("unsupported: insert into select")
case sqlparser.Values:
rows = insertValues
if hasSubquery(rows) {
return nil, errors.New("unsupported: subquery in insert values")
}
default:
panic(fmt.Sprintf("BUG: unexpected construct in insert: %T", insertValues))
}
for _, value := range rows {
if len(ins.Columns) != len(value) {
return nil, errors.New("column list doesn't match values")
}
}
if eins.Table.AutoIncrement != nil {
if err := modifyForAutoinc(ins, eins); err != nil {
return nil, err
}
}
// Fill out the 3-d Values structure. Please see documentation of Insert.Values for details.
routeValues := make([]sqltypes.PlanValue, len(eins.Table.ColumnVindexes))
for vIdx, colVindex := range eins.Table.ColumnVindexes {
routeValues[vIdx].Values = make([]sqltypes.PlanValue, len(colVindex.Columns))
for colIdx, col := range colVindex.Columns {
routeValues[vIdx].Values[colIdx].Values = make([]sqltypes.PlanValue, len(rows))
colNum := findOrAddColumn(ins, col)
// swap bind variables
baseName := ":_" + col.CompliantName()
for rowNum, row := range rows {
innerpv, err := sqlparser.NewPlanValue(row[colNum])
if err != nil {
return nil, fmt.Errorf("could not compute value for vindex or auto-inc column: %v", err)
}
routeValues[vIdx].Values[colIdx].Values[rowNum] = innerpv
row[colNum] = sqlparser.NewValArg([]byte(baseName + strconv.Itoa(rowNum)))
}
}
}
eins.VindexValues = routeValues
eins.Query = generateQuery(ins)
generateInsertShardedQuery(ins, eins, rows)
return eins, nil
}
func generateInsertShardedQuery(node *sqlparser.Insert, eins *engine.Insert, valueTuples sqlparser.Values) {
prefixBuf := sqlparser.NewTrackedBuffer(dmlFormatter)
midBuf := sqlparser.NewTrackedBuffer(dmlFormatter)
suffixBuf := sqlparser.NewTrackedBuffer(dmlFormatter)
eins.Mid = make([]string, len(valueTuples))
prefixBuf.Myprintf("insert %v%sinto %v%v values ",
node.Comments, node.Ignore,
node.Table, node.Columns)
eins.Prefix = prefixBuf.String()
for rowNum, val := range valueTuples {
midBuf.Myprintf("%v", val)
eins.Mid[rowNum] = midBuf.String()
midBuf.Truncate(0)
}
suffixBuf.Myprintf("%v", node.OnDup)
eins.Suffix = suffixBuf.String()
}
// modifyForAutoinc modfies the AST and the plan to generate
// necessary autoinc values. It must be called only if eins.Table.AutoIncrement
// is set.
func modifyForAutoinc(ins *sqlparser.Insert, eins *engine.Insert) error {
pos := findOrAddColumn(ins, eins.Table.AutoIncrement.Column)
autoIncValues, err := swapBindVariables(ins.Rows.(sqlparser.Values), pos, ":"+engine.SeqVarName)
if err != nil {
return err
}
eins.Generate = &engine.Generate{
Keyspace: eins.Table.AutoIncrement.Sequence.Keyspace,
Query: fmt.Sprintf("select next :n values from %s", sqlparser.String(eins.Table.AutoIncrement.Sequence.Name)),
Values: autoIncValues,
}
return nil
}
// swapBindVariables swaps in bind variable names at the the specified
// column position in the AST values and returns the converted values back.
// Bind variable names are generated using baseName.
func swapBindVariables(rows sqlparser.Values, colNum int, baseName string) (sqltypes.PlanValue, error) {
pv := sqltypes.PlanValue{}
for rowNum, row := range rows {
innerpv, err := sqlparser.NewPlanValue(row[colNum])
if err != nil {
return pv, fmt.Errorf("could not compute value for vindex or auto-inc column: %v", err)
}
pv.Values = append(pv.Values, innerpv)
row[colNum] = sqlparser.NewValArg([]byte(baseName + strconv.Itoa(rowNum)))
}
return pv, nil
}
// findOrAddColumn finds the position of a column in the insert. If it's
// absent it appends it to the with NULL values and returns that position.
func findOrAddColumn(ins *sqlparser.Insert, col sqlparser.ColIdent) int {
for i, column := range ins.Columns {
if col.Equal(column) {
return i
}
}
ins.Columns = append(ins.Columns, col)
rows := ins.Rows.(sqlparser.Values)
for i := range rows {
rows[i] = append(rows[i], &sqlparser.NullVal{})
}
return len(ins.Columns) - 1
}
// isVindexChanging returns true if any of the update
// expressions modify a vindex column.
func isVindexChanging(setClauses sqlparser.UpdateExprs, colVindexes []*vindexes.ColumnVindex) bool {
for _, assignment := range setClauses {
for _, vcol := range colVindexes {
for _, col := range vcol.Columns {
if col.Equal(assignment.Name.Name) {
valueExpr, isValuesFuncExpr := assignment.Expr.(*sqlparser.ValuesFuncExpr)
if !isValuesFuncExpr {
return true
}
// update on duplicate key is changing the vindex column, not supported.
if !valueExpr.Name.Name.Equal(assignment.Name.Name) {
return true
}
}
}
}
}
return false
}