forked from dolthub/go-mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
catalog.go
340 lines (286 loc) · 9.86 KB
/
catalog.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
// Copyright 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 (
"fmt"
"strings"
"sync"
"github.com/gabereiser/go-mysql-server/internal/similartext"
"github.com/gabereiser/go-mysql-server/sql"
"github.com/gabereiser/go-mysql-server/sql/expression/function"
"github.com/gabereiser/go-mysql-server/sql/information_schema"
"github.com/gabereiser/go-mysql-server/sql/mysql_db"
)
type Catalog struct {
MySQLDb *mysql_db.MySQLDb
InfoSchema sql.Database
Provider sql.DatabaseProvider
builtInFunctions function.Registry
mu sync.RWMutex
locks sessionLocks
}
var _ sql.Catalog = (*Catalog)(nil)
var _ sql.FunctionProvider = (*Catalog)(nil)
var _ sql.TableFunctionProvider = (*Catalog)(nil)
var _ sql.ExternalStoredProcedureProvider = (*Catalog)(nil)
type tableLocks map[string]struct{}
type dbLocks map[string]tableLocks
type sessionLocks map[uint32]dbLocks
// NewCatalog returns a new empty Catalog with the given provider
func NewCatalog(provider sql.DatabaseProvider) *Catalog {
return &Catalog{
MySQLDb: mysql_db.CreateEmptyMySQLDb(),
InfoSchema: information_schema.NewInformationSchemaDatabase(),
Provider: provider,
builtInFunctions: function.NewRegistry(),
locks: make(sessionLocks),
}
}
// TODO: kill this
func NewDatabaseProvider(dbs ...sql.Database) sql.DatabaseProvider {
return sql.NewDatabaseProvider(dbs...)
}
func (c *Catalog) AllDatabases(ctx *sql.Context) []sql.Database {
var dbs []sql.Database
dbs = append(dbs, c.InfoSchema)
if c.MySQLDb.Enabled {
dbs = append(dbs, mysql_db.NewPrivilegedDatabaseProvider(c.MySQLDb, c.Provider).AllDatabases(ctx)...)
} else {
dbs = append(dbs, c.Provider.AllDatabases(ctx)...)
}
return dbs
}
// CreateDatabase creates a new Database and adds it to the catalog.
func (c *Catalog) CreateDatabase(ctx *sql.Context, dbName string, collation sql.CollationID) error {
c.mu.Lock()
defer c.mu.Unlock()
if collatedDbProvider, ok := c.Provider.(sql.CollatedDatabaseProvider); ok {
// If the database provider supports creation with a collation, then we call that function directly
return collatedDbProvider.CreateCollatedDatabase(ctx, dbName, collation)
} else if mut, ok := c.Provider.(sql.MutableDatabaseProvider); ok {
err := mut.CreateDatabase(ctx, dbName)
if err != nil {
return err
}
// It's possible that the db provider doesn't support creation with a collation, in which case we create the
// database and then set the collation. If the database doesn't support collations at all, then we ignore the
// provided collation rather than erroring.
if db, err := c.Database(ctx, dbName); err == nil {
if collatedDb, ok := db.(sql.CollatedDatabase); ok {
return collatedDb.SetCollation(ctx, collation)
}
}
return nil
} else {
return sql.ErrImmutableDatabaseProvider.New()
}
}
// RemoveDatabase removes a database from the catalog.
func (c *Catalog) RemoveDatabase(ctx *sql.Context, dbName string) error {
c.mu.Lock()
defer c.mu.Unlock()
mut, ok := c.Provider.(sql.MutableDatabaseProvider)
if ok {
return mut.DropDatabase(ctx, dbName)
} else {
return sql.ErrImmutableDatabaseProvider.New()
}
}
func (c *Catalog) HasDB(ctx *sql.Context, db string) bool {
db = strings.ToLower(db)
if db == "information_schema" {
return true
} else if c.MySQLDb.Enabled {
return mysql_db.NewPrivilegedDatabaseProvider(c.MySQLDb, c.Provider).HasDatabase(ctx, db)
} else {
return c.Provider.HasDatabase(ctx, db)
}
}
// Database returns the database with the given name.
func (c *Catalog) Database(ctx *sql.Context, db string) (sql.Database, error) {
if strings.ToLower(db) == "information_schema" {
return c.InfoSchema, nil
} else if c.MySQLDb.Enabled {
return mysql_db.NewPrivilegedDatabaseProvider(c.MySQLDb, c.Provider).Database(ctx, db)
} else {
return c.Provider.Database(ctx, db)
}
}
// LockTable adds a lock for the given table and session client. It is assumed
// the database is the current database in use.
func (c *Catalog) LockTable(ctx *sql.Context, table string) {
id := ctx.ID()
db := ctx.GetCurrentDatabase()
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.locks[id]; !ok {
c.locks[id] = make(dbLocks)
}
if _, ok := c.locks[id][db]; !ok {
c.locks[id][db] = make(tableLocks)
}
c.locks[id][db][table] = struct{}{}
}
// UnlockTables unlocks all tables for which the given session client has a
// lock.
func (c *Catalog) UnlockTables(ctx *sql.Context, id uint32) error {
c.mu.Lock()
defer c.mu.Unlock()
var errors []string
for db, tables := range c.locks[id] {
for t := range tables {
database, err := c.Provider.Database(ctx, db)
if err != nil {
return err
}
table, _, err := database.GetTableInsensitive(ctx, t)
if err == nil {
if lockable, ok := table.(sql.Lockable); ok {
if e := lockable.Unlock(ctx, id); e != nil {
errors = append(errors, e.Error())
}
}
} else {
errors = append(errors, err.Error())
}
}
}
delete(c.locks, id)
if len(errors) > 0 {
return fmt.Errorf("error unlocking tables for %d: %s", id, strings.Join(errors, ", "))
}
return nil
}
// Table returns the table in the given database with the given name.
func (c *Catalog) Table(ctx *sql.Context, dbName, tableName string) (sql.Table, sql.Database, error) {
c.mu.RLock()
defer c.mu.RUnlock()
db, err := c.Database(ctx, dbName)
if err != nil {
return nil, nil, err
}
tbl, ok, err := db.GetTableInsensitive(ctx, tableName)
if err != nil {
return nil, nil, err
} else if !ok {
return nil, nil, suggestSimilarTables(db, ctx, tableName)
}
return tbl, db, nil
}
// TableAsOf returns the table in the given database with the given name, as it existed at the time given. The database
// named must support timed queries.
func (c *Catalog) TableAsOf(ctx *sql.Context, dbName, tableName string, asOf interface{}) (sql.Table, sql.Database, error) {
c.mu.RLock()
defer c.mu.RUnlock()
db, err := c.Database(ctx, dbName)
if err != nil {
return nil, nil, err
}
versionedDb, ok := db.(sql.VersionedDatabase)
if !ok {
return nil, nil, sql.ErrAsOfNotSupported.New(tableName)
}
tbl, ok, err := versionedDb.GetTableInsensitiveAsOf(ctx, tableName, asOf)
if err != nil {
return nil, nil, err
} else if !ok {
return nil, nil, suggestSimilarTablesAsOf(versionedDb, ctx, tableName, asOf)
}
return tbl, versionedDb, nil
}
// RegisterFunction registers the functions given, adding them to the built-in functions.
// Integrators with custom functions should typically use the FunctionProvider interface instead.
func (c *Catalog) RegisterFunction(ctx *sql.Context, fns ...sql.Function) {
for _, fn := range fns {
err := c.builtInFunctions.Register(fn)
if err != nil {
panic(err)
}
}
}
// Function returns the function with the name given, or sql.ErrFunctionNotFound if it doesn't exist
func (c *Catalog) Function(ctx *sql.Context, name string) (sql.Function, error) {
if fp, ok := c.Provider.(sql.FunctionProvider); ok {
f, err := fp.Function(ctx, name)
if err != nil && !sql.ErrFunctionNotFound.Is(err) {
return nil, err
} else if f != nil {
return f, nil
}
}
return c.builtInFunctions.Function(ctx, name)
}
// ExternalStoredProcedure implements sql.ExternalStoredProcedureProvider
func (c *Catalog) ExternalStoredProcedure(ctx *sql.Context, name string, numOfParams int) (*sql.ExternalStoredProcedureDetails, error) {
if espp, ok := c.Provider.(sql.ExternalStoredProcedureProvider); ok {
esp, err := espp.ExternalStoredProcedure(ctx, name, numOfParams)
if err != nil {
return nil, err
} else if esp != nil {
return esp, nil
}
}
return nil, nil
}
// ExternalStoredProcedures implements sql.ExternalStoredProcedureProvider
func (c *Catalog) ExternalStoredProcedures(ctx *sql.Context, name string) ([]sql.ExternalStoredProcedureDetails, error) {
if espp, ok := c.Provider.(sql.ExternalStoredProcedureProvider); ok {
esps, err := espp.ExternalStoredProcedures(ctx, name)
if err != nil {
return nil, err
} else if esps != nil {
return esps, nil
}
}
return nil, nil
}
// TableFunction implements the TableFunctionProvider interface
func (c *Catalog) TableFunction(ctx *sql.Context, name string) (sql.TableFunction, error) {
if fp, ok := c.Provider.(sql.TableFunctionProvider); ok {
tf, err := fp.TableFunction(ctx, name)
if err != nil {
return nil, err
} else if tf != nil {
return tf, nil
}
}
return nil, sql.ErrTableFunctionNotFound.New(name)
}
func (c *Catalog) Statistics(ctx *sql.Context) (sql.StatsReadWriter, error) {
t, _, err := c.Table(ctx, sql.InformationSchemaDatabaseName, information_schema.StatisticsTableName)
if err != nil {
return nil, err
}
stats, ok := t.(sql.StatsReadWriter)
if !ok {
return nil, fmt.Errorf("information_schema.statistics does not implement sql.StatsReadWriter")
}
return stats.AssignCatalog(c).(sql.StatsReadWriter), nil
}
func suggestSimilarTables(db sql.Database, ctx *sql.Context, tableName string) error {
tableNames, err := db.GetTableNames(ctx)
if err != nil {
return err
}
similar := similartext.Find(tableNames, tableName)
return sql.ErrTableNotFound.New(tableName + similar)
}
func suggestSimilarTablesAsOf(db sql.VersionedDatabase, ctx *sql.Context, tableName string, time interface{}) error {
tableNames, err := db.GetTableNamesAsOf(ctx, time)
if err != nil {
return err
}
similar := similartext.Find(tableNames, tableName)
return sql.ErrTableNotFound.New(tableName + similar)
}