Skip to content

chore: support RESET ALL in the Connection API #3142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ implementation 'com.google.cloud:google-cloud-spanner'
If you are using Gradle without BOM, add this to your dependencies:

```Groovy
implementation 'com.google.cloud:google-cloud-spanner:6.68.0'
implementation 'com.google.cloud:google-cloud-spanner:6.68.1'
```

If you are using SBT, add this to your dependencies:

```Scala
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.68.0"
libraryDependencies += "com.google.cloud" % "google-cloud-spanner" % "6.68.1"
```
<!-- {x-version-update-end} -->

Expand Down Expand Up @@ -671,7 +671,7 @@ Java is a registered trademark of Oracle and/or its affiliates.
[kokoro-badge-link-5]: http://storage.googleapis.com/cloud-devrel-public/java/badges/java-spanner/java11.html
[stability-image]: https://img.shields.io/badge/stability-stable-green
[maven-version-image]: https://img.shields.io/maven-central/v/com.google.cloud/google-cloud-spanner.svg
[maven-version-link]: https://central.sonatype.com/artifact/com.google.cloud/google-cloud-spanner/6.68.0
[maven-version-link]: https://central.sonatype.com/artifact/com.google.cloud/google-cloud-spanner/6.68.1
[authentication]: https://github.com/googleapis/google-cloud-java#authentication
[auth-scopes]: https://developers.google.com/identity/protocols/oauth2/scopes
[predefined-iam-roles]: https://cloud.google.com/iam/docs/understanding-roles#predefined_roles
Expand Down
7 changes: 7 additions & 0 deletions google-cloud-spanner/clirr-ignored-differences.xml
Original file line number Diff line number Diff line change
Expand Up @@ -718,4 +718,11 @@
<className>com/google/cloud/spanner/SessionPoolOptions$Builder</className>
<method>com.google.cloud.spanner.SessionPoolOptions$Builder setUseMultiplexedSession(boolean)</method>
</difference>

<!-- Added reset() method -->
<difference>
<differenceType>7012</differenceType>
<className>com/google/cloud/spanner/connection/Connection</className>
<method>void reset()</method>
</difference>
</differences>
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,19 @@ public interface Connection extends AutoCloseable {
/** @return <code>true</code> if this connection has been closed. */
boolean isClosed();

/**
* Resets the state of this connection to the default state that it had when it was first created.
* Calling this method after a transaction has started (that is; after a statement has been
* executed in the transaction), does not change the active transaction. If for example a
* transaction has been started with a transaction tag, the transaction tag for the active
* transaction is not reset.
*
* <p>You can use this method to reset the state of the connection before returning a connection
* to a connection pool, and/or before using a connection that was retrieved from a connection
* pool.
*/
void reset();

/**
* Sets autocommit on/off for this {@link Connection}. Connections in autocommit mode will apply
* any changes to the database directly without waiting for an explicit commit. DDL- and DML
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,21 +306,10 @@ static UnitOfWorkType of(TransactionMode transactionMode) {
}
this.dbClient = spanner.getDatabaseClient(options.getDatabaseId());
this.batchClient = spanner.getBatchClient(options.getDatabaseId());
this.retryAbortsInternally = options.isRetryAbortsInternally();
this.readOnly = options.isReadOnly();
this.autocommit = options.isAutocommit();
this.queryOptions = this.queryOptions.toBuilder().mergeFrom(options.getQueryOptions()).build();
this.rpcPriority = options.getRPCPriority();
this.ddlInTransactionMode = options.getDdlInTransactionMode();
this.returnCommitStats = options.isReturnCommitStats();
this.delayTransactionStartUntilFirstWrite = options.isDelayTransactionStartUntilFirstWrite();
this.dataBoostEnabled = options.isDataBoostEnabled();
this.autoPartitionMode = options.isAutoPartitionMode();
this.maxPartitions = options.getMaxPartitions();
this.maxPartitionedParallelism = options.getMaxPartitionedParallelism();
this.maxCommitDelay = options.getMaxCommitDelay();
this.ddlClient = createDdlClient();
setDefaultTransactionOptions();

// (Re)set the state of the connection to the default.
reset();
}

/** Constructor only for test purposes. */
Expand Down Expand Up @@ -434,6 +423,42 @@ public ApiFuture<Void> closeAsync() {
return ApiFutures.immediateFuture(null);
}

/**
* Resets the state of this connection to the default state in the {@link ConnectionOptions} of
* this connection.
*/
public void reset() {
ConnectionPreconditions.checkState(!isClosed(), CLOSED_ERROR_MSG);

this.retryAbortsInternally = options.isRetryAbortsInternally();
this.readOnly = options.isReadOnly();
this.autocommit = options.isAutocommit();
this.queryOptions =
QueryOptions.getDefaultInstance().toBuilder().mergeFrom(options.getQueryOptions()).build();
this.rpcPriority = options.getRPCPriority();
this.ddlInTransactionMode = options.getDdlInTransactionMode();
this.returnCommitStats = options.isReturnCommitStats();
this.delayTransactionStartUntilFirstWrite = options.isDelayTransactionStartUntilFirstWrite();
this.dataBoostEnabled = options.isDataBoostEnabled();
this.autoPartitionMode = options.isAutoPartitionMode();
this.maxPartitions = options.getMaxPartitions();
this.maxPartitionedParallelism = options.getMaxPartitionedParallelism();
this.maxCommitDelay = options.getMaxCommitDelay();

this.autocommitDmlMode = AutocommitDmlMode.TRANSACTIONAL;
this.readOnlyStaleness = TimestampBound.strong();
this.statementTag = null;
this.statementTimeout = new StatementExecutor.StatementTimeout();
this.directedReadOptions = null;
this.savepointSupport = SavepointSupport.FAIL_AFTER_ROLLBACK;
this.protoDescriptors = null;
this.protoDescriptorsFilePath = null;

if (!isTransactionStarted()) {
setDefaultTransactionOptions();
}
}

/** Get the current unit-of-work type of this connection. */
UnitOfWorkType getUnitOfWorkType() {
return unitOfWorkType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ StatementResult statementSetPgSessionCharacteristicsTransactionMode(

StatementResult statementAbortBatch();

StatementResult statementResetAll();

StatementResult statementSetRPCPriority(Priority priority);

StatementResult statementShowRPCPriority();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.ABORT_BATCH;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.BEGIN;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.COMMIT;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.RESET_ALL;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.ROLLBACK;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.RUN_BATCH;
import static com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType.SET_AUTOCOMMIT;
Expand Down Expand Up @@ -528,6 +529,12 @@ public StatementResult statementAbortBatch() {
return noResult(ABORT_BATCH);
}

@Override
public StatementResult statementResetAll() {
getConnection().reset();
return noResult(RESET_ALL);
}

@Override
public StatementResult statementSetRPCPriority(Priority priority) {
RpcPriority value = validRPCPriorityValues.get(priority);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ enum ClientSideStatementType {
START_BATCH_DML,
RUN_BATCH,
ABORT_BATCH,
RESET_ALL,
SET_RPC_PRIORITY,
SHOW_RPC_PRIORITY,
SHOW_TRANSACTION_ISOLATION_LEVEL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,15 @@
"exampleStatements": ["abort batch"],
"examplePrerequisiteStatements": ["start batch ddl"]
},
{
"name": "RESET ALL",
"executorName": "ClientSideStatementNoParamExecutor",
"resultType": "NO_RESULT",
"statementType": "RESET_ALL",
"regex": "(?is)\\A\\s*(?:reset)(?:\\s+all)\\s*\\z",
"method": "statementResetAll",
"exampleStatements": ["reset all"]
},
{
"name": "SET AUTOCOMMIT = TRUE|FALSE",
"executorName": "ClientSideStatementSetExecutor",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,15 @@
"exampleStatements": ["abort batch"],
"examplePrerequisiteStatements": ["start batch ddl"]
},
{
"name": "RESET ALL",
"executorName": "ClientSideStatementNoParamExecutor",
"resultType": "NO_RESULT",
"statementType": "RESET_ALL",
"regex": "(?is)\\A\\s*(?:reset)(?:\\s+all)\\s*\\z",
"method": "statementResetAll",
"exampleStatements": ["reset all"]
},
{
"name": "SET AUTOCOMMIT =|TO TRUE|FALSE",
"executorName": "ClientSideStatementSetExecutor",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,31 @@
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.MockSpannerServiceImpl;
import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime;
import com.google.cloud.spanner.Options.RpcPriority;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
import com.google.common.collect.ImmutableList;
import com.google.spanner.v1.BatchCreateSessionsRequest;
import com.google.spanner.v1.CommitRequest;
import com.google.spanner.v1.DirectedReadOptions;
import com.google.spanner.v1.DirectedReadOptions.ExcludeReplicas;
import com.google.spanner.v1.DirectedReadOptions.ReplicaSelection;
import com.google.spanner.v1.ExecuteBatchDmlRequest;
import com.google.spanner.v1.ExecuteSqlRequest;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import com.google.spanner.v1.RequestOptions;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import org.junit.After;
import org.junit.AfterClass;
Expand Down Expand Up @@ -228,6 +237,145 @@ public void testBatchUpdateAborted() {
}
}
}

@Test
public void testReset() {
try (ConnectionImpl connection = (ConnectionImpl) createConnection()) {
assertResetBooleanProperty(
connection,
true,
connection::setRetryAbortsInternally,
connection::isRetryAbortsInternally);
assertResetBooleanProperty(
connection, false, connection::setReadOnly, connection::isReadOnly);
assertResetBooleanProperty(
connection, false, connection::setAutocommit, connection::isAutocommit);
assertResetBooleanProperty(
connection, false, connection::setReturnCommitStats, connection::isReturnCommitStats);
assertResetBooleanProperty(
connection,
false,
connection::setDelayTransactionStartUntilFirstWrite,
connection::isDelayTransactionStartUntilFirstWrite);
assertResetBooleanProperty(
connection, false, connection::setDataBoostEnabled, connection::isDataBoostEnabled);
assertResetBooleanProperty(
connection, false, connection::setAutoPartitionMode, connection::isAutoPartitionMode);
assertResetBooleanProperty(
connection,
false,
connection::setExcludeTxnFromChangeStreams,
connection::isExcludeTxnFromChangeStreams);

assertResetProperty(
connection, "", "1", connection::setOptimizerVersion, connection::getOptimizerVersion);
assertResetProperty(
connection,
null,
RpcPriority.LOW,
connection::setRPCPriority,
connection::getRPCPriority);
assertResetProperty(
connection,
DdlInTransactionMode.ALLOW_IN_EMPTY_TRANSACTION,
DdlInTransactionMode.AUTO_COMMIT_TRANSACTION,
connection::setDdlInTransactionMode,
connection::getDdlInTransactionMode);
assertResetProperty(
connection, 0, 4, connection::setMaxPartitions, connection::getMaxPartitions);
assertResetProperty(
connection,
1,
8,
connection::setMaxPartitionedParallelism,
connection::getMaxPartitionedParallelism);
assertResetProperty(
connection,
null,
Duration.ofMillis(20),
connection::setMaxCommitDelay,
connection::getMaxCommitDelay);
assertResetProperty(
connection,
TimestampBound.strong(),
TimestampBound.ofExactStaleness(10L, TimeUnit.SECONDS),
connection::setReadOnlyStaleness,
connection::getReadOnlyStaleness);
assertResetProperty(
connection, null, "tag", connection::setStatementTag, connection::getStatementTag);
assertResetProperty(
connection, null, "tag", connection::setTransactionTag, connection::getTransactionTag);
assertResetProperty(
connection,
null,
DirectedReadOptions.newBuilder()
.setExcludeReplicas(
ExcludeReplicas.newBuilder()
.addReplicaSelections(
ReplicaSelection.newBuilder().setLocation("foo").build())
.build())
.build(),
connection::setDirectedRead,
connection::getDirectedRead);
assertResetProperty(
connection,
SavepointSupport.FAIL_AFTER_ROLLBACK,
SavepointSupport.ENABLED,
connection::setSavepointSupport,
connection::getSavepointSupport);
assertResetProperty(
connection,
null,
"descriptor".getBytes(StandardCharsets.UTF_8),
connection::setProtoDescriptors,
connection::getProtoDescriptors);
assertResetProperty(
connection,
null,
"filename",
connection::setProtoDescriptorsFilePath,
connection::getProtoDescriptorsFilePath);

// Test the AutocommitDmlMode property that is only supported in auto-commit mode.
connection.rollback();
connection.setAutocommit(true);
assertResetProperty(
connection,
AutocommitDmlMode.TRANSACTIONAL,
AutocommitDmlMode.PARTITIONED_NON_ATOMIC,
connection::setAutocommitDmlMode,
connection::getAutocommitDmlMode);
connection.setAutocommit(false);

// Statement timeouts use a customer getter/setter, so we need to manually test that.
assertEquals(0L, connection.getStatementTimeout(TimeUnit.MILLISECONDS));
connection.setStatementTimeout(10L, TimeUnit.SECONDS);
assertEquals(10L, connection.getStatementTimeout(TimeUnit.SECONDS));
connection.reset();
assertEquals(0L, connection.getStatementTimeout(TimeUnit.MILLISECONDS));
}
}

private void assertResetBooleanProperty(
ConnectionImpl connection,
boolean defaultValue,
Consumer<Boolean> setter,
Supplier<Boolean> getter) {
assertResetProperty(connection, defaultValue, !defaultValue, setter, getter);
}

private <T> void assertResetProperty(
ConnectionImpl connection,
T defaultValue,
T alternativeValue,
Consumer<T> setter,
Supplier<T> getter) {
assertEquals(defaultValue, getter.get());
setter.accept(alternativeValue);
assertEquals(alternativeValue, getter.get());
connection.reset();
assertEquals(defaultValue, getter.get());
}
}

public static class ConnectionMinSessionsTest extends AbstractMockServerTest {
Expand Down
Loading
Loading