-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathclient_side_statement.go
373 lines (334 loc) · 13.8 KB
/
client_side_statement.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
// Copyright 2021 Google LLC All Rights Reserved.
//
// 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 spannerdriver
import (
"context"
"database/sql/driver"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"time"
"cloud.google.com/go/spanner"
"cloud.google.com/go/spanner/apiv1/spannerpb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// statementExecutor is an empty struct that is used to hold the execution methods
// of the different client side statements. This makes it possible to look up the
// methods using reflection, which is not possible if the methods do not belong to
// a struct. The methods all accept the same arguments and return the same types.
// This is to ensure that they can be assigned to a compiled clientSideStatement.
//
// The different methods of statementExecutor are invoked by a connection when one
// of the valid client side statements is executed on a connection. These methods
// are responsible for any argument parsing and translating that might be needed
// before the corresponding method on the connection can be called.
//
// The names of the methods are exactly equal to the naming in the
// client_side_statements.json file. This means that some methods do not adhere
// to the Go style guide, as these method names are equal for all languages that
// implement the Connection API.
type statementExecutor struct {
}
func (s *statementExecutor) ShowCommitTimestamp(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
ts, err := c.CommitTimestamp()
var commitTs *time.Time
if err == nil {
commitTs = &ts
}
it, err := createTimestampIterator("CommitTimestamp", commitTs)
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowRetryAbortsInternally(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createBooleanIterator("RetryAbortsInternally", c.RetryAbortsInternally())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowAutocommitDmlMode(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createStringIterator("AutocommitDMLMode", c.AutocommitDMLMode().String())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowReadOnlyStaleness(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createStringIterator("ReadOnlyStaleness", c.ReadOnlyStaleness().String())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowExcludeTxnFromChangeStreams(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createBooleanIterator("ExcludeTxnFromChangeStreams", c.ExcludeTxnFromChangeStreams())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowMaxCommitDelay(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createStringIterator("MaxCommitDelay", c.MaxCommitDelay().String())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowTransactionTag(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createStringIterator("TransactionTag", c.TransactionTag())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) ShowStatementTag(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Rows, error) {
it, err := createStringIterator("StatementTag", c.StatementTag())
if err != nil {
return nil, err
}
return &rows{it: it}, nil
}
func (s *statementExecutor) StartBatchDdl(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Result, error) {
return c.startBatchDDL()
}
func (s *statementExecutor) StartBatchDml(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Result, error) {
return c.startBatchDML()
}
func (s *statementExecutor) RunBatch(ctx context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Result, error) {
return c.runBatch(ctx)
}
func (s *statementExecutor) AbortBatch(_ context.Context, c *conn, _ string, _ []driver.NamedValue) (driver.Result, error) {
return c.abortBatch()
}
func (s *statementExecutor) SetRetryAbortsInternally(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
if params == "" {
return nil, spanner.ToSpannerError(status.Error(codes.InvalidArgument, "no value given for RetryAbortsInternally"))
}
retry, err := strconv.ParseBool(params)
if err != nil {
return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid boolean value: %s", params))
}
return c.setRetryAbortsInternally(retry)
}
func (s *statementExecutor) SetAutocommitDmlMode(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
if params == "" {
return nil, spanner.ToSpannerError(status.Error(codes.InvalidArgument, "no value given for AutocommitDMLMode"))
}
var mode AutocommitDMLMode
switch strings.ToUpper(params) {
case fmt.Sprintf("'%s'", strings.ToUpper(Transactional.String())):
mode = Transactional
case fmt.Sprintf("'%s'", strings.ToUpper(PartitionedNonAtomic.String())):
mode = PartitionedNonAtomic
default:
return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid AutocommitDMLMode value: %s", params))
}
return c.setAutocommitDMLMode(mode)
}
func (s *statementExecutor) SetExcludeTxnFromChangeStreams(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
if params == "" {
return nil, spanner.ToSpannerError(status.Error(codes.InvalidArgument, "no value given for ExcludeTxnFromChangeStreams"))
}
exclude, err := strconv.ParseBool(params)
if err != nil {
return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid boolean value: %s", params))
}
return c.setExcludeTxnFromChangeStreams(exclude)
}
var maxCommitDelayRegexp = regexp.MustCompile(`(?i)^\s*('(?P<duration>(\d{1,19})(s|ms|us|ns))'|(?P<number>\d{1,19})|(?P<null>NULL))\s*$`)
func (s *statementExecutor) SetMaxCommitDelay(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
duration, err := parseDuration(maxCommitDelayRegexp, "max_commit_delay", params)
if err != nil {
return nil, err
}
return c.setMaxCommitDelay(duration)
}
func (s *statementExecutor) SetTransactionTag(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
tag, err := parseTag(params)
if err != nil {
return nil, err
}
return c.setTransactionTag(tag)
}
func (s *statementExecutor) SetStatementTag(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
tag, err := parseTag(params)
if err != nil {
return nil, err
}
return c.setStatementTag(tag)
}
func parseTag(params string) (string, error) {
if params == "" {
return "", spanner.ToSpannerError(status.Error(codes.InvalidArgument, "no value given for tag"))
}
tag := strings.TrimSpace(params)
if !(strings.HasPrefix(tag, "'") && strings.HasSuffix(tag, "'")) {
return "", spanner.ToSpannerError(status.Error(codes.InvalidArgument, "missing single quotes around tag"))
}
tag = strings.TrimLeft(tag, "'")
tag = strings.TrimRight(tag, "'")
return tag, nil
}
var strongRegexp = regexp.MustCompile("(?i)'STRONG'")
var exactStalenessRegexp = regexp.MustCompile(`(?i)'(?P<type>EXACT_STALENESS)[\t ]+(?P<duration>(\d{1,19})(s|ms|us|ns))'`)
var maxStalenessRegexp = regexp.MustCompile(`(?i)'(?P<type>MAX_STALENESS)[\t ]+(?P<duration>(\d{1,19})(s|ms|us|ns))'`)
var readTimestampRegexp = regexp.MustCompile(`(?i)'(?P<type>READ_TIMESTAMP)[\t ]+(?P<timestamp>(\d{4})-(\d{2})-(\d{2})([Tt](\d{2}):(\d{2}):(\d{2})(\.\d{1,9})?)([Zz]|([+-])(\d{2}):(\d{2})))'`)
var minReadTimestampRegexp = regexp.MustCompile(`(?i)'(?P<type>MIN_READ_TIMESTAMP)[\t ]+(?P<timestamp>(\d{4})-(\d{2})-(\d{2})([Tt](\d{2}):(\d{2}):(\d{2})(\.\d{1,9})?)([Zz]|([+-])(\d{2}):(\d{2})))'`)
func (s *statementExecutor) SetReadOnlyStaleness(_ context.Context, c *conn, params string, _ []driver.NamedValue) (driver.Result, error) {
if params == "" {
return nil, spanner.ToSpannerError(status.Error(codes.InvalidArgument, "no value given for ReadOnlyStaleness"))
}
invalidErr := spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid ReadOnlyStaleness value: %s", params))
var staleness spanner.TimestampBound
if strongRegexp.MatchString(params) {
staleness = spanner.StrongRead()
} else if exactStalenessRegexp.MatchString(params) {
d, err := parseDuration(exactStalenessRegexp, "staleness", params)
if err != nil {
return nil, err
}
staleness = spanner.ExactStaleness(d)
} else if maxStalenessRegexp.MatchString(params) {
d, err := parseDuration(maxStalenessRegexp, "staleness", params)
if err != nil {
return nil, err
}
staleness = spanner.MaxStaleness(d)
} else if readTimestampRegexp.MatchString(params) {
t, err := parseTimestamp(readTimestampRegexp, params)
if err != nil {
return nil, err
}
staleness = spanner.ReadTimestamp(t)
} else if minReadTimestampRegexp.MatchString(params) {
t, err := parseTimestamp(minReadTimestampRegexp, params)
if err != nil {
return nil, err
}
staleness = spanner.MinReadTimestamp(t)
} else {
return nil, invalidErr
}
return c.setReadOnlyStaleness(staleness)
}
func parseDuration(re *regexp.Regexp, name, params string) (time.Duration, error) {
matches := matchesToMap(re, params)
if matches["duration"] == "" && matches["number"] == "" && matches["null"] == "" {
return 0, spanner.ToSpannerError(status.Error(codes.InvalidArgument, fmt.Sprintf("No duration found in %s string: %v", name, params)))
}
if matches["duration"] != "" {
d, err := time.ParseDuration(matches["duration"])
if err != nil {
return 0, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "Invalid duration: %s", matches["duration"]))
}
return d, nil
} else if matches["number"] != "" {
d, err := strconv.Atoi(matches["number"])
if err != nil {
return 0, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "Invalid duration: %s", matches["number"]))
}
return time.Millisecond * time.Duration(d), nil
} else if matches["null"] != "" {
return time.Duration(0), nil
}
return time.Duration(0), spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "Unrecognized duration: %s", params))
}
func parseTimestamp(re *regexp.Regexp, params string) (time.Time, error) {
matches := matchesToMap(re, params)
if matches["timestamp"] == "" {
return time.Time{}, spanner.ToSpannerError(status.Error(codes.InvalidArgument, "No timestamp found in staleness string"))
}
t, err := time.Parse(time.RFC3339Nano, matches["timestamp"])
if err != nil {
return time.Time{}, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "Invalid timestamp: %s", matches["timestamp"]))
}
return t, nil
}
func matchesToMap(re *regexp.Regexp, s string) map[string]string {
matches := make(map[string]string)
match := re.FindStringSubmatch(s)
if match == nil {
return matches
}
for i, name := range re.SubexpNames() {
if i != 0 && name != "" {
matches[name] = match[i]
}
}
return matches
}
// createBooleanIterator creates a row iterator with a single BOOL column with
// one row. This is used for client side statements that return a result set
// containing a BOOL value.
func createBooleanIterator(column string, value bool) (*clientSideIterator, error) {
return createSingleValueIterator(column, value, spannerpb.TypeCode_BOOL)
}
// createStringIterator creates a row iterator with a single STRING column with
// one row. This is used for client side statements that return a result set
// containing a STRING value.
func createStringIterator(column string, value string) (*clientSideIterator, error) {
return createSingleValueIterator(column, value, spannerpb.TypeCode_STRING)
}
// createTimestampIterator creates a row iterator with a single TIMESTAMP column with
// one row. This is used for client side statements that return a result set
// containing a TIMESTAMP value.
func createTimestampIterator(column string, value *time.Time) (*clientSideIterator, error) {
return createSingleValueIterator(column, value, spannerpb.TypeCode_TIMESTAMP)
}
func createSingleValueIterator(column string, value interface{}, code spannerpb.TypeCode) (*clientSideIterator, error) {
row, err := spanner.NewRow([]string{column}, []interface{}{value})
if err != nil {
return nil, err
}
return &clientSideIterator{
metadata: &spannerpb.ResultSetMetadata{
RowType: &spannerpb.StructType{
Fields: []*spannerpb.StructType_Field{
{Name: column, Type: &spannerpb.Type{Code: code}},
},
},
},
rows: []*spanner.Row{row},
}, nil
}
// clientSideIterator implements the rowIterator interface for client side
// statements. All values are created and kept in memory, and this struct
// should only be used for small result sets.
type clientSideIterator struct {
metadata *spannerpb.ResultSetMetadata
rows []*spanner.Row
index int
stopped bool
}
func (t *clientSideIterator) Next() (*spanner.Row, error) {
if t.index == len(t.rows) {
return nil, io.EOF
}
row := t.rows[t.index]
t.index++
return row, nil
}
func (t *clientSideIterator) Stop() {
t.stopped = true
t.rows = nil
t.metadata = nil
}
func (t *clientSideIterator) Metadata() *spannerpb.ResultSetMetadata {
return t.metadata
}