-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathConnectionImpl.java
More file actions
2449 lines (2220 loc) · 98 KB
/
ConnectionImpl.java
File metadata and controls
2449 lines (2220 loc) · 98 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
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.
*/
package com.google.cloud.spanner.connection;
import static com.google.cloud.spanner.SpannerApiFutures.get;
import static com.google.cloud.spanner.connection.ConnectionOptions.isEnableTransactionalConnectionStateForPostgreSQL;
import static com.google.cloud.spanner.connection.ConnectionPreconditions.checkValidIdentifier;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTOCOMMIT;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTOCOMMIT_DML_MODE;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTO_BATCH_DML;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTO_BATCH_DML_UPDATE_COUNT;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION;
import static com.google.cloud.spanner.connection.ConnectionProperties.AUTO_PARTITION_MODE;
import static com.google.cloud.spanner.connection.ConnectionProperties.DATA_BOOST_ENABLED;
import static com.google.cloud.spanner.connection.ConnectionProperties.DDL_IN_TRANSACTION_MODE;
import static com.google.cloud.spanner.connection.ConnectionProperties.DEFAULT_ISOLATION_LEVEL;
import static com.google.cloud.spanner.connection.ConnectionProperties.DEFAULT_SEQUENCE_KIND;
import static com.google.cloud.spanner.connection.ConnectionProperties.DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE;
import static com.google.cloud.spanner.connection.ConnectionProperties.DIRECTED_READ;
import static com.google.cloud.spanner.connection.ConnectionProperties.KEEP_TRANSACTION_ALIVE;
import static com.google.cloud.spanner.connection.ConnectionProperties.MAX_COMMIT_DELAY;
import static com.google.cloud.spanner.connection.ConnectionProperties.MAX_PARTITIONED_PARALLELISM;
import static com.google.cloud.spanner.connection.ConnectionProperties.MAX_PARTITIONS;
import static com.google.cloud.spanner.connection.ConnectionProperties.OPTIMIZER_STATISTICS_PACKAGE;
import static com.google.cloud.spanner.connection.ConnectionProperties.OPTIMIZER_VERSION;
import static com.google.cloud.spanner.connection.ConnectionProperties.READONLY;
import static com.google.cloud.spanner.connection.ConnectionProperties.READ_ONLY_STALENESS;
import static com.google.cloud.spanner.connection.ConnectionProperties.RETRY_ABORTS_INTERNALLY;
import static com.google.cloud.spanner.connection.ConnectionProperties.RETURN_COMMIT_STATS;
import static com.google.cloud.spanner.connection.ConnectionProperties.RPC_PRIORITY;
import static com.google.cloud.spanner.connection.ConnectionProperties.SAVEPOINT_SUPPORT;
import static com.google.cloud.spanner.connection.ConnectionProperties.TRACING_PREFIX;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.gax.core.GaxProperties;
import com.google.cloud.ByteArray;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncResultSet;
import com.google.cloud.spanner.BatchClient;
import com.google.cloud.spanner.BatchReadOnlyTransaction;
import com.google.cloud.spanner.CommitResponse;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Dialect;
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.ReadQueryUpdateTransactionOption;
import com.google.cloud.spanner.Options.RpcPriority;
import com.google.cloud.spanner.Options.UpdateOption;
import com.google.cloud.spanner.PartitionOptions;
import com.google.cloud.spanner.ReadContext.QueryAnalyzeMode;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.ResultSets;
import com.google.cloud.spanner.Spanner;
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.TimestampBound.Mode;
import com.google.cloud.spanner.connection.AbstractStatementParser.ParsedStatement;
import com.google.cloud.spanner.connection.AbstractStatementParser.StatementType;
import com.google.cloud.spanner.connection.ConnectionProperty.Context;
import com.google.cloud.spanner.connection.ConnectionState.Type;
import com.google.cloud.spanner.connection.StatementExecutor.StatementExecutorType;
import com.google.cloud.spanner.connection.StatementExecutor.StatementTimeout;
import com.google.cloud.spanner.connection.StatementResult.ResultType;
import com.google.cloud.spanner.connection.UnitOfWork.CallType;
import com.google.cloud.spanner.connection.UnitOfWork.EndTransactionCallback;
import com.google.cloud.spanner.connection.UnitOfWork.UnitOfWorkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.spanner.v1.DirectedReadOptions;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import com.google.spanner.v1.ResultSetStats;
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** Implementation for {@link Connection}, the generic Spanner connection API (not JDBC). */
class ConnectionImpl implements Connection {
private static final String INSTRUMENTATION_SCOPE = "cloud.google.com/java";
private static final String SINGLE_USE_TRANSACTION = "SingleUseTransaction";
private static final String READ_ONLY_TRANSACTION = "ReadOnlyTransaction";
private static final String READ_WRITE_TRANSACTION = "ReadWriteTransaction";
private static final String DDL_BATCH = "DdlBatch";
private static final String DDL_STATEMENT = "DdlStatement";
private static final String CLOSED_ERROR_MSG = "This connection is closed";
private static final String ONLY_ALLOWED_IN_AUTOCOMMIT =
"This method may only be called while in autocommit mode";
private static final String NOT_ALLOWED_IN_AUTOCOMMIT =
"This method may not be called while in autocommit mode";
private static final ParsedStatement COMMIT_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("COMMIT"));
private static final ParsedStatement ROLLBACK_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("ROLLBACK"));
private static final ParsedStatement START_BATCH_DDL_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("START BATCH DDL"));
private static final ParsedStatement START_BATCH_DML_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("START BATCH DML"));
// These SAVEPOINT statements are used as sentinels to recognize the start/rollback/release of a
// savepoint.
private static final ParsedStatement SAVEPOINT_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("SAVEPOINT s1"));
private static final ParsedStatement ROLLBACK_TO_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("ROLLBACK TO s1"));
private static final ParsedStatement RELEASE_STATEMENT =
AbstractStatementParser.getInstance(Dialect.GOOGLE_STANDARD_SQL)
.parse(Statement.of("RELEASE s1"));
/**
* Exception that is used to register the stacktrace of the code that opened a {@link Connection}.
* This exception is logged if the application closes without first closing the connection.
*/
static class LeakedConnectionException extends RuntimeException {
private static final long serialVersionUID = 7119433786832158700L;
private LeakedConnectionException() {
super("Connection was opened at " + Instant.now());
}
}
private volatile LeakedConnectionException leakedException;
private final SpannerPool spannerPool;
private AbstractStatementParser statementParser;
/**
* The {@link ConnectionStatementExecutor} is responsible for translating parsed {@link
* ClientSideStatement}s into actual method calls on this {@link ConnectionImpl}. I.e. the {@link
* ClientSideStatement} 'SET AUTOCOMMIT ON' will be translated into the method call {@link
* ConnectionImpl#setAutocommit(boolean)} with value <code>true</code>.
*/
private final ConnectionStatementExecutor connectionStatementExecutor =
new ConnectionStatementExecutorImpl(this);
/**
* Statements are executed using a separate thread in order to be able to cancel these. Statements
* are automatically cancelled if the configured {@link ConnectionImpl#statementTimeout} is
* exceeded. In autocommit mode, the connection will try to rollback the effects of an update
* statement, but this is not guaranteed to actually succeed.
*/
private final StatementExecutor statementExecutor;
/**
* The {@link ConnectionOptions} that were used to create this {@link ConnectionImpl}. This is
* retained as it is used for getting a {@link Spanner} object and removing this connection from
* the {@link SpannerPool}.
*/
private final ConnectionOptions options;
enum Caller {
APPLICATION,
TRANSACTION_RUNNER,
}
/** The supported batch modes. */
enum BatchMode {
NONE,
DDL,
DML
}
/** The combination of all transaction modes and batch modes. */
enum UnitOfWorkType {
READ_ONLY_TRANSACTION {
@Override
TransactionMode getTransactionMode() {
return TransactionMode.READ_ONLY_TRANSACTION;
}
},
READ_WRITE_TRANSACTION {
@Override
TransactionMode getTransactionMode() {
return TransactionMode.READ_WRITE_TRANSACTION;
}
},
DML_BATCH {
@Override
TransactionMode getTransactionMode() {
return TransactionMode.READ_WRITE_TRANSACTION;
}
},
DDL_BATCH {
@Override
TransactionMode getTransactionMode() {
return null;
}
};
abstract TransactionMode getTransactionMode();
static UnitOfWorkType of(TransactionMode transactionMode) {
switch (transactionMode) {
case READ_ONLY_TRANSACTION:
return UnitOfWorkType.READ_ONLY_TRANSACTION;
case READ_WRITE_TRANSACTION:
return UnitOfWorkType.READ_WRITE_TRANSACTION;
default:
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT, "Unknown transaction mode: " + transactionMode);
}
}
}
private StatementExecutor.StatementTimeout statementTimeout =
new StatementExecutor.StatementTimeout();
private boolean closed = false;
private final Spanner spanner;
private final Tracer tracer;
private final Attributes openTelemetryAttributes;
private final DdlClient ddlClient;
private final DatabaseClient dbClient;
private final BatchClient batchClient;
private final ConnectionState connectionState;
private UnitOfWork currentUnitOfWork = null;
/**
* This field is only used in autocommit mode to indicate that the user has explicitly started a
* transaction.
*/
private boolean inTransaction = false;
/**
* This field is used to indicate that a transaction begin has been indicated. This is done by
* calling beginTransaction or by setting a transaction property while not in autocommit mode.
*/
private boolean transactionBeginMarked = false;
/** This field is set to true when a transaction runner is active for this connection. */
private boolean transactionRunnerActive = false;
private BatchMode batchMode;
private UnitOfWorkType unitOfWorkType;
private final Stack<UnitOfWork> transactionStack = new Stack<>();
private final List<TransactionRetryListener> transactionRetryListeners = new ArrayList<>();
// The following properties are not 'normal' connection properties, but transient properties that
// are automatically reset after executing a transaction or statement.
private IsolationLevel transactionIsolationLevel;
private String transactionTag;
private String statementTag;
private boolean excludeTxnFromChangeStreams;
private byte[] protoDescriptors;
private String protoDescriptorsFilePath;
/** Create a connection and register it in the SpannerPool. */
ConnectionImpl(ConnectionOptions options) {
Preconditions.checkNotNull(options);
this.leakedException =
options.isTrackConnectionLeaks() ? new LeakedConnectionException() : null;
StatementExecutorType statementExecutorType;
if (options.getStatementExecutorType() != null) {
statementExecutorType = options.getStatementExecutorType();
} else {
statementExecutorType =
options.isUseVirtualThreads()
? StatementExecutorType.VIRTUAL_THREAD
: StatementExecutorType.PLATFORM_THREAD;
}
this.statementExecutor =
new StatementExecutor(statementExecutorType, options.getStatementExecutionInterceptors());
this.spannerPool = SpannerPool.INSTANCE;
this.options = options;
this.spanner = spannerPool.getSpanner(options, this);
this.tracer =
spanner
.getOptions()
.getOpenTelemetry()
.getTracer(
INSTRUMENTATION_SCOPE,
GaxProperties.getLibraryVersion(spanner.getOptions().getClass()));
this.openTelemetryAttributes = createOpenTelemetryAttributes(options.getDatabaseId());
if (options.isAutoConfigEmulator()) {
EmulatorUtil.maybeCreateInstanceAndDatabase(
spanner, options.getDatabaseId(), options.getDialect());
}
this.dbClient = spanner.getDatabaseClient(options.getDatabaseId());
this.batchClient = spanner.getBatchClient(options.getDatabaseId());
this.ddlClient = createDdlClient();
this.connectionState =
new ConnectionState(
options.getInitialConnectionPropertyValues(),
Suppliers.memoize(
() ->
isEnableTransactionalConnectionStateForPostgreSQL()
&& getDialect() == Dialect.POSTGRESQL
? Type.TRANSACTIONAL
: Type.NON_TRANSACTIONAL));
// (Re)set the state of the connection to the default.
setDefaultTransactionOptions(getDefaultIsolationLevel());
}
/** Constructor only for test purposes. */
@VisibleForTesting
ConnectionImpl(
ConnectionOptions options,
SpannerPool spannerPool,
DdlClient ddlClient,
DatabaseClient dbClient,
BatchClient batchClient) {
this.leakedException =
options.isTrackConnectionLeaks() ? new LeakedConnectionException() : null;
this.statementExecutor =
new StatementExecutor(
options.isUseVirtualThreads()
? StatementExecutorType.VIRTUAL_THREAD
: StatementExecutorType.PLATFORM_THREAD,
Collections.emptyList());
this.spannerPool = Preconditions.checkNotNull(spannerPool);
this.options = Preconditions.checkNotNull(options);
this.spanner = spannerPool.getSpanner(options, this);
this.tracer = OpenTelemetry.noop().getTracer(INSTRUMENTATION_SCOPE);
this.openTelemetryAttributes = Attributes.empty();
this.ddlClient = Preconditions.checkNotNull(ddlClient);
this.dbClient = Preconditions.checkNotNull(dbClient);
this.batchClient = Preconditions.checkNotNull(batchClient);
this.connectionState =
new ConnectionState(
options.getInitialConnectionPropertyValues(),
Suppliers.ofInstance(Type.NON_TRANSACTIONAL));
setReadOnly(options.isReadOnly());
setAutocommit(options.isAutocommit());
setReturnCommitStats(options.isReturnCommitStats());
setDefaultTransactionOptions(getDefaultIsolationLevel());
}
@Override
public Spanner getSpanner() {
return this.spanner;
}
private DdlClient createDdlClient() {
return DdlClient.newBuilder()
.setDatabaseAdminClient(spanner.getDatabaseAdminClient())
.setProjectId(options.getProjectId())
.setInstanceId(options.getInstanceId())
.setDatabaseName(options.getDatabaseName())
.build();
}
private AbstractStatementParser getStatementParser() {
if (this.statementParser == null) {
this.statementParser = AbstractStatementParser.getInstance(dbClient.getDialect());
}
return this.statementParser;
}
Attributes getOpenTelemetryAttributes() {
return this.openTelemetryAttributes;
}
@VisibleForTesting
static Attributes createOpenTelemetryAttributes(DatabaseId databaseId) {
AttributesBuilder attributesBuilder = Attributes.builder();
attributesBuilder.put("connection_id", UUID.randomUUID().toString());
attributesBuilder.put("database", databaseId.getDatabase());
attributesBuilder.put("instance_id", databaseId.getInstanceId().getInstance());
attributesBuilder.put("project_id", databaseId.getInstanceId().getProject());
return attributesBuilder.build();
}
@VisibleForTesting
ConnectionState.Type getConnectionStateType() {
return this.connectionState.getType();
}
@Override
public void close() {
try {
closeAsync().get(10L, TimeUnit.SECONDS);
} catch (SpannerException | InterruptedException | ExecutionException | TimeoutException e) {
// ignore and continue to close the connection.
} finally {
statementExecutor.shutdownNow();
}
}
public ApiFuture<Void> closeAsync() {
synchronized (this) {
if (!isClosed()) {
List<ApiFuture<Void>> futures = new ArrayList<>();
if (isBatchActive()) {
abortBatch();
}
if (isTransactionStarted()) {
try {
futures.add(rollbackAsync());
} catch (Exception exception) {
// ignore and continue to close the connection.
}
}
// Try to wait for the current statement to finish (if any) before we actually close the
// connection.
this.closed = true;
// Add a no-op statement to the executor. Once this has been executed, we know that all
// preceding statements have also been executed, as the executor is single-threaded and
// executes all statements in order of submitting. The Executor#submit method can throw a
// RejectedExecutionException if the executor is no longer in state where it accepts new
// tasks.
try {
futures.add(statementExecutor.submit(() -> null));
} catch (RejectedExecutionException ignored) {
// ignore and continue to close the connection.
}
statementExecutor.shutdown();
leakedException = null;
spannerPool.removeConnection(options, this);
return ApiFutures.transform(
ApiFutures.allAsList(futures), ignored -> null, MoreExecutors.directExecutor());
}
}
return ApiFutures.immediateFuture(null);
}
private Context getCurrentContext() {
return Context.USER;
}
/**
* Resets the state of this connection to the default state in the {@link ConnectionOptions} of
* this connection.
*/
public void reset() {
reset(getCurrentContext(), isInTransaction());
}
private void reset(Context context, boolean inTransaction) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
// TODO: Replace all of these with a resetAll in ConnectionState.
this.connectionState.resetValue(RETRY_ABORTS_INTERNALLY, context, inTransaction);
this.connectionState.resetValue(AUTOCOMMIT, context, inTransaction);
this.connectionState.resetValue(READONLY, context, inTransaction);
this.connectionState.resetValue(DEFAULT_ISOLATION_LEVEL, context, inTransaction);
this.connectionState.resetValue(READ_ONLY_STALENESS, context, inTransaction);
this.connectionState.resetValue(OPTIMIZER_VERSION, context, inTransaction);
this.connectionState.resetValue(OPTIMIZER_STATISTICS_PACKAGE, context, inTransaction);
this.connectionState.resetValue(RPC_PRIORITY, context, inTransaction);
this.connectionState.resetValue(DDL_IN_TRANSACTION_MODE, context, inTransaction);
this.connectionState.resetValue(RETURN_COMMIT_STATS, context, inTransaction);
this.connectionState.resetValue(
DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE, context, inTransaction);
this.connectionState.resetValue(KEEP_TRANSACTION_ALIVE, context, inTransaction);
this.connectionState.resetValue(AUTO_PARTITION_MODE, context, inTransaction);
this.connectionState.resetValue(DATA_BOOST_ENABLED, context, inTransaction);
this.connectionState.resetValue(MAX_PARTITIONS, context, inTransaction);
this.connectionState.resetValue(MAX_PARTITIONED_PARALLELISM, context, inTransaction);
this.connectionState.resetValue(MAX_COMMIT_DELAY, context, inTransaction);
this.connectionState.resetValue(AUTOCOMMIT_DML_MODE, context, inTransaction);
this.statementTag = null;
this.statementTimeout = new StatementExecutor.StatementTimeout();
this.connectionState.resetValue(DIRECTED_READ, context, inTransaction);
this.connectionState.resetValue(SAVEPOINT_SUPPORT, context, inTransaction);
this.protoDescriptors = null;
this.protoDescriptorsFilePath = null;
if (!isTransactionStarted()) {
setDefaultTransactionOptions(getDefaultIsolationLevel());
}
}
/** Get the current unit-of-work type of this connection. */
UnitOfWorkType getUnitOfWorkType() {
return unitOfWorkType;
}
/** @return <code>true</code> if this connection is in a batch. */
boolean isInBatch() {
return batchMode != BatchMode.NONE;
}
/** Get the call stack from when the {@link Connection} was opened. */
LeakedConnectionException getLeakedException() {
return leakedException;
}
@Override
public Dialect getDialect() {
return dbClient.getDialect();
}
@Override
public DatabaseClient getDatabaseClient() {
return dbClient;
}
@Override
public boolean isClosed() {
return closed;
}
private <T> T getConnectionPropertyValue(
com.google.cloud.spanner.connection.ConnectionProperty<T> property) {
return this.connectionState.getValue(property).getValue();
}
private <T> void setConnectionPropertyValue(ConnectionProperty<T> property, T value) {
setConnectionPropertyValue(property, value, /* local = */ false);
}
private <T> void setConnectionPropertyValue(
ConnectionProperty<T> property, T value, boolean local) {
if (local) {
setLocalConnectionPropertyValue(property, value);
} else {
this.connectionState.setValue(property, value, getCurrentContext(), isInTransaction());
}
}
/**
* Sets a connection property value only for the duration of the current transaction. The effects
* of this will be undone once the transaction ends, regardless whether the transaction is
* committed or rolled back. 'Local' properties are supported for both {@link
* com.google.cloud.spanner.connection.ConnectionState.Type#TRANSACTIONAL} and {@link
* com.google.cloud.spanner.connection.ConnectionState.Type#NON_TRANSACTIONAL} connection states.
*
* <p>NOTE: This feature is not yet exposed in the public API.
*/
private <T> void setLocalConnectionPropertyValue(ConnectionProperty<T> property, T value) {
ConnectionPreconditions.checkState(
isInTransaction(), "SET LOCAL statements are only supported in transactions");
this.connectionState.setLocalValue(property, value);
}
@Override
public void setAutocommit(boolean autocommit) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
if (isAutocommit() == autocommit) {
return;
}
ConnectionPreconditions.checkState(!isBatchActive(), "Cannot set autocommit while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(), "Cannot set autocommit while a transaction is active");
ConnectionPreconditions.checkState(
!(isAutocommit() && isInTransaction()),
"Cannot set autocommit while in a temporary transaction");
ConnectionPreconditions.checkState(
!transactionBeginMarked, "Cannot set autocommit when a transaction has begun");
setConnectionPropertyValue(AUTOCOMMIT, autocommit);
if (autocommit) {
// Commit the current transaction state if we went from autocommit=false to autocommit=true.
// Otherwise, we get the strange situation that autocommit=true cannot be committed, as we no
// longer have a transaction. Note that all the above state checks essentially mean that
// autocommit can only be set before a transaction has actually started, and not in the
// middle of a transaction.
this.connectionState.commit();
}
clearLastTransactionAndSetDefaultTransactionOptions(getDefaultIsolationLevel());
// Reset the readOnlyStaleness value if it is no longer compatible with the new autocommit
// value.
if (!autocommit) {
TimestampBound readOnlyStaleness = getReadOnlyStaleness();
if (readOnlyStaleness.getMode() == Mode.MAX_STALENESS
|| readOnlyStaleness.getMode() == Mode.MIN_READ_TIMESTAMP) {
setConnectionPropertyValue(READ_ONLY_STALENESS, TimestampBound.strong());
}
}
}
@Override
public boolean isAutocommit() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return internalIsAutocommit();
}
private boolean internalIsAutocommit() {
return getConnectionPropertyValue(AUTOCOMMIT);
}
@Override
public void setReadOnly(boolean readOnly) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isBatchActive(), "Cannot set read-only while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(), "Cannot set read-only while a transaction is active");
ConnectionPreconditions.checkState(
!(isAutocommit() && isInTransaction()),
"Cannot set read-only while in a temporary transaction");
ConnectionPreconditions.checkState(
!transactionBeginMarked, "Cannot set read-only when a transaction has begun");
setConnectionPropertyValue(READONLY, readOnly);
clearLastTransactionAndSetDefaultTransactionOptions(getDefaultIsolationLevel());
}
@Override
public boolean isReadOnly() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(READONLY);
}
@Override
public void setDefaultIsolationLevel(IsolationLevel isolationLevel) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot default isolation level while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"Cannot set default isolation level while a transaction is active");
setConnectionPropertyValue(DEFAULT_ISOLATION_LEVEL, isolationLevel);
clearLastTransactionAndSetDefaultTransactionOptions(isolationLevel);
}
@Override
public IsolationLevel getDefaultIsolationLevel() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(DEFAULT_ISOLATION_LEVEL);
}
private void clearLastTransactionAndSetDefaultTransactionOptions(IsolationLevel isolationLevel) {
setDefaultTransactionOptions(isolationLevel);
this.currentUnitOfWork = null;
}
@Override
public void setAutocommitDmlMode(AutocommitDmlMode mode) {
Preconditions.checkNotNull(mode);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot set autocommit DML mode while in a batch");
ConnectionPreconditions.checkState(
!isInTransaction() && isAutocommit(),
"Cannot set autocommit DML mode while not in autocommit mode or while a transaction is active");
ConnectionPreconditions.checkState(
!isReadOnly(), "Cannot set autocommit DML mode for a read-only connection");
setConnectionPropertyValue(AUTOCOMMIT_DML_MODE, mode);
}
@Override
public AutocommitDmlMode getAutocommitDmlMode() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot get autocommit DML mode while in a batch");
return getConnectionPropertyValue(AUTOCOMMIT_DML_MODE);
}
@Override
public void setReadOnlyStaleness(TimestampBound staleness) {
Preconditions.checkNotNull(staleness);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isBatchActive(), "Cannot set read-only while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"Cannot set read-only staleness when a transaction has been started");
if (staleness.getMode() == Mode.MAX_STALENESS
|| staleness.getMode() == Mode.MIN_READ_TIMESTAMP) {
// These values are only allowed in autocommit mode.
ConnectionPreconditions.checkState(
isAutocommit() && !inTransaction,
"MAX_STALENESS and MIN_READ_TIMESTAMP are only allowed in autocommit mode");
}
setConnectionPropertyValue(READ_ONLY_STALENESS, staleness);
}
@Override
public TimestampBound getReadOnlyStaleness() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isBatchActive(), "Cannot get read-only while in a batch");
return getConnectionPropertyValue(READ_ONLY_STALENESS);
}
@Override
public void setDirectedRead(DirectedReadOptions directedReadOptions) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"Cannot set directed read options when a transaction has been started");
setConnectionPropertyValue(DIRECTED_READ, directedReadOptions);
}
@Override
public DirectedReadOptions getDirectedRead() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(DIRECTED_READ);
}
@Override
public void setOptimizerVersion(String optimizerVersion) {
Preconditions.checkNotNull(optimizerVersion);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
setConnectionPropertyValue(OPTIMIZER_VERSION, optimizerVersion);
}
@Override
public String getOptimizerVersion() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(OPTIMIZER_VERSION);
}
@Override
public void setOptimizerStatisticsPackage(String optimizerStatisticsPackage) {
Preconditions.checkNotNull(optimizerStatisticsPackage);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
setConnectionPropertyValue(OPTIMIZER_STATISTICS_PACKAGE, optimizerStatisticsPackage);
}
@Override
public String getOptimizerStatisticsPackage() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(OPTIMIZER_STATISTICS_PACKAGE);
}
private QueryOptions buildQueryOptions() {
return QueryOptions.newBuilder()
.setOptimizerVersion(getConnectionPropertyValue(OPTIMIZER_VERSION))
.setOptimizerStatisticsPackage(getConnectionPropertyValue(OPTIMIZER_STATISTICS_PACKAGE))
.build();
}
@Override
public void setRPCPriority(RpcPriority rpcPriority) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
setConnectionPropertyValue(RPC_PRIORITY, rpcPriority);
}
@Override
public RpcPriority getRPCPriority() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(RPC_PRIORITY);
}
@Override
public DdlInTransactionMode getDdlInTransactionMode() {
return getConnectionPropertyValue(DDL_IN_TRANSACTION_MODE);
}
@Override
public void setDdlInTransactionMode(DdlInTransactionMode ddlInTransactionMode) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot set DdlInTransactionMode while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(), "Cannot set DdlInTransactionMode while a transaction is active");
setConnectionPropertyValue(DDL_IN_TRANSACTION_MODE, ddlInTransactionMode);
}
@Override
public String getDefaultSequenceKind() {
return getConnectionPropertyValue(DEFAULT_SEQUENCE_KIND);
}
@Override
public void setDefaultSequenceKind(String defaultSequenceKind) {
setConnectionPropertyValue(DEFAULT_SEQUENCE_KIND, defaultSequenceKind);
}
@Override
public void setStatementTimeout(long timeout, TimeUnit unit) {
Preconditions.checkArgument(timeout > 0L, "Zero or negative timeout values are not allowed");
Preconditions.checkArgument(
StatementTimeout.isValidTimeoutUnit(unit),
"Time unit must be one of NANOSECONDS, MICROSECONDS, MILLISECONDS or SECONDS");
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
this.statementTimeout.setTimeoutValue(timeout, unit);
}
@Override
public void clearStatementTimeout() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
this.statementTimeout.clearTimeoutValue();
}
@Override
public long getStatementTimeout(TimeUnit unit) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
Preconditions.checkArgument(
StatementTimeout.isValidTimeoutUnit(unit),
"Time unit must be one of NANOSECONDS, MICROSECONDS, MILLISECONDS or SECONDS");
return this.statementTimeout.getTimeoutValue(unit);
}
@Override
public boolean hasStatementTimeout() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return this.statementTimeout.hasTimeout();
}
@Override
public void cancel() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
if (this.currentUnitOfWork != null) {
currentUnitOfWork.cancel();
}
}
@Override
public TransactionMode getTransactionMode() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isDdlBatchActive(), "This connection is in a DDL batch");
ConnectionPreconditions.checkState(isInTransaction(), "This connection has no transaction");
return unitOfWorkType.getTransactionMode();
}
@Override
public void setTransactionMode(TransactionMode transactionMode) {
Preconditions.checkNotNull(transactionMode);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot set transaction mode while in a batch");
ConnectionPreconditions.checkState(isInTransaction(), "This connection has no transaction");
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"The transaction mode cannot be set after the transaction has started");
ConnectionPreconditions.checkState(
!isReadOnly() || transactionMode == TransactionMode.READ_ONLY_TRANSACTION,
"The transaction mode can only be READ_ONLY when the connection is in read_only mode");
this.transactionBeginMarked = true;
this.unitOfWorkType = UnitOfWorkType.of(transactionMode);
}
@Override
public String getTransactionTag() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isDdlBatchActive(), "This connection is in a DDL batch");
return transactionTag;
}
@Override
public void setTransactionTag(String tag) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot set transaction tag while in a batch");
ConnectionPreconditions.checkState(isInTransaction(), "This connection has no transaction");
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"The transaction tag cannot be set after the transaction has started");
ConnectionPreconditions.checkState(
getTransactionMode() == TransactionMode.READ_WRITE_TRANSACTION,
"Transaction tag can only be set for a read/write transaction");
this.transactionBeginMarked = true;
this.transactionTag = tag;
}
@Override
public String getStatementTag() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Statement tags are not allowed inside a batch");
return statementTag;
}
@Override
public void setStatementTag(String tag) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Statement tags are not allowed inside a batch");
this.statementTag = tag;
}
@Override
public boolean isExcludeTxnFromChangeStreams() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(!isDdlBatchActive(), "This connection is in a DDL batch");
return excludeTxnFromChangeStreams;
}
@Override
public void setExcludeTxnFromChangeStreams(boolean excludeTxnFromChangeStreams) {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Cannot set exclude_txn_from_change_streams while in a batch");
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"exclude_txn_from_change_streams cannot be set after the transaction has started");
this.excludeTxnFromChangeStreams = excludeTxnFromChangeStreams;
}
@Override
public byte[] getProtoDescriptors() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
if (this.protoDescriptors == null && this.protoDescriptorsFilePath != null) {
// Read from file if filepath is valid
try {
File protoDescriptorsFile = new File(this.protoDescriptorsFilePath);
if (!protoDescriptorsFile.isFile()) {
throw SpannerExceptionFactory.newSpannerException(
ErrorCode.INVALID_ARGUMENT,
String.format(
"File %s is not a valid proto descriptors file", this.protoDescriptorsFilePath));
}
InputStream pdStream = Files.newInputStream(protoDescriptorsFile.toPath());
this.protoDescriptors = ByteArray.copyFrom(pdStream).toByteArray();
} catch (Exception exception) {
throw SpannerExceptionFactory.newSpannerException(exception);
}
}
return this.protoDescriptors;
}
@Override
public void setProtoDescriptors(@Nonnull byte[] protoDescriptors) {
Preconditions.checkNotNull(protoDescriptors);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Proto descriptors cannot be set when a batch is active");
this.protoDescriptors = protoDescriptors;
this.protoDescriptorsFilePath = null;
}
void setProtoDescriptorsFilePath(@Nonnull String protoDescriptorsFilePath) {
Preconditions.checkNotNull(protoDescriptorsFilePath);
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isBatchActive(), "Proto descriptors file path cannot be set when a batch is active");
this.protoDescriptorsFilePath = protoDescriptorsFilePath;
this.protoDescriptors = null;
}
String getProtoDescriptorsFilePath() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return this.protoDescriptorsFilePath;
}
/**
* Throws an {@link SpannerException} with code {@link ErrorCode#FAILED_PRECONDITION} if the
* current state of this connection does not allow changing the setting for retryAbortsInternally.
*/
private void checkSetRetryAbortsInternallyAvailable() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
ConnectionPreconditions.checkState(
!isTransactionStarted(),
"RetryAbortsInternally cannot be set after the transaction has started");
}
@Override
public boolean isRetryAbortsInternally() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);
return getConnectionPropertyValue(RETRY_ABORTS_INTERNALLY);
}
@Override
public void setRetryAbortsInternally(boolean retryAbortsInternally) {
setRetryAbortsInternally(retryAbortsInternally, /* local = */ false);
}
void setRetryAbortsInternally(boolean retryAbortsInternally, boolean local) {
checkSetRetryAbortsInternallyAvailable();
setConnectionPropertyValue(RETRY_ABORTS_INTERNALLY, retryAbortsInternally, local);
}
@Override
public void addTransactionRetryListener(TransactionRetryListener listener) {
Preconditions.checkNotNull(listener);
transactionRetryListeners.add(listener);
}
@Override