1/*
2Copyright 2018 Google LLC
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package spanner
18
19import (
20	"context"
21	"sync"
22	"testing"
23	"time"
24
25	. "cloud.google.com/go/spanner/internal/testutil"
26	sppb "google.golang.org/genproto/googleapis/spanner/v1"
27)
28
29func TestPartitionRoundTrip(t *testing.T) {
30	t.Parallel()
31	for i, want := range []Partition{
32		{rreq: &sppb.ReadRequest{Table: "t"}},
33		{qreq: &sppb.ExecuteSqlRequest{Sql: "sql"}},
34	} {
35		got := serdesPartition(t, i, &want)
36		if !testEqual(got, want) {
37			t.Errorf("got: %#v\nwant:%#v", got, want)
38		}
39	}
40}
41
42func TestBROTIDRoundTrip(t *testing.T) {
43	t.Parallel()
44	tm := time.Now()
45	want := BatchReadOnlyTransactionID{
46		tid: []byte("tid"),
47		sid: "sid",
48		rts: tm,
49	}
50	data, err := want.MarshalBinary()
51	if err != nil {
52		t.Fatal(err)
53	}
54	var got BatchReadOnlyTransactionID
55	if err := got.UnmarshalBinary(data); err != nil {
56		t.Fatal(err)
57	}
58	if !testEqual(got, want) {
59		t.Errorf("got: %#v\nwant:%#v", got, want)
60	}
61}
62
63// serdesPartition is a helper that serialize a Partition then deserialize it.
64func serdesPartition(t *testing.T, i int, p1 *Partition) (p2 Partition) {
65	var (
66		data []byte
67		err  error
68	)
69	if data, err = p1.MarshalBinary(); err != nil {
70		t.Fatalf("#%d: encoding failed %v", i, err)
71	}
72	if err = p2.UnmarshalBinary(data); err != nil {
73		t.Fatalf("#%d: decoding failed %v", i, err)
74	}
75	return p2
76}
77
78func TestPartitionQuery_QueryOptions(t *testing.T) {
79	for _, tt := range queryOptionsTestCases() {
80		t.Run(tt.name, func(t *testing.T) {
81			if tt.env.Options != nil {
82				unset := setQueryOptionsEnvVars(tt.env.Options)
83				defer unset()
84			}
85
86			ctx := context.Background()
87			_, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{QueryOptions: tt.client})
88			defer teardown()
89
90			var (
91				err  error
92				txn  *BatchReadOnlyTransaction
93				ps   []*Partition
94				stmt = NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums)
95			)
96
97			if txn, err = client.BatchReadOnlyTransaction(ctx, StrongRead()); err != nil {
98				t.Fatal(err)
99			}
100			defer txn.Cleanup(ctx)
101
102			if tt.query.Options == nil {
103				ps, err = txn.PartitionQuery(ctx, stmt, PartitionOptions{0, 3})
104			} else {
105				ps, err = txn.PartitionQueryWithOptions(ctx, stmt, PartitionOptions{0, 3}, tt.query)
106			}
107			if err != nil {
108				t.Fatal(err)
109			}
110
111			for _, p := range ps {
112				if got, want := p.qreq.QueryOptions.OptimizerVersion, tt.want.Options.OptimizerVersion; got != want {
113					t.Fatalf("Incorrect optimizer version: got %v, want %v", got, want)
114				}
115				if got, want := p.qreq.QueryOptions.OptimizerStatisticsPackage, tt.want.Options.OptimizerStatisticsPackage; got != want {
116					t.Fatalf("Incorrect optimizer statistics package: got %v, want %v", got, want)
117				}
118			}
119		})
120	}
121}
122
123func TestPartitionQuery_Parallel(t *testing.T) {
124	ctx := context.Background()
125	server, client, teardown := setupMockedTestServer(t)
126	defer teardown()
127
128	txn, err := client.BatchReadOnlyTransaction(ctx, StrongRead())
129	if err != nil {
130		t.Fatal(err)
131	}
132	defer txn.Cleanup(ctx)
133	ps, err := txn.PartitionQuery(ctx, NewStatement(SelectSingerIDAlbumIDAlbumTitleFromAlbums), PartitionOptions{0, 10})
134	if err != nil {
135		t.Fatal(err)
136	}
137	for i, p := range ps {
138		server.TestSpanner.PutPartitionResult(p.pt, server.CreateSingleRowSingersResult(int64(i)))
139	}
140
141	wg := &sync.WaitGroup{}
142	mu := sync.Mutex{}
143	var total int64
144
145	for _, p := range ps {
146		p := p
147		go func() {
148			iter := txn.Execute(context.Background(), p)
149			defer iter.Stop()
150
151			var count int64
152			err := iter.Do(func(row *Row) error {
153				count++
154				return nil
155			})
156			if err != nil {
157				return
158			}
159
160			mu.Lock()
161			total += count
162			mu.Unlock()
163			wg.Done()
164		}()
165		wg.Add(1)
166	}
167
168	wg.Wait()
169	if g, w := total, SelectSingerIDAlbumIDAlbumTitleFromAlbumsRowCount; g != w {
170		t.Errorf("Row count mismatch\nGot: %d\nWant: %d", g, w)
171	}
172}
173