Google.Cloud.Spanner.Data - Class SpannerConnection (5.0.0-beta04)

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

Google.Cloud.Spanner.Data

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
Name Description
connectionStringBuilder SpannerConnectionStringBuilder

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
Name Description
connectionString string

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

googleCredential GoogleCredential

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
Name Description
connectionString string

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

credentials ChannelCredentials

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; }

Gets or sets the string used to open the connection.

Property Value
Type Description
string

The connection string used to establish the initial connection. The exact contents of the connection string depend on the specific data source for this connection. The default value is an empty string.

Overrides

DataSource

public override string DataSource { get; }

Gets the name of the database server to which to connect.

Property Value
Type Description
string

The name of the database server to which to connect. The default value is an empty string.

Overrides

Database

public override string Database { get; }

Gets the name of the current database after a connection is opened, or the database name specified in the connection string before the connection is opened.

Property Value
Type Description
string

The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string.

Overrides

DbProviderFactory

protected override DbProviderFactory DbProviderFactory { get; }

Gets the DbProviderFactory for this DbConnection.

Property Value
Type Description
DbProviderFactory

A set of methods for creating instances of a provider's implementation of the data source classes.

Overrides

EnlistInTransaction

public bool EnlistInTransaction { get; set; }

Gets or Sets whether to participate in the active TransactionScope

Property Value
Type Description
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
Type Description
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. Google.Cloud.Spanner.V1.Internal.Logging.Logger.LogCommitStats(Google.Cloud.Spanner.V1.CommitRequest, Google.Cloud.Spanner.V1.CommitResponse)

Project

public string Project { get; }

The Spanner project name.

Property Value
Type Description
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
Type Description
QueryOptions

ServerVersion

public override string ServerVersion { get; }

Gets a string that represents the version of the server to which the object is connected.

Property Value
Type Description
string

The version of the database. The format of the string returned depends on the specific type of connection you are using.

Overrides
Exceptions
Type Description
InvalidOperationException

ServerVersion was called while the returned Task was not completed and the connection was not opened after a call to System.Data.Common.DbConnection.OpenAsync*.

SpannerInstance

public string SpannerInstance { get; }

The Spanner instance name

Property Value
Type Description
string

State

public override ConnectionState State { get; }

Gets a string that describes the state of the connection.

Property Value
Type Description
ConnectionState

The state of the connection. The format of the string returned depends on the specific type of connection you are using.

Overrides

Methods

BeginDbTransaction(IsolationLevel)

protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)

Starts a database transaction.

Parameter
Name Description
isolationLevel IsolationLevel

Specifies the isolation level for the transaction.

Returns
Type Description
DbTransaction

An object representing the new transaction.

Overrides

BeginDbTransactionAsync(IsolationLevel, CancellationToken)

protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
Parameters
Name Description
isolationLevel IsolationLevel
cancellationToken CancellationToken
Returns
Type Description
ValueTaskDbTransaction
Overrides

BeginReadOnlyTransaction()

[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public SpannerTransaction BeginReadOnlyTransaction()

Begins a read-only transaction.

Returns
Type Description
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)

[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
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
Name Description
targetReadTimestamp TimestampBound

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

Returns
Type Description
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)

[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public SpannerTransaction BeginReadOnlyTransaction(TransactionId transactionId)

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

Parameter
Name Description
transactionId TransactionId

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

Returns
Type Description
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)

[Obsolete("Use the BeginTransactionAsync overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
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
Name Description
targetReadTimestamp TimestampBound

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

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
TaskSpannerTransaction

The newly created SpannerTransaction.

BeginReadOnlyTransactionAsync(CancellationToken)

[Obsolete("Use the BeginTransactionAsync overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
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
Name Description
cancellationToken CancellationToken

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

Returns
Type Description
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
Type Description
SpannerTransaction

BeginTransaction(SpannerTransactionCreationOptions)

public SpannerTransaction BeginTransaction(SpannerTransactionCreationOptions transactionCreationOptions)

Creates a SpannerTransaction based on the given creation options.

Parameter
Name Description
transactionCreationOptions SpannerTransactionCreationOptions
Returns
Type Description
SpannerTransaction

BeginTransactionAsync(SpannerTransactionCreationOptions, CancellationToken)

public Task<SpannerTransaction> BeginTransactionAsync(SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)

Creates a SpannerTransaction based on the given creation options.

Parameters
Name Description
transactionCreationOptions SpannerTransactionCreationOptions
cancellationToken CancellationToken
Returns
Type Description
TaskSpannerTransaction

BeginTransactionAsync(CancellationToken)

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

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

Parameter
Name Description
cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
TaskSpannerTransaction

A new SpannerTransaction

ChangeDatabase(string)

public override void ChangeDatabase(string newDataSource)

Changes the current database for an open connection.

Parameter
Name Description
newDataSource string
Overrides

Close()

public override void Close()

Closes the connection to the database. This is the preferred method of closing any open connection.

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
Type Description
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
Name Description
partition CommandPartition

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

transaction SpannerTransaction

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

Returns
Type Description
SpannerCommand

A configured SpannerCommand

CreateDbCommand()

protected override DbCommand CreateDbCommand()

Creates and returns a DbCommand object associated with the current connection.

Returns
Type Description
DbCommand

A DbCommand object.

Overrides

CreateDdlCommand(string, FileDescriptorSet, params string[])

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

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

Parameters
Name Description
ddlStatement string

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

protobufDescriptors FileDescriptorSet

The set of protobuf descriptors that can be used to create proto bundles. May be null.

extraDdlStatements string

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

Returns
Type Description
SpannerCommand

A configured SpannerCommand

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
Name Description
ddlStatement string

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

extraDdlStatements string

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

Returns
Type Description
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
Name Description
databaseTable string

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

primaryKeys SpannerParameterCollection

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

Returns
Type Description
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");
        selectCmd.Transaction = transaction;
        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);
        updateCmd.Transaction = transaction;
        await updateCmd.ExecuteNonQueryAsync();

        // Delete row for keys[1]
        SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
        deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
        deleteCmd.Transaction = transaction;
        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
Name Description
dmlStatement string

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

dmlParameters SpannerParameterCollection

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

Returns
Type Description
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
Name Description
databaseTable string

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

insertedColumns SpannerParameterCollection

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

Returns
Type Description
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
Name Description
databaseTable string

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

insertUpdateColumns SpannerParameterCollection

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

Returns
Type Description
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
Name Description
databaseTable string

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

readOptions ReadOptions

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

keySet KeySet

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

Returns
Type Description
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
Name Description
sqlQueryStatement string

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

selectParameters SpannerParameterCollection

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

Returns
Type Description
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");
        selectCmd.Transaction = transaction;
        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);
        updateCmd.Transaction = transaction;
        await updateCmd.ExecuteNonQueryAsync();

        // Delete row for keys[1]
        SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
        deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
        deleteCmd.Transaction = transaction;
        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
Name Description
databaseTable string

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

updateColumns SpannerParameterCollection

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
Type Description
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");
        selectCmd.Transaction = transaction;
        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);
        updateCmd.Transaction = transaction;
        await updateCmd.ExecuteNonQueryAsync();

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

Dispose(bool)

protected override void Dispose(bool disposing)

Releases the unmanaged resources used by the Component and optionally releases the managed resources.

Parameter
Name Description
disposing bool

true to release both managed and unmanaged resources; false to release only unmanaged resources.

Overrides

EnlistTransaction(Transaction)

public override void EnlistTransaction(Transaction transaction)

Enlists in the specified transaction.

Parameter
Name Description
transaction Transaction

A reference to an existing Transaction in which to enlist.

Overrides

GetSessionPoolSegmentStatistics()

public SessionPool.SessionPoolSegmentStatistics GetSessionPoolSegmentStatistics()

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

Returns
Type Description
Google.Cloud.Spanner.V1.SessionPoolGoogle.Cloud.Spanner.V1.SessionPool.SessionPoolSegmentStatistics

The session pool statistics, or null if there is no current session pool associated with the Google.Cloud.Spanner.V1.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 sessions: {stats.PoolCount}");
        // ... or just use the overridden ToString method to log all the statistics in one go:
        Console.WriteLine(stats);
    }
}

Open()

public override void Open()

Opens a database connection with the settings specified by the ConnectionString.

Overrides

Open(SpannerTransactionCreationOptions, SpannerTransactionOptions)

public void Open(SpannerTransactionCreationOptions creationOptions, SpannerTransactionOptions options)

Opens the connection within a TransactionScope with specific SpannerTransactionCreationOptions and SpannerTransactionOptions.

Parameters
Name Description
creationOptions SpannerTransactionCreationOptions

Options to be used when creating the ambient SpannerTransaction. Must not be null.

options SpannerTransactionOptions

Options to be applied to the ambient SpannerTransaction after creation. May be null, in which case defaults will be used. A copy of this value will be used internally, so any changes to options made after calling this method will have no effect on the ambient transaction.

OpenAsReadOnly(TimestampBound)

[Obsolete("Use the Open overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
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
Name Description
timestampBound TimestampBound

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

OpenAsReadOnly(TransactionId)

[Obsolete("Use the Open overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
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
Name Description
transactionId TransactionId

The TransactionId representing an active readonly SpannerTransaction.

OpenAsReadOnlyAsync(TimestampBound, CancellationToken)

[Obsolete("Use the OpenAsync overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
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
Name Description
timestampBound TimestampBound

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

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
Task

OpenAsync(SpannerTransactionCreationOptions, SpannerTransactionOptions, CancellationToken)

public Task OpenAsync(SpannerTransactionCreationOptions creationOptions, SpannerTransactionOptions options, CancellationToken cancellationToken)

Opens the connection within a TransactionScope with specific SpannerTransactionCreationOptions and SpannerTransactionOptions.

Parameters
Name Description
creationOptions SpannerTransactionCreationOptions

Options to be used when creating the ambient SpannerTransaction. Must not be null.

options SpannerTransactionOptions

Options to be applied to the ambient SpannerTransaction after creation. May be null, in which case defaults will be used. A copy of this value will be used internally, so any changes to options made after calling this method will have no effect on the ambient transaction.

cancellationToken CancellationToken

The cancellation token for the operation.

Returns
Type Description
Task

OpenAsync(CancellationToken)

public override Task OpenAsync(CancellationToken cancellationToken)

This is the asynchronous version of Open(). Providers should override with an appropriate implementation. The cancellation token can optionally be honored.
The default implementation invokes the synchronous Open() call and returns a completed task. The default implementation will return a cancelled task if passed an already cancelled cancellationToken. Exceptions thrown by Open will be communicated via the returned Task Exception property.
Do not invoke other methods and properties of the DbConnection object until the returned Task is complete.

Parameter
Name Description
cancellationToken CancellationToken

The cancellation instruction.

Returns
Type Description
Task

A task representing the asynchronous operation.

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
Name Description
work ActionSpannerTransaction

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(Action<SpannerTransaction>, SpannerTransactionCreationOptions)

public void RunWithRetriableTransaction(Action<SpannerTransaction> work, SpannerTransactionCreationOptions transactionCreationOptions)

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

Parameters
Name Description
work ActionSpannerTransaction

The work to perform in each transaction attempt.

transactionCreationOptions SpannerTransactionCreationOptions

Options for creating transactions. These options should be for a read-write transaction that is not detached. May be null in which case defaults will be used.

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>, SpannerTransactionCreationOptions, CancellationToken)

public Task RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task> asyncWork, SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)

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

Parameters
Name Description
asyncWork FuncSpannerTransactionTask

The work to perform in each transaction attempt.

transactionCreationOptions SpannerTransactionCreationOptions

Options for creating transactions. These options should be for a read-write transaction that is not detached. May be null in which case defaults will be used.

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
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(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
Name Description
asyncWork FuncSpannerTransactionTask

The work to perform in each transaction attempt.

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
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>>, SpannerTransactionCreationOptions, CancellationToken)

public Task<TResult> RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>> asyncWork, SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)

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

Parameters
Name Description
asyncWork FuncSpannerTransactionTask

The work to perform in each transaction attempt.

transactionCreationOptions SpannerTransactionCreationOptions

Options for creating transactions. These options should be for a read-write transaction that is not detached. May be null in which case defaults will be used.

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
Task

The value returned by asyncWork if the transaction commits successfully.

Type Parameter
Name Description
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.

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
Name Description
asyncWork FuncSpannerTransactionTask

The work to perform in each transaction attempt.

cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
Task

The value returned by asyncWork if the transaction commits successfully.

Type Parameter
Name Description
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.

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
Name Description
work FuncSpannerTransaction

The work to perform in each transaction attempt.

Returns
Type Description
TResult

The value returned by work if the transaction commits successfully.

Type Parameter
Name Description
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.

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

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

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

Parameters
Name Description
work FuncSpannerTransaction

The work to perform in each transaction attempt.

transactionCreationOptions SpannerTransactionCreationOptions

Options for creating transactions. These options should be for a read-write transaction that is not detached. May be null in which case defaults will be used.

Returns
Type Description
TResult

The value returned by work if the transaction commits successfully.

Type Parameter
Name Description
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.

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
Name Description
cancellationToken CancellationToken

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

Returns
Type Description
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
Name Description
cancellationToken CancellationToken

An optional token for canceling the call.

Returns
Type Description
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();
}