-
Notifications
You must be signed in to change notification settings - Fork 25
/
table.go
613 lines (512 loc) · 12.7 KB
/
table.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// Copyright 2019 Masahiro Sano
//
// 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
//
// https://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 server
import (
"fmt"
"strconv"
"github.com/cloudspannerecosystem/memefish/ast"
)
type Table struct {
ast *ast.CreateTable
Name string
columns []*Column
columnsMap map[string]*Column
primaryKey *TableIndex
index []*TableIndex
}
func newTable() *Table {
return &Table{
columnsMap: make(map[string]*Column),
}
}
func (t *Table) TableIndex(idx string) (*TableIndex, bool) {
if idx == "" {
return t.primaryKey, true
}
for _, index := range t.index {
if index.Name() == idx {
return index, true
}
}
return nil, false
}
func (t *Table) TableView() *TableView {
return createTableViewFromTable(t, "")
}
func (t *Table) TableViewWithAlias(alias string) *TableView {
return createTableViewFromTable(t, alias)
}
// NonNullableAndNonGeneratedColumnsExist checks non nullable columns exist in the spciefied columns.
// It returns true and the columns if non nullable and non generated columns exist.
func (t *Table) NonNullableAndNonGeneratedColumnsExist(columns []string) (bool, []string) {
usedColumns := make(map[string]struct{}, len(columns))
for _, name := range columns {
usedColumns[name] = struct{}{}
}
var noExistNonNullableColumns []string
for _, c := range t.columns {
if c.nullable {
continue
}
if c.ast != nil && c.ast.GeneratedExpr != nil {
continue
}
n := c.Name()
if _, ok := usedColumns[n]; !ok {
noExistNonNullableColumns = append(noExistNonNullableColumns, n)
}
}
if len(noExistNonNullableColumns) > 0 {
return true, noExistNonNullableColumns
}
return false, nil
}
func createTableFromAST(stmt *ast.CreateTable) (*Table, error) {
t := newTable()
t.Name = stmt.Name.Name
t.ast = stmt
for _, col := range stmt.Columns {
t.addColumn(col)
}
t.reorderColumnPosition()
if err := t.setPrimaryKeys(stmt.PrimaryKeys); err != nil {
return nil, err
}
return t, nil
}
func (t *Table) addColumn(col *ast.ColumnDef) {
column := newColumn(col)
t.columns = append(t.columns, column)
t.columnsMap[column.Name()] = column
}
func (t *Table) reorderColumnPosition() {
for i := range t.columns {
t.columns[i].setPosition(i + 1)
}
}
func (t *Table) setPrimaryKeys(pkey []*ast.IndexKey) error {
index, err := createPrimaryKey(t, pkey)
if err != nil {
return err
}
t.primaryKey = index
for i, col := range index.IndexColumns() {
col.markPrimaryKey(i + 1)
}
return nil
}
func (t *Table) createIndex(stmt *ast.CreateIndex) (*TableIndex, error) {
idx, err := createTableIndexFromAST(t, stmt)
if err != nil {
return nil, err
}
t.index = append(t.index, idx)
return idx, nil
}
func (t *Table) getColumn(name string) (*Column, error) {
c, ok := t.columnsMap[name]
if !ok {
return nil, newSpannerColumnNotFoundError(t.Name, name)
}
return c, nil
}
func (t *Table) getColumnsByName(names []string) ([]*Column, error) {
columns := make([]*Column, len(names))
for i, name := range names {
c, err := t.getColumn(name)
if err != nil {
return nil, err
}
columns[i] = c
}
return columns, nil
}
type Column struct {
ast *ast.ColumnDef
pos int
alias string
valueType ValueType
dbDataType dbDataType
nullable bool
isArray bool
isSized bool
isMax bool
size int64
allowCommitTimestamp bool
isPrimaryKey bool
primaryKeyPos int
}
func (c *Column) Name() string {
return c.ast.Name.Name
}
func (c *Column) Alias() string {
if c.alias != "" {
return c.alias
}
return c.ast.Name.Name
}
func (c *Column) setPosition(pos int) {
c.pos = pos
}
func (c *Column) markPrimaryKey(pos int) {
c.isPrimaryKey = true
c.primaryKeyPos = pos
}
type columnType struct {
dataType ast.ScalarTypeName
isArray bool
isSized bool
isMax bool
size int64
}
type dbDataType string
const (
DBDTInteger dbDataType = "INTEGER"
DBDTReal dbDataType = "REAL"
DBDTText dbDataType = "TEXT"
DBDTBlob dbDataType = "BLOB"
DBDTJson dbDataType = "JSON"
)
func (ct columnType) SqliteDataType() string {
switch ct.dataType {
case ast.BoolTypeName:
return "INTEGER"
case ast.Int64TypeName:
return "INTEGER"
case ast.Float64TypeName:
return "REAL"
case ast.StringTypeName:
return "TEXT"
case ast.BytesTypeName:
return "BLOB"
case ast.DateTypeName:
return "TEXT"
case ast.TimestampTypeName:
return "TEXT"
}
panic(fmt.Sprintf("unknown data type: %s", ct.dataType))
}
func newColumn(def *ast.ColumnDef) *Column {
ct := toColumnType(def.Type)
vt := toValueType(def.Type)
var dbdt dbDataType
switch vt.Code {
default:
panic(fmt.Sprintf("unknown value type %#v", vt))
case TCBool:
dbdt = DBDTInteger
case TCInt64:
dbdt = DBDTInteger
case TCFloat64:
dbdt = DBDTReal
case TCString:
dbdt = DBDTText
case TCBytes:
dbdt = DBDTBlob
case TCDate:
dbdt = DBDTText
case TCTimestamp:
dbdt = DBDTText
case TCArray:
dbdt = DBDTJson
case TCJson:
dbdt = DBDTJson
}
var allowCommitTimestamp bool
if def.Options != nil {
allowCommitTimestamp = def.Options.AllowCommitTimestamp
}
return &Column{
ast: def,
valueType: vt,
dbDataType: dbdt,
nullable: !def.NotNull,
isArray: ct.isArray,
isSized: ct.isSized,
isMax: ct.isMax,
size: ct.size,
allowCommitTimestamp: allowCommitTimestamp,
}
}
func astTypeToTypeCode(astTypeName ast.ScalarTypeName) TypeCode {
switch astTypeName {
case ast.BoolTypeName:
return TCBool
case ast.Int64TypeName:
return TCInt64
case ast.Float64TypeName:
return TCFloat64
case ast.StringTypeName:
return TCString
case ast.BytesTypeName:
return TCBytes
case ast.DateTypeName:
return TCDate
case ast.TimestampTypeName:
return TCTimestamp
case ast.ScalarTypeName("JSON"):
return TCJson
default:
panic("unknown type")
}
}
func toValueType(t ast.SchemaType) ValueType {
switch v := t.(type) {
case *ast.ScalarSchemaType:
return ValueType{Code: astTypeToTypeCode(v.Name)}
case *ast.SizedSchemaType:
return ValueType{Code: astTypeToTypeCode(v.Name)}
case *ast.ArraySchemaType:
arrType := toValueType(v.Item)
return ValueType{
Code: TCArray,
ArrayType: &arrType,
}
default:
panic(fmt.Sprintf("unknow type %v", t))
}
}
func schemaTypetoTypString(t ast.SchemaType) string {
switch v := t.(type) {
case *ast.ScalarSchemaType:
return astTypeToTypeCode(v.Name).String()
case *ast.SizedSchemaType:
typ := astTypeToTypeCode(v.Name).String()
size := "MAX"
if !v.Max {
intLit := v.Size.(*ast.IntLiteral)
size = intLit.Value // TODO: respect base?
}
return fmt.Sprintf("%s(%s)", typ, size)
case *ast.ArraySchemaType:
arrType := schemaTypetoTypString(v.Item)
return fmt.Sprintf("ARRAY<%s>", arrType)
default:
panic(fmt.Sprintf("unknow type %v", t))
}
}
func toColumnType(t ast.SchemaType) columnType {
switch v := t.(type) {
case *ast.ScalarSchemaType:
return columnType{
dataType: v.Name,
}
case *ast.SizedSchemaType:
if v.Max {
return columnType{
dataType: v.Name,
isSized: true,
isMax: true,
}
}
intLit, ok := v.Size.(*ast.IntLiteral)
if !ok {
panic(fmt.Sprintf("expected IntLiteral but %v", v.Size))
}
n, err := strconv.ParseInt(intLit.Value, intLit.Base, 64)
if err != nil {
panic(fmt.Sprintf("cannot parse IntLiteral: %v", intLit))
}
return columnType{
dataType: v.Name,
isSized: true,
isMax: false,
size: n,
}
case *ast.ArraySchemaType:
ct := toColumnType(v.Item)
ct.isArray = true
return ct
default:
panic(fmt.Sprintf("unknow type %v", t))
}
}
type TableIndex struct {
ast *ast.CreateIndex
astIndexKeys []*ast.IndexKey
name string
table *Table
unique bool
nullFiltered bool
columnsRef []*Column
columnNames []string
columnDirctions []string
storedColumns map[string]struct{}
}
func createTableIndexFromAST(table *Table, stmt *ast.CreateIndex) (*TableIndex, error) {
return createTableIndex(table, stmt.Keys, stmt)
}
func createPrimaryKey(table *Table, pkeys []*ast.IndexKey) (*TableIndex, error) {
return createTableIndex(table, pkeys, nil)
}
func createTableIndex(table *Table, keys []*ast.IndexKey, secondaryIdx *ast.CreateIndex) (*TableIndex, error) {
columns := make([]*Column, len(keys))
columnNames := make([]string, len(keys))
columnDirctions := make([]string, len(keys))
for i, key := range keys {
col, ok := table.columnsMap[key.Name.Name]
if !ok {
return nil, fmt.Errorf("primary key not found: %s", key.Name.Name)
}
columns[i] = col
columnNames[i] = col.Name()
dir := string(key.Dir)
if dir == "" { // work around
dir = "ASC"
}
columnDirctions[i] = dir
}
name := "PRIMARY_KEY"
unique := true
nullFiltered := false
storedColumns := make(map[string]struct{})
if secondaryIdx != nil {
name = secondaryIdx.Name.Name
unique = secondaryIdx.Unique
nullFiltered = secondaryIdx.NullFiltered
// columns for Index Keys
for _, c := range columns {
storedColumns[c.Name()] = struct{}{}
}
// secondary index also has primary key columns by default
for _, name := range table.primaryKey.IndexColumnNames() {
storedColumns[name] = struct{}{}
}
// storing columns
if secondaryIdx.Storing != nil {
for _, c := range secondaryIdx.Storing.Columns {
storedColumns[c.Name] = struct{}{}
}
}
} else {
// Primry Keys have all columns
for _, c := range table.columns {
storedColumns[c.Name()] = struct{}{}
}
}
return &TableIndex{
ast: secondaryIdx,
astIndexKeys: keys,
name: name,
table: table,
unique: unique,
nullFiltered: nullFiltered,
columnsRef: columns,
columnNames: columnNames,
storedColumns: storedColumns,
columnDirctions: columnDirctions,
}, nil
}
func (i *TableIndex) Name() string {
return i.name
}
func (i *TableIndex) IndexColumns() []*Column {
return i.columnsRef
}
func (i *TableIndex) IndexColumnNames() []string {
return i.columnNames
}
func (i *TableIndex) IndexColumnDirections() []string {
return i.columnDirctions
}
func (i *TableIndex) HasColumn(c string) bool {
_, ok := i.storedColumns[c]
return ok
}
type TableView struct {
ResultItems []ResultItem
ResultItemsMap map[string]ResultItem
ambiguous map[string]struct{}
}
func (v *TableView) AllItems() []ResultItem {
return v.ResultItems
}
func (v *TableView) Get(id string) (ResultItem, bool, bool) {
if _, ok := v.ambiguous[id]; ok {
return ResultItem{}, true, false
}
item, ok := v.ResultItemsMap[id]
if !ok {
return ResultItem{}, false, true
}
return item, false, false
}
func (v *TableView) ToStruct() *StructType {
names := make([]string, len(v.ResultItems))
vts := make([]*ValueType, len(v.ResultItems))
for i := range v.ResultItems {
names[i] = v.ResultItems[i].Name
vts[i] = &v.ResultItems[i].ValueType
}
return &StructType{
FieldNames: names,
FieldTypes: vts,
IsTable: true,
}
}
func createTableViewFromItems(items1 []ResultItem, items2 []ResultItem) *TableView {
newItems := make([]ResultItem, 0, len(items1)+len(items2))
newItemsMap := make(map[string]ResultItem, len(items1)+len(items2))
ambiguous := make(map[string]struct{})
for _, items := range [][]ResultItem{items1, items2} {
for _, item := range items {
newItems = append(newItems, item)
if item.Name != "" {
_, ok := newItemsMap[item.Name]
if ok {
ambiguous[item.Name] = struct{}{}
} else {
newItemsMap[item.Name] = item
}
}
}
}
return &TableView{
ResultItems: newItems,
ResultItemsMap: newItemsMap,
ambiguous: ambiguous,
}
}
func createTableViewFromTable(table *Table, alias string) *TableView {
items := make([]ResultItem, 0, len(table.columns))
itemsMap := make(map[string]ResultItem, len(table.columns))
for _, column := range table.columns {
item := createResultItemFromColumn(column)
// if alias specified, add the alias to Expr
if alias != "" {
item.Expr.Raw = fmt.Sprintf("%s.%s", QuoteString(alias), item.Expr.Raw)
}
items = append(items, item)
itemsMap[column.Name()] = item
}
return &TableView{
ResultItems: items,
ResultItemsMap: itemsMap,
}
}
type ResultItem struct {
Name string
ValueType ValueType
Expr Expr
}
func createResultItemFromColumn(column *Column) ResultItem {
return ResultItem{
Name: column.Name(),
ValueType: column.valueType,
Expr: Expr{
Raw: QuoteString(column.Name()),
ValueType: column.valueType,
},
}
}