spannerdriver

package module
v1.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 14, 2025 License: Apache-2.0 Imports: 37 Imported by: 83

README

go-sql-spanner

go.dev reference

Google Cloud Spanner driver for Go's database/sql package.

import _ "github.com/googleapis/go-sql-spanner"

db, err := sql.Open("spanner", "projects/PROJECT/instances/INSTANCE/databases/DATABASE")
if err != nil {
    log.Fatal(err)
}

// Print tweets with more than 500 likes.
rows, err := db.QueryContext(ctx, "SELECT id, text FROM tweets WHERE likes > @likes", sql.Named("likes", 500))
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var (
    id   int64
    text string
)
for rows.Next() {
    if err := rows.Scan(&id, &text); err != nil {
        log.Fatal(err)
    }
    fmt.Println(id, text)
}

Statements

Statements support follows the official Google Cloud Spanner Go client style arguments as well as positional parameters. It is highly recommended to use either positional parameters in combination with positional arguments, or named parameters in combination with named arguments.

Using positional parameters with positional arguments
db.QueryContext(ctx, "SELECT id, text FROM tweets WHERE likes > ?", 500)

db.ExecContext(ctx, "INSERT INTO tweets (id, text, rts) VALUES (?, ?, ?)", id, text, 10000)
Using named parameters with named arguments
db.ExecContext(ctx, "DELETE FROM tweets WHERE id = @id", sql.Named("id", 14544498215374))

db.ExecContext(ctx, "INSERT INTO tweets (id, text, rts) VALUES (@id, @text, @rts)",
	sql.Named("id", id), sql.Named("text", text), sql.Named("rts", 10000))

Named parameters can also be used in combination with positional arguments, but this is not recommended, as the behavior can be hard to predict if the same named query parameter is used in multiple places in the statement.

// Possible, but not recommended.
db.ExecContext(ctx, "DELETE FROM tweets WHERE id = @id", 14544498215374)
Query Options

Query options can be passed in as arguments to a query. Pass in a value of type spannerdriver.ExecOptions to supply additional execution options for a statement. The spanner.QueryOptions will be passed through to the Spanner client as the query options to use for the query or DML statement.

tx.ExecContext(ctx, "INSERT INTO Singers (SingerId, Name) VALUES (@id, @name)",
	spannerdriver.ExecOptions{QueryOptions: spanner.QueryOptions{RequestTag: "insert_singer"}},
    123, "Bruce Allison")
tx.QueryContext(ctx, "SELECT SingerId, Name FROM Singers WHERE SingerId = ?",
    spannerdriver.ExecOptions{QueryOptions: spanner.QueryOptions{RequestTag: "select_singer"}},
    123)

Statement tags (request tags) can also be set using the custom SQL statement set statement_tag='my_tag':

tx.ExecContext(ctx, "set statement_tag = 'select_singer'")
tx.QueryContext(ctx, "SELECT SingerId, Name FROM Singers WHERE SingerId = ?", 123)

Transactions

  • Read-write transactions always uses the strongest isolation level and ignore the user-specified level.
  • Read-only transactions do strong-reads by default. Read-only transactions must be ended by calling either Commit or Rollback. Calling either of these methods will end the current read-only transaction and return the session that is used to the session pool.
tx, err := db.BeginTx(ctx, &sql.TxOptions{}) // Read-write transaction.

// Read-write transaction with a transaction tag.
conn, _ := db.Conn(ctx)
_, _ := conn.ExecContext(ctx, "SET TRANSACTION_TAG='my_transaction_tag'")
tx, err := conn.BeginTx(ctx, &sql.TxOptions{})


tx, err := db.BeginTx(ctx, &sql.TxOptions{
    ReadOnly: true, // Read-only transaction using strong reads.
})

conn, _ := db.Conn(ctx)
_, _ := conn.ExecContext(ctx, "SET READ_ONLY_STALENESS='EXACT_STALENESS 10s'")
tx, err := conn.BeginTx(ctx, &sql.TxOptions{
    ReadOnly: true, // Read-only transaction using a 10 second exact staleness.
})

Transaction Runner (Retry Transactions)

Spanner can abort a read/write transaction if concurrent modifications are detected that would violate the transaction consistency. When this happens, the driver will return the ErrAbortedDueToConcurrentModification error. You can use the RunTransaction and RunTransactionWithOptions functions to let the driver automatically retry transactions that are aborted by Spanner.

package sample

import (
  "context"
  "database/sql"
  "fmt"

  _ "github.com/googleapis/go-sql-spanner"
  spannerdriver "github.com/googleapis/go-sql-spanner"
)

spannerdriver.RunTransactionWithOptions(ctx, db, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error {
    row := tx.QueryRowContext(ctx, "select Name from Singers where SingerId=@id", 123)
    var name string
    if err := row.Scan(&name); err != nil {
        return err
    }
    return nil
}, spanner.TransactionOptions{TransactionTag: "my_transaction_tag"})

See also the transaction runner sample.

DDL Statements

DDL statements are not supported in transactions per Cloud Spanner restriction. Instead, run them on a connection without an active transaction:

db.ExecContext(ctx, "CREATE TABLE ...")

Multiple DDL statements can be sent in one batch to Cloud Spanner by defining a DDL batch:

conn, _ := db.Conn(ctx)
_, _ := conn.ExecContext(ctx, "START BATCH DDL")
_, _ = conn.ExecContext(ctx, "CREATE TABLE Singers (SingerId INT64, Name STRING(MAX)) PRIMARY KEY (SingerId)")
_, _ = conn.ExecContext(ctx, "CREATE INDEX Idx_Singers_Name ON Singers (Name)")
// Executing `RUN BATCH` will run the previous DDL statements as one batch.
_, _ := conn.ExecContext(ctx, "RUN BATCH")

See also the batch DDL example.

Examples

The examples directory contains standalone code samples that show how to use common features of Cloud Spanner and/or the database/sql package. Each standalone code sample can be executed without any prior setup, as long as Docker is installed on your local system.

Raw Connection / Specific Cloud Spanner Features

Use the Conn.Raw method to get access to a Cloud Spanner specific connection instance. This instance can be used to access Cloud Spanner specific features and settings, such as mutations, read-only staleness settings and commit timestamps.

conn, _ := db.Conn(ctx)
_ = conn.Raw(func(driverConn interface{}) error {
    spannerConn, ok := driverConn.(spannerdriver.SpannerConn)
    if !ok {
        return fmt.Errorf("unexpected driver connection %v, expected SpannerConn", driverConn)
    }
    // Use the `SpannerConn` interface to set specific Cloud Spanner settings or access
    // specific Cloud Spanner features.

    // Example: Set and get the current read-only staleness of the connection.
    _ = spannerConn.SetReadOnlyStaleness(spanner.ExactStaleness(10 * time.Second))
    _ = spannerConn.ReadOnlyStaleness()

    return nil
})

See also the examples directory for further code samples.

Emulator

See Google Cloud Spanner Emulator to learn how to start the emulator. Once the emulator is started and the host environmental flag is set, the driver will automatically connect to the emulator.

$ gcloud beta emulators spanner start
$ export SPANNER_EMULATOR_HOST=localhost:9010

Spanner PostgreSQL Interface

This driver only works with the Spanner GoogleSQL dialect. For the Spanner PostgreSQL dialect, any PostgreSQL driver that implements the database/sql interface can be used in combination with PGAdapter.

For example, the pgx driver can be used in combination with PGAdapter: https://github.com/GoogleCloudPlatform/pgadapter/blob/postgresql-dialect/docs/pgx.md

Troubleshooting

The driver will retry any Aborted error that is returned by Cloud Spanner during a read/write transaction. If the driver detects that the data that was used by the transaction was changed by another transaction between the initial attempt and the retry attempt, the Aborted error will be propagated to the client application as an spannerdriver.ErrAbortedDueToConcurrentModification error.

Go Versions Supported

Our libraries are compatible with at least the three most recent, major Go releases. They are currently compatible with:

  • Go 1.23
  • Go 1.22
  • Go 1.21

Authorization

By default, each API will use Google Application Default Credentials for authorization credentials used in calling the API endpoints. This will allow your application to run in many environments without requiring explicit configuration.

Contributing

Contributions are welcome. Please, see the CONTRIBUTING document for details.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Contributor Code of Conduct for more information.

Documentation

Index

Examples

Constants

View Source
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

View Source
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.

func (*Driver) Open

func (d *Driver) Open(name string) (driver.Conn, error)

Open opens a connection to a Google Cloud Spanner database. Use fully qualified string:

Example: projects/$PROJECT/instances/$INSTANCE/databases/$DATABASE

func (*Driver) OpenConnector

func (d *Driver) OpenConnector(name string) (driver.Connector, error)

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) Execute added in v1.11.0

func (pq *PartitionedQuery) Execute(ctx context.Context, index int, db *sql.DB) (*sql.Rows, error)

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.

Directories

Path Synopsis
benchmarks module
examples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL