Package com.google.cloud.spanner

A client for Cloud Spanner - A no-compromise relational database service. See Also: Cloud Spanner

Classes

AbstractLazyInitializer<T>

Generic AbstractLazyInitializer for any heavy-weight object that might throw an exception during initialization. The underlying object is initialized at most once.

AbstractStructReader

Base class for assisting StructReader implementations.

This class implements the majority of the StructReader interface, leaving subclasses to implement core data access via the getTypeNameInternal() methods. AbstractStructReader guarantees that these will only be called for non-NULL columns of a type appropriate for the method.

Backup

Represents a Cloud Spanner database backup. Backup adds a layer of service related functionality over BackupInfo.

Backup.Builder

BackupId

Represents an id of a Cloud Spanner backup resource.

BackupInfo

Represents a Cloud Spanner database backup.

BackupInfo.Builder

BatchClientImpl

Default implementation for Batch Client interface.

BatchTransactionId

BatchTransactionId is unique identifier for BatchReadOnlyTransaction. It can be used to re-initialize a BatchReadOnlyTransaction on different machine or process by calling BatchClient#batchReadOnlyTransaction(BatchTransactionId).

CommitResponse

Represents a response from a commit operation.

CommitStats

Commit statistics are returned by a read/write transaction if specifically requested by passing in Options#commitStats() to the transaction.

Database

Represents a Cloud Spanner database. Database adds a layer of service related functionality over DatabaseInfo.

Database.Builder

DatabaseId

Represents an id of a Cloud Spanner database resource.

DatabaseInfo

Represents a Cloud Spanner database.

DatabaseInfo.Builder

ForwardingAsyncResultSet

Forwarding implementation of AsyncResultSet that forwards all calls to a delegate.

ForwardingResultSet

Forwarding implementation of ResultSet that forwards all calls to a delegate.

ForwardingStructReader

Forwarding implements of StructReader

Instance

Represents a Cloud Spanner Instance. Instance adds a layer of service related functionality over InstanceInfo.

Instance.Builder

Builder of Instance.

InstanceConfig

Represents a Cloud Spanner instance config.InstanceConfig adds a layer of service related functionality over InstanceConfigInfo.

InstanceConfigId

Returns id of a Cloud Spanner instance config.

InstanceConfigInfo

Represents a Cloud Spanner instance config resource.

InstanceId

Represents the resource name of a Cloud Spanner Instance.

InstanceInfo

Represents a Cloud Spanner Instance.

InstanceInfo.Builder

Builder for InstanceInfo.

IsRetryableInternalError

IsSslHandshakeException

Key

Represents a row key in a Cloud Spanner table or index. A key is a tuple of values constrained to the scalar Cloud Spanner types: currently these are BOOLEAN, INT64, FLOAT64, STRING, BYTES and TIMESTAMP. Values may be null where the table definition permits it.

Key is used to define the row, or endpoints of a range of rows, to retrieve in read operations or to delete in a mutation.

Key instances are immutable.

Key.Builder

Builder for Key instances.

KeyRange

Represents a range of rows in a table or index.

A range has a start key and an end key. These keys can be open or closed, indicating if the range includes rows with that key.

For example, consider the following table definition:

 CREATE TABLE UserEvents (
   UserName STRING(MAX),
   EventDate STRING(10),
 ) PRIMARY KEY(UserName, EventDate);

The following keys name rows in this table:

  • Key.of("Bob", "2014-09-23")
  • Key.of("Alfred", "2015-06-12")

Since the UserEvents table's PRIMARY KEY clause names two columns, each UserEvents key has two elements; the first is the UserName, and the second is the EventDate.

Key ranges with multiple components are interpreted lexicographically by component using the table or index key's declared sort order. For example, the following range returns all events for user "Bob" that occurred in the year 2015:

 KeyRange.closedClosed(
     Key.of("Bob", "2015-01-01"),
     Key.of("Bob", "2015-12-31"))

Start and end keys can omit trailing key components. This affects the inclusion and exclusion of rows that exactly match the provided key components: if the key is closed, then rows that exactly match the provided components are included; if the key is open, then rows that exactly match are not included.

For example, the following range includes all events for "Bob" that occurred during and after the year 2000:

 KeyRange.closedClosed(
     Key.of("Bob", "2000-01-01"),
     Key.of("Bob"))

The next example retrieves all events for "Bob":

 KeyRange.prefix(Key.of("Bob"))

To retrieve events before the year 2000:

 KeyRange.closedOpen(
     Key.of("Bob"),
     Key.of("Bob", "2000-01-01"))

The following range includes all rows in the table:

 KeyRange.all()

This range returns all users whose UserName begins with any character from A to C:

 KeyRange.closedOpen(Key.of("A"), Key.of("D"))

This range returns all users whose UserName begins with B:

 KeyRange.closedOpen(Key.of("B"), Key.of("C"))

Key ranges honor column sort order. For example, suppose a table is defined as follows:

 CREATE TABLE DescendingSortedTable {
   Key INT64,
   ...
 ) PRIMARY KEY(Key DESC);

The following range retrieves all rows with key values between 1 and 100 inclusive:

 KeyRange.closedClosed(Key.of(100), Key.of(1))

Note that 100 is passed as the start, and 1 is passed as the end, because Key is a descending column in the schema.

KeyRange instances are immutable.

KeyRange.Builder

Builder for KeyRange instances.

KeySet

Defines a collection of Cloud Spanner keys and/or key ranges. All the keys are expected to be in the same table or index. The keys need not be sorted in any particular way.

If the same key is specified multiple times in the set (for example if two ranges, two keys, or a key and a range overlap), the Cloud Spanner backend behaves as if the key were only specified once. However, the KeySet object itself does not perform any de-duplication.

KeySet instances are immutable.

KeySet.Builder

Builder for KeySet instances.

LazySpannerInitializer

Default implementation of AbstractLazyInitializer for a Spanner instance.

Mutation

Represents an individual table modification to be applied to Cloud Spanner.

The types of mutation that can be created are defined by Op. To construct a mutation, use one of the builder methods. For example, to create a mutation that will insert a value of "x" into "C1" and a value of "y" into "C2" of table "T", write the following code:

 Mutation m = Mutation.newInsertBuilder("T")
     .set("C1").to("x")
     .set("C2").to("y")
     .build();

Mutations are applied to a database by performing a standalone write or buffering them as part of a transaction. TODO(user): Add links/code samples once the corresponding APIs are available.

Mutation instances are immutable.

Mutation.WriteBuilder

Builder for Op#INSERT, Op#INSERT_OR_UPDATE, Op#UPDATE, and Op#REPLACE mutations.

Operation<R,M>

Represents a long running operation.

Options

Specifies options for various spanner operations

Partition

Defines the segments of data to be read in a batch read/query context. They can be serialized and processed across several different machines or processes.

PartitionOptions

Defines the configuration for the number and size of partitions returned from BatchReadOnlyTransaction#partitionRead, BatchReadOnlyTransaction#partitionReadUsingIndex and BatchReadOnlyTransaction#partitionQuery

Note: these options may not be honored based on the other parameters in the request.

PartitionOptions.Builder

Builder for PartitionOptions instance.

PartitionedDmlTransaction

ReplicaInfo

Represents a Cloud Spanner replica information.

ReplicaInfo.BuilderImpl

Restore

Represents a restore operation of a Cloud Spanner backup.

Restore.Builder

RestoreInfo

Represents the restore information of a Cloud Spanner database.

ResultSets

Utility methods for working with com.google.cloud.spanner.ResultSet.

SessionPoolOptions

Options for the session pool used by DatabaseClient.

SessionPoolOptions.Builder

Builder for creating SessionPoolOptions.

SpannerApiFutures

SpannerExceptionFactory

A factory for creating instances of SpannerException and its subtypes. All creation of these exceptions is directed through the factory. This ensures that particular types of errors are always expressed as the same concrete exception type. For example, exceptions of type ErrorCode#ABORTED are always represented by AbortedException.

SpannerOptions

Options for the Cloud Spanner service.

SpannerOptions.Builder

Builder for SpannerOptions instances.

SpannerOptions.FixedCloseableExecutorProvider

Implementation of CloseableExecutorProvider that uses a fixed single ScheduledExecutorService.

SpannerOptions.SpannerCallContextTimeoutConfigurator

Helper class to configure timeouts for specific Spanner RPCs. The SpannerCallContextTimeoutConfigurator must be set as a value on the Context using the SpannerOptions#CALL_CONTEXT_CONFIGURATOR_KEY key.

Example usage:


 // Create a context with a ExecuteQuery timeout of 10 seconds.
 Context context =
     Context.current()
         .withValue(
             SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY,
             SpannerCallContextTimeoutConfigurator.create()
                 .withExecuteQueryTimeout(Duration.ofSeconds(10L)));
 context.run(
     () -> {
       try (ResultSet rs =
           client
               .singleUse()
               .executeQuery(
                   Statement.of(
                       "SELECT SingerId, FirstName, LastName FROM Singers ORDER BY LastName"))) {
         while (rs.next()) {
           System.out.printf("%d %s %s%n", rs.getLong(0), rs.getString(1), rs.getString(2));
         }
       } catch (SpannerException e) {
         if (e.getErrorCode() == ErrorCode.DEADLINE_EXCEEDED) {
           // Handle timeout.
         }
       }
     }
 

Statement

A SQL statement and optional bound parameters that can be executed in a ReadContext.

The SQL query string can contain parameter placeholders. A parameter placeholder consists of @ followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

Parameters can appear anywhere that a literal value is expected. The same parameter name can be used more than once, for example: WHERE id > @msg_id AND id < @msg_id + 100

It is an error to execute an SQL query with placeholders for unbound parameters.

Statements are constructed using a builder. Parameter values are specified by calling Builder#bind(String). For example, code to build a query using the clause above and bind a value to id might look like the following:


 Statement statement = Statement
     .newBuilder("SELECT name WHERE id > @msg_id AND id < @msg_id="" +="" 100")="" .bind("msg_id").to(500)="" .build();="">

Statement instances are immutable.

Statement.Builder

Builder for Statement.

Struct

Represents a non-NULL value of Type.Code#STRUCT. Such values are a tuple of named and typed columns, where individual columns may be null. Individual rows from a read or query operation can be considered as structs; ResultSet#getCurrentRowAsStruct() allows an immutable struct to be created from the row that the result set is currently positioned over.

Struct instances are immutable.

This class does not support representing typed NULL Struct values.

However, struct values inside SQL queries are always typed and can be externally supplied to a query only in the form of struct/array-of-struct query parameter values for which typed NULL struct values can be specified in the following ways:

1. As a standalone NULL struct value or as a nested struct field value, constructed using ValueBinder#to(Type, Struct) or Value#struct(Type, Struct).

2. As as a null Struct reference representing a NULL struct typed element value inside an array/list of 'Struct' references, that is used to construct an array-of-struct value using Value#structArray(Type, Iterable) or ValueBinder#toStructArray(Type, Iterable). In this case, the type of the NULL struct value is assumed to be the same as the explicitly specified struct element type of the array/list.

Struct.Builder

Builder for constructing non-NULL Struct instances.

TimestampBound

Defines how Cloud Spanner will choose a timestamp for a read-only transaction or a single read/query.

The types of timestamp bound are:

  • Strong (the default).
  • Bounded staleness.
  • Exact staleness.

If the Cloud Spanner database to be read is geographically distributed, stale read-only transactions can execute more quickly than strong or read-write transactions, because they are able to execute far from the leader replica.

Each type of timestamp bound is discussed in detail below.

Strong reads

Strong reads are guaranteed to see the effects of all transactions that have committed before the start of the read. Furthermore, all rows yielded by a single read are consistent with each other - if any part of the read observes a transaction, all parts of the read see the transaction.

Strong reads are not repeatable: two consecutive strong read-only transactions might return inconsistent results if there are concurrent writes. If consistency across reads is required, the reads should be executed within a transaction or at an exact read timestamp.

Use #strong() to create a bound of this type.

Exact Staleness

These timestamp bounds execute reads at a user-specified timestamp. Reads at a timestamp are guaranteed to see a consistent prefix of the global transaction history: they observe modifications done by all transactions with a commit timestamp less than or equal to the read timestamp, and observe none of the modifications done by transactions with a larger commit timestamp. They will block until all conflicting transactions that may be assigned commit timestamps less than or equal to the read timestamp have finished.

The timestamp can either be expressed as an absolute Cloud Spanner commit timestamp or a staleness relative to the current time.

These modes do not require a "negotiation phase" to pick a timestamp. As a result, they execute slightly faster than the equivalent bounded stale concurrency modes. On the other hand, boundedly stale reads usually return fresher results.

Use #ofReadTimestamp(Timestamp) and #ofExactStaleness(long, TimeUnit) to create a bound of this type.

Bounded Staleness

Bounded staleness modes allow Cloud Spanner to pick the read timestamp, subject to a user-provided staleness bound. Cloud Spanner chooses the newest timestamp within the staleness bound that allows execution of the reads at the closest available replica without blocking.

All rows yielded are consistent with each other -- if any part of the read observes a transaction, all parts of the read see the transaction. Bounded stale reads are not repeatable: two stale reads, even if they use the same staleness bound, can execute at different timestamps and thus return inconsistent results.

Boundedly stale reads execute in two phases: the first phase negotiates a timestamp among all replicas needed to serve the read. In the second phase, reads are executed at the negotiated timestamp.

As a result of the two phase execution, bounded staleness reads are usually a little slower than comparable exact staleness reads. However, they are typically able to return fresher results, and are more likely to execute at the closest replica.

Because the timestamp negotiation requires up-front knowledge of which rows will be read, it can only be used with single-use reads and single-use read-only transactions.

Use #ofMinReadTimestamp(Timestamp) and #ofMaxStaleness(long, TimeUnit) to create a bound of this type.

Old Read Timestamps and Garbage Collection

Cloud Spanner continuously garbage collects deleted and overwritten data in the background to reclaim storage space. This process is known as "version GC". By default, version GC reclaims versions after they are four hours old. Because of this, Cloud Spanner cannot perform reads at read timestamps more than four hours in the past. This restriction also applies to in-progress reads and/or SQL queries whose timestamp become too old while executing. Reads and SQL queries with too-old read timestamps fail with the error ErrorCode#FAILED_PRECONDITION. See Also: Session#readOnlyTransaction(TimestampBound), Session#singleUseReadOnlyTransaction(TimestampBound), Session#singleUse(TimestampBound)

Type

Describes a type in the Cloud Spanner type system. Types can either be primitive (for example, INT64 and STRING) or composite (for example, ARRAY<INT64> or STRUCT<INT64,STRING>).

Type instances are immutable.

Type.StructField

Describes an individual field in a STRUCT type.

Value

Represents a value to be consumed by the Cloud Spanner API. A value can be NULL or non-NULL; regardless, values always have an associated type.

The Value API is optimized for construction, since this is the majority use-case when using this class with the Cloud Spanner libraries. The factory method signatures and internal representations are design to minimize memory usage and object creation while still maintaining the immutability contract of this class. In particular, arrays of primitive types can be constructed without requiring boxing into collections of wrapper types. The getters in this class are intended primarily for test purposes, and so do not share the same performance characteristics; in particular, getters for array types may be expensive.

Value instances are immutable.

ValueBinder<R>

An interface for binding a Value in some context. Users of the Cloud Spanner client library never create a ValueBinder directly; instead this interface is returned from other parts of the library involved in Value construction. For example, Mutation.WriteBuilder#set(String) returns a binder to bind a column value, and Statement#bind(String) returns a binder to bind a parameter to a value.

ValueBinder subclasses typically carry state and are therefore not thread-safe, although the core implementation itself is thread-safe.

Interfaces

AsyncResultSet

Interface for result sets returned by async query methods.

AsyncResultSet.ReadyCallback

Interface for receiving asynchronous callbacks when new data is ready. See AsyncResultSet#setCallback(Executor, ReadyCallback).

AsyncRunner

AsyncRunner.AsyncWork<R>

Functional interface for executing a read/write transaction asynchronously that returns a result of type R.

AsyncTransactionManager

An interface for managing the life cycle of a read write transaction including all its retries. See TransactionContext for a description of transaction semantics.

At any point in time there can be at most one active transaction in this manager. When that transaction is committed, if it fails with an ABORTED error, calling #resetForRetryAsync() would create a new TransactionContextFuture. The newly created transaction would use the same session thus increasing its lock priority. If the transaction is committed successfully, or is rolled back or commit fails with any error other than ABORTED, the manager is considered complete and no further transactions are allowed to be created in it.

Every AsyncTransactionManager should either be committed or rolled back. Failure to do so can cause resources to be leaked and deadlocks. Easiest way to guarantee this is by calling #close() in a finally block. See Also: DatabaseClient#transactionManagerAsync()

AsyncTransactionManager.AsyncTransactionFunction<I,O>

Each step in a transaction chain is defined by an AsyncTransactionFunction. It receives a TransactionContext and the output value of the previous transaction step as its input parameters. The method should return an ApiFuture that will return the result of this step.

AsyncTransactionManager.AsyncTransactionStep<I,O>

AsyncTransactionStep is returned by TransactionContextFuture#then(AsyncTransactionFunction) and AsyncTransactionStep#then(AsyncTransactionFunction) and allows transaction steps that should be executed serially to be chained together. Each step can contain one or more statements that may execute in parallel.

Example usage:


 final String column = "FirstName";
 final long singerId = 1L;
 AsyncTransactionManager manager = client.transactionManagerAsync();
 TransactionContextFuture txnFuture = manager.beginAsync();
 txnFuture
   .then((transaction, ignored) ->
     transaction.readRowAsync("Singers", Key.of(singerId), Collections.singleton(column)),
     executor)
   .then((transaction, row) ->
     transaction.bufferAsync(
         Mutation.newUpdateBuilder("Singers")
           .set(column).to(row.getString(column).toUpperCase())
           .build()),
     executor)
   .commitAsync();
 

AsyncTransactionManager.CommitTimestampFuture

ApiFuture that returns the commit Timestamp of a Cloud Spanner transaction that is executed using an AsyncTransactionManager. This future is returned by the call to AsyncTransactionStep#commitAsync() of the last step in the transaction.

AsyncTransactionManager.TransactionContextFuture

ApiFuture that returns a TransactionContext and that supports chaining of multiple TransactionContextFutures to form a transaction.

BatchClient

Interface for the Batch Client that is used to read data from a Cloud Spanner database. An instance of this is tied to a specific database.

BatchClient is useful when one wants to read or query a large amount of data from Cloud Spanner across multiple processes, even across different machines. It allows to create partitions of Cloud Spanner database and then read or query over each partition independently yet at the same snapshot.

BatchReadOnlyTransaction

BatchReadOnlyTransaction can be configured to read at timestamps in the past and allows for exporting arbitrarily large amounts of data from Cloud Spanner databases. This is a read only transaction which additionally allows to partition a read or query request. Read/query request can then be executed independently over each partition while observing the same snapshot of the database. BatchReadOnlyTransaction can also be shared across multiple processes/machines by passing around the BatchTransactionId and then recreating the transaction using BatchClient#batchReadOnlyTransaction(BatchTransactionId).

Unlike locking read-write transactions, BatchReadOnlyTransaction never abort. They can fail if the chosen read timestamp is garbage collected; however any read or query activity within an hour on the transaction avoids garbage collection and most applications do not need to worry about this in practice.

To execute a BatchReadOnlyTransaction, specify a TimestampBound, which tells Cloud Spanner how to choose a read timestamp.

DatabaseAdminClient

Client to do admin operations on a Cloud Spanner Database.

DatabaseClient

Interface for all the APIs that are used to read/write data into a Cloud Spanner database. An instance of this is tied to a specific database.

InstanceAdminClient

Client to do admin operations on Cloud Spanner Instance and Instance Configs.

Options.ListOption

Marker interface to mark options applicable to list operations in admin API.

Options.QueryOption

Marker interface to mark options applicable to query operation.

Options.ReadAndQueryOption

Marker interface to mark options applicable to both Read and Query operations

Options.ReadOption

Marker interface to mark options applicable to read operation

Options.ReadQueryUpdateTransactionOption

Marker interface to mark options applicable to Read, Query, Update and Write operations

Options.TransactionOption

Marker interface to mark options applicable to write operations

Options.UpdateOption

Marker interface to mark options applicable to update operation.

ReadContext

A concurrency context in which to run a read or SQL statement. All ReadContexts are implicitly bound to a Session and therefore a particular Database.

ReadOnlyTransaction

A transaction type that provides guaranteed consistency across several reads, but does not allow writes. Snapshot read-only transactions can be configured to read at timestamps in the past. Snapshot read-only transactions do not need to be committed.

Snapshot read-only transactions provide a simpler method than locking read-write transactions for doing several consistent reads. However, this type of transaction does not support writes.

Snapshot read-only transactions do not take locks. Instead, they work by choosing a Cloud Spanner timestamp, then executing all reads at that timestamp. Since they do not acquire locks, they do not block concurrent read-write transactions.

Unlike locking read-write transactions, snapshot read-only transactions never abort. They can fail if the chosen read timestamp is garbage collected; however, the default garbage collection policy is generous enough that most applications do not need to worry about this in practice. See the class documentation of TimestampBound for more details.

To execute a snapshot transaction, specify a TimestampBound, which tells Cloud Spanner how to choose a read timestamp. See Also: Session#readOnlyTransaction(TimestampBound), Session#singleUseReadOnlyTransaction(TimestampBound)

ResultSet

Provides access to the data returned by a Cloud Spanner read or query. ResultSet allows a single row to be inspected at a time through the methods from the StructReader interface, in the order that the rows were returned by the read or query. The result set can be positioned over the next row, if one exists, by calling #next(); this method returns false when all rows returned have been seen. The result set is initially positioned before the first row, so a call to next() is required before the first row can be inspected.

ResultSet implementations may buffer data ahead and/or maintain a persistent streaming connection to the remote service until all data has been returned or the resultSet closed. As such, it is important that all uses of ResultSet either fully consume it (that is, call next() until false is returned or it throws an exception) or explicitly call #close(): failure to do so may result in wasted work or leaked resources.

ResultSet implementations are not required to be thread-safe: if methods are called from multiple threads, external synchronization must be used.

Session

A Session can be used to perform transactions that read and/or modify data in a Cloud Spanner database.

Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.

Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour, or due to internal errors. If a session is deleted, requests to it return ErrorCode#NOT_FOUND.

Idle sessions can be kept alive by sending a trivial SQL query periodically, for example, SELECT 1.

Sessions are long-lived objects intended to be reused for many consecutive operations; a typical application will maintain a pool of sessions to use during its lifetime.

Since only one transaction can be performed at a time within any given session, instances require external synchronization; Session implementations are not required to be thread-safe.

Spanner

An interface for Cloud Spanner. Typically, there would only be one instance of this for the lifetime of the application which must be closed by invoking #close() when it is no longer needed. Failure to do so may result in leaking session resources and exhausting session quota.

SpannerFactory

Factory to create instance of Spanner.

SpannerOptions.CallContextConfigurator

CallContextConfigurator can be used to modify the ApiCallContext for one or more specific RPCs. This can be used to set specific timeout value for RPCs or use specific CallCredentials for an RPC. The CallContextConfigurator must be set as a value on the Context using the SpannerOptions#CALL_CONTEXT_CONFIGURATOR_KEY key.

This API is meant for advanced users. Most users should instead use the SpannerCallContextTimeoutConfigurator for setting timeouts per RPC.

Example usage:


 CallContextConfigurator configurator =
     new CallContextConfigurator() {
       public <ReqT, RespT> ApiCallContext configure(
           ApiCallContext context, ReqT request, MethodDescriptor<ReqT, RespT> method) {
         if (method == SpannerGrpc.getExecuteBatchDmlMethod()) {
           return GrpcCallContext.createDefault()
               .withCallOptions(CallOptions.DEFAULT.withDeadlineAfter(60L, TimeUnit.SECONDS));
         }
         return null;
       }
     };
 Context context =
     Context.current().withValue(SpannerOptions.CALL_CONTEXT_CONFIGURATOR_KEY, configurator);
 context.run(
     () -> {
       try {
         client
             .readWriteTransaction()
             .run(
                 new TransactionCallable

SpannerOptions.CallCredentialsProvider

Interface that can be used to provide CallCredentials instead of Credentials to SpannerOptions.

SpannerOptions.CloseableExecutorProvider

ExecutorProvider that is used for AsyncResultSet.

SpannerOptions.SpannerEnvironment

The environment to read configuration values from. The default implementation uses environment variables.

StructReader

A base interface for reading the fields of a STRUCT. The Cloud Spanner yields StructReader instances as one of the subclasses ResultSet or Struct, most commonly as the result of a read or query operation. At any point in time, a StructReader provides access to a single tuple of data comprising multiple typed columns. Each column may have a NULL or non-NULL value; in both cases, columns always have a type.

Column values are accessed using the getTypeName() methods; a set of methods exists for each Java type that a column may be read as, and depending on the type of the column, only a subset of those methods will be appropriate. For example, #getString(int) and #getString(String) exist for reading columns of type Type#string(); attempting to call those methods for columns of other types will result in an IllegalStateException. The getTypeName() methods should only be called for non-NULL values, otherwise a NullPointerException is raised; #isNull(int)/#isNull(String) can be used to test for NULL-ness if necessary.

All methods for accessing a column have overloads that accept an int column index and a String column name. Column indices are zero-based. The column name overloads will fail with IllegalArgumentException if the column name does not appear exactly once in this instance's #getType(). The int overloads are typically more efficient than their String counterparts.

StructReader itself does not define whether the implementing type is mutable or immutable. For example, ResultSet is a mutable implementation of StructReader, where the StructReader methods provide access to the row that the result set is currently positioned over and ResultSet#next() changes that view to the next row, whereas Struct is an immutable implementation of StructReader.

TransactionContext

Context for a single attempt of a locking read-write transaction. This type of transaction is the only way to write data into Cloud Spanner; Session#write(Iterable) and Session#writeAtLeastOnce(Iterable) use transactions internally. These transactions rely on pessimistic locking and, if necessary, two-phase commit. Locking read-write transactions may abort, requiring the application to retry. However, the interface exposed by TransactionRunner eliminates the need for applications to write retry loops explicitly.

Locking transactions may be used to atomically read-modify-write data anywhere in a database. This type of transaction is externally consistent.

Clients should attempt to minimize the amount of time a transaction is active. Faster transactions commit with higher probability and cause less contention. Cloud Spanner attempts to keep read locks active as long as the transaction continues to do reads, and the transaction has not been terminated by returning from a TransactionRunner.TransactionCallable. Long periods of inactivity at the client may cause Cloud Spanner to release a transaction's locks and abort it.

Reads performed within a transaction acquire locks on the data being read. Writes can only be done at commit time, after all reads have been completed.

Conceptually, a read-write transaction consists of zero or more reads or SQL queries followed by a commit.

Semantics

Cloud Spanner can commit the transaction if all read locks it acquired are still valid at commit time, and it is able to acquire write locks for all writes. Cloud Spanner can abort the transaction for any reason. If a commit attempt returns ABORTED, Cloud Spanner guarantees that the transaction has not modified any user data in Cloud Spanner.

Unless the transaction commits, Cloud Spanner makes no guarantees about how long the transaction's locks were held for. It is an error to use Cloud Spanner locks for any sort of mutual exclusion other than between Cloud Spanner transactions themselves.

Retrying Aborted Transactions

When a transaction aborts, the application can choose to retry the whole transaction again. To maximize the chances of successfully committing the retry, the client should execute the retry in the same session as the original attempt. The original session's lock priority increases with each consecutive abort, meaning that each attempt has a slightly better chance of success than the previous.

Under some circumstances (e.g., many transactions attempting to modify the same row(s)), a transaction can abort many times in a short period before successfully committing. Thus, it is not a good idea to cap the number of retries a transaction can attempt; instead, it is better to limit the total amount of wall time spent retrying.

Application code does not need to retry explicitly; TransactionRunner will automatically retry a transaction if an attempt results in an abort.

Idle Transactions

A transaction is considered idle if it has no outstanding reads or SQL queries and has not started a read or SQL query within the last 10 seconds. Idle transactions can be aborted by Cloud Spanner so that they don't hold on to locks indefinitely. In that case, the commit will fail with error ABORTED.

If this behavior is undesirable, periodically executing a simple SQL query in the transaction (e.g., SELECT 1) prevents the transaction from becoming idle. See Also: TransactionRunner, Session#readWriteTransaction()

TransactionManager

An interface for managing the life cycle of a read write transaction including all its retries. See TransactionContext for a description of transaction semantics.

At any point in time there can be at most one active transaction in this manager. When that transaction is committed, if it fails with an ABORTED error, calling #resetForRetry() would create a new TransactionContext. The newly created transaction would use the same session thus increasing its lock priority. If the transaction is committed successfully, or is rolled back or commit fails with any error other than ABORTED, the manager is considered complete and no further transactions are allowed to be created in it.

Every TransactionManager should either be committed or rolled back. Failure to do so can cause resources to be leaked and deadlocks. Easiest way to guarantee this is by calling #close() in a finally block. See Also: DatabaseClient#transactionManager()

TransactionRunner

An interface for executing a body of work in the context of a read-write transaction, with retries for transaction aborts. See TransactionContext for a description of transaction semantics. TransactionRunner instances are obtained by calling Session#readWriteTransaction().

A TransactionRunner instance can only be used for a single invocation of #run(TransactionCallable).

TransactionRunner.TransactionCallable<T>

A unit of work to be performed in the context of a transaction.

Enums

AsyncResultSet.CallbackResponse

AsyncResultSet.CursorState

Response code from tryNext().

BackupInfo.State

State of the backup.

DatabaseInfo.State

State of the database.

Dialect

ErrorCode

Enumerates the major types of error that the Cloud Spanner service can produce. These codes are accessible via SpannerException#getErrorCode().

InstanceInfo.InstanceField

Represent an updatable field in Cloud Spanner instance.

InstanceInfo.State

State of the Instance.

KeyRange.Endpoint

Defines whether a range includes or excludes its endpoint keys.

Mutation.Op

Enumerates the types of mutation that can be applied.

Options.RpcPriority

Priority for an RPC invocation. The default priority is #HIGH. This enum can be used to set a lower priority for a specific RPC invocation.

ReadContext.QueryAnalyzeMode

Used to specify the mode in which the query should be analyzed by ReadContext#analyzeQuery(Statement,QueryAnalyzeMode).

ReplicaInfo.ReplicaType

Indicates the type of the replica. See the replica types documentation at https://cloud.google.com/spanner/docs/replication#replica_types for more details.

RestoreInfo.RestoreSourceType

Source of the restore information.

TimestampBound.Mode

The type of timestamp bound. See the class documentation of TimestampBound for a detailed discussion of the various modes.

TransactionManager.TransactionState

State of the transaction manager.

Type.Code

Enumerates the categories of types.

Exceptions

AbortedDueToConcurrentModificationException

Exception thrown by a Connection when a database operation detects that a transaction has aborted and an internal retry failed because of a concurrent modification. This type of error has its own subclass since it is often necessary to handle this specific kind of aborted exceptions differently to other types of errors.

AbortedException

Exception thrown by Cloud Spanner when an operation detects that a transaction has aborted. This type of error has its own subclass since it is often necessary to handle aborted differently to other types of errors, most typically by retrying the transaction.

AdminRequestsPerMinuteExceededException

Exception thrown by Cloud Spanner the number of administrative requests per minute has been exceeded.

DatabaseNotFoundException

Exception thrown by Cloud Spanner when an operation detects that the database that is being used no longer exists. This type of error has its own subclass as it is a condition that should cause the client library to stop trying to send RPCs to the backend until the user has taken action.

InstanceNotFoundException

Exception thrown by Cloud Spanner when an operation detects that the instance that is being used no longer exists. This type of error has its own subclass as it is a condition that should cause the client library to stop trying to send RPCs to the backend until the user has taken action.

SessionNotFoundException

Exception thrown by Cloud Spanner when an operation detects that the session that is being used is no longer valid. This type of error has its own subclass as it is a condition that should normally be hidden from the user, and the client library should try to fix this internally.

SpannerBatchUpdateException

SpannerException

Base exception type for all exceptions produced by the Cloud Spanner service.

SpannerException.ResourceNotFoundException

Base exception type for NOT_FOUND exceptions for known resource types.