-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples_test.go
793 lines (729 loc) · 20.2 KB
/
examples_test.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
/*
Copyright 2017 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 spanner_test
import (
"context"
"errors"
"fmt"
"sync"
"time"
sppb "cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/storj/exp-spanner"
"google.golang.org/api/iterator"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func ExampleNewClient() {
ctx := context.Background()
const myDB = "projects/my-project/instances/my-instance/database/my-db"
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
_ = client // TODO: Use client.
}
const myDB = "projects/my-project/instances/my-instance/database/my-db"
func ExampleNewClientWithConfig() {
ctx := context.Background()
const myDB = "projects/my-project/instances/my-instance/database/my-db"
client, err := spanner.NewClientWithConfig(ctx, myDB, spanner.ClientConfig{
NumChannels: 10,
})
if err != nil {
// TODO: Handle error.
}
_ = client // TODO: Use client.
client.Close() // Close client when done.
}
func ExampleClient_Single() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().Query(ctx, spanner.NewStatement("SELECT FirstName FROM Singers"))
_ = iter // TODO: iterate using Next or Do.
}
func ExampleClient_ReadOnlyTransaction() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
t := client.ReadOnlyTransaction()
defer t.Close()
// TODO: Read with t using Read, ReadRow, ReadUsingIndex, or Query.
}
func ExampleClient_ReadWriteTransaction() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
var balance int64
row, err := txn.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
if err != nil {
// This function will be called again if this is an IsAborted error.
return err
}
if err := row.Column(0, &balance); err != nil {
return err
}
if balance <= 10 {
return errors.New("insufficient funds in account")
}
balance -= 10
m := spanner.Update("Accounts", []string{"user", "balance"}, []interface{}{"alice", balance})
// The buffered mutation will be committed. If the commit fails with an
// IsAborted error, this function will be called again.
return txn.BufferWrite([]*spanner.Mutation{m})
})
if err != nil {
// TODO: Handle error.
}
}
func ExampleUpdate() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
row, err := txn.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
if err != nil {
return err
}
var balance int64
if err := row.Column(0, &balance); err != nil {
return err
}
return txn.BufferWrite([]*spanner.Mutation{
spanner.Update("Accounts", []string{"user", "balance"}, []interface{}{"alice", balance + 10}),
})
})
if err != nil {
// TODO: Handle error.
}
}
// This example is the same as the one for Update, except for the use of UpdateMap.
func ExampleUpdateMap() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
row, err := txn.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
if err != nil {
return err
}
var balance int64
if err := row.Column(0, &balance); err != nil {
return err
}
return txn.BufferWrite([]*spanner.Mutation{
spanner.UpdateMap("Accounts", map[string]interface{}{
"user": "alice",
"balance": balance + 10,
}),
})
})
if err != nil {
// TODO: Handle error.
}
}
// This example is the same as the one for Update, except for the use of
// UpdateStruct.
func ExampleUpdateStruct() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
type account struct {
User string `spanner:"user"`
Balance int64 `spanner:"balance"`
}
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
row, err := txn.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
if err != nil {
return err
}
var balance int64
if err := row.Column(0, &balance); err != nil {
return err
}
m, err := spanner.UpdateStruct("Accounts", account{
User: "alice",
Balance: balance + 10,
})
if err != nil {
return err
}
return txn.BufferWrite([]*spanner.Mutation{m})
})
if err != nil {
// TODO: Handle error.
}
}
func ExampleClient_Apply() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
m := spanner.Update("Users", []string{"name", "email"}, []interface{}{"alice", "[email protected]"})
_, err = client.Apply(ctx, []*spanner.Mutation{m})
if err != nil {
// TODO: Handle error.
}
}
func ExampleInsert() {
m := spanner.Insert("Users", []string{"name", "email"}, []interface{}{"alice", "[email protected]"})
_ = m // TODO: use with Client.Apply or in a ReadWriteTransaction.
}
func ExampleInsertMap() {
m := spanner.InsertMap("Users", map[string]interface{}{
"name": "alice",
"email": "[email protected]",
})
_ = m // TODO: use with Client.Apply or in a ReadWriteTransaction.
}
func ExampleInsertStruct() {
type User struct {
Name, Email string
}
u := User{Name: "alice", Email: "[email protected]"}
m, err := spanner.InsertStruct("Users", u)
if err != nil {
// TODO: Handle error.
}
_ = m // TODO: use with Client.Apply or in a ReadWriteTransaction.
}
func ExampleDelete() {
m := spanner.Delete("Users", spanner.Key{"alice"})
_ = m // TODO: use with Client.Apply or in a ReadWriteTransaction.
}
func ExampleDelete_keyRange() {
m := spanner.Delete("Users", spanner.KeyRange{
Start: spanner.Key{"alice"},
End: spanner.Key{"bob"},
Kind: spanner.ClosedClosed,
})
_ = m // TODO: use with Client.Apply or in a ReadWriteTransaction.
}
func ExampleRowIterator_Next() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().Query(ctx, spanner.NewStatement("SELECT FirstName FROM Singers"))
defer iter.Stop()
for {
row, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
var firstName string
if err := row.Column(0, &firstName); err != nil {
// TODO: Handle error.
}
fmt.Println(firstName)
}
}
func ExampleRowIterator_Do() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().Query(ctx, spanner.NewStatement("SELECT FirstName FROM Singers"))
err = iter.Do(func(r *spanner.Row) error {
var firstName string
if err := r.Column(0, &firstName); err != nil {
return err
}
fmt.Println(firstName)
return nil
})
if err != nil {
// TODO: Handle error.
}
}
func ExampleRow_Size() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
fmt.Println(row.Size()) // 2
}
func ExampleRow_ColumnName() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
fmt.Println(row.ColumnName(1)) // "balance"
}
func ExampleRow_ColumnIndex() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
index, err := row.ColumnIndex("balance")
if err != nil {
// TODO: Handle error.
}
fmt.Println(index)
}
func ExampleRow_ColumnNames() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
fmt.Println(row.ColumnNames())
}
func ExampleRow_ColumnByName() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
var balance int64
if err := row.ColumnByName("balance", &balance); err != nil {
// TODO: Handle error.
}
fmt.Println(balance)
}
func ExampleRow_Columns() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
var name string
var balance int64
if err := row.Columns(&name, &balance); err != nil {
// TODO: Handle error.
}
fmt.Println(name, balance)
}
func ExampleRow_ToStruct() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"name", "balance"})
if err != nil {
// TODO: Handle error.
}
type Account struct {
Name string
Balance int64
}
var acct Account
if err := row.ToStruct(&acct); err != nil {
// TODO: Handle error.
}
fmt.Println(acct)
}
func ExampleRow_ToStructLenient() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"accountID", "name", "balance"})
if err != nil {
// TODO: Handle error.
}
type Account struct {
Name string
Balance int64
NickName string
}
var acct Account
if err := row.ToStructLenient(&acct); err != nil {
// TODO: Handle error.
}
fmt.Println(acct)
}
func ExampleReadOnlyTransaction_Read() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().Read(ctx, "Users",
spanner.KeySets(spanner.Key{"alice"}, spanner.Key{"bob"}),
[]string{"name", "email"})
_ = iter // TODO: iterate using Next or Do.
}
func ExampleReadOnlyTransaction_ReadUsingIndex() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().ReadUsingIndex(ctx, "Users",
"UsersByEmail",
spanner.KeySets(spanner.Key{"[email protected]"}, spanner.Key{"[email protected]"}),
[]string{"name", "email"})
_ = iter // TODO: iterate using Next or Do.
}
func ExampleReadOnlyTransaction_ReadWithOptions() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
// Use an index, and limit to 100 rows at most.
iter := client.Single().ReadWithOptions(ctx, "Users",
spanner.KeySets(spanner.Key{"[email protected]"}, spanner.Key{"[email protected]"}),
[]string{"name", "email"}, &spanner.ReadOptions{
Index: "UsersByEmail",
Limit: 100,
})
_ = iter // TODO: iterate using Next or Do.
}
func ExampleReadOnlyTransaction_ReadRow() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
row, err := client.Single().ReadRow(ctx, "Users", spanner.Key{"alice"},
[]string{"name", "email"})
if err != nil {
// TODO: Handle error.
}
_ = row // TODO: use row
}
func ExampleReadOnlyTransaction_Query() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
iter := client.Single().Query(ctx, spanner.NewStatement("SELECT FirstName FROM Singers"))
_ = iter // TODO: iterate using Next or Do.
}
func ExampleNewStatement() {
stmt := spanner.NewStatement("SELECT FirstName, LastName FROM SINGERS WHERE LastName >= @start")
stmt.Params["start"] = "Dylan"
// TODO: Use stmt in Query.
}
func ExampleNewStatement_structLiteral() {
stmt := spanner.Statement{
SQL: `SELECT FirstName, LastName FROM SINGERS WHERE LastName = ("Lea", "Martin")`,
}
_ = stmt // TODO: Use stmt in Query.
}
func ExampleStructParam() {
stmt := spanner.Statement{
SQL: "SELECT * FROM SINGERS WHERE (FirstName, LastName) = @singerinfo",
Params: map[string]interface{}{
"singerinfo": struct {
FirstName string
LastName string
}{"Bob", "Dylan"},
},
}
_ = stmt // TODO: Use stmt in Query.
}
func ExampleArrayOfStructParam() {
stmt := spanner.Statement{
SQL: "SELECT * FROM SINGERS WHERE (FirstName, LastName) IN UNNEST(@singerinfo)",
Params: map[string]interface{}{
"singerinfo": []struct {
FirstName string
LastName string
}{
{"Ringo", "Starr"},
{"John", "Lennon"},
},
},
}
_ = stmt // TODO: Use stmt in Query.
}
func ExampleReadOnlyTransaction_Timestamp() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
txn := client.Single()
row, err := txn.ReadRow(ctx, "Users", spanner.Key{"alice"},
[]string{"name", "email"})
if err != nil {
// TODO: Handle error.
}
readTimestamp, err := txn.Timestamp()
if err != nil {
// TODO: Handle error.
}
fmt.Println("read happened at", readTimestamp)
_ = row // TODO: use row
}
func ExampleReadOnlyTransaction_WithTimestampBound() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
txn := client.Single().WithTimestampBound(spanner.MaxStaleness(30 * time.Second))
row, err := txn.ReadRow(ctx, "Users", spanner.Key{"alice"}, []string{"name", "email"})
if err != nil {
// TODO: Handle error.
}
_ = row // TODO: use row
readTimestamp, err := txn.Timestamp()
if err != nil {
// TODO: Handle error.
}
fmt.Println("read happened at", readTimestamp)
}
func ExampleGenericColumnValue_Decode() {
// In real applications, rows can be retrieved by methods like client.Single().ReadRow().
row, err := spanner.NewRow([]string{"intCol", "strCol"}, []interface{}{42, "my-text"})
if err != nil {
// TODO: Handle error.
}
for i := 0; i < row.Size(); i++ {
var col spanner.GenericColumnValue
if err := row.Column(i, &col); err != nil {
// TODO: Handle error.
}
switch col.Type.Code {
case sppb.TypeCode_INT64:
var v int64
if err := col.Decode(&v); err != nil {
// TODO: Handle error.
}
fmt.Println("int", v)
case sppb.TypeCode_STRING:
var v string
if err := col.Decode(&v); err != nil {
// TODO: Handle error.
}
fmt.Println("string", v)
}
}
// Output:
// int 42
// string my-text
}
func ExampleClient_BatchReadOnlyTransaction() {
ctx := context.Background()
var (
client *spanner.Client
txn *spanner.BatchReadOnlyTransaction
err error
)
if client, err = spanner.NewClient(ctx, myDB); err != nil {
// TODO: Handle error.
}
defer client.Close()
if txn, err = client.BatchReadOnlyTransaction(ctx, spanner.StrongRead()); err != nil {
// TODO: Handle error.
}
defer txn.Close()
// Singer represents the elements in a row from the Singers table.
type Singer struct {
SingerID int64
FirstName string
LastName string
SingerInfo []byte
}
stmt := spanner.Statement{SQL: "SELECT * FROM Singers;"}
partitions, err := txn.PartitionQuery(ctx, stmt, spanner.PartitionOptions{})
if err != nil {
// TODO: Handle error.
}
// Note: here we use multiple goroutines, but you should use separate
// processes/machines.
wg := sync.WaitGroup{}
for i, p := range partitions {
wg.Add(1)
go func(i int, p *spanner.Partition) {
defer wg.Done()
iter := txn.Execute(ctx, p)
defer iter.Stop()
for {
row, err := iter.Next()
if err == iterator.Done {
break
} else if err != nil {
// TODO: Handle error.
}
var s Singer
if err := row.ToStruct(&s); err != nil {
// TODO: Handle error.
}
_ = s // TODO: Process the row.
}
}(i, p)
}
wg.Wait()
}
func ExampleCommitTimestamp() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
type account struct {
User string
Creation spanner.NullTime // time.Time can also be used if column isNOT NULL
}
a := account{User: "Joe", Creation: spanner.NullTime{spanner.CommitTimestamp, true}}
m, err := spanner.InsertStruct("Accounts", a)
if err != nil {
// TODO: Handle error.
}
_, err = client.Apply(ctx, []*spanner.Mutation{m}, spanner.ApplyAtLeastOnce())
if err != nil {
// TODO: Handle error.
}
if r, e := client.Single().ReadRow(ctx, "Accounts", spanner.Key{"Joe"}, []string{"User", "Creation"}); e != nil {
// TODO: Handle error.
} else {
var got account
if err := r.ToStruct(&got); err != nil {
// TODO: Handle error.
}
_ = got // TODO: Process row.
}
}
func ExampleStatement_regexpContains() {
// Search for accounts with valid emails using regexp as per:
// https://cloud.google.com/spanner/docs/functions-and-operators#regexp_contains
stmt := spanner.Statement{
SQL: `SELECT * FROM users WHERE REGEXP_CONTAINS(email, @valid_email)`,
Params: map[string]interface{}{
"valid_email": `\Q@\E`,
},
}
_ = stmt // TODO: Use stmt in a query.
}
func ExampleKeySets() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
// Get some rows from the Accounts table using a secondary index. In this case we get all users who are in Georgia.
iter := client.Single().ReadUsingIndex(context.Background(), "Accounts", "idx_state", spanner.Key{"GA"}, []string{"state"})
// Create a empty KeySet by calling the KeySets function with no parameters.
ks := spanner.KeySets()
// Loop the results of a previous query iterator.
for {
row, err := iter.Next()
if err == iterator.Done {
break
} else if err != nil {
// TODO: Handle error.
}
var id string
err = row.ColumnByName("User", &id)
if err != nil {
// TODO: Handle error.
}
ks = spanner.KeySets(spanner.KeySets(spanner.Key{id}, ks))
}
_ = ks //TODO: Go use the KeySet in another query.
}
func ExampleNewReadWriteStmtBasedTransaction() {
ctx := context.Background()
client, err := spanner.NewClient(ctx, myDB)
if err != nil {
// TODO: Handle error.
}
defer client.Close()
f := func(tx *spanner.ReadWriteStmtBasedTransaction) error {
var balance int64
row, err := tx.ReadRow(ctx, "Accounts", spanner.Key{"alice"}, []string{"balance"})
if err != nil {
return err
}
if err := row.Column(0, &balance); err != nil {
return err
}
if balance <= 10 {
return errors.New("insufficient funds in account")
}
balance -= 10
m := spanner.Update("Accounts", []string{"user", "balance"}, []interface{}{"alice", balance})
return tx.BufferWrite([]*spanner.Mutation{m})
}
for {
tx, err := spanner.NewReadWriteStmtBasedTransaction(ctx, client)
if err != nil {
// TODO: Handle error.
break
}
err = f(tx)
if err != nil && status.Code(err) != codes.Aborted {
tx.Rollback(ctx)
// TODO: Handle error.
break
} else if err == nil {
_, err = tx.Commit(ctx)
if err == nil {
break
} else if status.Code(err) != codes.Aborted {
// TODO: Handle error.
break
}
}
// Set a default sleep time if the server delay is absent.
delay := 10 * time.Millisecond
if serverDelay, hasServerDelay := spanner.ExtractRetryDelay(err); hasServerDelay {
delay = serverDelay
}
time.Sleep(delay)
}
}