Documentation
¶
Index ¶
- Constants
- Variables
- func BeginBatchReadOnlyTransaction(ctx context.Context, db *sql.DB, options BatchReadOnlyTransactionOptions) (*sql.Tx, error)
- func BeginReadOnlyTransaction(ctx context.Context, db *sql.DB, options ReadOnlyTransactionOptions) (*sql.Tx, error)
- func BeginReadWriteTransaction(ctx context.Context, db *sql.DB, options ReadWriteTransactionOptions) (*sql.Tx, error)
- func CreateConnector(config ConnectorConfig) (driver.Connector, error)
- func RunTransaction(ctx context.Context, db *sql.DB, opts *sql.TxOptions, ...) error
- func RunTransactionWithOptions(ctx context.Context, db *sql.DB, opts *sql.TxOptions, ...) error
- func WithBatchReadOnly(level sql.IsolationLevel) sql.IsolationLevel
- func WithDisableRetryAborts(level sql.IsolationLevel) sql.IsolationLevel
- type AutocommitDMLMode
- type BatchReadOnlyTransactionOptions
- type ConnectorConfig
- type DecodeOption
- type Driver
- type ExecOptions
- type ExecutePartition
- type PartitionedQuery
- type PartitionedQueryOptions
- type ReadOnlyTransactionOptions
- type ReadWriteTransactionOptions
- type SpannerConn
Examples ¶
Constants ¶
const LevelNotice = slog.LevelInfo - 1
LevelNotice is the default logging level that the Spanner database/sql driver uses for informational logs. This level is deliberately chosen to be one level lower than the default log level, which is slog.LevelInfo. This prevents the driver from adding noise to any default logger that has been set for the application.
Variables ¶
var ErrAbortedDueToConcurrentModification = status.Error(codes.Aborted, "Transaction was aborted due to a concurrent modification")
ErrAbortedDueToConcurrentModification is returned by a read/write transaction that was aborted by Cloud Spanner, and where the internal retry attempt failed because it detected that the results during the retry were different from the initial attempt.
Use the RunTransaction function to execute a read/write transaction in a retry loop. This function will never return ErrAbortedDueToConcurrentModification.
Functions ¶
func BeginBatchReadOnlyTransaction ¶ added in v1.11.0
func BeginBatchReadOnlyTransaction(ctx context.Context, db *sql.DB, options BatchReadOnlyTransactionOptions) (*sql.Tx, error)
BeginBatchReadOnlyTransaction begins a batch read-only transaction on a Spanner database. The underlying spanner.BatchReadOnlyTransaction can be used to partition queries and execute the individual partitions that are returned. It can also be used with the PartitionedQueryOptions.AutoPartitionQuery option to automatically partition and execute a query.
NOTE: You *MUST* end the transaction by calling either Commit or Rollback on the transaction. Failure to do so will cause the connection that is used for the transaction to be leaked.
func BeginReadOnlyTransaction ¶ added in v1.10.0
func BeginReadOnlyTransaction(ctx context.Context, db *sql.DB, options ReadOnlyTransactionOptions) (*sql.Tx, error)
BeginReadOnlyTransaction begins a read-only transaction on a Spanner database.
NOTE: You *MUST* end the transaction by calling either Commit or Rollback on the transaction. Failure to do so will cause the connection that is used for the transaction to be leaked.
func BeginReadWriteTransaction ¶ added in v1.10.0
func BeginReadWriteTransaction(ctx context.Context, db *sql.DB, options ReadWriteTransactionOptions) (*sql.Tx, error)
BeginReadWriteTransaction begins a read/write transaction on a Spanner database. This function allows more options to be passed in that the generic sql.DB.BeginTx function.
NOTE: You *MUST* end the transaction by calling either Commit or Rollback on the transaction. Failure to do so will cause the connection that is used for the transaction to be leaked.
func CreateConnector ¶ added in v1.10.0
func CreateConnector(config ConnectorConfig) (driver.Connector, error)
CreateConnector creates a new driver.Connector for Spanner. A connector can be passed in to sql.OpenDB to obtain a sql.DB.
Use this method if you want to supply custom configuration for your Spanner connections, and cache the connector that is returned in your application. The same connector should be used to create all connections that should share the same configuration and the same underlying Spanner client.
Note: This function always creates a new connector, even if one with the same configuration has been created previously.
Example ¶
connectorConfig := ConnectorConfig{ Project: "my-project", Instance: "my-instance", Database: "my-database", Configurator: func(config *spanner.ClientConfig, opts *[]option.ClientOption) { config.DisableRouteToLeader = true }, } c, err := CreateConnector(connectorConfig) if err != nil { fmt.Println(err) return } db := sql.OpenDB(c) // Use the database ... defer db.Close()
Output:
func RunTransaction ¶ added in v1.8.0
func RunTransaction(ctx context.Context, db *sql.DB, opts *sql.TxOptions, f func(ctx context.Context, tx *sql.Tx) error) error
RunTransaction runs the given function in a transaction on the given database. If the connection is a connection to a Spanner database, the transaction will automatically be retried if the transaction is aborted by Spanner. Any other errors will be propagated to the caller and the transaction will be rolled back. The transaction will be committed if the supplied function did not return an error.
If the connection is to a non-Spanner database, no retries will be attempted, and any error that occurs during the transaction will be propagated to the caller.
The application should *NOT* call tx.Commit() or tx.Rollback(). This is done automatically by this function, depending on whether the transaction function returned an error or not.
This function will never return ErrAbortedDueToConcurrentModification.
func RunTransactionWithOptions ¶ added in v1.10.0
func RunTransactionWithOptions(ctx context.Context, db *sql.DB, opts *sql.TxOptions, f func(ctx context.Context, tx *sql.Tx) error, spannerOptions spanner.TransactionOptions) error
RunTransactionWithOptions runs the given function in a transaction on the given database. If the connection is a connection to a Spanner database, the transaction will automatically be retried if the transaction is aborted by Spanner. Any other errors will be propagated to the caller and the transaction will be rolled back. The transaction will be committed if the supplied function did not return an error.
If the connection is to a non-Spanner database, no retries will be attempted, and any error that occurs during the transaction will be propagated to the caller.
The application should *NOT* call tx.Commit() or tx.Rollback(). This is done automatically by this function, depending on whether the transaction function returned an error or not.
The given spanner.TransactionOptions will be used for the transaction.
This function will never return ErrAbortedDueToConcurrentModification.
func WithBatchReadOnly ¶ added in v1.11.0
func WithBatchReadOnly(level sql.IsolationLevel) sql.IsolationLevel
WithBatchReadOnly returns a specific Spanner isolation level that contains both the given standard isolation level and a custom Spanner isolation level that instructs Spanner to use a spanner.BatchReadOnlyTransaction. This isolation level should only be used for read-only transactions.
func WithDisableRetryAborts ¶ added in v1.9.0
func WithDisableRetryAborts(level sql.IsolationLevel) sql.IsolationLevel
WithDisableRetryAborts returns a specific Spanner isolation level that contains both the given standard isolation level and a custom Spanner isolation level that disables internal retries for aborted transactions for a single transaction.
Types ¶
type AutocommitDMLMode ¶
type AutocommitDMLMode int
AutocommitDMLMode indicates whether a single DML statement should be executed in a normal atomic transaction or as a Partitioned DML statement. See https://cloud.google.com/spanner/docs/dml-partitioned for more information.
const ( Transactional AutocommitDMLMode = iota PartitionedNonAtomic )
func (AutocommitDMLMode) String ¶
func (mode AutocommitDMLMode) String() string
type BatchReadOnlyTransactionOptions ¶ added in v1.11.0
type BatchReadOnlyTransactionOptions struct { TimestampBound spanner.TimestampBound // contains filtered or unexported fields }
type ConnectorConfig ¶ added in v1.10.0
type ConnectorConfig struct { // Host is the Spanner host that the connector should connect to. // Leave this empty to use the standard Spanner API endpoint. Host string // Project, Instance, and Database identify the database that the connector // should create connections for. Project string Instance string Database string // Params contains key/value pairs for commonly used configuration parameters // for connections. The valid values are the same as the parameters that can // be added to a connection string. Params map[string]string // The initial values for automatic DML batching. // The values in the Params map take precedence above these. AutoBatchDml bool AutoBatchDmlUpdateCount int64 DisableAutoBatchDmlUpdateCountVerification bool // DecodeToNativeArrays determines whether arrays that have a Go native // type should be decoded to those types rather than the corresponding // spanner.NullTypeName type. // Enabling this option will for example decode ARRAY<BOOL> to []bool instead // of []spanner.NullBool. // // See ExecOptions.DecodeToNativeArrays for more information. DecodeToNativeArrays bool // Configurator is called with the spanner.ClientConfig and []option.ClientOption // that will be used to create connections by the driver.Connector. Use this // function to set any further advanced configuration options that cannot be set // with a standard key/value pair in the Params map. Configurator func(config *spanner.ClientConfig, opts *[]option.ClientOption) // contains filtered or unexported fields }
ConnectorConfig contains the configuration for a Spanner driver.Connector.
func ExtractConnectorConfig ¶ added in v1.10.0
func ExtractConnectorConfig(dsn string) (ConnectorConfig, error)
ExtractConnectorConfig extracts a ConnectorConfig for Spanner from the given data source name.
func (*ConnectorConfig) String ¶ added in v1.10.0
func (cc *ConnectorConfig) String() string
type DecodeOption ¶ added in v1.10.0
type DecodeOption int
const ( // DecodeOptionNormal decodes into idiomatic Go types (e.g. bool, string, int64, etc.) DecodeOptionNormal DecodeOption = iota // DecodeOptionProto does not decode the returned rows at all, and instead just returns // the underlying protobuf objects. Use this for advanced use-cases where you want // direct access to the underlying values. // All values should be scanned into an instance of spanner.GenericColumnValue like this: // // var v spanner.GenericColumnValue // row.Scan(&v) DecodeOptionProto )
type Driver ¶
type Driver struct {
// contains filtered or unexported fields
}
Driver represents a Google Cloud Spanner database/sql driver.
type ExecOptions ¶ added in v1.10.0
type ExecOptions struct { // DecodeOption indicates how the returned rows should be decoded. DecodeOption DecodeOption // DecodeToNativeArrays determines whether arrays that have a Go // native type should use that. This option has an effect on arrays // that contain: // * BOOL // * INT64 and ENUM // * STRING // * FLOAT32 // * FLOAT64 // * DATE // * TIMESTAMP // These arrays will by default be decoded to the following types: // * []spanner.NullBool // * []spanner.NullInt64 // * []spanner.NullString // * []spanner.NullFloat32 // * []spanner.NullFloat64 // * []spanner.NullDate // * []spanner.NullTime // By setting DecodeToNativeArrays, these arrays will instead be // decoded to: // * []bool // * []int64 // * []string // * []float32 // * []float64 // * []civil.Date // * []time.Time // If this option is used with rows that contains an array with // at least one NULL element, the decoding will fail. // This option has no effect on arrays of type JSON, NUMERIC and BYTES. DecodeToNativeArrays bool // TransactionOptions are the transaction options that will be used for // the transaction that is started by the statement. TransactionOptions spanner.TransactionOptions // QueryOptions are the query options that will be used for the statement. QueryOptions spanner.QueryOptions // PartitionedQueryOptions are used for partitioned queries, and ignored // for all other statements. PartitionedQueryOptions PartitionedQueryOptions }
ExecOptions can be passed in as an argument to the Query, QueryContext, Exec, and ExecContext functions to specify additional execution options for a statement.
type ExecutePartition ¶ added in v1.11.0
type ExecutePartition struct { PartitionedQuery *PartitionedQuery Index int }
ExecutePartition is used to instruct the driver to execute one of the partitions that was returned by a previous call to PartitionQuery.
type PartitionedQuery ¶ added in v1.11.0
type PartitionedQuery struct { Partitions []*spanner.Partition // contains filtered or unexported fields }
PartitionedQuery is returned by the driver when a query is executed on a BatchReadOnlyTransaction with the PartitionedQueryOptions.PartitionQuery option set to true.
func (*PartitionedQuery) Close ¶ added in v1.11.0
func (pq *PartitionedQuery) Close()
func (*PartitionedQuery) Scan ¶ added in v1.11.0
func (pq *PartitionedQuery) Scan(value any) error
type PartitionedQueryOptions ¶ added in v1.11.0
type PartitionedQueryOptions struct { // AutoPartitionQuery instructs the Spanner driver to automatically // partition the query, execute each partition, and return the results // as a single set of sql.Rows. This option can be used for queries // that are executed in a spanner.BatchReadOnlyTransaction and for // ad-hoc queries outside a transaction. AutoPartitionQuery bool // MaxParallelism is the maximum number of goroutines that will be // used to read data from an auto-partitioned query. This option // is only used if AutoPartitionQuery has been set to true. // Defaults to runtime.NumCPU. MaxParallelism int // PartitionQuery instructs the driver to only partition the query that // is being executed, instead of actually executing the query. The returned // rows will contain only one row with one column. This value should be // scanned into a spannerdriver.PartitionedQuery value. // This option can only be for queries that are executed using a transaction // that was started by spannerdriver.BeginBatchReadOnlyTransaction. // // Example: // tx, _ := spannerdriver.BeginBatchReadOnlyTransaction(ctx, db, BatchReadOnlyTransactionOptions{}) // row := tx.QueryRowContext(ctx, testutil.SelectFooFromBar, spannerdriver.ExecOptions{ // PartitionedQueryOptions: spannerdriver.PartitionedQueryOptions{ // PartitionQuery: true, // }}) // var pq spannerdriver.PartitionedQuery // _ = row.Scan(&pq) // // Execute each of the partitions. // for index := range pq.Partitions { // rows, _ := pq.Execute(ctx, index, db) // for rows.Next() { // // Read data ... // } // rows.Close() // } // _ = tx.Commit() PartitionQuery bool // PartitionOptions are used to partition the given query. These // options are only used when one of AutoPartitionQuery or PartitionQuery // are set to true. PartitionOptions spanner.PartitionOptions // ExecutePartition instructs the driver to execute a specific spanner.Partition // that has previously been returned by a PartitionQuery call. ExecutePartition ExecutePartition }
PartitionedQueryOptions are used for queries that use the AutoPartitionQuery option, or for calls to PartitionQuery. These options are ignored for all other statements.
type ReadOnlyTransactionOptions ¶ added in v1.10.0
type ReadOnlyTransactionOptions struct { TimestampBound spanner.TimestampBound // contains filtered or unexported fields }
ReadOnlyTransactionOptions can be used to create a read-only transaction on a Spanner connection.
type ReadWriteTransactionOptions ¶ added in v1.10.0
type ReadWriteTransactionOptions struct { // TransactionOptions are passed through to the Spanner client to use for // the read/write transaction. TransactionOptions spanner.TransactionOptions // DisableInternalRetries disables checksum-based retries of Aborted errors // for this transaction. By default, read/write transactions keep track of // a running checksum of all results it receives from Spanner. If Spanner // aborts the transaction, the transaction is retried by the driver and the // checksums of the initial attempt and the retry are compared. If the // checksums differ, the transaction fails with an Aborted error. // // If DisableInternalRetries is set to true, checksum-based retries are // disabled, and any Aborted error from Spanner is propagated to the // application. DisableInternalRetries bool // contains filtered or unexported fields }
type SpannerConn ¶
type SpannerConn interface { // StartBatchDDL starts a DDL batch on the connection. After calling this // method all subsequent DDL statements will be cached locally. Calling // RunBatch will send all cached DDL statements to Spanner as one batch. // Use DDL batching to speed up the execution of multiple DDL statements. // Note that a DDL batch is not atomic. It is possible that some DDL // statements are executed successfully and some not. // See https://cloud.google.com/spanner/docs/schema-updates#order_of_execution_of_statements_in_batches // for more information on how Cloud Spanner handles DDL batches. StartBatchDDL() error // StartBatchDML starts a DML batch on the connection. After calling this // method all subsequent DML statements will be cached locally. Calling // RunBatch will send all cached DML statements to Spanner as one batch. // Use DML batching to speed up the execution of multiple DML statements. // DML batches can be executed both outside of a transaction and during // a read/write transaction. If a DML batch is executed outside an active // transaction, the batch will be applied atomically to the database if // successful and rolled back if one or more of the statements fail. // If a DML batch is executed as part of a transaction, the error will // be returned to the application, and the application can decide whether // to commit or rollback the transaction. StartBatchDML() error // RunBatch sends all batched DDL or DML statements to Spanner. This is a // no-op if no statements have been batched or if there is no active batch. RunBatch(ctx context.Context) error // AbortBatch aborts the current DDL or DML batch and discards all batched // statements. AbortBatch() error // InDDLBatch returns true if the connection is currently in a DDL batch. InDDLBatch() bool // InDMLBatch returns true if the connection is currently in a DML batch. InDMLBatch() bool // GetBatchedStatements returns a copy of the statements that are currently // buffered to be executed as a DML or DDL batch. It returns an empty slice // if no batch is active, or if there are no statements buffered. GetBatchedStatements() []spanner.Statement // AutoBatchDml determines whether DML statements should automatically // be batched and sent to Spanner when a non-DML statement is encountered. // The update count that is returned for DML statements that are buffered // is by default 1. This default can be changed by setting the connection // variable AutoBatchDmlUpdateCount to a value other than 1. // This feature is only used in read/write transactions. DML statements // outside transactions are always executed directly. AutoBatchDml() bool SetAutoBatchDml(autoBatch bool) error // AutoBatchDmlUpdateCount determines the update count that is returned for // DML statements that are executed when AutoBatchDml is true. AutoBatchDmlUpdateCount() int64 SetAutoBatchDmlUpdateCount(updateCount int64) error // AutoBatchDmlUpdateCountVerification enables/disables the verification // that the update count that was returned for automatically batched DML // statements was correct. AutoBatchDmlUpdateCountVerification() bool SetAutoBatchDmlUpdateCountVerification(verify bool) error // RetryAbortsInternally returns true if the connection automatically // retries all aborted transactions. RetryAbortsInternally() bool // SetRetryAbortsInternally enables/disables the automatic retry of aborted // transactions. If disabled, any aborted error from a transaction will be // propagated to the application. SetRetryAbortsInternally(retry bool) error // AutocommitDMLMode returns the current mode that is used for DML // statements outside a transaction. The default is Transactional. AutocommitDMLMode() AutocommitDMLMode // SetAutocommitDMLMode sets the mode to use for DML statements that are // executed outside transactions. The default is Transactional. Change to // PartitionedNonAtomic to use Partitioned DML instead of Transactional DML. // See https://cloud.google.com/spanner/docs/dml-partitioned for more // information on Partitioned DML. SetAutocommitDMLMode(mode AutocommitDMLMode) error // ReadOnlyStaleness returns the current staleness that is used for // queries in autocommit mode, and for read-only transactions. ReadOnlyStaleness() spanner.TimestampBound // SetReadOnlyStaleness sets the staleness to use for queries in autocommit // mode and for read-only transaction. SetReadOnlyStaleness(staleness spanner.TimestampBound) error // TransactionTag returns the transaction tag that will be applied to the next // read/write transaction on this connection. The transaction tag that is set // on the connection is cleared when a read/write transaction is started. TransactionTag() string // SetTransactionTag sets the transaction tag that should be applied to the // next read/write transaction on this connection. The tag is cleared when a // read/write transaction is started. SetTransactionTag(transactionTag string) error // MaxCommitDelay returns the max commit delay that will be applied to read/write // transactions on this connection. MaxCommitDelay() time.Duration // SetMaxCommitDelay sets the max commit delay that will be applied to read/write // transactions on this connection. SetMaxCommitDelay(delay time.Duration) error // ExcludeTxnFromChangeStreams returns true if the next transaction should be excluded from change streams with the // DDL option `allow_txn_exclusion=true`. ExcludeTxnFromChangeStreams() bool // SetExcludeTxnFromChangeStreams sets whether the next transaction should be excluded from change streams with the // DDL option `allow_txn_exclusion=true`. SetExcludeTxnFromChangeStreams(excludeTxnFromChangeStreams bool) error // DecodeToNativeArrays indicates whether arrays with a Go native type // should be decoded to those native types instead of the corresponding // spanner.NullTypeName (e.g. []bool vs []spanner.NullBool). // See ExecOptions.DecodeToNativeArrays for more information. DecodeToNativeArrays() bool // SetDecodeToNativeArrays sets whether arrays with a Go native type // should be decoded to those native types instead of the corresponding // spanner.NullTypeName (e.g. []bool vs []spanner.NullBool). // See ExecOptions.DecodeToNativeArrays for more information. SetDecodeToNativeArrays(decodeToNativeArrays bool) error // Apply writes an array of mutations to the database. This method may only be called while the connection // is outside a transaction. Use BufferWrite to write mutations in a transaction. // See also spanner.Client#Apply Apply(ctx context.Context, ms []*spanner.Mutation, opts ...spanner.ApplyOption) (commitTimestamp time.Time, err error) // BufferWrite writes an array of mutations to the current transaction. This method may only be called while the // connection is in a read/write transaction. Use Apply to write mutations outside a transaction. // See also spanner.ReadWriteTransaction#BufferWrite BufferWrite(ms []*spanner.Mutation) error // CommitTimestamp returns the commit timestamp of the last implicit or explicit read/write transaction that // was executed on the connection, or an error if the connection has not executed a read/write transaction // that committed successfully. The timestamp is in the local timezone. CommitTimestamp() (commitTimestamp time.Time, err error) // UnderlyingClient returns the underlying Spanner client for the database. // The client cannot be used to access the current transaction or batch on // this connection. Executing a transaction or batch using the client that is // returned, does not affect this connection. // Note that multiple connections share the same Spanner client. Calling // this function on different connections to the same database, can // return the same Spanner client. UnderlyingClient() (client *spanner.Client, err error) // contains filtered or unexported methods }
SpannerConn is the public interface for the raw Spanner connection for the sql driver. This interface can be used with the db.Conn().Raw() method.