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 .
Namespace
Google.Cloud.Spanner.DataAssembly
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
|
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
|
credentials | ChannelCredentials An optional credential for operations to be performed on the Spanner database. May be null. |
string connectionString = "Data Source=projects/my-project/instances/my-instance/databases/my-db";
SpannerConnection connection = new SpannerConnection(connectionString);
Console.WriteLine(connection.Project);
Console.WriteLine(connection.SpannerInstance);
Console.WriteLine(connection.Database);
Properties
ConnectionString
public override string ConnectionString { get; set; }
Property Value | |
---|---|
Type | Description |
string |
Database
public override string Database { get; }
Property Value | |
---|---|
Type | Description |
string |
DataSource
public override string DataSource { get; }
Property Value | |
---|---|
Type | Description |
string |
DbProviderFactory
protected override DbProviderFactory DbProviderFactory { get; }
Property Value | |
---|---|
Type | Description |
DbProviderFactory |
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 |
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; }
Property Value | |
---|---|
Type | Description |
string |
SpannerInstance
public string SpannerInstance { get; }
The Spanner instance name
Property Value | |
---|---|
Type | Description |
string |
State
public override ConnectionState State { get; }
Property Value | |
---|---|
Type | Description |
ConnectionState |
Methods
BeginDbTransaction(IsolationLevel)
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
Parameter | |
---|---|
Name | Description |
isolationLevel | IsolationLevel |
Returns | |
---|---|
Type | Description |
DbTransaction |
BeginDbTransactionAsync(IsolationLevel, CancellationToken)
protected override ValueTask<DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
Parameters | |
---|---|
Name | Description |
isolationLevel | IsolationLevel |
cancellationToken | CancellationToken |
Returns | |
---|---|
Type | Description |
ValueTaskDbTransaction |
BeginReadOnlyTransaction()
public SpannerTransaction BeginReadOnlyTransaction()
Begins a read-only transaction.
Returns | |
---|---|
Type | Description |
SpannerTransaction | The newly created SpannerTransaction. |
Read-only transactions are preferred if possible because they do not impose locks internally. Read-only transactions run with strong consistency and return the latest copy of data.
This method is thread safe.
BeginReadOnlyTransaction(TimestampBound)
public SpannerTransaction BeginReadOnlyTransaction(TimestampBound targetReadTimestamp)
Begins a read-only transaction using the provided TimestampBound to control the read timestamp and/or staleness of data.
Parameter | |
---|---|
Name | Description |
targetReadTimestamp | TimestampBound Specifies the timestamp or allowed staleness of data. Must not be null. |
Returns | |
---|---|
Type | Description |
SpannerTransaction | The newly created SpannerTransaction. |
Read-only transactions are preferred if possible because they do not impose locks internally. Read-only transactions run with strong consistency and return the latest copy of data.
This method is thread safe.
BeginReadOnlyTransaction(TransactionId)
public SpannerTransaction BeginReadOnlyTransaction(TransactionId transactionId)
Begins a read-only transaction using the provided TransactionId to refer to an existing server-side transaction.
Parameter | |
---|---|
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
|
Read-only transactions are preferred if possible because they do not impose locks internally. Providing a transaction ID will connect to an already created transaction which is useful for batch reads. This method differs from the parameterless overload and the overload accepting a TimestampBound as it uses an existing transaction rather than creating a new server-side transaction.
BeginReadOnlyTransactionAsync(TimestampBound, CancellationToken)
public Task<SpannerTransaction> BeginReadOnlyTransactionAsync(TimestampBound targetReadTimestamp, CancellationToken cancellationToken = default)
Begins a read-only transaction using the optionally provided CancellationToken and provided TimestampBound to control the read timestamp and/or staleness of data. Read transactions are preferred if possible because they do not impose locks internally. Stale read-only transactions can execute more quickly than strong or read-write transactions,. This method is thread safe.
Parameters | |
---|---|
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)
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 |
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)
Parameter | |
---|---|
Name | Description |
newDataSource | string |
Close()
public override void Close()
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()
Returns | |
---|---|
Type | Description |
DbCommand |
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 |
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 |
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
// Read the first two keys in the database.
List<string> keys = new List<string>();
SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
{
while (keys.Count < 3 && await reader.ReadAsync())
{
keys.Add(reader.GetFieldValue<string>("Key"));
}
}
// Update the Int64Value of keys[0]
// Include the primary key and update columns.
SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
await updateCmd.ExecuteNonQueryAsync();
// Delete row for keys[1]
SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
await deleteCmd.ExecuteNonQueryAsync();
});
CreateDmlCommand(string, SpannerParameterCollection)
public SpannerCommand CreateDmlCommand(string dmlStatement, SpannerParameterCollection dmlParameters = null)
Creates a new SpannerCommand to execute a general DML (UPDATE, INSERT, DELETE) statement. This method is thread safe.
Parameters | |
---|---|
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 |
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 |
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
// Read the first two keys in the database.
List<string> keys = new List<string>();
SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
{
while (keys.Count < 3 && await reader.ReadAsync())
{
keys.Add(reader.GetFieldValue<string>("Key"));
}
}
// Update the Int64Value of keys[0]
// Include the primary key and update columns.
SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
await updateCmd.ExecuteNonQueryAsync();
// Delete row for keys[1]
SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
await deleteCmd.ExecuteNonQueryAsync();
});
CreateUpdateCommand(string, SpannerParameterCollection)
public SpannerCommand CreateUpdateCommand(string databaseTable, SpannerParameterCollection updateColumns = null)
Creates a new SpannerCommand to update rows in a Spanner database table. This method is thread safe.
Parameters | |
---|---|
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 |
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
// Read the first two keys in the database.
List<string> keys = new List<string>();
SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
{
while (keys.Count < 3 && await reader.ReadAsync())
{
keys.Add(reader.GetFieldValue<string>("Key"));
}
}
// Update the Int64Value of keys[0]
// Include the primary key and update columns.
SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
await updateCmd.ExecuteNonQueryAsync();
// Delete row for keys[1]
SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
await deleteCmd.ExecuteNonQueryAsync();
});
Dispose(bool)
protected override void Dispose(bool disposing)
Parameter | |
---|---|
Name | Description |
disposing | bool |
EnlistTransaction(Transaction)
public override void EnlistTransaction(Transaction transaction)
Parameter | |
---|---|
Name | Description |
transaction | Transaction |
GetSessionPoolDatabaseStatistics()
[Obsolete("Use GetSessionPoolSegmentStatistics instead. Both methods return the same data, but the $GetSessionPoolSegmentStatistics name better reflects the fact that sessions are pooled on aspects other than database name.")]
public SessionPool.DatabaseStatistics GetSessionPoolDatabaseStatistics()
Retrieves the database-specific statistics for the session pool associated with the connection string. The connection string must include a database name.
Returns | |
---|---|
Type | Description |
Google.Cloud.Spanner.V1.SessionPoolGoogle.Cloud.Spanner.V1.SessionPool.DatabaseStatistics | The session pool statistics, or |
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 |
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
SessionPool.SessionPoolSegmentStatistics stats = connection.GetSessionPoolSegmentStatistics();
if (stats is null)
{
Console.WriteLine("No session pool for this connection string yet");
}
else
{
// Access individual properties...
Console.WriteLine($"Database name: {stats.DatabaseName}");
Console.WriteLine($"Active sessions: {stats.ActiveSessionCount}");
Console.WriteLine($"Pooled read-only sessions: {stats.ReadPoolCount}");
Console.WriteLine($"Pooled read-write sessions: {stats.ReadWritePoolCount}");
// ... or just use the overridden ToString method to log all the statistics in one go:
Console.WriteLine(stats);
}
}
Open()
public override void Open()
OpenAsReadOnly(TimestampBound)
public void OpenAsReadOnly(TimestampBound timestampBound = null)
Call OpenAsReadOnly within a TransactionScope to open the connection with a read-only transaction with the given TimestampBound settings
Parameter | |
---|---|
Name | Description |
timestampBound | TimestampBound Specifies the timestamp or maximum staleness of a read operation. May be null. |
OpenAsReadOnly(TransactionId)
public void OpenAsReadOnly(TransactionId transactionId)
If this connection is being opened within a TransactionScope, this
will connect to an existing transaction identified by transactionId
.
Parameter | |
---|---|
Name | Description |
transactionId | TransactionId The TransactionId representing an active readonly SpannerTransaction. |
OpenAsReadOnlyAsync(TimestampBound, CancellationToken)
public Task OpenAsReadOnlyAsync(TimestampBound timestampBound = null, CancellationToken cancellationToken = default)
If this connection is being opened within a TransactionScope, this forces the created Cloud Spanner transaction to be a read-only transaction with the given TimestampBound settings.
Parameters | |
---|---|
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(CancellationToken)
public override Task OpenAsync(CancellationToken cancellationToken)
Parameter | |
---|---|
Name | Description |
cancellationToken | CancellationToken |
Returns | |
---|---|
Type | Description |
Task |
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. |
work
will be fully retried whenever the SpannerTransaction
that it receives as a parameter aborts. work
won't be retried if any other errors occur.
work
must be prepared to be called more than once.
A new SpannerTransaction will be passed to work
each time it is rerun.
work
doesn't need to handle the lifecycle of the SpannerTransaction,
it will be automatically committed after work
has finished or rollbacked if an
Exception (other than because the transaction aborted) is thrown by work
.
RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult>)
public TResult RunWithRetriableTransaction<TResult>(Func<SpannerTransaction, TResult> work)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by work
.
Parameter | |
---|---|
Name | Description |
work | FuncSpannerTransaction The work to perform in each transaction attempt. |
Returns | |
---|---|
Type | Description |
TResult | The value returned by |
Type Parameter | |
---|---|
Name | Description |
TResult |
work
will be fully retried whenever the SpannerTransaction
that it receives as a parameter aborts. work
won't be retried if any other errors occur.
work
must be prepared to be called more than once.
A new SpannerTransaction will be passed to work
each time it is rerun.
work
doesn't need to handle the lifecycle of the SpannerTransaction,
it will be automatically committed after work
has finished or rollbacked if an
Exception (other than because the transaction aborted) is thrown by work
.
RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task>, CancellationToken)
public Task RunWithRetriableTransactionAsync(Func<SpannerTransaction, Task> asyncWork, CancellationToken cancellationToken = default)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Parameters | |
---|---|
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. |
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
.
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
await connection.RunWithRetriableTransactionAsync(async transaction =>
{
SpannerCommand cmd = connection.CreateInsertCommand("TestTable");
SpannerParameter keyParameter = cmd.Parameters.Add("Key", SpannerDbType.String);
SpannerParameter stringValueParameter = cmd.Parameters.Add("StringValue", SpannerDbType.String);
SpannerParameter int64ValueParameter = cmd.Parameters.Add("Int64Value", SpannerDbType.Int64);
cmd.Transaction = transaction;
// This executes 5 distinct insert commands using the retriable transaction.
// The mutations will be effective once the transaction has committed successfully.
for (int i = 0; i < 5; i++)
{
keyParameter.Value = Guid.NewGuid().ToString("N");
stringValueParameter.Value = $"StringValue{i}";
int64ValueParameter.Value = i;
int rowsAffected = await cmd.ExecuteNonQueryAsync();
Console.WriteLine($"{rowsAffected} rows written...");
}
});
}
RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>>, CancellationToken)
public Task<TResult> RunWithRetriableTransactionAsync<TResult>(Func<SpannerTransaction, Task<TResult>> asyncWork, CancellationToken cancellationToken = default)
Executes a read-write transaction, with retries as necessary.
The work to perform in each transaction attempt is defined by asyncWork
.
Parameters | |
---|---|
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 |
Type Parameter | |
---|---|
Name | Description |
TResult |
asyncWork
will be fully retried whenever the SpannerTransaction
that it receives as a parameter aborts. asyncWork
won't be retried if any other errors occur.
asyncWork
must be prepared to be called more than once.
A new SpannerTransaction will be passed to asyncWork
each time it is rerun.
asyncWork
doesn't need to handle the lifecycle of the SpannerTransaction,
it will be automatically committed after asyncWork
has finished or rollbacked if an
Exception (other than because the transaction commit aborted) is thrown by asyncWork
.
ShutdownSessionPoolAsync(CancellationToken)
public Task ShutdownSessionPoolAsync(CancellationToken cancellationToken = default)
Shuts down the session pool associated with the connection. Further attempts to acquire sessions will fail immediately.
Parameter | |
---|---|
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. |
This call will delete all pooled sessions, and wait for all active sessions to be released back to the pool and also deleted.
// 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. |
If the pool is unhealthy or becomes unhealthy before it reaches its minimum size, the returned task will be faulted with an RpcException.
// 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();
}