This repository was archived by the owner on Apr 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathDmlBatch.java
More file actions
361 lines (320 loc) · 12.7 KB
/
Copy pathDmlBatch.java
File metadata and controls
361 lines (320 loc) · 12.7 KB
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
/*
* 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.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.core.SettableApiFuture;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.CommitResponse;
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.Options.UpdateOption;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.cloud.spanner.connection.AbstractStatementParser.ParsedStatement;
import com.google.cloud.spanner.connection.AbstractStatementParser.StatementType;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.MoreExecutors;
import io.opentelemetry.context.Scope;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
/**
* {@link UnitOfWork} that is used when a DML batch is started. These batches only accept DML
* statements. All DML statements are buffered locally and sent to Spanner when runBatch() is
* called.
*/
class DmlBatch extends AbstractBaseUnitOfWork {
private final boolean autoBatch;
private final Supplier<Long> autoBatchUpdateCountSupplier;
private final Supplier<Boolean> verifyUpdateCountsSupplier;
private final Supplier<Long> dmlbatchUpdateCountSupplier;
private final UnitOfWork transaction;
private final String statementTag;
private final List<ParsedStatement> statements = new ArrayList<>();
private long[] updateCounts = new long[0];
private UnitOfWorkState state = UnitOfWorkState.STARTED;
static class Builder extends AbstractBaseUnitOfWork.Builder<Builder, DmlBatch> {
private boolean autoBatch;
private Supplier<Long> autoBatchUpdateCountSupplier = Suppliers.ofInstance(1L);
private Supplier<Boolean> verifyUpdateCountsSupplier = Suppliers.ofInstance(Boolean.FALSE);
private Supplier<Long> dmlbatchUpdateCountSupplier = Suppliers.ofInstance(-1L);
private UnitOfWork transaction;
private String statementTag;
private Builder() {}
Builder setAutoBatch(boolean autoBatch) {
this.autoBatch = autoBatch;
return this;
}
Builder setAutoBatchUpdateCountSupplier(Supplier<Long> updateCountSupplier) {
this.autoBatchUpdateCountSupplier = Preconditions.checkNotNull(updateCountSupplier);
return this;
}
Builder setAutoBatchUpdateCountVerificationSupplier(Supplier<Boolean> verificationSupplier) {
this.verifyUpdateCountsSupplier = verificationSupplier;
return this;
}
Builder setDmlBatchUpdateCountSupplier(Supplier<Long> dmlbatchUpdateCountSupplier) {
Preconditions.checkNotNull(dmlbatchUpdateCountSupplier);
this.dmlbatchUpdateCountSupplier = dmlbatchUpdateCountSupplier;
return this;
}
Builder setTransaction(UnitOfWork transaction) {
Preconditions.checkNotNull(transaction);
this.transaction = transaction;
return this;
}
Builder setStatementTag(String tag) {
this.statementTag = tag;
return this;
}
@Override
DmlBatch build() {
Preconditions.checkState(transaction != null, "No transaction specified");
return new DmlBatch(this);
}
}
static Builder newBuilder() {
return new Builder();
}
private DmlBatch(Builder builder) {
super(builder);
this.autoBatch = builder.autoBatch;
this.autoBatchUpdateCountSupplier = builder.autoBatchUpdateCountSupplier;
this.verifyUpdateCountsSupplier = builder.verifyUpdateCountsSupplier;
this.dmlbatchUpdateCountSupplier = builder.dmlbatchUpdateCountSupplier;
this.transaction = Preconditions.checkNotNull(builder.transaction);
this.statementTag = builder.statementTag;
}
boolean isAutoBatch() {
return this.autoBatch;
}
@Override
public boolean isSingleUse() {
return false;
}
@Override
public Type getType() {
return Type.BATCH;
}
@Override
public UnitOfWorkState getState() {
return this.state;
}
@Override
public boolean isActive() {
return getState().isActive();
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public ApiFuture<ResultSet> executeQueryAsync(
CallType callType,
ParsedStatement statement,
AnalyzeMode analyzeMode,
QueryOption... options) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Executing queries is not allowed for DML batches.");
}
@Override
public Timestamp getReadTimestamp() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "There is no read timestamp available for DML batches.");
}
@Override
public Timestamp getReadTimestampOrNull() {
return null;
}
@Override
public Timestamp getCommitTimestamp() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "There is no commit timestamp available for DML batches.");
}
@Override
public Timestamp getCommitTimestampOrNull() {
return null;
}
@Override
public CommitResponse getCommitResponse() {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "There is no commit response available for DML batches.");
}
@Override
public CommitResponse getCommitResponseOrNull() {
return null;
}
@Override
public ApiFuture<Void> executeDdlAsync(CallType callType, ParsedStatement ddl) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Executing DDL statements is not allowed for DML batches.");
}
long getUpdateCount() {
// Auto-batching returns update count 1 by default, as this is what ORMs normally expect.
// Standard batches return -1 by default, to indicate that the update count is unknown.
return isAutoBatch() ? autoBatchUpdateCountSupplier.get() : dmlbatchUpdateCountSupplier.get();
}
@Override
public ApiFuture<Long> executeUpdateAsync(
CallType callType, ParsedStatement update, UpdateOption... options) {
ConnectionPreconditions.checkState(
state == UnitOfWorkState.STARTED,
"The batch is no longer active and cannot be used for further statements");
Preconditions.checkArgument(
update.getType() == StatementType.UPDATE,
"Only DML statements are allowed. \"" + update.getSql() + "\" is not a DML-statement.");
long updateCount = getUpdateCount();
this.statements.add(update);
this.updateCounts = Arrays.copyOf(this.updateCounts, this.updateCounts.length + 1);
this.updateCounts[this.updateCounts.length - 1] = updateCount;
return ApiFutures.immediateFuture(updateCount);
}
@Override
public ApiFuture<ResultSet> analyzeUpdateAsync(
CallType callType, ParsedStatement update, AnalyzeMode analyzeMode, UpdateOption... options) {
if (transaction.isSingleUse()) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Analyzing updates is not allowed for DML batches.");
}
return transaction.analyzeUpdateAsync(callType, update, analyzeMode, options);
}
@Override
public ApiFuture<long[]> executeBatchUpdateAsync(
CallType callType, Iterable<ParsedStatement> updates, UpdateOption... options) {
ConnectionPreconditions.checkState(
state == UnitOfWorkState.STARTED,
"The batch is no longer active and cannot be used for further statements");
for (ParsedStatement update : updates) {
Preconditions.checkArgument(
update.getType() == StatementType.UPDATE,
"Only DML statements are allowed. \"" + update.getSql() + "\" is not a DML-statement.");
}
long[] updateCountArray = new long[Iterables.size(updates)];
Arrays.fill(updateCountArray, getUpdateCount());
Iterables.addAll(this.statements, updates);
this.updateCounts =
Arrays.copyOf(this.updateCounts, this.updateCounts.length + updateCountArray.length);
System.arraycopy(
updateCountArray,
0,
this.updateCounts,
this.updateCounts.length - updateCountArray.length,
updateCountArray.length);
return ApiFutures.immediateFuture(updateCountArray);
}
@Override
public ApiFuture<Void> writeAsync(CallType callType, Iterable<Mutation> mutations) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Writing mutations is not allowed for DML batches.");
}
@Override
public ApiFuture<long[]> runBatchAsync(CallType callType) {
ConnectionPreconditions.checkState(
state == UnitOfWorkState.STARTED, "The batch is no longer active and cannot be ran");
try (Scope ignore = span.makeCurrent()) {
if (statements.isEmpty()) {
this.state = UnitOfWorkState.RAN;
return ApiFutures.immediateFuture(new long[0]);
}
this.state = UnitOfWorkState.RUNNING;
// Use a SettableApiFuture to return the result, instead of directly returning the future that
// is returned by the executeBatchUpdateAsync method. This is needed because the state of the
// batch is set after the update has finished, and this happens in a listener. A listener is
// executed AFTER a Future is done, which means that a user could read the state of the Batch
// before it has been changed.
final SettableApiFuture<long[]> res = SettableApiFuture.create();
int numOptions = 0;
if (statementTag != null) {
numOptions++;
}
if (this.rpcPriority != null) {
numOptions++;
}
UpdateOption[] options = new UpdateOption[numOptions];
int index = 0;
if (statementTag != null) {
options[index++] = Options.tag(statementTag);
}
if (this.rpcPriority != null) {
options[index++] = Options.priority(this.rpcPriority);
}
ApiFuture<long[]> updateCounts =
transaction.executeBatchUpdateAsync(callType, statements, options);
ApiFutures.addCallback(
updateCounts,
new ApiFutureCallback<long[]>() {
@Override
public void onFailure(Throwable t) {
state = UnitOfWorkState.RUN_FAILED;
res.setException(t);
}
@Override
public void onSuccess(long[] result) {
state = UnitOfWorkState.RAN;
if (!verifyUpdateCounts(result)) {
res.setException(
SpannerExceptionFactory.newDmlBatchUpdateCountVerificationFailedException(
DmlBatch.this.updateCounts, result));
} else {
res.set(result);
}
}
},
MoreExecutors.directExecutor());
asyncEndUnitOfWorkSpan();
return res;
}
}
private boolean verifyUpdateCounts(long[] actualUpdateCounts) {
if (!this.autoBatch || !this.verifyUpdateCountsSupplier.get()) {
// We only need to do an actual verification if the batch was an auto-batch and verification
// is enabled.
return true;
}
return Arrays.equals(this.updateCounts, actualUpdateCounts);
}
@Override
public void abortBatch() {
ConnectionPreconditions.checkState(
state == UnitOfWorkState.STARTED, "The batch is no longer active and cannot be aborted.");
asyncEndUnitOfWorkSpan();
this.state = UnitOfWorkState.ABORTED;
}
@Override
public ApiFuture<Void> commitAsync(
@Nonnull CallType callType, @Nonnull EndTransactionCallback callback) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Commit is not allowed for DML batches.");
}
@Override
public ApiFuture<Void> rollbackAsync(
@Nonnull CallType callType, @Nonnull EndTransactionCallback callback) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.FAILED_PRECONDITION, "Rollback is not allowed for DML batches.");
}
@Override
String getUnitOfWorkName() {
return "DML batch";
}
}