-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathintegration_test.go
1666 lines (1583 loc) · 52.6 KB
/
integration_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
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.
*/
/*
This file holds tests for the in-memory fake for comparing it against a real Cloud Spanner.
By default it uses the Spanner client against the in-memory fake; set the
-test_db flag to "projects/P/instances/I/databases/D" to make it use a real
Cloud Spanner database instead. You may need to provide -timeout=5m too.
*/
package spannertest
import (
"context"
"flag"
"fmt"
"reflect"
"sort"
"testing"
"time"
"cloud.google.com/go/civil"
"cloud.google.com/go/spanner"
dbadmin "cloud.google.com/go/spanner/admin/database/apiv1"
v1 "cloud.google.com/go/spanner/apiv1"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
dbadminpb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"cloud.google.com/go/spanner/apiv1/spannerpb"
structpb "google.golang.org/protobuf/types/known/structpb"
)
var testDBFlag = flag.String("test_db", "", "Fully-qualified database name to test against; empty means use an in-memory fake.")
func dbName() string {
if *testDBFlag != "" {
return *testDBFlag
}
return "projects/fake-proj/instances/fake-instance/databases/fake-db"
}
func makeClient(t *testing.T) (*spanner.Client, *dbadmin.DatabaseAdminClient, *v1.Client, func()) {
// Despite the docs, this context is also used for auth,
// so it needs to be long-lived.
ctx := context.Background()
if *testDBFlag != "" {
t.Logf("Using real Spanner DB %s", *testDBFlag)
dialOpt := option.WithGRPCDialOption(grpc.WithTimeout(5 * time.Second))
client, err := spanner.NewClient(ctx, *testDBFlag, dialOpt)
if err != nil {
t.Fatalf("Connecting to %s: %v", *testDBFlag, err)
}
adminClient, err := dbadmin.NewDatabaseAdminClient(ctx, dialOpt)
if err != nil {
client.Close()
t.Fatalf("Connecting DB admin client: %v", err)
}
gapicClient, err := v1.NewClient(ctx, dialOpt)
if err != nil {
client.Close()
adminClient.Close()
t.Fatalf("Connecting Spanner generated client: %v", err)
}
return client, adminClient, gapicClient, func() { client.Close(); adminClient.Close(); gapicClient.Close() }
}
// Don't use SPANNER_EMULATOR_HOST because we need the raw connection for
// the database admin client anyway.
t.Logf("Using in-memory fake Spanner DB")
srv, err := NewServer("localhost:0")
if err != nil {
t.Fatalf("Starting in-memory fake: %v", err)
}
srv.SetLogger(t.Logf)
dialCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
conn, err := grpc.DialContext(dialCtx, srv.Addr, grpc.WithInsecure())
if err != nil {
srv.Close()
t.Fatalf("Dialing in-memory fake: %v", err)
}
client, err := spanner.NewClient(ctx, dbName(), option.WithGRPCConn(conn))
if err != nil {
srv.Close()
t.Fatalf("Connecting to in-memory fake: %v", err)
}
adminClient, err := dbadmin.NewDatabaseAdminClient(ctx, option.WithGRPCConn(conn))
if err != nil {
srv.Close()
t.Fatalf("Connecting to in-memory fake DB admin: %v", err)
}
gapicClient, err := v1.NewClient(ctx, option.WithGRPCConn(conn))
if err != nil {
srv.Close()
t.Fatalf("Connecting to in-memory fake generated Spanner client: %v", err)
}
return client, adminClient, gapicClient, func() {
client.Close()
adminClient.Close()
gapicClient.Close()
conn.Close()
srv.Close()
}
}
func TestIntegration_SpannerBasics(t *testing.T) {
client, adminClient, generatedClient, cleanup := makeClient(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// Do a trivial query to verify the connection works.
it := client.Single().Query(ctx, spanner.NewStatement("SELECT 1"))
row, err := it.Next()
if err != nil {
t.Fatalf("Getting first row of trivial query: %v", err)
}
var value int64
if err := row.Column(0, &value); err != nil {
t.Fatalf("Decoding row data from trivial query: %v", err)
}
if value != 1 {
t.Errorf("Trivial query gave %d, want 1", value)
}
// There shouldn't be a next row.
_, err = it.Next()
if err != iterator.Done {
t.Errorf("Reading second row of trivial query gave %v, want iterator.Done", err)
}
it.Stop()
// Try to execute the equivalent of a session pool ping.
// This used to cause a panic as ExecuteSql did not expect any requests
// that would execute a query without a transaction selector.
// https://github.com/googleapis/google-cloud-go/issues/3639
s, err := generatedClient.CreateSession(ctx, &spannerpb.CreateSessionRequest{Database: dbName()})
if err != nil {
t.Fatalf("Creating session: %v", err)
}
rs, err := generatedClient.ExecuteSql(ctx, &spannerpb.ExecuteSqlRequest{
Session: s.Name,
Sql: "SELECT 1",
})
if err != nil {
t.Fatalf("Executing ping: %v", err)
}
if len(rs.Rows) != 1 {
t.Fatalf("Ping gave %v rows, want 1", len(rs.Rows))
}
if len(rs.Rows[0].Values) != 1 {
t.Fatalf("Ping gave %v cols, want 1", len(rs.Rows[0].Values))
}
if rs.Rows[0].Values[0].GetStringValue() != "1" {
t.Fatalf("Ping gave value %v, want '1'", rs.Rows[0].Values[0].GetStringValue())
}
if err = generatedClient.DeleteSession(ctx, &spannerpb.DeleteSessionRequest{Name: s.Name}); err != nil {
t.Fatalf("Deleting session: %v", err)
}
// Drop any previous test table/index, and make a fresh one in a few stages.
const tableName = "Characters"
err = updateDDL(t, adminClient, "DROP INDEX AgeIndex")
// NotFound is an acceptable failure mode here.
if st, _ := status.FromError(err); st.Code() == codes.NotFound {
err = nil
}
if err != nil {
t.Fatalf("Dropping old index: %v", err)
}
if err := dropTable(t, adminClient, tableName); err != nil {
t.Fatal(err)
}
err = updateDDL(t, adminClient,
`CREATE TABLE `+tableName+` (
FirstName STRING(20) NOT NULL,
LastName STRING(20) NOT NULL,
Alias STRING(MAX),
) PRIMARY KEY (FirstName, LastName)`)
if err != nil {
t.Fatalf("Setting up fresh table: %v", err)
}
err = updateDDL(t, adminClient,
`ALTER TABLE `+tableName+` ADD COLUMN Age INT64`,
`CREATE INDEX AgeIndex ON `+tableName+` (Age DESC)`)
if err != nil {
t.Fatalf("Adding new column: %v", err)
}
// Insert some data.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert(tableName,
[]string{"FirstName", "LastName", "Alias", "Age"},
[]interface{}{"Steve", "Rogers", "Captain America", 101}),
spanner.Insert(tableName,
[]string{"LastName", "FirstName", "Age", "Alias"},
[]interface{}{"Romanoff", "Natasha", 35, "Black Widow"}),
spanner.Insert(tableName,
[]string{"Age", "Alias", "FirstName", "LastName"},
[]interface{}{49, "Iron Man", "Tony", "Stark"}),
spanner.Insert(tableName,
[]string{"FirstName", "Alias", "LastName"}, // no Age
[]interface{}{"Clark", "Superman", "Kent"}),
// Two rows with the same value in one column,
// but with distinct primary keys.
spanner.Insert(tableName,
[]string{"FirstName", "LastName", "Alias"},
[]interface{}{"Peter", "Parker", "Spider-Man"}),
spanner.Insert(tableName,
[]string{"FirstName", "LastName", "Alias"},
[]interface{}{"Peter", "Quill", "Star-Lord"}),
})
if err != nil {
t.Fatalf("Applying mutations: %v", err)
}
// Delete some data.
_, err = client.Apply(ctx, []*spanner.Mutation{
// Whoops. DC, not MCU.
spanner.Delete(tableName, spanner.Key{"Clark", "Kent"}),
})
if err != nil {
t.Fatalf("Applying mutations: %v", err)
}
// Read a single row.
row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Alias", "Age"})
if err != nil {
t.Fatalf("Reading single row: %v", err)
}
var alias string
var age int64
if err := row.Columns(&alias, &age); err != nil {
t.Fatalf("Decoding single row: %v", err)
}
if alias != "Iron Man" || age != 49 {
t.Errorf(`Single row read gave (%q, %d), want ("Iron Man", 49)`, alias, age)
}
// Read all rows, and do a local age sum.
rows := client.Single().Read(ctx, tableName, spanner.AllKeys(), []string{"Age"})
var ageSum int64
err = rows.Do(func(row *spanner.Row) error {
var age spanner.NullInt64
if err := row.Columns(&age); err != nil {
return err
}
if age.Valid {
ageSum += age.Int64
}
return nil
})
if err != nil {
t.Fatalf("Iterating over all row read: %v", err)
}
if want := int64(101 + 35 + 49); ageSum != want {
t.Errorf("Age sum after iterating over all rows = %d, want %d", ageSum, want)
}
// Do a more complex query to find the aliases of the two oldest non-centenarian characters.
stmt := spanner.NewStatement(`SELECT Alias FROM ` + tableName + ` WHERE Age < @ageLimit AND Alias IS NOT NULL ORDER BY Age DESC LIMIT @limit`)
stmt.Params = map[string]interface{}{
"ageLimit": 100,
"limit": 2,
}
rows = client.Single().Query(ctx, stmt)
var oldFolk []string
err = rows.Do(func(row *spanner.Row) error {
var alias string
if err := row.Columns(&alias); err != nil {
return err
}
oldFolk = append(oldFolk, alias)
return nil
})
if err != nil {
t.Fatalf("Iterating over complex query: %v", err)
}
if want := []string{"Iron Man", "Black Widow"}; !reflect.DeepEqual(oldFolk, want) {
t.Errorf("Complex query results = %v, want %v", oldFolk, want)
}
// Apply an update.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Update(tableName,
[]string{"FirstName", "LastName", "Age"},
[]interface{}{"Steve", "Rogers", 102}),
})
if err != nil {
t.Fatalf("Applying mutations: %v", err)
}
row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Steve", "Rogers"}, []string{"Age"})
if err != nil {
t.Fatalf("Reading single row: %v", err)
}
if err := row.Columns(&age); err != nil {
t.Fatalf("Decoding single row: %v", err)
}
if age != 102 {
t.Errorf("After updating Captain America, age = %d, want 102", age)
}
// Do a query where the result type isn't deducible from the first row.
stmt = spanner.NewStatement(`SELECT Age FROM ` + tableName + ` WHERE FirstName = "Peter"`)
rows = client.Single().Query(ctx, stmt)
var nullPeters int
err = rows.Do(func(row *spanner.Row) error {
var age spanner.NullInt64
if err := row.Column(0, &age); err != nil {
return err
}
if age.Valid {
t.Errorf("Got non-NULL Age %d for a Peter", age.Int64)
} else {
nullPeters++
}
return nil
})
if err != nil {
t.Fatalf("Counting Peters with NULL Ages: %v", err)
}
if nullPeters != 2 {
t.Errorf("Found %d Peters with NULL Ages, want 2", nullPeters)
}
// Check handling of array types.
err = updateDDL(t, adminClient, `ALTER TABLE `+tableName+` ADD COLUMN Allies ARRAY<STRING(20)>`)
if err != nil {
t.Fatalf("Adding new array-typed column: %v", err)
}
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Update(tableName,
[]string{"FirstName", "LastName", "Allies"},
[]interface{}{"Steve", "Rogers", []string{}}),
spanner.Update(tableName,
[]string{"FirstName", "LastName", "Allies"},
[]interface{}{"Tony", "Stark", []string{"Black Widow", "Spider-Man"}}),
})
if err != nil {
t.Fatalf("Applying mutations: %v", err)
}
row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Allies"})
if err != nil {
t.Fatalf("Reading row with array value: %v", err)
}
var names []string
if err := row.Column(0, &names); err != nil {
t.Fatalf("Unpacking array value: %v", err)
}
if want := []string{"Black Widow", "Spider-Man"}; !reflect.DeepEqual(names, want) {
t.Errorf("Read array value: got %q, want %q", names, want)
}
row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Steve", "Rogers"}, []string{"Allies"})
if err != nil {
t.Fatalf("Reading row with empty array value: %v", err)
}
if err := row.Column(0, &names); err != nil {
t.Fatalf("Unpacking empty array value: %v", err)
}
if len(names) > 0 {
t.Errorf("Read empty array value: got %q", names)
}
// Exercise commit timestamp.
err = updateDDL(t, adminClient, `ALTER TABLE `+tableName+` ADD COLUMN Updated TIMESTAMP OPTIONS (allow_commit_timestamp=true)`)
if err != nil {
t.Fatalf("Adding new timestamp column: %v", err)
}
cts, err := client.Apply(ctx, []*spanner.Mutation{
// Update one row in place.
spanner.Update(tableName,
[]string{"FirstName", "LastName", "Allies", "Updated"},
[]interface{}{"Tony", "Stark", []string{"Spider-Man", "Professor Hulk"}, spanner.CommitTimestamp}),
})
if err != nil {
t.Fatalf("Applying mutations: %v", err)
}
cts = cts.In(time.UTC)
if d := time.Since(cts); d < 0 || d > 10*time.Second {
t.Errorf("Commit timestamp %v not in the last 10s", cts)
}
row, err = client.Single().ReadRow(ctx, tableName, spanner.Key{"Tony", "Stark"}, []string{"Allies", "Updated"})
if err != nil {
t.Fatalf("Reading single row: %v", err)
}
var gotAllies []string
var gotUpdated time.Time
if err := row.Columns(&gotAllies, &gotUpdated); err != nil {
t.Fatalf("Decoding single row: %v", err)
}
if want := []string{"Spider-Man", "Professor Hulk"}; !reflect.DeepEqual(gotAllies, want) {
t.Errorf("After updating Iron Man, allies = %+v, want %+v", gotAllies, want)
}
if !gotUpdated.Equal(cts) {
t.Errorf("After updating Iron Man, updated = %v, want %v", gotUpdated, cts)
}
// Check if IN UNNEST works.
stmt = spanner.NewStatement(`SELECT Age FROM ` + tableName + ` WHERE FirstName IN UNNEST(@list)`)
stmt.Params = map[string]interface{}{
"list": []string{"Peter", "Steve"},
}
rows = client.Single().Query(ctx, stmt)
var ages []int64
err = rows.Do(func(row *spanner.Row) error {
var age spanner.NullInt64
if err := row.Column(0, &age); err != nil {
return err
}
ages = append(ages, age.Int64) // zero for NULL
return nil
})
if err != nil {
t.Fatalf("Getting ages using IN UNNEST: %v", err)
}
sort.Slice(ages, func(i, j int) bool { return ages[i] < ages[j] })
wantAges := []int64{0, 0, 102} // Peter Parker, Peter Quill, Steve Rogers (modified)
if !reflect.DeepEqual(ages, wantAges) {
t.Errorf("Query with IN UNNEST gave wrong ages: got %+v, want %+v", ages, wantAges)
}
}
func TestIntegration_ReadsAndQueries(t *testing.T) {
client, adminClient, _, cleanup := makeClient(t)
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// Drop any old tables.
// Do them all concurrently; this saves a lot of time.
allTables := []string{
"Staff",
"PlayerStats",
"JoinA", "JoinB", "JoinC", "JoinD", "JoinE", "JoinF",
"SomeStrings", "Updateable",
}
errc := make(chan error)
for _, table := range allTables {
go func(table string) {
errc <- dropTable(t, adminClient, table)
}(table)
}
var bad bool
for range allTables {
if err := <-errc; err != nil {
t.Error(err)
bad = true
}
}
if bad {
t.FailNow()
}
err := updateDDL(t, adminClient,
`CREATE TABLE Staff (
Tenure INT64,
ID INT64,
Name STRING(MAX),
Cool BOOL,
Height FLOAT64,
) PRIMARY KEY (Name, ID)`)
if err != nil {
t.Fatal(err)
}
// Insert a subset of columns.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert("Staff", []string{"ID", "Name", "Tenure", "Height"}, []interface{}{1, "Jack", 10, 1.85}),
spanner.Insert("Staff", []string{"ID", "Name", "Tenure", "Height"}, []interface{}{2, "Daniel", 11, 1.83}),
})
if err != nil {
t.Fatalf("Inserting data: %v", err)
}
// Insert a different set of columns.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Sam", 3, false, 9, 1.75}),
spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Teal'c", 4, true, 8, 1.91}),
spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"George", 5, nil, 6, 1.73}),
spanner.Insert("Staff", []string{"Name", "ID", "Cool", "Tenure", "Height"}, []interface{}{"Harry", 6, true, nil, nil}),
})
if err != nil {
t.Fatalf("Inserting more data: %v", err)
}
// Delete that last one.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Delete("Staff", spanner.Key{"Harry", 6}),
})
if err != nil {
t.Fatalf("Deleting a row: %v", err)
}
// Turns out this guy isn't cool after all.
_, err = client.Apply(ctx, []*spanner.Mutation{
// Missing columns should be left alone.
spanner.Update("Staff", []string{"Name", "ID", "Cool"}, []interface{}{"Daniel", 2, false}),
})
if err != nil {
t.Fatalf("Updating a row: %v", err)
}
// Read some specific keys.
ri := client.Single().Read(ctx, "Staff", spanner.KeySets(
spanner.Key{"George", 5},
spanner.Key{"Harry", 6}, // Missing key should be silently ignored.
spanner.Key{"Sam", 3},
spanner.Key{"George", 5}, // Duplicate key should be silently ignored.
), []string{"Name", "Tenure"})
if err != nil {
t.Fatalf("Reading keys: %v", err)
}
all := mustSlurpRows(t, ri)
wantAll := [][]interface{}{
{"George", int64(6)},
{"Sam", int64(9)},
}
if !reflect.DeepEqual(all, wantAll) {
t.Errorf("Read data by keys wrong.\n got %v\nwant %v", all, wantAll)
}
// Read the same, but by key range.
ri = client.Single().Read(ctx, "Staff", spanner.KeySets(
spanner.KeyRange{Start: spanner.Key{"Gabriel"}, End: spanner.Key{"Harpo"}, Kind: spanner.OpenOpen},
spanner.KeyRange{Start: spanner.Key{"Sam", 3}, End: spanner.Key{"Teal'c", 4}, Kind: spanner.ClosedOpen},
), []string{"Name", "Tenure"})
all = mustSlurpRows(t, ri)
if !reflect.DeepEqual(all, wantAll) {
t.Errorf("Read data by key ranges wrong.\n got %v\nwant %v", all, wantAll)
}
// Read a subset of all rows, with a limit.
ri = client.Single().ReadWithOptions(ctx, "Staff", spanner.AllKeys(), []string{"Tenure", "Name", "Height"},
&spanner.ReadOptions{Limit: 4})
all = mustSlurpRows(t, ri)
wantAll = [][]interface{}{
// Primary key is (Name, ID), so results should come back sorted by Name then ID.
{int64(11), "Daniel", 1.83},
{int64(6), "George", 1.73},
{int64(10), "Jack", 1.85},
{int64(9), "Sam", 1.75},
}
if !reflect.DeepEqual(all, wantAll) {
t.Errorf("ReadAll data wrong.\n got %v\nwant %v", all, wantAll)
}
// Add DATE and TIMESTAMP columns, and populate them with some data.
err = updateDDL(t, adminClient,
`ALTER TABLE Staff ADD COLUMN FirstSeen DATE`,
"ALTER TABLE Staff ADD COLUMN `To` TIMESTAMP", // "TO" is a keyword; needs quoting
)
if err != nil {
t.Fatalf("Adding columns: %v", err)
}
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"Jack", 1, "1994-10-28", nil}),
spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"Daniel", 2, "1994-10-28", nil}),
spanner.Update("Staff", []string{"Name", "ID", "FirstSeen", "To"}, []interface{}{"George", 5, "1997-07-27", "2008-07-29T11:22:43Z"}),
})
if err != nil {
t.Fatalf("Updating rows: %v", err)
}
// Add some more data, then delete it with a KeyRange.
// The queries below ensure that this was all deleted.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"01", 1}),
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"03", 3}),
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"06", 6}),
})
if err != nil {
t.Fatalf("Inserting data: %v", err)
}
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Delete("Staff", spanner.KeyRange{
/* This should work:
Start: spanner.Key{"01", 1},
End: spanner.Key{"9"},
However, that is unimplemented in the production Cloud Spanner, which rejects
that: ""For delete ranges, start and limit keys may only differ in the final key part"
*/
Start: spanner.Key{"01"},
End: spanner.Key{"9"},
Kind: spanner.ClosedOpen,
}),
})
if err != nil {
t.Fatalf("Deleting key range: %v", err)
}
// Re-add the data and delete with DML.
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"01", 1}),
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"03", 3}),
spanner.Insert("Staff", []string{"Name", "ID"}, []interface{}{"06", 6}),
})
if err != nil {
t.Fatalf("Inserting data: %v", err)
}
var n int64
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error {
stmt := spanner.NewStatement("DELETE FROM Staff WHERE Name >= @min AND Name < @max")
stmt.Params["min"] = "01"
stmt.Params["max"] = "07"
n, err = tx.Update(ctx, stmt)
return err
})
if err != nil {
t.Fatalf("Deleting with DML: %v", err)
}
if n != 3 {
t.Errorf("Deleting with DML affected %d rows, want 3", n)
}
// Add a BYTES column, and populate it with some data.
err = updateDDL(t, adminClient, `ALTER TABLE Staff ADD COLUMN RawBytes BYTES(MAX)`)
if err != nil {
t.Fatalf("Adding column: %v", err)
}
_, err = client.Apply(ctx, []*spanner.Mutation{
// bytes {0x01 0x00 0x01} encode as base-64 AQAB.
spanner.Update("Staff", []string{"Name", "ID", "RawBytes"}, []interface{}{"Jack", 1, []byte{0x01, 0x00, 0x01}}),
})
if err != nil {
t.Fatalf("Updating rows: %v", err)
}
// Prepare the sample tables from the Cloud Spanner docs.
// https://cloud.google.com/spanner/docs/query-syntax#appendix-a-examples-with-sample-data
err = updateDDL(t, adminClient,
// TODO: Roster, TeamMascot when we implement JOINs.
`CREATE TABLE PlayerStats (
LastName STRING(MAX),
OpponentID INT64,
PointsScored INT64,
) PRIMARY KEY (LastName, OpponentID)`, // TODO: is this right?
// JoinFoo are from https://cloud.google.com/spanner/docs/query-syntax#join_types.
// They aren't consistently named in the docs.
`CREATE TABLE JoinA ( w INT64, x STRING(MAX), a STRING(MAX) ) PRIMARY KEY (w, x)`,
`CREATE TABLE JoinB ( y INT64, z STRING(MAX), b STRING(MAX) ) PRIMARY KEY (y, z)`,
`CREATE TABLE JoinC ( x INT64, y STRING(MAX), c STRING(MAX) ) PRIMARY KEY (x, y)`,
`CREATE TABLE JoinD ( x INT64, z STRING(MAX), d STRING(MAX) ) PRIMARY KEY (x, z)`,
`CREATE TABLE JoinE ( w INT64, x STRING(MAX), e STRING(MAX) ) PRIMARY KEY (w, x)`,
`CREATE TABLE JoinF ( y INT64, z STRING(MAX), f STRING(MAX) ) PRIMARY KEY (y, z)`,
// Some other test tables.
`CREATE TABLE SomeStrings ( i INT64, str STRING(MAX) ) PRIMARY KEY (i)`,
`CREATE TABLE Updateable (
id INT64,
first STRING(MAX),
last STRING(MAX),
) PRIMARY KEY (id)`,
)
if err != nil {
t.Fatalf("Creating sample tables: %v", err)
}
_, err = client.Apply(ctx, []*spanner.Mutation{
spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Adams", 51, 3}),
spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Buchanan", 77, 0}),
spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Coolidge", 77, 1}),
spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Adams", 52, 4}),
spanner.Insert("PlayerStats", []string{"LastName", "OpponentID", "PointsScored"}, []interface{}{"Buchanan", 50, 13}),
spanner.Insert("JoinA", []string{"w", "x", "a"}, []interface{}{1, "a", "a1"}),
spanner.Insert("JoinA", []string{"w", "x", "a"}, []interface{}{2, "b", "a2"}),
spanner.Insert("JoinA", []string{"w", "x", "a"}, []interface{}{3, "c", "a3"}),
spanner.Insert("JoinA", []string{"w", "x", "a"}, []interface{}{3, "d", "a4"}),
spanner.Insert("JoinB", []string{"y", "z", "b"}, []interface{}{2, "k", "b1"}),
spanner.Insert("JoinB", []string{"y", "z", "b"}, []interface{}{3, "m", "b2"}),
spanner.Insert("JoinB", []string{"y", "z", "b"}, []interface{}{3, "n", "b3"}),
spanner.Insert("JoinB", []string{"y", "z", "b"}, []interface{}{4, "p", "b4"}),
// JoinC and JoinD have the same contents as JoinA and JoinB; they have different column names.
spanner.Insert("JoinC", []string{"x", "y", "c"}, []interface{}{1, "a", "c1"}),
spanner.Insert("JoinC", []string{"x", "y", "c"}, []interface{}{2, "b", "c2"}),
spanner.Insert("JoinC", []string{"x", "y", "c"}, []interface{}{3, "c", "c3"}),
spanner.Insert("JoinC", []string{"x", "y", "c"}, []interface{}{3, "d", "c4"}),
spanner.Insert("JoinD", []string{"x", "z", "d"}, []interface{}{2, "k", "d1"}),
spanner.Insert("JoinD", []string{"x", "z", "d"}, []interface{}{3, "m", "d2"}),
spanner.Insert("JoinD", []string{"x", "z", "d"}, []interface{}{3, "n", "d3"}),
spanner.Insert("JoinD", []string{"x", "z", "d"}, []interface{}{4, "p", "d4"}),
// JoinE and JoinF are used in the CROSS JOIN test.
spanner.Insert("JoinE", []string{"w", "x", "e"}, []interface{}{1, "a", "e1"}),
spanner.Insert("JoinE", []string{"w", "x", "e"}, []interface{}{2, "b", "e2"}),
spanner.Insert("JoinF", []string{"y", "z", "f"}, []interface{}{2, "c", "f1"}),
spanner.Insert("JoinF", []string{"y", "z", "f"}, []interface{}{3, "d", "f2"}),
spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{0, "afoo"}),
spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{1, "abar"}),
spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{2, nil}),
spanner.Insert("SomeStrings", []string{"i", "str"}, []interface{}{3, "bbar"}),
})
if err != nil {
t.Fatalf("Inserting sample data: %v", err)
}
// Perform INSERT DML; the results are checked later on.
n = 0
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error {
for _, u := range []string{
`INSERT INTO Updateable (id, first, last) VALUES (0, "joe", nil)`,
`INSERT INTO Updateable (id, first, last) VALUES (1, "doe", "joan")`,
`INSERT INTO Updateable (id, first, last) VALUES (2, "wong", "wong")`,
} {
nr, err := tx.Update(ctx, spanner.NewStatement(u))
if err != nil {
return err
}
n += nr
}
return nil
})
if err != nil {
t.Fatalf("Inserting with DML: %v", err)
}
if n != 3 {
t.Errorf("Inserting with DML affected %d rows, want 3", n)
}
// Perform INSERT DML with statement.Params; the results are checked later on.
n = 0
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error {
stmt := spanner.Statement{
SQL: "INSERT INTO Updateable (id, first, last) VALUES (@id, @first, @last)",
Params: map[string]interface{}{
"id": 3,
"first": "tom",
"last": "jerry",
},
}
nr, err := tx.Update(ctx, stmt)
if err != nil {
return err
}
n += nr
return nil
})
if err != nil {
t.Fatalf("Inserting with DML: %v", err)
}
if n != 1 {
t.Errorf("Inserting with DML affected %d rows, want 1", n)
}
// Perform INSERT DML with statement.Params and inline parameter; the results are checked later on.
n = 0
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error {
stmt := spanner.Statement{
SQL: `INSERT INTO Updateable (id, first, last) VALUES (@id, "jim", @last)`,
Params: map[string]interface{}{
"id": 4,
"last": nil,
},
}
nr, err := tx.Update(ctx, stmt)
if err != nil {
return err
}
n += nr
return nil
})
if err != nil {
t.Fatalf("Inserting with DML: %v", err)
}
if n != 1 {
t.Errorf("Inserting with DML affected %d rows, want 1", n)
}
// Perform UPDATE DML; the results are checked later on.
n = 0
_, err = client.ReadWriteTransaction(ctx, func(ctx context.Context, tx *spanner.ReadWriteTransaction) error {
for _, u := range []string{
`UPDATE Updateable SET last = "bloggs" WHERE id = 0`,
`UPDATE Updateable SET first = last, last = first WHERE id = 1`,
`UPDATE Updateable SET last = DEFAULT WHERE id = 2`,
`UPDATE Updateable SET first = "noname" WHERE id = 5`, // no id=5
} {
nr, err := tx.Update(ctx, spanner.NewStatement(u))
if err != nil {
return err
}
n += nr
}
return nil
})
if err != nil {
t.Fatalf("Updating with DML: %v", err)
}
if n != 3 {
t.Errorf("Updating with DML affected %d rows, want 3", n)
}
rows := client.Single().Query(ctx, spanner.NewStatement("SELECT CAST('Foo' AS INT64)"))
_, err = rows.Next()
if g, w := spanner.ErrCode(err), codes.InvalidArgument; g != w {
t.Errorf("error code mismatch for invalid CAST\n Got: %v\nWant: %v", g, w)
}
rows.Stop()
rows = client.Single().Query(ctx, spanner.NewStatement("SELECT EXTRACT(INVALID_PART FROM TIMESTAMP('2008-12-25T05:30:00Z')"))
_, err = rows.Next()
if g, w := spanner.ErrCode(err), codes.InvalidArgument; g != w {
t.Errorf("error code mismatch for invalid part from EXTRACT\n Got: %v\nWant: %v", g, w)
}
rows.Stop()
// Do some complex queries.
tests := []struct {
q string
params map[string]interface{}
want [][]interface{}
}{
{
`SELECT 17, "sweet", TRUE AND FALSE, NULL, B"hello", STARTS_WITH('Foo', 'B'), STARTS_WITH('Bar', 'B'), CAST(17 AS STRING), SAFE_CAST(TRUE AS STRING), SAFE_CAST('Foo' AS INT64), EXTRACT(DATE FROM TIMESTAMP('2008-12-25T05:30:00Z') AT TIME ZONE 'Europe/Amsterdam'), EXTRACT(YEAR FROM TIMESTAMP('2008-12-25T05:30:00Z')), FARM_FINGERPRINT('test'), MOD(5, 10)`,
nil,
[][]interface{}{{int64(17), "sweet", false, nil, []byte("hello"), false, true, "17", "true", nil, civil.Date{Year: 2008, Month: 12, Day: 25}, int64(2008), int64(1), int64(5)}},
},
// Check handling of NULL values for the IS operator.
// There was a bug that returned errors for some of these cases.
{
`SELECT @x IS TRUE, @x IS NOT TRUE, @x IS FALSE, @x IS NOT FALSE, @x IS NULL, @x IS NOT NULL`,
map[string]interface{}{"x": (*bool)(nil)},
[][]interface{}{
{false, true, false, true, true, false},
},
},
// Check handling of bools that might be NULL.
// There was a bug where logical operators always returned true/false.
{
`SELECT @x, NOT @x, @x AND TRUE, @x AND FALSE, @x OR TRUE, @x OR FALSE`,
map[string]interface{}{"x": (*bool)(nil)},
[][]interface{}{
// At the time of writing (9 Oct 2020), the docs are wrong for `NULL AND FALSE`;
// the production Spanner returns FALSE, which is what we match.
{nil, nil, nil, false, true, nil},
},
},
{
`SELECT Name FROM Staff WHERE Cool`,
nil,
[][]interface{}{{"Teal'c"}},
},
{
`SELECT ID FROM Staff WHERE Cool IS NOT NULL ORDER BY ID DESC`,
nil,
[][]interface{}{{int64(4)}, {int64(3)}, {int64(2)}},
},
{
`SELECT Name, Tenure FROM Staff WHERE Cool IS NULL OR Cool ORDER BY Name LIMIT 2`,
nil,
[][]interface{}{
{"George", int64(6)},
{"Jack", int64(10)},
},
},
{
`SELECT Name, ID + 100 FROM Staff WHERE @min <= Tenure AND Tenure < @lim ORDER BY Cool, Name DESC LIMIT @numResults`,
map[string]interface{}{"min": 9, "lim": 11, "numResults": 100},
[][]interface{}{
{"Jack", int64(101)},
{"Sam", int64(103)},
},
},
{
// Expression in SELECT list.
`SELECT Name, Cool IS NOT NULL FROM Staff WHERE Tenure/2 > 4 ORDER BY NOT Cool, Name`,
nil,
[][]interface{}{
{"Jack", false}, // Jack has NULL Cool (NULLs always come first in orderings)
{"Daniel", true}, // Daniel has Cool==true
{"Sam", true}, // Sam has Cool==false
},
},
{
`SELECT Name, Height FROM Staff ORDER BY Height DESC LIMIT 2`,
nil,
[][]interface{}{
{"Teal'c", 1.91},
{"Jack", 1.85},
},
},
{
`SELECT str FROM SomeStrings WHERE str LIKE "a%"`,
nil,
[][]interface{}{
{"afoo"},
{"abar"},
},
},
{
`SELECT Name FROM Staff WHERE Name LIKE "%e"`,
nil,
[][]interface{}{
{"George"},
},
},
{
`SELECT Name FROM Staff WHERE Name LIKE "J%k" OR Name LIKE "_am"`,
nil,
[][]interface{}{
{"Jack"},
{"Sam"},
},
},
{
`SELECT Name FROM Staff WHERE STARTS_WITH(Name, 'Ja')`,
nil,
[][]interface{}{
{"Jack"},
},
},
{
`SELECT Name, Height FROM Staff WHERE Height BETWEEN @min AND @max ORDER BY Height DESC`,
map[string]interface{}{"min": 1.75, "max": 1.85},
[][]interface{}{
{"Jack", 1.85},
{"Daniel", 1.83},
{"Sam", 1.75},
},
},
{
`SELECT COUNT(*) FROM Staff WHERE Name < "T"`,
nil,
[][]interface{}{
{int64(4)},
},
},
{
// Check that aggregation still works for the empty set.
`SELECT COUNT(*) FROM Staff WHERE Name = "Nobody"`,
nil,
[][]interface{}{
{int64(0)},
},
},
{
`SELECT * FROM Staff WHERE Name LIKE "S%"`,
nil,
[][]interface{}{
// These are returned in table column order, based on the appearance in the DDL.
// Our internal implementation sorts the primary key columns first,
// but that should not become visible via SELECT *.
{int64(9), int64(3), "Sam", false, 1.75, nil, nil, nil},
},
},
{
// Exactly the same as the previous, except with a redundant ORDER BY clause.
`SELECT * FROM Staff WHERE Name LIKE "S%" ORDER BY Name`,
nil,
[][]interface{}{
{int64(9), int64(3), "Sam", false, 1.75, nil, nil, nil},
},
},
{
`SELECT Name FROM Staff WHERE FirstSeen >= @min`,
map[string]interface{}{"min": civil.Date{Year: 1996, Month: 1, Day: 1}},
[][]interface{}{
{"George"},
},
},
{
`SELECT RawBytes FROM Staff WHERE RawBytes IS NOT NULL`,
nil,
[][]interface{}{
{[]byte("\x01\x00\x01")},
},
},
{
// The keyword "To" needs quoting in queries.
// Check coercion of comparison operator literal args too.
"SELECT COUNT(*) FROM Staff WHERE `To` > '2000-01-01T00:00:00Z'",
nil,
[][]interface{}{
{int64(1)},
},
},
{
`SELECT DISTINCT Cool, Tenure > 8 FROM Staff ORDER BY Cool`,
nil,
[][]interface{}{