Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -1172,6 +1172,11 @@
<className>com/google/cloud/spanner/DatabaseClient</className>
<method>java.lang.String getDatabaseDefaultIsolationLevelValue()</method>
</difference>
<difference>
<differenceType>7012</differenceType>
<className>com/google/cloud/spanner/DatabaseClient</className>
<method>com.google.spanner.v1.TransactionOptions$ReadWrite$ReadLockMode getDatabaseDefaultReadLockMode()</method>
</difference>

<!-- Added universe domain environment option -->
<difference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,23 @@ default IsolationLevel getDatabaseDefaultIsolationLevel() {
throw new UnsupportedOperationException("method should be overwritten");
}

/**
* Returns the default read lock mode that is configured for the database with the {@code
* default_read_lock_mode} database option. Returns {@link
* ReadLockMode#READ_LOCK_MODE_UNSPECIFIED} if the option has not been set, and {@link
* ReadLockMode#UNRECOGNIZED} if the option is set to a value that is not known to this version of
* the client.
*
* <p>The option is read once, together with the dialect of the database, and is cached for the
* lifetime of this client. Changes to the option after it has been read are not reflected.
*
* @return the default read lock mode configured for the database.
*/
@InternalApi
default ReadLockMode getDatabaseDefaultReadLockMode() {
throw new UnsupportedOperationException("method should be overwritten");
}

/**
* Returns the {@link DatabaseRole} used by the client connection. The database role that is used
* determines the access permissions that a connection has. This can for example be used to create
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.google.common.util.concurrent.ListenableFuture;
import com.google.spanner.v1.BatchWriteResponse;
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
import io.opentelemetry.api.common.Attributes;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -92,6 +93,11 @@ public String getDatabaseDefaultIsolationLevelValue() {
return this.multiplexedSessionDatabaseClient.getDatabaseDefaultIsolationLevelValue();
}

@Override
public ReadLockMode getDatabaseDefaultReadLockMode() {
return this.multiplexedSessionDatabaseClient.getDatabaseDefaultReadLockMode();
}

private final AbstractLazyInitializer<StatementFactory> statementFactorySupplier =
new AbstractLazyInitializer<StatementFactory>() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.cloud.spanner;

import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
import java.util.Locale;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
Expand All @@ -26,31 +27,41 @@
final class DatabaseMetadata {
static final String DATABASE_DIALECT_OPTION = "database_dialect";
static final String DEFAULT_TRANSACTION_ISOLATION_OPTION = "default_transaction_isolation";
static final String DEFAULT_READ_LOCK_MODE_OPTION = "default_read_lock_mode";

// The values of default_transaction_isolation. Spanner accepts any case when the option is set,
// and stores and returns these lower-case values for both GoogleSQL and PostgreSQL databases.
static final String SERIALIZABLE_VALUE = "serializable";
static final String REPEATABLE_READ_VALUE = "repeatable read";

// The values of default_read_lock_mode. Spanner stores and returns these lower-case values.
static final String OPTIMISTIC_VALUE = "optimistic";
static final String PESSIMISTIC_VALUE = "pessimistic";

/** Reads all the options in {@link DatabaseMetadata} with a single query. */
static final Statement STATEMENT =
Statement.of(
String.format(
"select option_name, option_value from information_schema.database_options "
+ "where option_name in ('%s', '%s')",
DATABASE_DIALECT_OPTION, DEFAULT_TRANSACTION_ISOLATION_OPTION));
+ "where option_name in ('%s', '%s', '%s')",
DATABASE_DIALECT_OPTION,
DEFAULT_TRANSACTION_ISOLATION_OPTION,
DEFAULT_READ_LOCK_MODE_OPTION));

private final String dialect;
private final IsolationLevel defaultIsolationLevel;
private final @Nullable String defaultIsolationLevelValue;
private final ReadLockMode defaultReadLockMode;

private DatabaseMetadata(
String dialect,
IsolationLevel defaultIsolationLevel,
@Nullable String defaultIsolationLevelValue) {
@Nullable String defaultIsolationLevelValue,
ReadLockMode defaultReadLockMode) {
this.dialect = dialect;
this.defaultIsolationLevel = defaultIsolationLevel;
this.defaultIsolationLevelValue = defaultIsolationLevelValue;
this.defaultReadLockMode = defaultReadLockMode;
}

/**
Expand All @@ -61,6 +72,7 @@ static DatabaseMetadata fromResultSet(ResultSet resultSet) {
String dialect = Dialect.GOOGLE_STANDARD_SQL.name();
IsolationLevel defaultIsolationLevel = IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED;
String defaultIsolationLevelValue = null;
ReadLockMode defaultReadLockMode = ReadLockMode.READ_LOCK_MODE_UNSPECIFIED;
while (resultSet.next()) {
switch (resultSet.getString(0)) {
case DATABASE_DIALECT_OPTION:
Expand All @@ -70,11 +82,16 @@ static DatabaseMetadata fromResultSet(ResultSet resultSet) {
defaultIsolationLevelValue = resultSet.isNull(1) ? null : resultSet.getString(1);
defaultIsolationLevel = parseIsolationLevel(defaultIsolationLevelValue);
break;
case DEFAULT_READ_LOCK_MODE_OPTION:
defaultReadLockMode =
parseReadLockMode(resultSet.isNull(1) ? null : resultSet.getString(1));
break;
default:
break;
}
}
return new DatabaseMetadata(dialect, defaultIsolationLevel, defaultIsolationLevelValue);
return new DatabaseMetadata(
dialect, defaultIsolationLevel, defaultIsolationLevelValue, defaultReadLockMode);
}

/**
Expand All @@ -97,6 +114,25 @@ private static IsolationLevel parseIsolationLevel(@Nullable String optionValue)
}
}

/**
* Parses the value of the {@code default_read_lock_mode} option. {@code null} means that the
* option has not been set and returns {@link ReadLockMode#READ_LOCK_MODE_UNSPECIFIED}. Values
* that are not known to this version of the client return {@link ReadLockMode#UNRECOGNIZED}.
*/
private static ReadLockMode parseReadLockMode(@Nullable String optionValue) {
if (optionValue == null) {
return ReadLockMode.READ_LOCK_MODE_UNSPECIFIED;
}
switch (optionValue.toLowerCase(Locale.ROOT)) {
case OPTIMISTIC_VALUE:
return ReadLockMode.OPTIMISTIC;
case PESSIMISTIC_VALUE:
return ReadLockMode.PESSIMISTIC;
default:
return ReadLockMode.UNRECOGNIZED;
}
}

Dialect getDialect() {
return Dialect.fromName(dialect);
}
Expand All @@ -108,4 +144,15 @@ IsolationLevel getDefaultIsolationLevel() {
@Nullable String getDefaultIsolationLevelValue() {
return defaultIsolationLevelValue;
}

ReadLockMode getDefaultReadLockMode() {
return defaultReadLockMode;
}

@Override
public String toString() {
return String.format(
"DatabaseMetadata{dialect=%s, defaultIsolationLevel=%s, defaultReadLockMode=%s}",
dialect, defaultIsolationLevel, defaultReadLockMode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import com.google.common.util.concurrent.Futures;
import com.google.spanner.v1.BatchWriteResponse;
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
Expand Down Expand Up @@ -300,14 +301,9 @@ public void onSessionReady(SessionImpl session) {
// place. Starting it under the lock guarantees that a concurrent close() stops it.
maintainer.start();
}
sessionReferenceFuture.set(session.getSessionReference());
if (sessionClient
.getSpanner()
.getOptions()
.getSessionPoolOptions()
.isAutoDetectDialect()) {
MAINTAINER_SERVICE.submit(() -> getDialect());
}
SessionReference sessionReference = session.getSessionReference();
sessionReferenceFuture.set(sessionReference);
MAINTAINER_SERVICE.submit(() -> attachDatabaseMetadata(sessionReference));
}

@Override
Expand Down Expand Up @@ -587,7 +583,12 @@ private int getSingleUseChannelHint() {
new AbstractLazyInitializer<DatabaseMetadata>() {
@Override
protected DatabaseMetadata initialize() {
try (ResultSet resultSet = singleUse().executeQuery(DatabaseMetadata.STATEMENT)) {
Preconditions.checkState(!isClosed, "This client has been closed");
// Query the session directly, so this internal query is not counted as a user
// transaction and does not claim a single-use channel hint.
SessionImpl session =
new SessionImpl(sessionClient.getSpanner(), getCurrentSessionReference());
try (ResultSet resultSet = session.singleUse().executeQuery(DatabaseMetadata.STATEMENT)) {
return DatabaseMetadata.fromResultSet(resultSet);
}
}
Expand Down Expand Up @@ -634,6 +635,34 @@ public String getDatabaseDefaultIsolationLevelValue() {
}
}

@Override
public ReadLockMode getDatabaseDefaultReadLockMode() {
try {
return databaseMetadataSupplier.get().getDefaultReadLockMode();
} catch (Exception exception) {
throw SpannerExceptionFactory.asSpannerException(exception);
}
}

/**
* Reads the {@link DatabaseMetadata} in the background and attaches it to the given multiplexed
* session, so read/write transactions on that session can resolve their effective isolation level
* and read lock mode for Leader-Aware Routing decisions. Runs when a multiplexed session is
* created or replaced. Errors are ignored here: transactions keep routing to the leader until the
* metadata is available, and the next call to {@link #getDialect()} or similar surfaces the
* error.
*/
private void attachDatabaseMetadata(SessionReference sessionReference) {
if (isClosed) {
return;
}
try {
sessionReference.setDatabaseMetadata(databaseMetadataSupplier.get());
} catch (Exception ignore) {
// The metadata is optional for routing. Any error is surfaced by getDialect() and similar.
}
}

@Override
public String getDatabaseRole() {
return this.sessionClient.getSpanner().getOptions().getDatabaseRole();
Expand Down Expand Up @@ -796,8 +825,9 @@ public void onSessionReady(SessionImpl session) {
// session belongs to a client that no longer exists and is ignored.
return;
}
multiplexedSessionReference.set(
ApiFutures.immediateFuture(session.getSessionReference()));
SessionReference sessionReference = session.getSessionReference();
multiplexedSessionReference.set(ApiFutures.immediateFuture(sessionReference));
MAINTAINER_SERVICE.submit(() -> attachDatabaseMetadata(sessionReference));
expirationDate.set(
clock
.instant()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ class SessionReference {
@Nullable private final Instant createTime;
private final boolean isMultiplexed;

/**
* The database options that are used to resolve the effective isolation level and read lock mode
* of read/write transactions on this session. This is set in the background after a multiplexed
* session has been created, and is null until the metadata has been read.
*/
private volatile @Nullable DatabaseMetadata databaseMetadata;

SessionReference(String name, @Nullable String databaseRole, Map<SpannerRpc.Option, ?> options) {
this.options = options;
this.name = checkNotNull(name);
Expand Down Expand Up @@ -92,6 +99,15 @@ boolean getIsMultiplexed() {
return isMultiplexed;
}

@Nullable
DatabaseMetadata getDatabaseMetadata() {
return databaseMetadata;
}

void setDatabaseMetadata(DatabaseMetadata databaseMetadata) {
this.databaseMetadata = databaseMetadata;
}

void markUsed(Instant instant) {
lastUseTime = instant;
}
Expand Down
Loading
Loading