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
Inherited Members
Namespace: Google.Cloud.Spanner.Data
Assembly: Google.Cloud.Spanner.Data.dll
Syntax
public sealed class SpannerConnection : DbConnection, IComponent, IDbConnection, IDisposable, IAsyncDisposable
Constructors
SpannerConnection()
Creates a SpannerConnection with no datasource or credential specified.
Declaration
public SpannerConnection()
SpannerConnection(SpannerConnectionStringBuilder)
Creates a SpannerConnection with a datasource contained in connectionString.
Declaration
public SpannerConnection(SpannerConnectionStringBuilder connectionStringBuilder)
Parameters
Type | Name | Description |
---|---|---|
SpannerConnectionStringBuilder | connectionStringBuilder | A SpannerConnectionStringBuilder containing a formatted connection string. Must not be null. |
SpannerConnection(string, GoogleCredential)
Creates a SpannerConnection with a datasource contained in connectionString
and optional credential information supplied in connectionString
or the googleCredential
argument.
Declaration
public SpannerConnection(string connectionString, GoogleCredential googleCredential)
Parameters
Type | Name | Description |
---|---|---|
string | connectionString | A Spanner formatted connection string. This is usually of the form
|
GoogleCredential | googleCredential | An optional credential for operations to be performed on the Spanner database. May be null. |
SpannerConnection(string, ChannelCredentials)
Creates a SpannerConnection with a datasource contained in connectionString
and optional credential information supplied in connectionString
or the credentials
argument.
Declaration
public SpannerConnection(string connectionString, ChannelCredentials credentials = null)
Parameters
Type | Name | Description |
---|---|---|
string | connectionString | A Spanner formatted connection string. This is usually of the form
|
ChannelCredentials | credentials | An optional credential for operations to be performed on the Spanner database. May be null. |
Sample code
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
Gets or sets the string used to open the connection.
Declaration
public override string ConnectionString { get; set; }
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
Gets the name of the database server to which to connect.
Declaration
public override string DataSource { get; }
Property Value
Type | Description |
---|---|
string | The name of the database server to which to connect. The default value is an empty string. |
Overrides
Database
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.
Declaration
public override string Database { get; }
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
Gets the DbProviderFactory for this DbConnection.
Declaration
protected override DbProviderFactory DbProviderFactory { get; }
Property Value
Type | Description |
---|---|
DbProviderFactory | A set of methods for creating instances of a provider's implementation of the data source classes. |
Overrides
EnlistInTransaction
Gets or Sets whether to participate in the active TransactionScope
Declaration
public bool EnlistInTransaction { get; set; }
Property Value
Type | Description |
---|---|
bool |
LogCommitStats
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.
Declaration
public bool LogCommitStats { get; }
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
The Spanner project name.
Declaration
public string Project { get; }
Property Value
Type | Description |
---|---|
string |
QueryOptions
Query options to use throughout the lifetime of the connection when running SQL and streaming SQL requests.
Declaration
public QueryOptions QueryOptions { get; set; }
Property Value
Type | Description |
---|---|
QueryOptions |
ServerVersion
Gets a string that represents the version of the server to which the object is connected.
Declaration
public override string ServerVersion { get; }
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 | Condition |
---|---|
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
The Spanner instance name
Declaration
public string SpannerInstance { get; }
Property Value
Type | Description |
---|---|
string |
State
Gets a string that describes the state of the connection.
Declaration
public override ConnectionState State { get; }
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)
Starts a database transaction.
Declaration
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
Parameters
Type | 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)
Declaration
protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
IsolationLevel | isolationLevel | |
CancellationToken | cancellationToken |
Returns
Type | Description |
---|---|
ValueTask<DbTransaction> |
Overrides
BeginReadOnlyTransaction()
Begins a read-only transaction.
Declaration
[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public SpannerTransaction BeginReadOnlyTransaction()
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)
Begins a read-only transaction using the provided TimestampBound to control the read timestamp and/or staleness of data.
Declaration
[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public SpannerTransaction BeginReadOnlyTransaction(TimestampBound targetReadTimestamp)
Parameters
Type | Name | Description |
---|---|---|
TimestampBound | targetReadTimestamp | 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)
Begins a read-only transaction using the provided TransactionId to refer to an existing server-side transaction.
Declaration
[Obsolete("Use the BeginTransaction overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public SpannerTransaction BeginReadOnlyTransaction(TransactionId transactionId)
Parameters
Type | 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
|
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)
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.
Declaration
[Obsolete("Use the BeginTransactionAsync overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public Task<SpannerTransaction> BeginReadOnlyTransactionAsync(TimestampBound targetReadTimestamp, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
TimestampBound | targetReadTimestamp | Specifies the timestamp or allowed staleness of data. Must not be null. |
CancellationToken | cancellationToken | An optional token for canceling the call. |
Returns
Type | Description |
---|---|
Task<SpannerTransaction> | The newly created SpannerTransaction. |
BeginReadOnlyTransactionAsync(CancellationToken)
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.
Declaration
[Obsolete("Use the BeginTransactionAsync overload that takes SpannerTransactionCreationOptions as a parameter instead.")]
public Task<SpannerTransaction> BeginReadOnlyTransactionAsync(CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellationToken | An optional token for canceling the call. May be null. |
Returns
Type | Description |
---|---|
Task<SpannerTransaction> | The newly created SpannerTransaction. |
BeginTransaction()
Begins a new Spanner transaction synchronously. This method hides BeginTransaction(), but behaves the same way, just with a more specific return type.
Declaration
public SpannerTransaction BeginTransaction()
Returns
Type | Description |
---|---|
SpannerTransaction |
BeginTransaction(SpannerTransactionCreationOptions)
Creates a SpannerTransaction based on the given creation options.
Declaration
public SpannerTransaction BeginTransaction(SpannerTransactionCreationOptions transactionCreationOptions)
Parameters
Type | Name | Description |
---|---|---|
SpannerTransactionCreationOptions | transactionCreationOptions |
Returns
Type | Description |
---|---|
SpannerTransaction |
BeginTransactionAsync(SpannerTransactionCreationOptions, CancellationToken)
Creates a SpannerTransaction based on the given creation options.
Declaration
public Task<SpannerTransaction> BeginTransactionAsync(SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
SpannerTransactionCreationOptions | transactionCreationOptions | |
CancellationToken | cancellationToken |
Returns
Type | Description |
---|---|
Task<SpannerTransaction> |
BeginTransactionAsync(CancellationToken)
Begins a new read/write transaction. This method is thread safe.
Declaration
public Task<SpannerTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellationToken | An optional token for canceling the call. |
Returns
Type | Description |
---|---|
Task<SpannerTransaction> | A new SpannerTransaction |
ChangeDatabase(string)
Changes the current database for an open connection.
Declaration
public override void ChangeDatabase(string newDataSource)
Parameters
Type | Name | Description |
---|---|---|
string | newDataSource |
Overrides
Close()
Closes the connection to the database. This is the preferred method of closing any open connection.
Declaration
public override void Close()
Overrides
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).
Declaration
public SpannerBatchCommand CreateBatchDmlCommand()
Returns
Type | Description |
---|---|
SpannerBatchCommand |
CreateCommandWithPartition(CommandPartition, SpannerTransaction)
Creates a new SpannerCommand from a CommandPartition. The newly created command will execute on a subset of data defined by the PartitionId
Declaration
public SpannerCommand CreateCommandWithPartition(CommandPartition partition, SpannerTransaction transaction)
Parameters
Type | Name | Description |
---|---|---|
CommandPartition | partition | Information that represents a command to execute against a subset of data. |
SpannerTransaction | transaction | The SpannerTransaction used when creating the CommandPartition. See BeginReadOnlyTransaction(TransactionId). |
Returns
Type | Description |
---|---|
SpannerCommand | A configured SpannerCommand |
CreateDbCommand()
Creates and returns a DbCommand object associated with the current connection.
Declaration
protected override DbCommand CreateDbCommand()
Returns
Type | Description |
---|---|
DbCommand | A DbCommand object. |
Overrides
CreateDdlCommand(string, FileDescriptorSet, params string[])
Creates a new SpannerCommand to execute a DDL (CREATE/DROP TABLE, etc) statement. This method is thread safe.
Declaration
public SpannerCommand CreateDdlCommand(string ddlStatement, FileDescriptorSet protobufDescriptors, params string[] extraDdlStatements)
Parameters
Type | Name | Description |
---|---|---|
string | ddlStatement | The DDL statement (eg 'CREATE TABLE MYTABLE ...'). Must not be null. |
FileDescriptorSet | protobufDescriptors | The set of protobuf descriptors that can be used to create proto bundles. May be null. |
string[] | extraDdlStatements | 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[])
Creates a new SpannerCommand to execute a DDL (CREATE/DROP TABLE, etc) statement. This method is thread safe.
Declaration
public SpannerCommand CreateDdlCommand(string ddlStatement, params string[] extraDdlStatements)
Parameters
Type | Name | Description |
---|---|---|
string | ddlStatement | The DDL statement (eg 'CREATE TABLE MYTABLE ...'). Must not be null. |
string[] | extraDdlStatements | 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 |
Sample code
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)
Creates a new SpannerCommand to delete rows from a Spanner database table. This method is thread safe.
Declaration
public SpannerCommand CreateDeleteCommand(string databaseTable, SpannerParameterCollection primaryKeys = null)
Parameters
Type | Name | Description |
---|---|---|
string | databaseTable | The name of the table from which to delete rows. Must not be null. |
SpannerParameterCollection | primaryKeys | The set of columns that form the primary key of the table. |
Returns
Type | Description |
---|---|
SpannerCommand | A configured SpannerCommand |
Sample code
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)
Creates a new SpannerCommand to execute a general DML (UPDATE, INSERT, DELETE) statement. This method is thread safe.
Declaration
public SpannerCommand CreateDmlCommand(string dmlStatement, SpannerParameterCollection dmlParameters = null)
Parameters
Type | Name | Description |
---|---|---|
string | dmlStatement | The DML statement (eg 'DELETE FROM MYTABLE WHERE ...'). Must not be null. |
SpannerParameterCollection | dmlParameters | 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)
Creates a new SpannerCommand to insert rows into a Spanner database table. This method is thread safe.
Declaration
public SpannerCommand CreateInsertCommand(string databaseTable, SpannerParameterCollection insertedColumns = null)
Parameters
Type | Name | Description |
---|---|---|
string | databaseTable | The name of the table to insert rows into. Must not be null. |
SpannerParameterCollection | insertedColumns | 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)
Creates a new SpannerCommand to insert or update rows into a Spanner database table. This method is thread safe.
Declaration
public SpannerCommand CreateInsertOrUpdateCommand(string databaseTable, SpannerParameterCollection insertUpdateColumns = null)
Parameters
Type | Name | Description |
---|---|---|
string | databaseTable | The name of the table to insert or updates rows. Must not be null. |
SpannerParameterCollection | insertUpdateColumns | 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)
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.
Declaration
public SpannerCommand CreateReadCommand(string databaseTable, ReadOptions readOptions, KeySet keySet)
Parameters
Type | Name | Description |
---|---|---|
string | databaseTable | 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)
Creates a new SpannerCommand to select rows using a SQL query statement. This method is thread safe.
Declaration
public SpannerCommand CreateSelectCommand(string sqlQueryStatement, SpannerParameterCollection selectParameters = null)
Parameters
Type | Name | Description |
---|---|---|
string | sqlQueryStatement | A full SQL query statement that may optionally have replacement parameters. Must not be null. |
SpannerParameterCollection | selectParameters | 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 |
Sample code
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)
Creates a new SpannerCommand to update rows in a Spanner database table. This method is thread safe.
Declaration
public SpannerCommand CreateUpdateCommand(string databaseTable, SpannerParameterCollection updateColumns = null)
Parameters
Type | Name | Description |
---|---|---|
string | databaseTable | The name of the table to update rows. Must not be null. |
SpannerParameterCollection | updateColumns | 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 |
Sample code
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)
Releases the unmanaged resources used by the Component and optionally releases the managed resources.
Declaration
protected override void Dispose(bool disposing)
Parameters
Type | Name | Description |
---|---|---|
bool | disposing | true to release both managed and unmanaged resources; false to release only unmanaged resources. |
Overrides
EnlistTransaction(Transaction)
Enlists in the specified transaction.
Declaration
public override void EnlistTransaction(Transaction transaction)
Parameters
Type | Name | Description |
---|---|---|
Transaction | transaction | A reference to an existing Transaction in which to enlist. |
Overrides
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.
Declaration
public SessionPool.SessionPoolSegmentStatistics GetSessionPoolSegmentStatistics()
Returns
Type | Description |
---|---|
SessionPool.SessionPoolSegmentStatistics | The session pool statistics, or |
Sample code
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()
Opens a database connection with the settings specified by the ConnectionString.
Declaration
public override void Open()
Overrides
Open(SpannerTransactionCreationOptions, SpannerTransactionOptions)
Opens the connection within a TransactionScope with specific SpannerTransactionCreationOptions and SpannerTransactionOptions.
Declaration
public void Open(SpannerTransactionCreationOptions creationOptions, SpannerTransactionOptions options)
Parameters
Type | Name | Description |
---|---|---|
SpannerTransactionCreationOptions | creationOptions | Options to be used when creating the ambient SpannerTransaction. Must not be null. |
SpannerTransactionOptions | options | 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 |
OpenAsReadOnly(TimestampBound)
Call OpenAsReadOnly within a TransactionScope to open the connection with a read-only transaction with the given TimestampBound settings
Declaration
[Obsolete("Use the Open overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
public void OpenAsReadOnly(TimestampBound timestampBound = null)
Parameters
Type | Name | Description |
---|---|---|
TimestampBound | timestampBound | Specifies the timestamp or maximum staleness of a read operation. May be null. |
OpenAsReadOnly(TransactionId)
If this connection is being opened within a TransactionScope, this
will connect to an existing transaction identified by transactionId
.
Declaration
[Obsolete("Use the Open overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
public void OpenAsReadOnly(TransactionId transactionId)
Parameters
Type | Name | Description |
---|---|---|
TransactionId | transactionId | The TransactionId representing an active readonly SpannerTransaction. |
OpenAsReadOnlyAsync(TimestampBound, CancellationToken)
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.
Declaration
[Obsolete("Use the OpenAsync overload that takes SpannerTransactionCreationOptions and SpannerTransactionOptions parameters instead.")]
public Task OpenAsReadOnlyAsync(TimestampBound timestampBound = null, CancellationToken cancellationToken = default)
Parameters
Type | 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)
Opens the connection within a TransactionScope with specific SpannerTransactionCreationOptions and SpannerTransactionOptions.
Declaration
public Task OpenAsync(SpannerTransactionCreationOptions creationOptions, SpannerTransactionOptions options, CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
SpannerTransactionCreationOptions | creationOptions | Options to be used when creating the ambient SpannerTransaction. Must not be null. |
SpannerTransactionOptions | options | 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 |
CancellationToken | cancellationToken | The cancellation token for the operation. |
Returns
Type | Description |
---|---|
Task |
OpenAsync(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.
Declaration
public override Task OpenAsync(CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellationToken | The cancellation instruction. |
Returns
Type | Description |
---|---|
Task | A task representing the asynchronous operation. |
Overrides
RunWithRetriableTransaction(Action<SpannerTransaction>)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by work
.
Declaration
public void RunWithRetriableTransaction(Action<SpannerTransaction> work)
Parameters
Type | Name | Description |
---|---|---|
Action<SpannerTransaction> | work | 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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by work
.
Declaration
public void RunWithRetriableTransaction(Action<SpannerTransaction> work, SpannerTransactionCreationOptions transactionCreationOptions)
Parameters
Type | Name | Description |
---|---|---|
Action<SpannerTransaction> | work | The work to perform in each transaction attempt. |
SpannerTransactionCreationOptions | transactionCreationOptions | 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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Declaration
public Task RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task> asyncWork, SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, Task> | asyncWork | The work to perform in each transaction attempt. |
SpannerTransactionCreationOptions | transactionCreationOptions | 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
.
Sample code
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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Declaration
public Task RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task> asyncWork, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, Task> | asyncWork | 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
.
Sample code
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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Declaration
public Task<TResult> RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>> asyncWork, SpannerTransactionCreationOptions transactionCreationOptions, CancellationToken cancellationToken)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, Task<TResult>> | asyncWork | The work to perform in each transaction attempt. |
SpannerTransactionCreationOptions | transactionCreationOptions | 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<TResult> | The value returned by |
Type Parameters
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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Declaration
public Task<TResult> RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>> asyncWork, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, Task<TResult>> | asyncWork | The work to perform in each transaction attempt. |
CancellationToken | cancellationToken | An optional token for canceling the call. |
Returns
Type | Description |
---|---|
Task<TResult> | The value returned by |
Type Parameters
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>)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by work
.
Declaration
public TResult RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult> work)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, TResult> | work | The work to perform in each transaction attempt. |
Returns
Type | Description |
---|---|
TResult | The value returned by |
Type Parameters
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)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by work
.
Declaration
public TResult RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult> work, SpannerTransactionCreationOptions transactionCreationOptions)
Parameters
Type | Name | Description |
---|---|---|
Func<SpannerTransaction, TResult> | work | The work to perform in each transaction attempt. |
SpannerTransactionCreationOptions | transactionCreationOptions | 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 |
Type Parameters
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)
Shuts down the session pool associated with the connection. Further attempts to acquire sessions will fail immediately.
Declaration
public Task ShutdownSessionPoolAsync(CancellationToken cancellationToken = default)
Parameters
Type | 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.
Sample code
// 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)
Returns a task indicating when the session pool associated with the connection is populated up to its minimum size.
Declaration
public Task WhenSessionPoolReady(CancellationToken cancellationToken = default)
Parameters
Type | 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.
Sample code
// 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();
}