Google.Cloud.Spanner.Data - Class SpannerConnection (4.3.0)

public sealed class SpannerConnection : DbConnection, IComponent, IDbConnection, IDisposable, IAsyncDisposable

Reference documentation and code samples for the Google.Cloud.Spanner.Data class SpannerConnection.

Represents a connection to a single Spanner database. When opened, SpannerConnection will acquire and maintain a session with the target Spanner database. SpannerCommand instances using this SpannerConnection will use this session to execute their operation. Concurrent read operations can share this session, but concurrent write operations may cause additional sessions to be opened to the database. Underlying sessions with the Spanner database are pooled and are closed after a configurable .

Inheritance

object > MarshalByRefObject > Component > DbConnection > SpannerConnection

Namespace

GoogleCloudGoogle.Cloud.SpannerData

Assembly

Google.Cloud.Spanner.Data.dll

Constructors

SpannerConnection()

public SpannerConnection()

Creates a SpannerConnection with no datasource or credential specified.

SpannerConnection(SpannerConnectionStringBuilder)

public SpannerConnection(SpannerConnectionStringBuilder connectionStringBuilder)

Creates a SpannerConnection with a datasource contained in connectionString.

Parameter
NameDescription
connectionStringBuilderSpannerConnectionStringBuilder

A SpannerConnectionStringBuilder containing a formatted connection string. Must not be null.

SpannerConnection(string, GoogleCredential)

public SpannerConnection(string connectionString, GoogleCredential googleCredential)

Creates a SpannerConnection with a datasource contained in connectionString and optional credential information supplied in connectionString or the googleCredential argument.

Parameters
NameDescription
connectionStringstring

A Spanner formatted connection string. This is usually of the form Data Source=projects/{project}/instances/{instance}/databases/{database};[Host={hostname};][Port={portnumber}]

googleCredentialGoogleCredential

An optional credential for operations to be performed on the Spanner database. May be null.

SpannerConnection(string, ChannelCredentials)

public SpannerConnection(string connectionString, ChannelCredentials credentials = null)

Creates a SpannerConnection with a datasource contained in connectionString and optional credential information supplied in connectionString or the credentials argument.

Parameters
NameDescription
connectionStringstring

A Spanner formatted connection string. This is usually of the form Data Source=projects/{project}/instances/{instance}/databases/{database};[Host={hostname};][Port={portnumber}]

credentialsChannelCredentials

An optional credential for operations to be performed on the Spanner database. May be null.

Example
string connectionString = "Data Source=projects/my-project/instances/my-instance/databases/my-db";
SpannerConnection connection = new SpannerConnection(connectionString);
Console.WriteLine(connection.Project);
Console.WriteLine(connection.SpannerInstance);
Console.WriteLine(connection.Database);

Properties

ConnectionString

public override string ConnectionString { get; set; }
Property Value
TypeDescription
string
Overrides

Database

public override string Database { get; }
Property Value
TypeDescription
string
Overrides

DataSource

public override string DataSource { get; }
Property Value
TypeDescription
string
Overrides

DbProviderFactory

protected override DbProviderFactory DbProviderFactory { get; }
Property Value
TypeDescription
DbProviderFactory
Overrides

EnlistInTransaction

public bool EnlistInTransaction { get; set; }

Gets or Sets whether to participate in the active TransactionScope

Property Value
TypeDescription
bool

LogCommitStats

public bool LogCommitStats { get; }

Request commit statistics for all read/write transactions throughout the lifetime of the connection and log these. This value is set as the default for read/write transactions created by this connection, and is used for statements that are executed on this connection without a transaction.

Property Value
TypeDescription
bool
Remarks

Commit statistics that are returned for a transaction are logged using the logger of this connection. Applications can set a custom logger on the connection to log the output to a different destination. LogCommitStats(CommitRequest, CommitResponse)

Project

public string Project { get; }

The Spanner project name.

Property Value
TypeDescription
string

QueryOptions

public QueryOptions QueryOptions { get; set; }

Query options to use throughout the lifetime of the connection when running SQL and streaming SQL requests.

Property Value
TypeDescription
QueryOptions

ServerVersion

public override string ServerVersion { get; }
Property Value
TypeDescription
string
Overrides

SpannerInstance

public string SpannerInstance { get; }

The Spanner instance name

Property Value
TypeDescription
string

State

public override ConnectionState State { get; }
Property Value
TypeDescription
ConnectionState
Overrides

Methods

BeginDbTransaction(IsolationLevel)

protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
Parameter
NameDescription
isolationLevelIsolationLevel
Returns
TypeDescription
DbTransaction
Overrides

BeginDbTransactionAsync(IsolationLevel, CancellationToken)

protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
Parameters
NameDescription
isolationLevelIsolationLevel
cancellationTokenCancellationToken
Returns
TypeDescription
ValueTaskDbTransaction
Overrides

BeginReadOnlyTransaction()

public SpannerTransaction BeginReadOnlyTransaction()

Begins a read-only transaction.

Returns
TypeDescription
SpannerTransaction

The newly created SpannerTransaction.

Remarks

Read-only transactions are preferred if possible because they do not impose locks internally. Read-only transactions run with strong consistency and return the latest copy of data.

This method is thread safe.

BeginReadOnlyTransaction(TimestampBound)

public SpannerTransaction BeginReadOnlyTransaction(TimestampBound targetReadTimestamp)

Begins a read-only transaction using the provided TimestampBound to control the read timestamp and/or staleness of data.

Parameter
NameDescription
targetReadTimestampTimestampBound

Specifies the timestamp or allowed staleness of data. Must not be null.

Returns
TypeDescription
SpannerTransaction

The newly created SpannerTransaction.

Remarks

Read-only transactions are preferred if possible because they do not impose locks internally. Read-only transactions run with strong consistency and return the latest copy of data.

This method is thread safe.

BeginReadOnlyTransaction(TransactionId)

public SpannerTransaction BeginReadOnlyTransaction(TransactionId transactionId)

Begins a read-only transaction using the provided TransactionId to refer to an existing server-side transaction.

Parameter
NameDescription
transactionIdTransactionId

Specifies the transaction ID of an existing read-only transaction.

Returns
TypeDescription
SpannerTransaction

A SpannerTransaction attached to the existing transaction represented by transactionId.

Remarks

Read-only transactions are preferred if possible because they do not impose locks internally. Providing a transaction ID will connect to an already created transaction which is useful for batch reads. This method differs from the parameterless overload and the overload accepting a TimestampBound as it uses an existing transaction rather than creating a new server-side transaction.

BeginReadOnlyTransactionAsync(TimestampBound, CancellationToken)

public Task<SpannerTransaction> BeginReadOnlyTransactionAsync(TimestampBound targetReadTimestamp, CancellationToken cancellationToken = default)

Begins a read-only transaction using the optionally provided CancellationToken and provided TimestampBound to control the read timestamp and/or staleness of data. Read transactions are preferred if possible because they do not impose locks internally. Stale read-only transactions can execute more quickly than strong or read-write transactions,. This method is thread safe.

Parameters
NameDescription
targetReadTimestampTimestampBound

Specifies the timestamp or allowed staleness of data. Must not be null.

cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
TaskSpannerTransaction

The newly created SpannerTransaction.

BeginReadOnlyTransactionAsync(CancellationToken)

public Task<SpannerTransaction> BeginReadOnlyTransactionAsync(CancellationToken cancellationToken = default)

Begins a read-only transaction using the optionally provided CancellationToken. Read transactions are preferred if possible because they do not impose locks internally. ReadOnly transactions run with strong consistency and return the latest copy of data. This method is thread safe.

Parameter
NameDescription
cancellationTokenCancellationToken

An optional token for canceling the call. May be null.

Returns
TypeDescription
TaskSpannerTransaction

The newly created SpannerTransaction.

BeginTransaction()

public SpannerTransaction BeginTransaction()

Begins a new Spanner transaction synchronously. This method hides BeginTransaction(), but behaves the same way, just with a more specific return type.

Returns
TypeDescription
SpannerTransaction

BeginTransactionAsync(CancellationToken)

public Task<SpannerTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)

Begins a new read/write transaction. This method is thread safe.

Parameter
NameDescription
cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
TaskSpannerTransaction

A new SpannerTransaction

ChangeDatabase(string)

public override void ChangeDatabase(string newDataSource)
Parameter
NameDescription
newDataSourcestring
Overrides

Close()

public override void Close()
Overrides

CreateBatchDmlCommand()

public SpannerBatchCommand CreateBatchDmlCommand()

Creates a new SpannerBatchCommand to execute batched DML statements with this connection, without using a transaction. You can add commands to the batch by using Add(SpannerCommand), Add(SpannerCommandTextBuilder, SpannerParameterCollection) and Add(string, SpannerParameterCollection).

Returns
TypeDescription
SpannerBatchCommand

CreateCommandWithPartition(CommandPartition, SpannerTransaction)

public SpannerCommand CreateCommandWithPartition(CommandPartition partition, SpannerTransaction transaction)

Creates a new SpannerCommand from a CommandPartition. The newly created command will execute on a subset of data defined by the PartitionId

Parameters
NameDescription
partitionCommandPartition

Information that represents a command to execute against a subset of data.

transactionSpannerTransaction

The SpannerTransaction used when creating the CommandPartition. See BeginReadOnlyTransaction(TransactionId).

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

CreateDbCommand()

protected override DbCommand CreateDbCommand()
Returns
TypeDescription
DbCommand
Overrides

CreateDdlCommand(string, params string[])

public SpannerCommand CreateDdlCommand(string ddlStatement, params string[] extraDdlStatements)

Creates a new SpannerCommand to execute a DDL (CREATE/DROP TABLE, etc) statement. This method is thread safe.

Parameters
NameDescription
ddlStatementstring

The DDL statement (eg 'CREATE TABLE MYTABLE ...'). Must not be null.

extraDdlStatementsstring

An optional set of additional DDL statements to execute after the first statement. Extra Ddl statements cannot be used to create additional databases.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    SpannerCommand createDbCmd = connection.CreateDdlCommand($"CREATE DATABASE {databaseName}");
    await createDbCmd.ExecuteNonQueryAsync();

    SpannerCommand createTableCmd = connection.CreateDdlCommand(
        @"CREATE TABLE TestTable (
                                Key                STRING(MAX) NOT NULL,
                                StringValue        STRING(MAX),
                                Int64Value         INT64,
                              ) PRIMARY KEY (Key)");
    await createTableCmd.ExecuteNonQueryAsync();
}

CreateDeleteCommand(string, SpannerParameterCollection)

public SpannerCommand CreateDeleteCommand(string databaseTable, SpannerParameterCollection primaryKeys = null)

Creates a new SpannerCommand to delete rows from a Spanner database table. This method is thread safe.

Parameters
NameDescription
databaseTablestring

The name of the table from which to delete rows. Must not be null.

primaryKeysSpannerParameterCollection

The set of columns that form the primary key of the table.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.OpenAsync();

    // If the transaction is aborted, RunWithRetriableTransactionAsync will
    // retry the whole unit of work with a fresh transaction each time.
    // Please be aware that the whole unit of work needs to be prepared
    // to be called more than once.
    await connection.RunWithRetriableTransactionAsync(async (transaction) =>
    {

        // Read the first two keys in the database.
        List<string> keys = new List<string>();
        SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
        using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
        {
            while (keys.Count < 3 && await reader.ReadAsync())
            {
                keys.Add(reader.GetFieldValue<string>("Key"));
            }
        }

        // Update the Int64Value of keys[0]
        // Include the primary key and update columns.
        SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
        updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
        updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
        await updateCmd.ExecuteNonQueryAsync();

        // Delete row for keys[1]
        SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
        deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
        await deleteCmd.ExecuteNonQueryAsync();
    });

CreateDmlCommand(string, SpannerParameterCollection)

public SpannerCommand CreateDmlCommand(string dmlStatement, SpannerParameterCollection dmlParameters = null)

Creates a new SpannerCommand to execute a general DML (UPDATE, INSERT, DELETE) statement. This method is thread safe.

Parameters
NameDescription
dmlStatementstring

The DML statement (eg 'DELETE FROM MYTABLE WHERE ...'). Must not be null.

dmlParametersSpannerParameterCollection

Optionally supplied set of SpannerParameter that correspond to the parameters used in the SQL query. May be null.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

Remarks

To insert, update, delete or "insert or update" a single row, the operation-specific methods (CreateUpdateCommand(string, SpannerParameterCollection) etc) are preferred as they are more efficient. This method is more appropriate for general-purpose DML which can perform modifications based on query results.

CreateInsertCommand(string, SpannerParameterCollection)

public SpannerCommand CreateInsertCommand(string databaseTable, SpannerParameterCollection insertedColumns = null)

Creates a new SpannerCommand to insert rows into a Spanner database table. This method is thread safe.

Parameters
NameDescription
databaseTablestring

The name of the table to insert rows into. Must not be null.

insertedColumnsSpannerParameterCollection

A collection of SpannerParameter where each instance represents a column in the Spanner database table being set. May be null.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

CreateInsertOrUpdateCommand(string, SpannerParameterCollection)

public SpannerCommand CreateInsertOrUpdateCommand(string databaseTable, SpannerParameterCollection insertUpdateColumns = null)

Creates a new SpannerCommand to insert or update rows into a Spanner database table. This method is thread safe.

Parameters
NameDescription
databaseTablestring

The name of the table to insert or updates rows. Must not be null.

insertUpdateColumnsSpannerParameterCollection

A collection of SpannerParameter where each instance represents a column in the Spanner database table being set. May be null

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

CreateReadCommand(string, ReadOptions, KeySet)

public SpannerCommand CreateReadCommand(string databaseTable, ReadOptions readOptions, KeySet keySet)

Creates a new SpannerCommand to read rows from a Spanner database table. The rows will be returned in the order of the primary key. This method is thread safe.

Parameters
NameDescription
databaseTablestring

The name of the table from which to read rows. Must not be null.

readOptionsReadOptions

The read options to use for the command. Must not be null.

keySetKeySet

The set of primary keys to read. Must not be null.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

CreateSelectCommand(string, SpannerParameterCollection)

public SpannerCommand CreateSelectCommand(string sqlQueryStatement, SpannerParameterCollection selectParameters = null)

Creates a new SpannerCommand to select rows using a SQL query statement. This method is thread safe.

Parameters
NameDescription
sqlQueryStatementstring

A full SQL query statement that may optionally have replacement parameters. Must not be null.

selectParametersSpannerParameterCollection

Optionally supplied set of SpannerParameter that correspond to the parameters used in the SQL query. May be null.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.OpenAsync();

    // If the transaction is aborted, RunWithRetriableTransactionAsync will
    // retry the whole unit of work with a fresh transaction each time.
    // Please be aware that the whole unit of work needs to be prepared
    // to be called more than once.
    await connection.RunWithRetriableTransactionAsync(async (transaction) =>
    {

        // Read the first two keys in the database.
        List<string> keys = new List<string>();
        SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
        using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
        {
            while (keys.Count < 3 && await reader.ReadAsync())
            {
                keys.Add(reader.GetFieldValue<string>("Key"));
            }
        }

        // Update the Int64Value of keys[0]
        // Include the primary key and update columns.
        SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
        updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
        updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
        await updateCmd.ExecuteNonQueryAsync();

        // Delete row for keys[1]
        SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
        deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
        await deleteCmd.ExecuteNonQueryAsync();
    });

CreateUpdateCommand(string, SpannerParameterCollection)

public SpannerCommand CreateUpdateCommand(string databaseTable, SpannerParameterCollection updateColumns = null)

Creates a new SpannerCommand to update rows in a Spanner database table. This method is thread safe.

Parameters
NameDescription
databaseTablestring

The name of the table to update rows. Must not be null.

updateColumnsSpannerParameterCollection

A collection of SpannerParameter where each instance represents a column in the Spanner database table being set. Primary keys of the rows to be updated must also be included. May be null.

Returns
TypeDescription
SpannerCommand

A configured SpannerCommand

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.OpenAsync();

    // If the transaction is aborted, RunWithRetriableTransactionAsync will
    // retry the whole unit of work with a fresh transaction each time.
    // Please be aware that the whole unit of work needs to be prepared
    // to be called more than once.
    await connection.RunWithRetriableTransactionAsync(async (transaction) =>
    {

        // Read the first two keys in the database.
        List<string> keys = new List<string>();
        SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
        using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
        {
            while (keys.Count < 3 && await reader.ReadAsync())
            {
                keys.Add(reader.GetFieldValue<string>("Key"));
            }
        }

        // Update the Int64Value of keys[0]
        // Include the primary key and update columns.
        SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
        updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
        updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
        await updateCmd.ExecuteNonQueryAsync();

        // Delete row for keys[1]
        SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
        deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
        await deleteCmd.ExecuteNonQueryAsync();
    });

Dispose(bool)

protected override void Dispose(bool disposing)
Parameter
NameDescription
disposingbool
Overrides

EnlistTransaction(Transaction)

public override void EnlistTransaction(Transaction transaction)
Parameter
NameDescription
transactionTransaction
Overrides

GetSessionPoolDatabaseStatistics()

[Obsolete("Use GetSessionPoolStatistics instead. Both methods return the same data, but the GetSessionPoolStatistics name better reflects the fact that sessions are pooled on aspects other than database name.")]
public SessionPool.DatabaseStatistics GetSessionPoolDatabaseStatistics()

Retrieves the database-specific statistics for the session pool associated with the connection string. The connection string must include a database name.

Returns
TypeDescription
SessionPoolDatabaseStatistics

The session pool statistics, or null if there is no current session pool for the database specified in the connection string.

GetSessionPoolSegmentStatistics()

public SessionPool.SessionPoolSegmentStatistics GetSessionPoolSegmentStatistics()

Retrieves statistics for the session pool associated with the corresponding SessionPool.SessionPoolSegmentKey. The connection string must include a database name.

Returns
TypeDescription
SessionPoolSessionPoolSegmentStatistics

The session pool statistics, or null if there is no current session pool associated with the SessionPool.SessionPoolSegmentKey.

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    SessionPool.SessionPoolSegmentStatistics stats = connection.GetSessionPoolSegmentStatistics();
    if (stats is null)
    {
        Console.WriteLine("No session pool for this connection string yet");
    }
    else
    {
        // Access individual properties...
        Console.WriteLine($"Database name: {stats.DatabaseName}");
        Console.WriteLine($"Active sessions: {stats.ActiveSessionCount}");
        Console.WriteLine($"Pooled read-only sessions: {stats.ReadPoolCount}");
        Console.WriteLine($"Pooled read-write sessions: {stats.ReadWritePoolCount}");
        // ... or just use the overridden ToString method to log all the statistics in one go:
        Console.WriteLine(stats);
    }
}

Open()

public override void Open()
Overrides

OpenAsReadOnly(TimestampBound)

public void OpenAsReadOnly(TimestampBound timestampBound = null)

Call OpenAsReadOnly within a TransactionScope to open the connection with a read-only transaction with the given TimestampBound settings

Parameter
NameDescription
timestampBoundTimestampBound

Specifies the timestamp or maximum staleness of a read operation. May be null.

OpenAsReadOnly(TransactionId)

public void OpenAsReadOnly(TransactionId transactionId)

If this connection is being opened within a TransactionScope, this will connect to an existing transaction identified by transactionId.

Parameter
NameDescription
transactionIdTransactionId

The TransactionId representing an active readonly SpannerTransaction.

OpenAsReadOnlyAsync(TimestampBound, CancellationToken)

public Task OpenAsReadOnlyAsync(TimestampBound timestampBound = null, CancellationToken cancellationToken = default)

If this connection is being opened within a TransactionScope, this forces the created Cloud Spanner transaction to be a read-only transaction with the given TimestampBound settings.

Parameters
NameDescription
timestampBoundTimestampBound

Specifies the timestamp or maximum staleness of a read operation. May be null.

cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
Task

OpenAsync(CancellationToken)

public override Task OpenAsync(CancellationToken cancellationToken)
Parameter
NameDescription
cancellationTokenCancellationToken
Returns
TypeDescription
Task
Overrides

RunWithRetriableTransaction(Action<SpannerTransaction>)

public void RunWithRetriableTransaction(Action<SpannerTransaction> work)

Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by work.

Parameter
NameDescription
workActionSpannerTransaction

The work to perform in each transaction attempt.

Remarks

work will be fully retried whenever the SpannerTransaction that it receives as a parameter aborts. work won't be retried if any other errors occur. work must be prepared to be called more than once. A new SpannerTransaction will be passed to work each time it is rerun. work doesn't need to handle the lifecycle of the SpannerTransaction, it will be automatically committed after work has finished or rollbacked if an Exception (other than because the transaction aborted) is thrown by work.

RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult>)

public TResult RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult> work)

Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by work.

Parameter
NameDescription
workFuncSpannerTransaction

The work to perform in each transaction attempt.

Returns
TypeDescription
TResult

The value returned by work if the transaction commits successfully.

Type Parameter
NameDescription
TResult
Remarks

work will be fully retried whenever the SpannerTransaction that it receives as a parameter aborts. work won't be retried if any other errors occur. work must be prepared to be called more than once. A new SpannerTransaction will be passed to work each time it is rerun. work doesn't need to handle the lifecycle of the SpannerTransaction, it will be automatically committed after work has finished or rollbacked if an Exception (other than because the transaction aborted) is thrown by work.

RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task>, CancellationToken)

public Task RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task> asyncWork, CancellationToken cancellationToken = default)

Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by asyncWork.

Parameters
NameDescription
asyncWorkFuncSpannerTransactionTask

The work to perform in each transaction attempt.

cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
Task

A task that when completed will signal that the work is done.

Remarks

asyncWork will be fully retried whenever the SpannerTransaction that it receives as a parameter aborts. asyncWork won't be retried if any other errors occur. asyncWork must be prepared to be called more than once. A new SpannerTransaction will be passed to asyncWork each time it is rerun. asyncWork doesn't need to handle the lifecycle of the SpannerTransaction, it will be automatically committed after asyncWork has finished or rollbacked if an Exception (other than because the transaction commit aborted) is thrown by asyncWork.

Example
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.OpenAsync();

    // If the transaction is aborted, RunWithRetriableTransactionAsync will
    // retry the whole unit of work with a fresh transaction each time.
    await connection.RunWithRetriableTransactionAsync(async transaction =>
    {
        SpannerCommand cmd = connection.CreateInsertCommand("TestTable");
        SpannerParameter keyParameter = cmd.Parameters.Add("Key", SpannerDbType.String);
        SpannerParameter stringValueParameter = cmd.Parameters.Add("StringValue", SpannerDbType.String);
        SpannerParameter int64ValueParameter = cmd.Parameters.Add("Int64Value", SpannerDbType.Int64);
        cmd.Transaction = transaction;

        // This executes 5 distinct insert commands using the retriable transaction.
        // The mutations will be effective once the transaction has committed successfully.
        for (int i = 0; i < 5; i++)
        {
            keyParameter.Value = Guid.NewGuid().ToString("N");
            stringValueParameter.Value = $"StringValue{i}";
            int64ValueParameter.Value = i;
            int rowsAffected = await cmd.ExecuteNonQueryAsync();
            Console.WriteLine($"{rowsAffected} rows written...");
        }
    });
}

RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>>, CancellationToken)

public Task<TResult> RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>> asyncWork, CancellationToken cancellationToken = default)

Executes a read-write transaction, with retries as necessary. The work to perform in each transaction attempt is defined by asyncWork.

Parameters
NameDescription
asyncWorkFuncSpannerTransactionTask

The work to perform in each transaction attempt.

cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
Task

The value returned by asyncWork if the transaction commits successfully.

Type Parameter
NameDescription
TResult
Remarks

asyncWork will be fully retried whenever the SpannerTransaction that it receives as a parameter aborts. asyncWork won't be retried if any other errors occur. asyncWork must be prepared to be called more than once. A new SpannerTransaction will be passed to asyncWork each time it is rerun. asyncWork doesn't need to handle the lifecycle of the SpannerTransaction, it will be automatically committed after asyncWork has finished or rollbacked if an Exception (other than because the transaction commit aborted) is thrown by asyncWork.

ShutdownSessionPoolAsync(CancellationToken)

public Task ShutdownSessionPoolAsync(CancellationToken cancellationToken = default)

Shuts down the session pool associated with the connection. Further attempts to acquire sessions will fail immediately.

Parameter
NameDescription
cancellationTokenCancellationToken

An optional token for canceling the returned task. This does not cancel the shutdown itself.

Returns
TypeDescription
Task

A task which will complete when the session pool has finished shutting down.

Remarks

This call will delete all pooled sessions, and wait for all active sessions to be released back to the pool and also deleted.

Example
// When your application is shutting down. Note that any pending or future requests
// for sessions will fail.
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.ShutdownSessionPoolAsync();
}

WhenSessionPoolReady(CancellationToken)

public Task WhenSessionPoolReady(CancellationToken cancellationToken = default)

Returns a task indicating when the session pool associated with the connection is populated up to its minimum size.

Parameter
NameDescription
cancellationTokenCancellationToken

An optional token for canceling the call.

Returns
TypeDescription
Task

A task which will complete when the session pool has reached its minimum size.

Remarks

If the pool is unhealthy or becomes unhealthy before it reaches its minimum size, the returned task will be faulted with an RpcException.

Example
// This would usually be executed during application start-up, before any Spanner
// operations are performed. It can be used at any time, however. It is purely passive:
// it doesn't modify the session pool or trigger any other actions.
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
    await connection.WhenSessionPoolReady();
}