-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathdb.go
1329 lines (1178 loc) · 35.5 KB
/
db.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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 Google LLC
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 spannertest
// This file contains the implementation of the Spanner fake itself,
// namely the part behind the RPC interface.
// TODO: missing transactionality in a serious way!
import (
"bytes"
"encoding/base64"
"fmt"
"sort"
"strconv"
"strings"
"sync"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
structpb "github.com/golang/protobuf/ptypes/struct"
"cloud.google.com/go/civil"
"cloud.google.com/go/spanner/spansql"
)
type database struct {
mu sync.Mutex
lastTS time.Time // last commit timestamp
tables map[spansql.ID]*table
indexes map[spansql.ID]struct{} // only record their existence
views map[spansql.ID]struct{} // only record their existence
rwMu sync.Mutex // held by read-write transactions
}
type table struct {
mu sync.Mutex
// Information about the table columns.
// They are reordered on table creation so the primary key columns come first.
cols []colInfo
colIndex map[spansql.ID]int // col name to index
origIndex map[spansql.ID]int // original index of each column upon construction
pkCols int // number of primary key columns (may be 0)
pkDesc []bool // whether each primary key column is in descending order
constraints []constraintInfo // constraints information of this table
rdw *spansql.RowDeletionPolicy // RowDeletionPolicy of this table (may be nil)
// Rows are stored in primary key order.
rows []row
}
// colInfo represents information about a column in a table or result set.
type colInfo struct {
Name spansql.ID
Type spansql.Type
Generated spansql.Expr
NotNull bool // only set for table columns
AggIndex int // Index+1 of SELECT list for which this is an aggregate value.
Alias spansql.PathExp // an alternate name for this column (result sets only)
}
// constraintInfo represents information about a constraint in a table
type constraintInfo struct {
Name spansql.ID
Constraint spansql.Constraint
}
// commitTimestampSentinel is a sentinel value for TIMESTAMP fields with allow_commit_timestamp=true.
// It is accepted, but never stored.
var commitTimestampSentinel = &struct{}{}
// transaction records information about a running transaction.
// This is not safe for concurrent use.
type transaction struct {
id string
// readOnly is whether this transaction was constructed
// for read-only use, and should yield errors if used
// to perform a mutation.
readOnly bool
d *database
commitTimestamp time.Time // not set if readOnly
unlock func() // may be nil
}
func (d *database) NewReadOnlyTransaction() *transaction {
return &transaction{
id: genRandomTransaction(),
readOnly: true,
}
}
func (d *database) NewTransaction() *transaction {
return &transaction{
id: genRandomTransaction(),
d: d,
}
}
// Start starts the transaction and commits to a specific commit timestamp.
// This also locks out any other read-write transaction on this database
// until Commit/Rollback are called.
func (tx *transaction) Start() {
// Commit timestamps are only guaranteed to be unique
// when transactions write to overlapping sets of fields.
// This simulated database exceeds that guarantee.
// Grab rwMu for the duration of this transaction.
// Take it before d.mu so we don't hold that lock
// while waiting for d.rwMu, which is held for longer.
tx.d.rwMu.Lock()
tx.d.mu.Lock()
const tsRes = 1 * time.Microsecond
now := time.Now().UTC().Truncate(tsRes)
if !now.After(tx.d.lastTS) {
now = tx.d.lastTS.Add(tsRes)
}
tx.d.lastTS = now
tx.d.mu.Unlock()
tx.commitTimestamp = now
tx.unlock = tx.d.rwMu.Unlock
}
func (tx *transaction) checkMutable() error {
if tx.readOnly {
// TODO: is this the right status?
return status.Errorf(codes.InvalidArgument, "transaction is read-only")
}
return nil
}
func (tx *transaction) Commit() (time.Time, error) {
if tx.unlock != nil {
tx.unlock()
}
return tx.commitTimestamp, nil
}
func (tx *transaction) Rollback() {
if tx.unlock != nil {
tx.unlock()
}
// TODO: actually rollback
}
/*
row represents a list of data elements.
The mapping between Spanner types and Go types internal to this package are:
BOOL bool
INT64 int64
FLOAT64 float64
STRING string
BYTES []byte
DATE civil.Date
TIMESTAMP time.Time (location set to UTC)
ARRAY<T> []interface{}
STRUCT TODO
*/
type row []interface{}
func (r row) copyDataElem(index int) interface{} {
v := r[index]
if is, ok := v.([]interface{}); ok {
// Deep-copy array values.
v = append([]interface{}(nil), is...)
}
return v
}
// copyData returns a copy of the row.
func (r row) copyAllData() row {
dst := make(row, 0, len(r))
for i := range r {
dst = append(dst, r.copyDataElem(i))
}
return dst
}
// copyData returns a copy of a subset of a row.
func (r row) copyData(indexes []int) row {
if len(indexes) == 0 {
return nil
}
dst := make(row, 0, len(indexes))
for _, i := range indexes {
dst = append(dst, r.copyDataElem(i))
}
return dst
}
func (d *database) LastCommitTimestamp() time.Time {
d.mu.Lock()
defer d.mu.Unlock()
return d.lastTS
}
func (d *database) GetDDL() []spansql.DDLStmt {
// This lacks fidelity, but captures the details we support.
d.mu.Lock()
defer d.mu.Unlock()
var stmts []spansql.DDLStmt
for name, t := range d.tables {
ct := &spansql.CreateTable{
Name: name,
}
t.mu.Lock()
for i, col := range t.cols {
ct.Columns = append(ct.Columns, spansql.ColumnDef{
Name: col.Name,
Type: col.Type,
NotNull: col.NotNull,
// TODO: AllowCommitTimestamp
})
if i < t.pkCols {
ct.PrimaryKey = append(ct.PrimaryKey, spansql.KeyPart{
Column: col.Name,
Desc: t.pkDesc[i],
})
}
}
t.mu.Unlock()
stmts = append(stmts, ct)
}
return stmts
}
func (d *database) ApplyDDL(stmt spansql.DDLStmt) *status.Status {
d.mu.Lock()
defer d.mu.Unlock()
// Lazy init.
if d.tables == nil {
d.tables = make(map[spansql.ID]*table)
}
if d.indexes == nil {
d.indexes = make(map[spansql.ID]struct{})
}
if d.views == nil {
d.views = make(map[spansql.ID]struct{})
}
switch stmt := stmt.(type) {
default:
return status.Newf(codes.Unimplemented, "unhandled DDL statement type %T", stmt)
case *spansql.CreateTable:
if _, ok := d.tables[stmt.Name]; ok {
return status.Newf(codes.AlreadyExists, "table %s already exists", stmt.Name)
}
if len(stmt.PrimaryKey) == 0 {
return status.Newf(codes.InvalidArgument, "table %s has no primary key", stmt.Name)
}
// TODO: check stmt.Interleave details.
// Record original column ordering.
orig := make(map[spansql.ID]int)
for i, col := range stmt.Columns {
orig[col.Name] = i
}
// Move primary keys first, preserving their order.
pk := make(map[spansql.ID]int)
var pkDesc []bool
for i, kp := range stmt.PrimaryKey {
pk[kp.Column] = -1000 + i
pkDesc = append(pkDesc, kp.Desc)
}
sort.SliceStable(stmt.Columns, func(i, j int) bool {
a, b := pk[stmt.Columns[i].Name], pk[stmt.Columns[j].Name]
return a < b
})
t := &table{
colIndex: make(map[spansql.ID]int),
origIndex: orig,
pkCols: len(pk),
pkDesc: pkDesc,
}
for _, cd := range stmt.Columns {
if st := t.addColumn(cd, true); st.Code() != codes.OK {
return st
}
}
for col := range pk {
if _, ok := t.colIndex[col]; !ok {
return status.Newf(codes.InvalidArgument, "primary key column %q not in table", col)
}
}
for _, constraint := range stmt.Constraints {
if st := t.addConstraint(constraint); st.Code() != codes.OK {
return st
}
}
t.rdw = stmt.RowDeletionPolicy
d.tables[stmt.Name] = t
return nil
case *spansql.CreateIndex:
if _, ok := d.indexes[stmt.Name]; ok {
return status.Newf(codes.AlreadyExists, "index %s already exists", stmt.Name)
}
d.indexes[stmt.Name] = struct{}{}
return nil
case *spansql.CreateView:
if !stmt.OrReplace {
if _, ok := d.views[stmt.Name]; ok {
return status.Newf(codes.AlreadyExists, "view %s already exists", stmt.Name)
}
}
d.views[stmt.Name] = struct{}{}
return nil
case *spansql.DropTable:
if _, ok := d.tables[stmt.Name]; !ok {
return status.Newf(codes.NotFound, "no table named %s", stmt.Name)
}
// TODO: check for indexes on this table.
delete(d.tables, stmt.Name)
return nil
case *spansql.DropIndex:
if _, ok := d.indexes[stmt.Name]; !ok {
return status.Newf(codes.NotFound, "no index named %s", stmt.Name)
}
delete(d.indexes, stmt.Name)
return nil
case *spansql.DropView:
if _, ok := d.views[stmt.Name]; !ok {
return status.Newf(codes.NotFound, "no view named %s", stmt.Name)
}
delete(d.views, stmt.Name)
return nil
case *spansql.AlterTable:
t, ok := d.tables[stmt.Name]
if !ok {
return status.Newf(codes.NotFound, "no table named %s", stmt.Name)
}
switch alt := stmt.Alteration.(type) {
default:
return status.Newf(codes.Unimplemented, "unhandled DDL table alteration type %T", alt)
case spansql.AddColumn:
if st := t.addColumn(alt.Def, false); st.Code() != codes.OK {
return st
}
return nil
case spansql.DropColumn:
if st := t.dropColumn(alt.Name); st.Code() != codes.OK {
return st
}
return nil
case spansql.AlterColumn:
if st := t.alterColumn(alt); st.Code() != codes.OK {
return st
}
return nil
case spansql.AddRowDeletionPolicy:
if st := t.addRowDeletionPolicy(alt); st.Code() != codes.OK {
return st
}
return nil
case spansql.ReplaceRowDeletionPolicy:
if st := t.replaceRowDeletionPolicy(alt); st.Code() != codes.OK {
return st
}
return nil
case spansql.DropRowDeletionPolicy:
if st := t.dropRowDeletionPolicy(alt); st.Code() != codes.OK {
return st
}
return nil
case spansql.AddConstraint:
// We do not validate if the referenced table and column exists.
if st := t.addConstraint(alt.Constraint); st.Code() != codes.OK {
return st
}
return nil
case spansql.DropConstraint:
if st := t.dropConstraint(alt); st.Code() != codes.OK {
return st
}
return nil
}
}
}
func (d *database) table(tbl spansql.ID) (*table, error) {
d.mu.Lock()
defer d.mu.Unlock()
t, ok := d.tables[tbl]
if !ok {
return nil, status.Errorf(codes.NotFound, "no table named %s", tbl)
}
return t, nil
}
// writeValues executes a write option (Insert, Update, etc.).
func (d *database) writeValues(tx *transaction, tbl spansql.ID, cols []spansql.ID, values []*structpb.ListValue, f func(t *table, colIndexes []int, r row) error) error {
if err := tx.checkMutable(); err != nil {
return err
}
t, err := d.table(tbl)
if err != nil {
return err
}
t.mu.Lock()
defer t.mu.Unlock()
colIndexes, err := t.colIndexes(cols)
if err != nil {
return err
}
revIndex := make(map[int]int) // table index to col index
for j, i := range colIndexes {
revIndex[i] = j
}
for pki := 0; pki < t.pkCols; pki++ {
_, ok := revIndex[pki]
if !ok {
return status.Errorf(codes.InvalidArgument, "primary key column %s not included in write", t.cols[pki].Name)
}
}
for _, vs := range values {
if len(vs.Values) != len(colIndexes) {
return status.Errorf(codes.InvalidArgument, "row of %d values can't be written to %d columns", len(vs.Values), len(colIndexes))
}
r := make(row, len(t.cols))
for j, v := range vs.Values {
i := colIndexes[j]
if t.cols[i].Generated != nil {
return status.Error(codes.InvalidArgument, "values can't be written to a generated column")
}
x, err := valForType(v, t.cols[i].Type)
if err != nil {
return err
}
if x == commitTimestampSentinel {
x = tx.commitTimestamp
}
if x == nil && t.cols[i].NotNull {
return status.Errorf(codes.FailedPrecondition, "%s must not be NULL in table %s", t.cols[i].Name, tbl)
}
r[i] = x
}
// TODO: enforce that provided timestamp for commit_timestamp=true columns
// are not ahead of the transaction's commit timestamp.
if err := f(t, colIndexes, r); err != nil {
return err
}
// Get row again after potential update merge to ensure we compute
// generated columns with fresh data.
pk := r[:t.pkCols]
rowNum, found := t.rowForPK(pk)
// This should never fail as the row was just inserted.
if !found {
return status.Error(codes.Internal, "row failed to be inserted")
}
row := t.rows[rowNum]
ec := evalContext{
cols: t.cols,
row: row,
}
// TODO: We would need to do a topological sort on dependencies
// (i.e. what other columns the expression references) to ensure we
// can handle generated columns which reference other generated columns
for i, col := range t.cols {
if col.Generated != nil {
res, err := ec.evalExpr(col.Generated)
if err != nil {
return err
}
row[i] = res
}
}
}
return nil
}
func (d *database) Insert(tx *transaction, tbl spansql.ID, cols []spansql.ID, values []*structpb.ListValue) error {
return d.writeValues(tx, tbl, cols, values, func(t *table, colIndexes []int, r row) error {
pk := r[:t.pkCols]
rowNum, found := t.rowForPK(pk)
if found {
return status.Errorf(codes.AlreadyExists, "row already in table")
}
t.insertRow(rowNum, r)
return nil
})
}
func (d *database) Update(tx *transaction, tbl spansql.ID, cols []spansql.ID, values []*structpb.ListValue) error {
return d.writeValues(tx, tbl, cols, values, func(t *table, colIndexes []int, r row) error {
if t.pkCols == 0 {
return status.Errorf(codes.InvalidArgument, "cannot update table %s with no columns in primary key", tbl)
}
pk := r[:t.pkCols]
rowNum, found := t.rowForPK(pk)
if !found {
// TODO: is this the right way to return `NOT_FOUND`?
return status.Errorf(codes.NotFound, "row not in table")
}
for _, i := range colIndexes {
t.rows[rowNum][i] = r[i]
}
return nil
})
}
func (d *database) InsertOrUpdate(tx *transaction, tbl spansql.ID, cols []spansql.ID, values []*structpb.ListValue) error {
return d.writeValues(tx, tbl, cols, values, func(t *table, colIndexes []int, r row) error {
pk := r[:t.pkCols]
rowNum, found := t.rowForPK(pk)
if !found {
// New row; do an insert.
t.insertRow(rowNum, r)
} else {
// Existing row; do an update.
for _, i := range colIndexes {
t.rows[rowNum][i] = r[i]
}
}
return nil
})
}
// TODO: Replace
func (d *database) Delete(tx *transaction, table spansql.ID, keys []*structpb.ListValue, keyRanges keyRangeList, all bool) error {
if err := tx.checkMutable(); err != nil {
return err
}
t, err := d.table(table)
if err != nil {
return err
}
t.mu.Lock()
defer t.mu.Unlock()
if all {
t.rows = nil
return nil
}
for _, key := range keys {
pk, err := t.primaryKey(key.Values)
if err != nil {
return err
}
// Not an error if the key does not exist.
rowNum, found := t.rowForPK(pk)
if found {
copy(t.rows[rowNum:], t.rows[rowNum+1:])
t.rows = t.rows[:len(t.rows)-1]
}
}
for _, r := range keyRanges {
r.startKey, err = t.primaryKeyPrefix(r.start.Values)
if err != nil {
return err
}
r.endKey, err = t.primaryKeyPrefix(r.end.Values)
if err != nil {
return err
}
startRow, endRow := t.findRange(r)
if n := endRow - startRow; n > 0 {
copy(t.rows[startRow:], t.rows[endRow:])
t.rows = t.rows[:len(t.rows)-n]
}
}
return nil
}
// readTable executes a read option (Read, ReadAll).
func (d *database) readTable(table spansql.ID, cols []spansql.ID, f func(*table, *rawIter, []int) error) (*rawIter, error) {
t, err := d.table(table)
if err != nil {
return nil, err
}
t.mu.Lock()
defer t.mu.Unlock()
colIndexes, err := t.colIndexes(cols)
if err != nil {
return nil, err
}
ri := &rawIter{}
for _, i := range colIndexes {
ri.cols = append(ri.cols, t.cols[i])
}
return ri, f(t, ri, colIndexes)
}
func (d *database) Read(tbl spansql.ID, cols []spansql.ID, keys []*structpb.ListValue, keyRanges keyRangeList, limit int64) (rowIter, error) {
// The real Cloud Spanner returns an error if the key set is empty by definition.
// That doesn't seem to be well-defined, but it is a common error to attempt a read with no keys,
// so catch that here and return a representative error.
if len(keys) == 0 && len(keyRanges) == 0 {
return nil, status.Error(codes.Unimplemented, "Cloud Spanner does not support reading no keys")
}
return d.readTable(tbl, cols, func(t *table, ri *rawIter, colIndexes []int) error {
// "If the same key is specified multiple times in the set (for
// example if two ranges, two keys, or a key and a range
// overlap), Cloud Spanner behaves as if the key were only
// specified once."
done := make(map[int]bool) // row numbers we've included in ri.
// Specific keys.
for _, key := range keys {
pk, err := t.primaryKey(key.Values)
if err != nil {
return err
}
// Not an error if the key does not exist.
rowNum, found := t.rowForPK(pk)
if !found {
continue
}
if done[rowNum] {
continue
}
done[rowNum] = true
ri.add(t.rows[rowNum], colIndexes)
if limit > 0 && len(ri.rows) >= int(limit) {
return nil
}
}
// Key ranges.
for _, r := range keyRanges {
var err error
r.startKey, err = t.primaryKeyPrefix(r.start.Values)
if err != nil {
return err
}
r.endKey, err = t.primaryKeyPrefix(r.end.Values)
if err != nil {
return err
}
startRow, endRow := t.findRange(r)
for rowNum := startRow; rowNum < endRow; rowNum++ {
if done[rowNum] {
continue
}
done[rowNum] = true
ri.add(t.rows[rowNum], colIndexes)
if limit > 0 && len(ri.rows) >= int(limit) {
return nil
}
}
}
return nil
})
}
func (d *database) ReadAll(tbl spansql.ID, cols []spansql.ID, limit int64) (*rawIter, error) {
return d.readTable(tbl, cols, func(t *table, ri *rawIter, colIndexes []int) error {
for _, r := range t.rows {
ri.add(r, colIndexes)
if limit > 0 && len(ri.rows) >= int(limit) {
break
}
}
return nil
})
}
func (t *table) addColumn(cd spansql.ColumnDef, newTable bool) *status.Status {
if !newTable && cd.NotNull {
return status.Newf(codes.InvalidArgument, "new non-key columns cannot be NOT NULL")
}
if _, ok := t.colIndex[cd.Name]; ok {
return status.Newf(codes.AlreadyExists, "column %s already exists", cd.Name)
}
t.mu.Lock()
defer t.mu.Unlock()
if len(t.rows) > 0 {
if cd.NotNull {
// TODO: what happens in this case?
return status.Newf(codes.Unimplemented, "can't add NOT NULL columns to non-empty tables yet")
}
for i := range t.rows {
if cd.Generated != nil {
ec := evalContext{
cols: t.cols,
row: t.rows[i],
}
val, err := ec.evalExpr(cd.Generated)
if err != nil {
return status.Newf(codes.InvalidArgument, "could not backfill values for generated column: %v", err)
}
t.rows[i] = append(t.rows[i], val)
} else {
t.rows[i] = append(t.rows[i], nil)
}
}
}
t.cols = append(t.cols, colInfo{
Name: cd.Name,
Type: cd.Type,
NotNull: cd.NotNull,
// TODO: We should figure out what columns the Generator expression
// relies on and check it is valid at this time currently it will
// fail when writing data instead as it is the first time we
// evaluate the expression.
Generated: cd.Generated,
})
t.colIndex[cd.Name] = len(t.cols) - 1
if !newTable {
t.origIndex[cd.Name] = len(t.cols) - 1
}
return nil
}
func (t *table) addConstraint(alt spansql.TableConstraint) *status.Status {
t.mu.Lock()
defer t.mu.Unlock()
for _, constraint := range t.constraints {
if constraint.Name == alt.Name {
return status.Newf(codes.AlreadyExists, "constraint name %s already exists", alt.Name)
}
}
t.constraints = append(t.constraints, constraintInfo{
Name: alt.Name,
Constraint: alt.Constraint,
})
return nil
}
func (t *table) dropColumn(name spansql.ID) *status.Status {
// Only permit dropping non-key columns that aren't part of a secondary index.
// We don't support indexes, so only check that it isn't part of the primary key.
t.mu.Lock()
defer t.mu.Unlock()
ci, ok := t.colIndex[name]
if !ok {
// TODO: What's the right response code?
return status.Newf(codes.InvalidArgument, "unknown column %q", name)
}
if ci < t.pkCols {
// TODO: What's the right response code?
return status.Newf(codes.InvalidArgument, "can't drop primary key column %q", name)
}
// Remove from cols and colIndex, and renumber colIndex and origIndex.
t.cols = append(t.cols[:ci], t.cols[ci+1:]...)
delete(t.colIndex, name)
for i, col := range t.cols {
t.colIndex[col.Name] = i
}
pre := t.origIndex[name]
delete(t.origIndex, name)
for n, i := range t.origIndex {
if i > pre {
t.origIndex[n]--
}
}
// Drop data.
for i := range t.rows {
t.rows[i] = append(t.rows[i][:ci], t.rows[i][ci+1:]...)
}
return nil
}
func (t *table) alterColumn(alt spansql.AlterColumn) *status.Status {
// Supported changes here are:
// Add NOT NULL to a non-key column, excluding ARRAY columns.
// Remove NOT NULL from a non-key column.
// Change a STRING column to a BYTES column or a BYTES column to a STRING column.
// Increase or decrease the length limit for a STRING or BYTES type (including to MAX).
// Enable or disable commit timestamps in value and primary key columns.
// https://cloud.google.com/spanner/docs/schema-updates#supported-updates
// TODO: codes.InvalidArgument is used throughout here for reporting errors,
// but that has not been validated against the real Spanner.
sct, ok := alt.Alteration.(spansql.SetColumnType)
if !ok {
return status.Newf(codes.InvalidArgument, "unsupported ALTER COLUMN %s", alt.SQL())
}
t.mu.Lock()
defer t.mu.Unlock()
ci, ok := t.colIndex[alt.Name]
if !ok {
return status.Newf(codes.InvalidArgument, "unknown column %q", alt.Name)
}
oldT, newT := t.cols[ci].Type, sct.Type
stringOrBytes := func(bt spansql.TypeBase) bool { return bt == spansql.String || bt == spansql.Bytes }
// First phase: Check the validity of the change.
// TODO: Don't permit changes to allow commit timestamps.
if !t.cols[ci].NotNull && sct.NotNull {
// Adding NOT NULL is not permitted for primary key columns or array typed columns.
if ci < t.pkCols {
return status.Newf(codes.InvalidArgument, "cannot set NOT NULL on primary key column %q", alt.Name)
}
if oldT.Array {
return status.Newf(codes.InvalidArgument, "cannot set NOT NULL on array-typed column %q", alt.Name)
}
// Validate that there are no NULL values.
for _, row := range t.rows {
if row[ci] == nil {
return status.Newf(codes.InvalidArgument, "cannot set NOT NULL on column %q that contains NULL values", alt.Name)
}
}
}
var conv func(x interface{}) interface{}
if stringOrBytes(oldT.Base) && stringOrBytes(newT.Base) && !oldT.Array && !newT.Array {
// Change between STRING and BYTES is fine, as is increasing/decreasing the length limit.
// TODO: This should permit array conversions too.
// TODO: Validate data; length limit changes should be rejected if they'd lead to data loss, for instance.
if oldT.Base == spansql.Bytes && newT.Base == spansql.String {
conv = func(x interface{}) interface{} { return string(x.([]byte)) }
} else if oldT.Base == spansql.String && newT.Base == spansql.Bytes {
conv = func(x interface{}) interface{} { return []byte(x.(string)) }
}
} else if oldT == newT {
// Same type; only NOT NULL changes.
} else { // TODO: Support other alterations.
return status.Newf(codes.InvalidArgument, "unsupported ALTER COLUMN %s", alt.SQL())
}
// Second phase: Make type transformations.
t.cols[ci].NotNull = sct.NotNull
t.cols[ci].Type = newT
if conv != nil {
for _, row := range t.rows {
if row[ci] != nil { // NULL stays as NULL.
row[ci] = conv(row[ci])
}
}
}
return nil
}
func (t *table) addRowDeletionPolicy(ard spansql.AddRowDeletionPolicy) *status.Status {
_, ok := t.colIndex[ard.RowDeletionPolicy.Column]
if !ok {
return status.Newf(codes.InvalidArgument, "unknown column %q", ard.RowDeletionPolicy.Column)
}
if t.rdw != nil {
return status.New(codes.InvalidArgument, "table already has a row deletion policy")
}
t.rdw = &ard.RowDeletionPolicy
return nil
}
func (t *table) replaceRowDeletionPolicy(ard spansql.ReplaceRowDeletionPolicy) *status.Status {
_, ok := t.colIndex[ard.RowDeletionPolicy.Column]
if !ok {
return status.Newf(codes.InvalidArgument, "unknown column %q", ard.RowDeletionPolicy.Column)
}
if t.rdw == nil {
return status.New(codes.InvalidArgument, "table does not have a row deletion policy")
}
t.rdw = &ard.RowDeletionPolicy
return nil
}
func (t *table) dropRowDeletionPolicy(ard spansql.DropRowDeletionPolicy) *status.Status {
if t.rdw == nil {
return status.New(codes.InvalidArgument, "table does not have a row deletion policy")
}
t.rdw = nil
return nil
}
func (t *table) dropConstraint(alt spansql.DropConstraint) *status.Status {
t.mu.Lock()
defer t.mu.Unlock()
var ci int = -1 // index of the constraint in t.constraints: constraint index
for i, constraint := range t.constraints {
if constraint.Name == alt.Name {
ci = i
}
}
if ci == -1 {
return status.Newf(codes.InvalidArgument, "unknown constraint name %q", alt.Name)
}
t.constraints = append(t.constraints[:ci], t.constraints[ci+1:]...)
return nil
}
func (t *table) insertRow(rowNum int, r row) {
t.rows = append(t.rows, nil)
copy(t.rows[rowNum+1:], t.rows[rowNum:])
t.rows[rowNum] = r
}
// findRange finds the rows included in the key range,
// reporting it as a half-open interval.
// r.startKey and r.endKey should be populated.
func (t *table) findRange(r *keyRange) (int, int) {
// startRow is the first row matching the range.
startRow := sort.Search(len(t.rows), func(i int) bool {
return rowCmp(r.startKey, t.rows[i][:t.pkCols], t.pkDesc) <= 0
})
if startRow == len(t.rows) {
return startRow, startRow
}
if !r.startClosed && rowCmp(r.startKey, t.rows[startRow][:t.pkCols], t.pkDesc) == 0 {
startRow++
}
// endRow is one more than the last row matching the range.
endRow := sort.Search(len(t.rows), func(i int) bool {
return rowCmp(r.endKey, t.rows[i][:t.pkCols], t.pkDesc) < 0
})
if !r.endClosed && rowCmp(r.endKey, t.rows[endRow-1][:t.pkCols], t.pkDesc) == 0 {
endRow--
}
return startRow, endRow
}
// colIndexes returns the indexes for the named columns.
func (t *table) colIndexes(cols []spansql.ID) ([]int, error) {
var is []int
for _, col := range cols {
i, ok := t.colIndex[col]
if !ok {
return nil, status.Errorf(codes.InvalidArgument, "column %s not in table", col)
}
is = append(is, i)
}
return is, nil
}
// primaryKey constructs the internal representation of a primary key.
// The list of given values must be in 1:1 correspondence with the primary key of the table.
func (t *table) primaryKey(values []*structpb.Value) ([]interface{}, error) {
if len(values) != t.pkCols {
return nil, status.Errorf(codes.InvalidArgument, "primary key length mismatch: got %d values, table has %d", len(values), t.pkCols)
}
return t.primaryKeyPrefix(values)
}