/
SingleUseTransaction.java
486 lines (440 loc) · 17.1 KB
/
SingleUseTransaction.java
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
/*
* 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.
*/
package com.google.cloud.spanner.connection;
import com.google.api.core.ApiFuture;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.CommitResponse;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Options;
import com.google.cloud.spanner.Options.QueryOption;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerApiFutures;
import com.google.cloud.spanner.SpannerBatchUpdateException;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionRunner;
import com.google.cloud.spanner.connection.StatementParser.ParsedStatement;
import com.google.cloud.spanner.connection.StatementParser.StatementType;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.spanner.admin.database.v1.DatabaseAdminGrpc;
import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata;
import com.google.spanner.v1.SpannerGrpc;
import io.grpc.MethodDescriptor;
import java.util.concurrent.Callable;
/**
* Transaction that is used when a {@link Connection} is in autocommit mode. Each method on this
* transaction actually starts a new transaction on Spanner. The type of transaction that is started
* depends on the type of statement that is being executed. A {@link SingleUseTransaction} will
* always try to choose the most efficient type of one-time transaction that is available for the
* statement.
*
* <p>A {@link SingleUseTransaction} can be used to execute any type of statement on Cloud Spanner:
*
* <ul>
* <li>Client side statements, e.g. SHOW VARIABLE AUTOCOMMIT
* <li>Queries, e.g. SELECT * FROM FOO
* <li>DML statements, e.g. UPDATE FOO SET BAR=1
* <li>DDL statements, e.g. CREATE TABLE FOO (...)
* </ul>
*/
class SingleUseTransaction extends AbstractBaseUnitOfWork {
private final boolean readOnly;
private final DdlClient ddlClient;
private final DatabaseClient dbClient;
private final TimestampBound readOnlyStaleness;
private final AutocommitDmlMode autocommitDmlMode;
private final boolean returnCommitStats;
private volatile SettableApiFuture<Timestamp> readTimestamp = null;
private volatile TransactionRunner writeTransaction;
private boolean used = false;
private volatile UnitOfWorkState state = UnitOfWorkState.STARTED;
static class Builder extends AbstractBaseUnitOfWork.Builder<Builder, SingleUseTransaction> {
private DdlClient ddlClient;
private DatabaseClient dbClient;
private boolean readOnly;
private TimestampBound readOnlyStaleness;
private AutocommitDmlMode autocommitDmlMode;
private boolean returnCommitStats;
private Builder() {}
Builder setDdlClient(DdlClient ddlClient) {
Preconditions.checkNotNull(ddlClient);
this.ddlClient = ddlClient;
return this;
}
Builder setDatabaseClient(DatabaseClient client) {
Preconditions.checkNotNull(client);
this.dbClient = client;
return this;
}
Builder setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
return this;
}
Builder setReadOnlyStaleness(TimestampBound staleness) {
Preconditions.checkNotNull(staleness);
this.readOnlyStaleness = staleness;
return this;
}
Builder setAutocommitDmlMode(AutocommitDmlMode dmlMode) {
Preconditions.checkNotNull(dmlMode);
this.autocommitDmlMode = dmlMode;
return this;
}
Builder setReturnCommitStats(boolean returnCommitStats) {
this.returnCommitStats = returnCommitStats;
return this;
}
@Override
SingleUseTransaction build() {
Preconditions.checkState(ddlClient != null, "No DDL client specified");
Preconditions.checkState(dbClient != null, "No DatabaseClient client specified");
Preconditions.checkState(readOnlyStaleness != null, "No read-only staleness specified");
Preconditions.checkState(autocommitDmlMode != null, "No autocommit dml mode specified");
return new SingleUseTransaction(this);
}
}
static Builder newBuilder() {
return new Builder();
}
private SingleUseTransaction(Builder builder) {
super(builder);
this.ddlClient = builder.ddlClient;
this.dbClient = builder.dbClient;
this.readOnly = builder.readOnly;
this.readOnlyStaleness = builder.readOnlyStaleness;
this.autocommitDmlMode = builder.autocommitDmlMode;
this.returnCommitStats = builder.returnCommitStats;
}
@Override
public Type getType() {
return Type.TRANSACTION;
}
@Override
public UnitOfWorkState getState() {
return state;
}
@Override
public boolean isActive() {
// Single-use transactions are never active as they can be used only once.
return false;
}
@Override
public boolean isReadOnly() {
return readOnly;
}
private void checkAndMarkUsed() {
Preconditions.checkState(!used, "This single-use transaction has already been used");
used = true;
}
@Override
public ApiFuture<ResultSet> executeQueryAsync(
final ParsedStatement statement,
final AnalyzeMode analyzeMode,
final QueryOption... options) {
Preconditions.checkNotNull(statement);
Preconditions.checkArgument(statement.isQuery(), "Statement is not a query");
checkAndMarkUsed();
final ReadOnlyTransaction currentTransaction =
dbClient.singleUseReadOnlyTransaction(readOnlyStaleness);
Callable<ResultSet> callable =
new Callable<ResultSet>() {
@Override
public ResultSet call() throws Exception {
try {
ResultSet rs;
if (analyzeMode == AnalyzeMode.NONE) {
rs = currentTransaction.executeQuery(statement.getStatement(), options);
} else {
rs =
currentTransaction.analyzeQuery(
statement.getStatement(), analyzeMode.getQueryAnalyzeMode());
}
// Return a DirectExecuteResultSet, which will directly do a next() call in order to
// ensure that the query is actually sent to Spanner.
ResultSet directRs = DirectExecuteResultSet.ofResultSet(rs);
state = UnitOfWorkState.COMMITTED;
readTimestamp.set(currentTransaction.getReadTimestamp());
return directRs;
} catch (Throwable t) {
state = UnitOfWorkState.COMMIT_FAILED;
readTimestamp.set(null);
currentTransaction.close();
throw t;
}
}
};
readTimestamp = SettableApiFuture.create();
ApiFuture<ResultSet> res =
executeStatementAsync(statement, callable, SpannerGrpc.getExecuteStreamingSqlMethod());
return res;
}
@Override
public Timestamp getReadTimestamp() {
ConnectionPreconditions.checkState(
SpannerApiFutures.getOrNull(readTimestamp) != null,
"There is no read timestamp available for this transaction.");
return SpannerApiFutures.get(readTimestamp);
}
@Override
public Timestamp getReadTimestampOrNull() {
return SpannerApiFutures.getOrNull(readTimestamp);
}
private boolean hasCommitResponse() {
return state == UnitOfWorkState.COMMITTED && writeTransaction != null;
}
@Override
public Timestamp getCommitTimestamp() {
ConnectionPreconditions.checkState(
hasCommitResponse(), "There is no commit timestamp available for this transaction.");
return getCommitResponse().getCommitTimestamp();
}
@Override
public Timestamp getCommitTimestampOrNull() {
CommitResponse response = getCommitResponseOrNull();
return response == null ? null : response.getCommitTimestamp();
}
@Override
public CommitResponse getCommitResponse() {
ConnectionPreconditions.checkState(
hasCommitResponse(), "There is no commit response available for this transaction.");
return writeTransaction.getCommitResponse();
}
@Override
public CommitResponse getCommitResponseOrNull() {
if (hasCommitResponse()) {
try {
return writeTransaction.getCommitResponse();
} catch (SpannerException e) {
// ignore
}
}
return null;
}
@Override
public ApiFuture<Void> executeDdlAsync(final ParsedStatement ddl) {
Preconditions.checkNotNull(ddl);
Preconditions.checkArgument(
ddl.getType() == StatementType.DDL, "Statement is not a ddl statement");
ConnectionPreconditions.checkState(
!isReadOnly(), "DDL statements are not allowed in read-only mode");
checkAndMarkUsed();
Callable<Void> callable =
new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
OperationFuture<Void, UpdateDatabaseDdlMetadata> operation =
ddlClient.executeDdl(ddl.getSqlWithoutComments());
Void res = getWithStatementTimeout(operation, ddl);
state = UnitOfWorkState.COMMITTED;
return res;
} catch (Throwable t) {
state = UnitOfWorkState.COMMIT_FAILED;
throw t;
}
}
};
return executeStatementAsync(ddl, callable, DatabaseAdminGrpc.getUpdateDatabaseDdlMethod());
}
@Override
public ApiFuture<Long> executeUpdateAsync(ParsedStatement update) {
Preconditions.checkNotNull(update);
Preconditions.checkArgument(update.isUpdate(), "Statement is not an update statement");
ConnectionPreconditions.checkState(
!isReadOnly(), "Update statements are not allowed in read-only mode");
checkAndMarkUsed();
ApiFuture<Long> res;
switch (autocommitDmlMode) {
case TRANSACTIONAL:
res = executeTransactionalUpdateAsync(update);
break;
case PARTITIONED_NON_ATOMIC:
res = executePartitionedUpdateAsync(update);
break;
default:
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Unknown dml mode: " + autocommitDmlMode);
}
return res;
}
private final ParsedStatement executeBatchUpdateStatement =
StatementParser.INSTANCE.parse(Statement.of("RUN BATCH"));
@Override
public ApiFuture<long[]> executeBatchUpdateAsync(Iterable<ParsedStatement> updates) {
Preconditions.checkNotNull(updates);
for (ParsedStatement update : updates) {
Preconditions.checkArgument(
update.isUpdate(),
"Statement is not an update statement: " + update.getSqlWithoutComments());
}
ConnectionPreconditions.checkState(
!isReadOnly(), "Batch update statements are not allowed in read-only mode");
checkAndMarkUsed();
switch (autocommitDmlMode) {
case TRANSACTIONAL:
return executeTransactionalBatchUpdateAsync(updates);
case PARTITIONED_NON_ATOMIC:
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Batch updates are not allowed in " + autocommitDmlMode);
default:
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Unknown dml mode: " + autocommitDmlMode);
}
}
private TransactionRunner createWriteTransaction() {
return returnCommitStats
? dbClient.readWriteTransaction(Options.commitStats())
: dbClient.readWriteTransaction();
}
private ApiFuture<Long> executeTransactionalUpdateAsync(final ParsedStatement update) {
Callable<Long> callable =
new Callable<Long>() {
@Override
public Long call() throws Exception {
try {
writeTransaction = createWriteTransaction();
Long res =
writeTransaction.run(
transaction -> transaction.executeUpdate(update.getStatement()));
state = UnitOfWorkState.COMMITTED;
return res;
} catch (Throwable t) {
state = UnitOfWorkState.COMMIT_FAILED;
throw t;
}
}
};
return executeStatementAsync(
update,
callable,
ImmutableList.<MethodDescriptor<?, ?>>of(
SpannerGrpc.getExecuteSqlMethod(), SpannerGrpc.getCommitMethod()));
}
private ApiFuture<Long> executePartitionedUpdateAsync(final ParsedStatement update) {
Callable<Long> callable =
new Callable<Long>() {
@Override
public Long call() throws Exception {
try {
Long res = dbClient.executePartitionedUpdate(update.getStatement());
state = UnitOfWorkState.COMMITTED;
return res;
} catch (Throwable t) {
state = UnitOfWorkState.COMMIT_FAILED;
throw t;
}
}
};
return executeStatementAsync(update, callable, SpannerGrpc.getExecuteStreamingSqlMethod());
}
private ApiFuture<long[]> executeTransactionalBatchUpdateAsync(
final Iterable<ParsedStatement> updates) {
Callable<long[]> callable =
new Callable<long[]>() {
@Override
public long[] call() throws Exception {
writeTransaction = createWriteTransaction();
return writeTransaction.run(
transaction -> {
try {
long[] res =
transaction.batchUpdate(
Iterables.transform(
updates,
new Function<ParsedStatement, Statement>() {
@Override
public Statement apply(ParsedStatement input) {
return input.getStatement();
}
}));
state = UnitOfWorkState.COMMITTED;
return res;
} catch (Throwable t) {
if (t instanceof SpannerBatchUpdateException) {
// Batch update exceptions does not cause a rollback.
state = UnitOfWorkState.COMMITTED;
} else {
state = UnitOfWorkState.COMMIT_FAILED;
}
throw t;
}
});
}
};
return executeStatementAsync(
executeBatchUpdateStatement, callable, SpannerGrpc.getExecuteBatchDmlMethod());
}
private final ParsedStatement commitStatement =
StatementParser.INSTANCE.parse(Statement.of("COMMIT"));
@Override
public ApiFuture<Void> writeAsync(final Iterable<Mutation> mutations) {
Preconditions.checkNotNull(mutations);
ConnectionPreconditions.checkState(
!isReadOnly(), "Update statements are not allowed in read-only mode");
checkAndMarkUsed();
Callable<Void> callable =
new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
writeTransaction = createWriteTransaction();
Void res =
writeTransaction.run(
transaction -> {
transaction.buffer(mutations);
return null;
});
state = UnitOfWorkState.COMMITTED;
return res;
} catch (Throwable t) {
state = UnitOfWorkState.COMMIT_FAILED;
throw t;
}
}
};
return executeStatementAsync(commitStatement, callable, SpannerGrpc.getCommitMethod());
}
@Override
public ApiFuture<Void> commitAsync() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Commit is not supported for single-use transactions");
}
@Override
public ApiFuture<Void> rollbackAsync() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Rollback is not supported for single-use transactions");
}
@Override
public ApiFuture<long[]> runBatchAsync() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Run batch is not supported for single-use transactions");
}
@Override
public void abortBatch() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Run batch is not supported for single-use transactions");
}
}