forked from dolthub/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.go
396 lines (347 loc) · 10.8 KB
/
engine.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// 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 sqle
import (
"fmt"
"github.com/sirupsen/logrus"
"github.com/dolthub/go-mysql-server/auth"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/analyzer"
"github.com/dolthub/go-mysql-server/sql/expression/function"
"github.com/dolthub/go-mysql-server/sql/parse"
"github.com/dolthub/go-mysql-server/sql/plan"
)
// Config for the Engine.
type Config struct {
// VersionPostfix to display with the `VERSION()` UDF.
VersionPostfix string
// Auth used for authentication and authorization.
Auth auth.Auth
}
// Engine is a SQL engine.
type Engine struct {
Catalog *sql.Catalog
Analyzer *analyzer.Analyzer
Auth auth.Auth
LS *sql.LockSubsystem
}
type ColumnWithRawDefault struct {
SqlColumn *sql.Column
Default string
}
// New creates a new Engine with custom configuration. To create an Engine with
// the default settings use `NewDefault`.
func New(c *sql.Catalog, a *analyzer.Analyzer, cfg *Config) *Engine {
var versionPostfix string
if cfg != nil {
versionPostfix = cfg.VersionPostfix
}
ls := sql.NewLockSubsystem()
c.MustRegister(
sql.FunctionN{
Name: "version",
Fn: function.NewVersion(versionPostfix),
},
sql.Function0{
Name: "database",
Fn: function.NewDatabase(c),
},
sql.Function0{
Name: "schema",
Fn: function.NewDatabase(c),
})
c.MustRegister(function.Defaults...)
c.MustRegister(function.GetLockingFuncs(ls)...)
// use auth.None if auth is not specified
var au auth.Auth
if cfg == nil || cfg.Auth == nil {
au = new(auth.None)
} else {
au = cfg.Auth
}
return &Engine{c, a, au, ls}
}
// NewDefault creates a new default Engine.
func NewDefault() *Engine {
c := sql.NewCatalog()
a := analyzer.NewDefault(c)
return New(c, a, nil)
}
// AnalyzeQuery analyzes a query and returns its Schema.
func (e *Engine) AnalyzeQuery(
ctx *sql.Context,
query string,
) (sql.Schema, error) {
parsed, err := parse.Parse(ctx, query)
if err != nil {
return nil, err
}
analyzed, err := e.Analyzer.Analyze(ctx, parsed, nil)
if err != nil {
return nil, err
}
return analyzed.Schema(), nil
}
// Query executes a query. If parsed is non-nil, it will be used instead of parsing the query from text.
func (e *Engine) Query(ctx *sql.Context, query string) (sql.Schema, sql.RowIter, error) {
return e.QueryWithBindings(ctx, query, nil)
}
// QueryWithBindings executes the query given with the bindings provided
func (e *Engine) QueryWithBindings(
ctx *sql.Context,
query string,
bindings map[string]sql.Expression,
) (sql.Schema, sql.RowIter, error) {
return e.QueryNodeWithBindings(ctx, query, nil, bindings)
}
// QueryNodeWithBindings executes the query given with the bindings provided. If parsed is non-nil, it will be used
// instead of parsing the query from text.
func (e *Engine) QueryNodeWithBindings(
ctx *sql.Context,
query string,
parsed sql.Node,
bindings map[string]sql.Expression,
) (sql.Schema, sql.RowIter, error) {
var (
analyzed sql.Node
iter sql.RowIter
err error
)
if parsed == nil {
parsed, err = parse.Parse(ctx, query)
if err != nil {
return nil, nil, err
}
}
err = e.authCheck(ctx, parsed)
if err != nil {
return nil, nil, err
}
if len(bindings) > 0 {
parsed, err = plan.ApplyBindings(ctx, parsed, bindings)
if err != nil {
return nil, nil, err
}
}
analyzed, err = e.Analyzer.Analyze(ctx, parsed, nil)
if err != nil {
return nil, nil, err
}
transactionDatabase, err := e.beginTransaction(ctx, parsed)
if err != nil {
return nil, nil, err
}
iter, err = analyzed.RowIter(ctx, nil)
if err != nil {
return nil, nil, err
}
autoCommit, err := isSessionAutocommit(ctx)
if err != nil {
return nil, nil, err
}
if autoCommit {
iter = transactionCommittingIter{iter, transactionDatabase}
}
return analyzed.Schema(), iter, nil
}
func (e *Engine) beginTransaction(ctx *sql.Context, parsed sql.Node) (string, error) {
// Before we begin a transaction, we need to know if the database being operated on is not the one
// currently selected
transactionDatabase := determineTransactionDatabase(ctx, parsed)
// TODO: this won't work with transactions that cross database boundaries, we need to detect that and error out
beginNewTransaction := ctx.GetTransaction() == nil
if beginNewTransaction {
if len(transactionDatabase) > 0 {
database, err := e.Catalog.Database(transactionDatabase)
if err != nil {
return "", err
}
tdb, ok := database.(sql.TransactionDatabase)
if ok {
tx, err := tdb.StartTransaction(ctx)
if err != nil {
return "", err
}
ctx.SetTransaction(tx)
}
}
}
return transactionDatabase, nil
}
// transactionCommittingIter is a simple RowIter wrapper to allow the engine to conditionally commit a transaction
// during the Close() operation
type transactionCommittingIter struct {
childIter sql.RowIter
transactionDatabase string
}
func (t transactionCommittingIter) Next() (sql.Row, error) {
return t.childIter.Next()
}
func (t transactionCommittingIter) Close(ctx *sql.Context) error {
err := t.childIter.Close(ctx)
if err != nil {
return err
}
tx := ctx.GetTransaction()
commitTransaction := (tx != nil) && !ctx.GetIgnoreAutoCommit()
if commitTransaction {
logrus.Tracef("committing transaction %s", tx)
if err := ctx.Session.CommitTransaction(ctx, t.transactionDatabase, tx); err != nil {
return err
}
// Clearing out the current transaction will tell us to start a new one the next time this session queries
ctx.SetTransaction(nil)
}
return nil
}
func isSessionAutocommit(ctx *sql.Context) (bool, error) {
autoCommitSessionVar, err := ctx.GetSessionVariable(ctx, sql.AutoCommitSessionVar)
if err != nil {
return false, err
}
return sql.ConvertToBool(autoCommitSessionVar)
}
func determineTransactionDatabase(ctx *sql.Context, parsed sql.Node) string {
// For USE DATABASE statements, we need to process them here, before executing the query, so that we can set the
// database for transactions appropriately
switch n := parsed.(type) {
case *plan.Use:
ctx.SetCurrentDatabase(n.Database().Name())
}
transactionDatabase := ctx.GetCurrentDatabase()
switch n := parsed.(type) {
case *plan.CreateTable:
if n.Database() != nil && n.Database().Name() != "" {
transactionDatabase = n.Database().Name()
}
case *plan.InsertInto:
if n.Database() != nil && n.Database().Name() != "" {
transactionDatabase = n.Database().Name()
}
case *plan.DeleteFrom:
if n.Database() != "" {
transactionDatabase = n.Database()
}
case *plan.Update:
if n.Database() != "" {
transactionDatabase = n.Database()
}
}
return transactionDatabase
}
func (e *Engine) authCheck(ctx *sql.Context, node sql.Node) error {
var perm = auth.ReadPerm
if plan.IsDDLNode(node) {
perm = auth.ReadPerm | auth.WritePerm
}
switch node.(type) {
case
*plan.DeleteFrom, *plan.InsertInto, *plan.Update, *plan.LockTables, *plan.UnlockTables:
perm = auth.ReadPerm | auth.WritePerm
}
return e.Auth.Allowed(ctx, perm)
}
// ResolveDefaults takes in a schema, along with each column's default value in a string form, and returns the schema
// with the default values parsed and resolved.
func ResolveDefaults(tableName string, schema []*ColumnWithRawDefault) (sql.Schema, error) {
ctx := sql.NewEmptyContext()
e := NewDefault()
db := plan.NewDummyResolvedDB("temporary")
unresolvedSchema := make(sql.Schema, len(schema))
defaultCount := 0
for i, col := range schema {
unresolvedSchema[i] = col.SqlColumn
if col.Default != "" {
var err error
unresolvedSchema[i].Default, err = parse.StringToColumnDefaultValue(ctx, col.Default)
if err != nil {
return nil, err
}
defaultCount++
}
}
// if all defaults are nil, we can skip the rest of this
if defaultCount == 0 {
return unresolvedSchema, nil
}
// *plan.CreateTable properly handles resolving default values, so we hijack it
createTable := plan.NewCreateTable(db, tableName, false, false, &plan.TableSpec{Schema: unresolvedSchema})
analyzed, err := e.Analyzer.Analyze(ctx, createTable, nil)
if err != nil {
return nil, err
}
analyzedQueryProcess, ok := analyzed.(*plan.QueryProcess)
if !ok {
return nil, fmt.Errorf("internal error: unknown analyzed result type `%T`", analyzed)
}
analyzedCreateTable, ok := analyzedQueryProcess.Child.(*plan.CreateTable)
if !ok {
return nil, fmt.Errorf("internal error: unknown query process child type `%T`", analyzedQueryProcess)
}
return analyzedCreateTable.Schema(), nil
}
// ApplyDefaults applies the default values of the given column indices to the given row, and returns a new row with the updated values.
// This assumes that the given row has placeholder `nil` values for the default entries, and also that each column in a table is
// present and in the order as represented by the schema. If no columns are given, then the given row is returned. Column indices should
// be sorted and in ascending order, however this is not enforced.
func ApplyDefaults(ctx *sql.Context, tblSch sql.Schema, cols []int, row sql.Row) (sql.Row, error) {
if len(cols) == 0 {
return row, nil
}
newRow := row.Copy()
if len(tblSch) != len(row) {
return nil, fmt.Errorf("any row given to ApplyDefaults must be of the same length as the table it represents")
}
var secondPass []int
for _, col := range cols {
if col < 0 || col > len(tblSch) {
return nil, fmt.Errorf("column index `%d` is out of bounds, table schema has `%d` number of columns", col, len(tblSch))
}
if !tblSch[col].Default.IsLiteral() {
secondPass = append(secondPass, col)
continue
} else if tblSch[col].Default == nil && !tblSch[col].Nullable {
val := tblSch[col].Type.Zero()
var err error
newRow[col], err = tblSch[col].Type.Convert(val)
if err != nil {
return nil, err
}
} else {
val, err := tblSch[col].Default.Eval(ctx, newRow)
if err != nil {
return nil, err
}
newRow[col], err = tblSch[col].Type.Convert(val)
if err != nil {
return nil, err
}
}
}
for _, col := range secondPass {
val, err := tblSch[col].Default.Eval(ctx, newRow)
if err != nil {
return nil, err
}
newRow[col], err = tblSch[col].Type.Convert(val)
if err != nil {
return nil, err
}
}
return newRow, nil
}
// AddDatabase adds the given database to the catalog.
func (e *Engine) AddDatabase(db sql.Database) {
e.Catalog.AddDatabase(db)
}