/
database.go
1513 lines (1253 loc) · 40.4 KB
/
database.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 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 (
"bytes"
"context"
"database/sql"
"fmt"
"log"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cloudspannerecosystem/memefish/ast"
uuidpkg "github.com/google/uuid"
sqlite "github.com/mattn/go-sqlite3"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
structpb "google.golang.org/protobuf/types/known/structpb"
)
type Database interface {
ApplyDDL(ctx context.Context, ddl ast.DDL) error
Read(ctx context.Context, tx *transaction, tbl, index string, cols []string, keyset *KeySet, limit int64) (RowIterator, error)
Query(ctx context.Context, tx *transaction, query *ast.QueryStatement, params map[string]Value) (RowIterator, error)
Execute(ctx context.Context, tx *transaction, dml ast.DML, params map[string]Value) (int64, error)
Insert(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error
Update(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error
Replace(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error
InsertOrUpdate(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error
Delete(ctx context.Context, tx *transaction, table string, keyset *KeySet) error
BeginTransaction(tx *transaction) error
Commit(tx *transaction) error
Rollback(tx *transaction) error
Close() error
}
type barrier struct {
locked int32
condMu *sync.Mutex
cond *sync.Cond
}
func newBarrier() *barrier {
mu := new(sync.Mutex)
cond := sync.NewCond(mu)
return &barrier{
locked: 0,
condMu: mu,
cond: cond,
}
}
// TryAcquire get a lock and blocks all other transactions enter critical section.
// When fail to get a lock, returns false. Please use Wait to wait the lock is released and
// try TryAcquire again.
func (l *barrier) TryAcquire() bool {
now := atomic.LoadInt32(&l.locked)
if now == 1 {
return false
}
ok := atomic.CompareAndSwapInt32(&l.locked, now, 1)
return ok
}
// Release releases the lock and notifies to transactions that wait releasing th lock.
func (l *barrier) Release() {
atomic.StoreInt32(&l.locked, 0)
l.cond.Broadcast()
}
// Wait waits until locked is released.
// This does not ensure only one transaction enters critical section.
// This makes sure one the lock is acquired by someone, other transactions are blocked until released.
func (l *barrier) Wait() {
now := atomic.LoadInt32(&l.locked)
if now == 0 {
return
}
l.condMu.Lock()
l.cond.Wait()
l.condMu.Unlock()
}
func (l *barrier) Released() bool {
now := atomic.LoadInt32(&l.locked)
return now == 0
}
var _ Database = (*database)(nil)
type database struct {
db *sql.DB
ctx context.Context
cancel func()
// schema level lock
schemaMu sync.RWMutex
tables map[string]*Table
// transactions
transactions map[string]*transaction
transactionsMu sync.Mutex
tablesInUse map[string]*tableTransaction
tablesInUseMu sync.RWMutex
// writeBarrier blocks other transactions try to write or commit
writeBarrier *barrier
writeTransaction *transaction
writeTransactionMu sync.RWMutex
}
type tableTransaction struct {
use sync.RWMutex
lockHolder *transaction
transactionsInUse map[string]*transaction
transactionsInUseMu sync.Mutex
}
func (tt *tableTransaction) Dump() {
if tt.lockHolder != nil {
fmt.Printf("lock holder: %s status=%v\n", tt.lockHolder.Name(), tt.lockHolder.Status())
} else {
fmt.Printf("lock holder: <nil>\n")
}
fmt.Printf("transactions in use\n")
for _, tx := range tt.transactionsInUse {
fmt.Printf(" - %s status=%v\n", tx.Name(), tx.Status())
}
}
func (tt *tableTransaction) Use(tx *transaction) {
if IsDebug() {
defer DebugStartEnd("[%s] tableTransaction.Use", tx.Name())()
}
// skip if the transction already holds the table lock
tt.transactionsInUseMu.Lock()
if tx.Equals(tt.lockHolder) {
tt.transactionsInUseMu.Unlock()
return
}
tt.transactionsInUseMu.Unlock()
// try to get read lock
tt.use.RLock()
defer tt.use.RUnlock()
tt.transactionsInUseMu.Lock()
defer tt.transactionsInUseMu.Unlock()
tt.transactionsInUse[tx.Name()] = tx
}
func (tt *tableTransaction) Lock(tx *transaction) {
if IsDebug() {
defer DebugStartEnd("[%s] tableTransaction.Lock", tx.Name())()
}
// skip if the transction already holds the table lock
tt.transactionsInUseMu.Lock()
if tx.Equals(tt.lockHolder) {
tt.transactionsInUseMu.Unlock()
return
}
tt.transactionsInUseMu.Unlock()
// try to get write lock
tt.use.Lock()
var uses []*transaction
func() {
tt.transactionsInUseMu.Lock()
defer tt.transactionsInUseMu.Unlock()
if !tx.Available() {
Debugf("[%s] transaction NOT AVAILABE in Lock: %v\n", tx.Name(), tx.Status())
panic(fmt.Sprintf("[%s] transaction NOT AVAILABE in Lock: %v\n", tx.Name(), tx.Status()))
}
tt.lockHolder = tx
for _, tx := range tt.transactionsInUse {
uses = append(uses, tx)
}
}()
// Abort all ransactions which hold read lock for the table
for _, tt := range uses {
if !tx.Equals(tt) {
tt.Done(TransactionAborted)
}
}
}
func (tt *tableTransaction) Release(tx *transaction) {
if IsDebug() {
defer DebugStartEnd("[%s] tableTransaction.Release", tx.Name())()
}
tt.transactionsInUseMu.Lock()
defer tt.transactionsInUseMu.Unlock()
delete(tt.transactionsInUse, tx.Name())
if !tx.Equals(tt.lockHolder) {
return
}
tt.lockHolder = nil
tt.use.Unlock()
}
func newTableTransaction() *tableTransaction {
return &tableTransaction{
transactionsInUse: make(map[string]*transaction),
}
}
func newDatabase() *database {
uuid := uuidpkg.New().String()
db, err := sql.Open("sqlite3_spanner", fmt.Sprintf("file:%s.db?cache=shared&mode=memory&_foreign_keys=true", uuid))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
conn, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
// keep at least 1 active connection to keep database
go func(conn *sql.Conn) {
t := time.NewTicker(1 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
newConn, err := db.Conn(ctx)
if err != nil {
continue
}
conn.Close()
conn = newConn
}
}(conn)
d := &database{
tables: make(map[string]*Table),
tablesInUse: make(map[string]*tableTransaction),
db: db,
ctx: ctx,
cancel: cancel,
transactions: make(map[string]*transaction),
writeBarrier: newBarrier(),
}
if err := d.prepareMetaTables(ctx); err != nil {
log.Fatalf("failed to prepare meta tables: %v", err)
}
return d
}
func (d *database) prepareMetaTables(ctx context.Context) error {
for _, table := range metaTables {
if err := d.CreateTable(ctx, table); err != nil {
return fmt.Errorf("failed to create table for %s: %v", table.Name.Name, err)
}
}
unixmicro := int64(time.Now().UnixNano() / 1000)
initialData := []string{
fmt.Sprintf(`INSERT INTO __INFORMATION_SCHEMA__SCHEMATA VALUES("", "", %d)`, unixmicro),
`INSERT INTO __INFORMATION_SCHEMA__SCHEMATA VALUES("", "INFORMATION_SCHEMA", NULL)`,
`INSERT INTO __INFORMATION_SCHEMA__SCHEMATA VALUES("", "SPANNER_SYS", NULL)`,
}
for _, query := range initialData {
if _, err := d.db.ExecContext(ctx, query); err != nil {
return fmt.Errorf("failed to prepare initial data: %v", err)
}
}
for _, table := range metaTables {
if err := d.registerInformationSchemaTables(ctx, table); err != nil {
return fmt.Errorf("failed to create table for %s: %v", table.Name.Name, err)
}
}
return nil
}
// waitUntilReadable marks database is used for read.
// If database is locked for write by other transaction, this function blocks until the lock is released.
func (d *database) waitUntilReadable(ctx context.Context, tx *transaction) error {
if IsDebug() {
defer DebugStartEnd("[%s] database.waitUntilReadable", tx.Name())()
}
// Skip if the transaction already holds write lock
d.writeTransactionMu.RLock()
curTx := d.writeTransaction
d.writeTransactionMu.RUnlock()
if tx.Equals(curTx) {
return nil
}
if d.writeBarrier.Released() {
return nil
}
ch := make(chan struct{}, 0)
go func() {
d.writeBarrier.Wait()
close(ch)
}()
select {
case <-ch:
case <-ctx.Done():
return status.FromContextError(ctx.Err()).Err()
}
if !tx.Available() {
return ErrNotAvailableTransaction
}
return nil
}
// waitUntilWritable locks database for write.
// This function does not ensure all other transactions don't have read lock.
// Once locked, other transactions cannot newly get read or write lock.
//
// This function blocks until the lock is acquired. Break the block when the context
// is done while waiting the lock.
func (d *database) waitUntilWritable(ctx context.Context, tx *transaction) error {
if IsDebug() {
defer DebugStartEnd("[%s] database.waitUntilWritable", tx.Name())()
}
// Skip if the transaction already holds write lock
d.writeTransactionMu.RLock()
curTx := d.writeTransaction
d.writeTransactionMu.RUnlock()
if tx.Equals(curTx) {
return nil
}
ch := make(chan struct{}, 0)
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
if !tx.Available() {
close(ch)
return
}
// Try to get lock
ok := d.writeBarrier.TryAcquire()
if ok {
// save the holder of write lock
d.writeTransactionMu.Lock()
d.writeTransaction = tx
d.writeTransactionMu.Unlock()
close(ch)
return
}
// Return if the lock is acrequired by own transaction
d.writeTransactionMu.RLock()
curTx := d.writeTransaction
d.writeTransactionMu.RUnlock()
if curTx != nil && bytes.Equal(curTx.ID(), tx.ID()) {
close(ch)
return
}
// Wait until the lock is released
d.writeBarrier.Wait()
}
}()
select {
case <-ch:
case <-ctx.Done():
return status.FromContextError(ctx.Err()).Err()
}
if !tx.Available() {
d.releaseWriteLock(tx)
return ErrNotAvailableTransaction
}
return nil
}
// releasewriteLock releases write lock for database
// This function can be called by any transactions but transactions don't hold write lock are ignored.
func (d *database) releaseWriteLock(tx *transaction) {
if IsDebug() {
defer DebugStartEnd("[%s] database.releaseWriteLock", tx.Name())()
}
d.writeTransactionMu.RLock()
curTx := d.writeTransaction
d.writeTransactionMu.RUnlock()
if !curTx.Equals(tx) {
return
}
d.writeTransactionMu.Lock()
defer d.writeTransactionMu.Unlock()
curTx = d.writeTransaction
if curTx.Equals(tx) {
d.writeTransaction = nil
d.writeBarrier.Release()
}
}
// useTable marks a table is used for read by the transaction.
// If the table is locked by other transaction, this function blocks until the lock is released.
func (d *database) useTable(tbl string, tx *transaction) (*Table, error) {
d.schemaMu.RLock()
defer d.schemaMu.RUnlock()
d.tablesInUseMu.Lock()
defer d.tablesInUseMu.Unlock()
table, ok := d.tables[tbl]
if !ok {
return nil, newSpannerTableNotFoundError(tbl)
}
use, ok := d.tablesInUse[tbl]
if !ok {
use = newTableTransaction()
d.tablesInUse[tbl] = use
}
use.Use(tx)
if !tx.Available() {
return nil, ErrNotAvailableTransaction
}
return table, nil
}
// useTableExclusive locks a table for write.
// Other transactions cannot read or write the table and wait until the lock is released.
// This function blocks until lock is acquired.
//
// When a transaction got the lock to a table, other transactions reading the table are
// aborted immediately.
func (d *database) useTableExclusive(tbl string, tx *transaction) (*Table, error) {
table, ok := d.tables[tbl]
if !ok {
return nil, newSpannerTableNotFoundError(tbl)
}
var tt *tableTransaction
func() {
d.tablesInUseMu.Lock()
defer d.tablesInUseMu.Unlock()
use, ok := d.tablesInUse[tbl]
if !ok {
use = newTableTransaction()
d.tablesInUse[tbl] = use
}
tt = use
}()
tt.Lock(tx)
return table, nil
}
func (d *database) ApplyDDL(ctx context.Context, ddl ast.DDL) error {
d.schemaMu.Lock()
defer d.schemaMu.Unlock()
switch val := ddl.(type) {
case *ast.CreateTable:
if err := d.CreateTable(ctx, val); err != nil {
return status.Errorf(codes.Unknown, "%v", err)
}
return nil
case *ast.CreateIndex:
if err := d.CreateIndex(ctx, val); err != nil {
return status.Errorf(codes.Unknown, "%v", err)
}
return nil
case *ast.DropTable:
return status.Errorf(codes.Unimplemented, "Drop Table is not supported yet")
case *ast.DropIndex:
return status.Errorf(codes.Unimplemented, "Drop Index is not supported yet")
case *ast.AlterTable:
return status.Errorf(codes.Unimplemented, "Alter Table is not supported yet")
case *ast.CreateChangeStream:
// skip CreateChangeStream
return nil
default:
return status.Errorf(codes.Unknown, "unknown DDL statement: %v", val)
}
}
func (d *database) Read(ctx context.Context, tx *transaction, tbl, idx string, cols []string, keyset *KeySet, limit int64) (RowIterator, error) {
if keyset == nil {
return nil, status.Errorf(codes.InvalidArgument, "Invalid StreamingRead request")
}
if tbl == "" {
return nil, status.Errorf(codes.InvalidArgument, "Invalid StreamingRead request")
}
if len(cols) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "Invalid StreamingRead request")
}
if err := d.waitUntilReadable(ctx, tx); err != nil {
return nil, err
}
table, err := d.useTable(tbl, tx)
if err != nil {
return nil, err
}
index, ok := table.TableIndex(idx)
if !ok {
return nil, newSpannerIndexnNotFoundError(tbl, idx)
}
columns, err := table.getColumnsByName(cols)
if err != nil {
return nil, err // getColumnsByName returns error with status code
}
// Check the index table has the specified columns
for _, column := range columns {
if !index.HasColumn(column.Name()) {
return nil, status.Errorf(codes.Unimplemented, "Reading non-indexed columns using an index is not supported. Consider adding %s to the index using a STORING clause.", column.Name())
}
}
resultItems := make([]ResultItem, len(cols))
for i := range columns {
resultItems[i] = createResultItemFromColumn(columns[i])
}
indexColumnsName := strings.Join(QuoteStringSlice(index.IndexColumnNames()), ", ")
indexColumns := index.IndexColumns()
indexColumnDirs := index.IndexColumnDirections()
colName := strings.Join(QuoteStringSlice(cols), ", ")
var args []interface{}
whereClause, whereArgs, err := buildWhereClauseFromKeySet(keyset, indexColumnsName, indexColumns, indexColumnDirs)
if err != nil {
return nil, err
}
args = append(args, whereArgs...)
orderByItems := make([]string, len(indexColumns))
for i := range indexColumns {
orderByItems[i] = fmt.Sprintf("%s %s", QuoteString(indexColumns[i].Name()), indexColumnDirs[i])
}
orderByClause := strings.Join(orderByItems, ", ")
query := fmt.Sprintf(`SELECT %s FROM %s %s ORDER BY %s`, colName, QuoteString(table.Name), whereClause, orderByClause)
if limit > 0 {
query += fmt.Sprintf(" LIMIT %d", limit)
}
var sqlRows *sql.Rows
err = tx.ReadTransaction(func(ctx context.Context, dbtx databaseReader) error {
r, err := dbtx.QueryContext(ctx, query, args...)
if err != nil {
return status.Errorf(codes.Unknown, "query failed: %v, query: %v", err, query)
}
sqlRows = r
return nil
})
if err != nil {
return nil, err
}
return &rows{rows: sqlRows, resultItems: resultItems, transaction: tx}, nil
}
func (d *database) Query(ctx context.Context, tx *transaction, stmt *ast.QueryStatement, params map[string]Value) (RowIterator, error) {
if err := d.waitUntilReadable(ctx, tx); err != nil {
return nil, err
}
query, args, resultItems, err := BuildQuery(d, tx, stmt.Query, params, false)
if err != nil {
return nil, err
}
var sqlRows *sql.Rows
err = tx.ReadTransaction(func(ctx context.Context, dbtx databaseReader) error {
r, err := dbtx.QueryContext(ctx, query, args...)
if err != nil {
return status.Errorf(codes.Unknown, "query failed: %v, query: %v", err, query)
}
sqlRows = r
return nil
})
if err != nil {
return nil, err
}
return &rows{rows: sqlRows, resultItems: resultItems, transaction: tx}, nil
}
func (d *database) Execute(ctx context.Context, tx *transaction, dml ast.DML, params map[string]Value) (int64, error) {
if err := d.waitUntilWritable(ctx, tx); err != nil {
return 0, err
}
if !tx.Available() {
return 0, ErrNotAvailableTransaction
}
if tx.Status() == TransactionAborted {
return 0, status.Errorf(codes.Aborted, "transaction aborted")
}
query, args, err := BuildDML(d, tx, dml, params)
if err != nil {
return 0, err
}
var affectedRows int64
err = tx.WriteTransaction(func(dbtx databaseWriter) error {
r, err := dbtx.ExecContext(ctx, query, args...)
if err != nil {
if sqliteErr, ok := err.(sqlite.Error); ok {
// This error should not be happend.
// This error means a tx tries to write a table which another tx holds read-lock
// to the table, or a tx tries to write a table which another tx holds global wite-lock
//
// It better to be panic but return Aborted to expect the client retries.
if sqliteErr.Code == sqlite.ErrLocked {
return status.Errorf(codes.Aborted, "transaction is aborted: database is locked")
}
}
return status.Errorf(codes.Unknown, "failed to write into sqlite: %v", err)
}
affectedRows, err = r.RowsAffected()
if err != nil {
return err
}
return nil
})
if err != nil {
return 0, err
}
return affectedRows, nil
}
func (d *database) write(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue,
nonNullCheck bool,
affectedRowsCheck bool,
buildQueryFn func(*Table, []*Column) string,
buildArgsFn func(*Table, []*Column, []interface{}) []interface{},
) error {
if IsDebug() {
defer DebugStartEnd("[%s] database.write", tx.Name())()
}
if err := d.waitUntilWritable(ctx, tx); err != nil {
return err
}
if !tx.Available() {
return ErrNotAvailableTransaction
}
if tx.Status() == TransactionAborted {
return status.Errorf(codes.Aborted, "transaction aborted")
}
table, err := d.useTableExclusive(tbl, tx)
if err != nil {
return err
}
if IsDebug() {
defer DebugStartEnd("[%s] database.write after write lock", tx.Name())()
}
primaryKey := table.primaryKey
// Check columns are defined in the table
columns, err := table.getColumnsByName(cols)
if err != nil {
return err // getColumnsByName returns error with status code
}
// Ensure multiple values are not specified
usedColumns := make(map[string]struct{}, len(cols))
for _, c := range columns {
n := c.Name()
if _, ok := usedColumns[n]; ok {
return status.Errorf(codes.InvalidArgument, "Multiple values for column %s", n)
}
usedColumns[n] = struct{}{}
}
// Check all primary keys are specified
for _, colName := range primaryKey.IndexColumnNames() {
if _, ok := usedColumns[colName]; !ok {
return status.Errorf(codes.FailedPrecondition, "%s must not be NULL in table %s.", colName, tbl)
}
}
// Check not nullable columns are specified for Insert/Replace
if nonNullCheck {
if exist, nonNullables := table.NonNullableAndNonGeneratedColumnsExist(cols); exist {
columns := strings.Join(nonNullables, ", ")
return status.Errorf(codes.FailedPrecondition,
"A new row in table %s does not specify a non-null value for these NOT NULL columns: %s",
tbl, columns,
)
}
}
if len(values) == 0 {
return nil
}
query := buildQueryFn(table, columns)
if query == "" {
return nil
}
err = tx.WriteTransaction(func(dbtx databaseWriter) error {
for _, vs := range values {
if len(vs.Values) != len(cols) {
return status.Error(codes.InvalidArgument, "Mutation has mismatched number of columns and values.")
}
data := make([]interface{}, 0, len(cols))
for i, v := range vs.Values {
col := columns[i]
vv, err := spannerValue2DatabaseValue(v, *col)
if err != nil {
return status.Errorf(codes.InvalidArgument, "%v", err)
}
if !col.nullable && vv == nil {
return status.Errorf(codes.FailedPrecondition,
"%s must not be NULL in table %s.",
col.Name(), tbl,
)
}
data = append(data, vv)
}
args := buildArgsFn(table, columns, data)
r, err := dbtx.ExecContext(ctx, query, args...)
if err != nil {
if sqliteErr, ok := err.(sqlite.Error); ok {
msg := sqliteErr.Error()
switch sqliteErr.ExtendedCode {
case sqlite.ErrConstraintPrimaryKey:
return status.Errorf(codes.AlreadyExists, "Row %v in table %s already exists", data, tbl)
case sqlite.ErrConstraintUnique:
if n := strings.Index(msg, ": "); n > 0 {
msg = msg[n+2:]
}
return status.Errorf(codes.AlreadyExists,
"Unique index violation at index key [%v]. It conflicts with row %v in table %s",
msg, data, tbl,
)
case sqlite.ErrConstraintCheck:
return status.Errorf(codes.FailedPrecondition, "%s", sqliteErr.Error())
}
// This error should not be happend.
// This error means a tx tries to write a table which another tx holds read-lock
// to the table, or a tx tries to write a table which another tx holds global wite-lock
//
// It better to be panic but return Aborted to expect the client retries.
if sqliteErr.Code == sqlite.ErrLocked {
return status.Errorf(codes.Aborted, "transaction is aborted: database is locked")
}
}
return status.Errorf(codes.Unknown, "failed to write into sqlite: %v", err)
}
if affectedRowsCheck {
// Check rows are updated
// When the row does not exist, sqlite returns success.
// But spanner should return NotFound
n, err := r.RowsAffected()
if err != nil {
return status.Errorf(codes.Unknown, "failed to get RowsAffected: %v", err)
}
if n == 0 {
// no details in real spanner
return status.Errorf(codes.NotFound, "Row %v in table %s is missing. Row cannot be updated.", data, tbl)
}
}
}
return nil
})
if err != nil {
return err
}
return nil
}
func (d *database) Insert(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error {
buildQueryFn := func(table *Table, columns []*Column) string {
columnName := strings.Join(QuoteStringSlice(cols), ", ")
placeholder := "?"
if len(cols) > 1 {
placeholder += strings.Repeat(", ?", len(cols)-1)
}
return fmt.Sprintf(`INSERT INTO %s (%s) VALUES (%s)`, QuoteString(tbl), columnName, placeholder)
}
buildArgsFn := func(table *Table, columns []*Column, data []interface{}) []interface{} {
return data
}
return d.write(ctx, tx, tbl, cols, values, true, false, buildQueryFn, buildArgsFn)
}
func (d *database) Update(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error {
buildQueryFn := func(table *Table, columns []*Column) string {
assigns := make([]string, 0, len(cols))
for _, c := range columns {
if c.isPrimaryKey {
continue
}
assigns = append(assigns, fmt.Sprintf("%s = ?", QuoteString(c.Name())))
}
// If no columns to be updated exist, it should be no-op.
if len(assigns) == 0 {
return ""
}
setClause := strings.Join(assigns, ", ")
pKeysNames := table.primaryKey.IndexColumnNames()
pkeysAssign := make([]string, len(pKeysNames))
for i, col := range pKeysNames {
pkeysAssign[i] = fmt.Sprintf("%s = ?", QuoteString(col))
}
whereClause := strings.Join(pkeysAssign, " AND ")
return fmt.Sprintf(`UPDATE %s SET %s WHERE %s`, QuoteString(tbl), setClause, whereClause)
}
buildArgsFn := func(table *Table, columns []*Column, data []interface{}) []interface{} {
numPKeys := len(table.primaryKey.IndexColumns())
values := make([]interface{}, 0, len(cols))
pkeyValues := make([]interface{}, numPKeys)
for i, column := range columns {
if column.isPrimaryKey {
pkeyValues[column.primaryKeyPos-1] = data[i]
} else {
values = append(values, data[i])
}
}
// First N(size=columns-pkeys) values are for SET clause
// Last M(size=pkeys) values are for WHERE clause
values = append(values, pkeyValues...)
return values
}
return d.write(ctx, tx, tbl, cols, values, false, true, buildQueryFn, buildArgsFn)
}
func (d *database) Replace(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error {
buildQueryFn := func(table *Table, columns []*Column) string {
columnName := strings.Join(QuoteStringSlice(cols), ", ")
placeholder := "?"
if len(cols) > 1 {
placeholder += strings.Repeat(", ?", len(cols)-1)
}
return fmt.Sprintf(`REPLACE INTO %s (%s) VALUES (%s)`, QuoteString(tbl), columnName, placeholder)
}
buildArgsFn := func(table *Table, columns []*Column, data []interface{}) []interface{} {
return data
}
return d.write(ctx, tx, tbl, cols, values, true, false, buildQueryFn, buildArgsFn)
}
func (d *database) InsertOrUpdate(ctx context.Context, tx *transaction, tbl string, cols []string, values []*structpb.ListValue) error {
buildQueryFn := func(table *Table, columns []*Column) string {
assigns := make([]string, 0, len(cols))
for _, c := range columns {
if c.isPrimaryKey {
continue
}
assigns = append(assigns, fmt.Sprintf("%s = ?", QuoteString(c.Name())))
}
setClause := strings.Join(assigns, ", ")
pkeysNamesSlice := table.primaryKey.IndexColumnNames()
pkeysNames := strings.Join(QuoteStringSlice(pkeysNamesSlice), ", ")
columnName := strings.Join(QuoteStringSlice(cols), ", ")
placeholder := "?"
if len(cols) > 1 {
placeholder += strings.Repeat(", ?", len(cols)-1)
}
return fmt.Sprintf(`INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO UPDATE SET %s`,
QuoteString(tbl), columnName, placeholder, pkeysNames, setClause)
}
buildArgsFn := func(table *Table, columns []*Column, data []interface{}) []interface{} {
setValues := make([]interface{}, 0, len(cols))
for i, column := range columns {
if !column.isPrimaryKey {
setValues = append(setValues, data[i])
}
}
// First N(size=columns) values are for VALUES clause
// Last M(size=columns-pkeys) values are for SET clause
data = append(data, setValues...)
return data
}
return d.write(ctx, tx, tbl, cols, values, false, false, buildQueryFn, buildArgsFn)
}
func (d *database) Delete(ctx context.Context, tx *transaction, tbl string, keyset *KeySet) error {
if err := d.waitUntilWritable(ctx, tx); err != nil {
return err
}
table, err := d.useTableExclusive(tbl, tx)
if err != nil {