@Generated(value="by gapic-generator") public class SpannerClient extends Object implements com.google.api.gax.core.BackgroundResource
The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases.
This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
Session response = spannerClient.createSession(database);
}
Note: close() needs to be called on the spannerClient object to clean up resources such as threads. In the example above, try-with-resources is used, which automatically calls close().
The surface of this class includes several types of Java methods for each of the API's methods:
See the individual methods for example code.
Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parse method to extract the individual identifiers contained within names that are returned.
This class can be customized by passing in a custom instance of SpannerSettings to create(). For example:
To customize credentials:
SpannerSettings spannerSettings =
SpannerSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
.build();
SpannerClient spannerClient =
SpannerClient.create(spannerSettings);
To customize the endpoint:
SpannerSettings spannerSettings =
SpannerSettings.newBuilder().setEndpoint(myEndpoint).build();
SpannerClient spannerClient =
SpannerClient.create(spannerSettings);
Modifier and Type | Class and Description |
---|---|
static class |
SpannerClient.ListSessionsFixedSizeCollection |
static class |
SpannerClient.ListSessionsPage |
static class |
SpannerClient.ListSessionsPagedResponse |
Modifier | Constructor and Description |
---|---|
protected |
SpannerClient(SpannerSettings settings)
Constructs an instance of SpannerClient, using the given settings.
|
protected |
SpannerClient(SpannerStub stub) |
Modifier and Type | Method and Description |
---|---|
boolean |
awaitTermination(long duration,
TimeUnit unit) |
BatchCreateSessionsResponse |
batchCreateSessions(BatchCreateSessionsRequest request)
Creates multiple new sessions.
|
BatchCreateSessionsResponse |
batchCreateSessions(DatabaseName database,
int sessionCount)
Creates multiple new sessions.
|
BatchCreateSessionsResponse |
batchCreateSessions(String database,
int sessionCount)
Creates multiple new sessions.
|
com.google.api.gax.rpc.UnaryCallable<BatchCreateSessionsRequest,BatchCreateSessionsResponse> |
batchCreateSessionsCallable()
Creates multiple new sessions.
|
Transaction |
beginTransaction(BeginTransactionRequest request)
Begins a new transaction.
|
Transaction |
beginTransaction(SessionName session,
TransactionOptions options)
Begins a new transaction.
|
Transaction |
beginTransaction(String session,
TransactionOptions options)
Begins a new transaction.
|
com.google.api.gax.rpc.UnaryCallable<BeginTransactionRequest,Transaction> |
beginTransactionCallable()
Begins a new transaction.
|
void |
close() |
CommitResponse |
commit(CommitRequest request)
Commits a transaction.
|
CommitResponse |
commit(SessionName session,
ByteString transactionId,
List<Mutation> mutations)
Commits a transaction.
|
CommitResponse |
commit(SessionName session,
TransactionOptions singleUseTransaction,
List<Mutation> mutations)
Commits a transaction.
|
CommitResponse |
commit(String session,
ByteString transactionId,
List<Mutation> mutations)
Commits a transaction.
|
CommitResponse |
commit(String session,
TransactionOptions singleUseTransaction,
List<Mutation> mutations)
Commits a transaction.
|
com.google.api.gax.rpc.UnaryCallable<CommitRequest,CommitResponse> |
commitCallable()
Commits a transaction.
|
static SpannerClient |
create()
Constructs an instance of SpannerClient with default settings.
|
static SpannerClient |
create(SpannerSettings settings)
Constructs an instance of SpannerClient, using the given settings.
|
static SpannerClient |
create(SpannerStub stub)
Constructs an instance of SpannerClient, using the given stub for making calls.
|
Session |
createSession(CreateSessionRequest request)
Creates a new session.
|
Session |
createSession(DatabaseName database)
Creates a new session.
|
Session |
createSession(String database)
Creates a new session.
|
com.google.api.gax.rpc.UnaryCallable<CreateSessionRequest,Session> |
createSessionCallable()
Creates a new session.
|
void |
deleteSession(DeleteSessionRequest request)
Ends a session, releasing server resources associated with it.
|
void |
deleteSession(SessionName name)
Ends a session, releasing server resources associated with it.
|
void |
deleteSession(String name)
Ends a session, releasing server resources associated with it.
|
com.google.api.gax.rpc.UnaryCallable<DeleteSessionRequest,Empty> |
deleteSessionCallable()
Ends a session, releasing server resources associated with it.
|
ExecuteBatchDmlResponse |
executeBatchDml(ExecuteBatchDmlRequest request)
Executes a batch of SQL DML statements.
|
com.google.api.gax.rpc.UnaryCallable<ExecuteBatchDmlRequest,ExecuteBatchDmlResponse> |
executeBatchDmlCallable()
Executes a batch of SQL DML statements.
|
ResultSet |
executeSql(ExecuteSqlRequest request)
Executes an SQL statement, returning all results in a single reply.
|
com.google.api.gax.rpc.UnaryCallable<ExecuteSqlRequest,ResultSet> |
executeSqlCallable()
Executes an SQL statement, returning all results in a single reply.
|
com.google.api.gax.rpc.ServerStreamingCallable<ExecuteSqlRequest,PartialResultSet> |
executeStreamingSqlCallable()
Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result set as a
stream.
|
Session |
getSession(GetSessionRequest request)
Gets a session.
|
Session |
getSession(SessionName name)
Gets a session.
|
Session |
getSession(String name)
Gets a session.
|
com.google.api.gax.rpc.UnaryCallable<GetSessionRequest,Session> |
getSessionCallable()
Gets a session.
|
SpannerSettings |
getSettings() |
SpannerStub |
getStub() |
boolean |
isShutdown() |
boolean |
isTerminated() |
SpannerClient.ListSessionsPagedResponse |
listSessions(DatabaseName database)
Lists all sessions in a given database.
|
SpannerClient.ListSessionsPagedResponse |
listSessions(ListSessionsRequest request)
Lists all sessions in a given database.
|
SpannerClient.ListSessionsPagedResponse |
listSessions(String database)
Lists all sessions in a given database.
|
com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,ListSessionsResponse> |
listSessionsCallable()
Lists all sessions in a given database.
|
com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,SpannerClient.ListSessionsPagedResponse> |
listSessionsPagedCallable()
Lists all sessions in a given database.
|
PartitionResponse |
partitionQuery(PartitionQueryRequest request)
Creates a set of partition tokens that can be used to execute a query operation in parallel.
|
com.google.api.gax.rpc.UnaryCallable<PartitionQueryRequest,PartitionResponse> |
partitionQueryCallable()
Creates a set of partition tokens that can be used to execute a query operation in parallel.
|
PartitionResponse |
partitionRead(PartitionReadRequest request)
Creates a set of partition tokens that can be used to execute a read operation in parallel.
|
com.google.api.gax.rpc.UnaryCallable<PartitionReadRequest,PartitionResponse> |
partitionReadCallable()
Creates a set of partition tokens that can be used to execute a read operation in parallel.
|
ResultSet |
read(ReadRequest request)
Reads rows from the database using key lookups and scans, as a simple key/value style
alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
|
com.google.api.gax.rpc.UnaryCallable<ReadRequest,ResultSet> |
readCallable()
Reads rows from the database using key lookups and scans, as a simple key/value style
alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
|
void |
rollback(RollbackRequest request)
Rolls back a transaction, releasing any locks it holds.
|
void |
rollback(SessionName session,
ByteString transactionId)
Rolls back a transaction, releasing any locks it holds.
|
void |
rollback(String session,
ByteString transactionId)
Rolls back a transaction, releasing any locks it holds.
|
com.google.api.gax.rpc.UnaryCallable<RollbackRequest,Empty> |
rollbackCallable()
Rolls back a transaction, releasing any locks it holds.
|
void |
shutdown() |
void |
shutdownNow() |
com.google.api.gax.rpc.ServerStreamingCallable<ReadRequest,PartialResultSet> |
streamingReadCallable()
Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a stream.
|
protected SpannerClient(SpannerSettings settings) throws IOException
IOException
@BetaApi(value="A restructuring of stub classes is planned, so this may break in the future") protected SpannerClient(SpannerStub stub)
public static final SpannerClient create() throws IOException
IOException
public static final SpannerClient create(SpannerSettings settings) throws IOException
IOException
@BetaApi(value="A restructuring of stub classes is planned, so this may break in the future") public static final SpannerClient create(SpannerStub stub)
public final SpannerSettings getSettings()
@BetaApi(value="A restructuring of stub classes is planned, so this may break in the future") public SpannerStub getStub()
public final Session createSession(DatabaseName 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.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
Session response = spannerClient.createSession(database);
}
database
- Required. The database in which the new session is created.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Session createSession(String 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.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
Session response = spannerClient.createSession(database.toString());
}
database
- Required. The database in which the new session is created.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Session createSession(CreateSessionRequest request)
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.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
CreateSessionRequest request = CreateSessionRequest.newBuilder()
.setDatabase(database.toString())
.build();
Session response = spannerClient.createSession(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<CreateSessionRequest,Session> createSessionCallable()
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.
Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
CreateSessionRequest request = CreateSessionRequest.newBuilder()
.setDatabase(database.toString())
.build();
ApiFuture<Session> future = spannerClient.createSessionCallable().futureCall(request);
// Do something
Session response = future.get();
}
public final BatchCreateSessionsResponse batchCreateSessions(DatabaseName database, int sessionCount)
This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(database, sessionCount);
}
database
- Required. The database in which the new sessions are created.sessionCount
- Required. The number of sessions to be created in this batch call. The API
may return fewer than the requested number of sessions. If a specific number of sessions
are desired, the client can make additional calls to BatchCreateSessions (adjusting
[session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count] as necessary).com.google.api.gax.rpc.ApiException
- if the remote call failspublic final BatchCreateSessionsResponse batchCreateSessions(String database, int sessionCount)
This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(database.toString(), sessionCount);
}
database
- Required. The database in which the new sessions are created.sessionCount
- Required. The number of sessions to be created in this batch call. The API
may return fewer than the requested number of sessions. If a specific number of sessions
are desired, the client can make additional calls to BatchCreateSessions (adjusting
[session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count] as necessary).com.google.api.gax.rpc.ApiException
- if the remote call failspublic final BatchCreateSessionsResponse batchCreateSessions(BatchCreateSessionsRequest request)
This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
BatchCreateSessionsRequest request = BatchCreateSessionsRequest.newBuilder()
.setDatabase(database.toString())
.setSessionCount(sessionCount)
.build();
BatchCreateSessionsResponse response = spannerClient.batchCreateSessions(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<BatchCreateSessionsRequest,BatchCreateSessionsResponse> batchCreateSessionsCallable()
This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
BatchCreateSessionsRequest request = BatchCreateSessionsRequest.newBuilder()
.setDatabase(database.toString())
.setSessionCount(sessionCount)
.build();
ApiFuture<BatchCreateSessionsResponse> future = spannerClient.batchCreateSessionsCallable().futureCall(request);
// Do something
BatchCreateSessionsResponse response = future.get();
}
public final Session getSession(SessionName name)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
Session response = spannerClient.getSession(name);
}
name
- Required. The name of the session to retrieve.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Session getSession(String name)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
Session response = spannerClient.getSession(name.toString());
}
name
- Required. The name of the session to retrieve.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Session getSession(GetSessionRequest request)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
GetSessionRequest request = GetSessionRequest.newBuilder()
.setName(name.toString())
.build();
Session response = spannerClient.getSession(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<GetSessionRequest,Session> getSessionCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
GetSessionRequest request = GetSessionRequest.newBuilder()
.setName(name.toString())
.build();
ApiFuture<Session> future = spannerClient.getSessionCallable().futureCall(request);
// Do something
Session response = future.get();
}
public final SpannerClient.ListSessionsPagedResponse listSessions(DatabaseName database)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
for (Session element : spannerClient.listSessions(database).iterateAll()) {
// doThingsWith(element);
}
}
database
- Required. The database in which to list sessions.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final SpannerClient.ListSessionsPagedResponse listSessions(String database)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
for (Session element : spannerClient.listSessions(database.toString()).iterateAll()) {
// doThingsWith(element);
}
}
database
- Required. The database in which to list sessions.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final SpannerClient.ListSessionsPagedResponse listSessions(ListSessionsRequest request)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
ListSessionsRequest request = ListSessionsRequest.newBuilder()
.setDatabase(database.toString())
.build();
for (Session element : spannerClient.listSessions(request).iterateAll()) {
// doThingsWith(element);
}
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,SpannerClient.ListSessionsPagedResponse> listSessionsPagedCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
ListSessionsRequest request = ListSessionsRequest.newBuilder()
.setDatabase(database.toString())
.build();
ApiFuture<ListSessionsPagedResponse> future = spannerClient.listSessionsPagedCallable().futureCall(request);
// Do something
for (Session element : future.get().iterateAll()) {
// doThingsWith(element);
}
}
public final com.google.api.gax.rpc.UnaryCallable<ListSessionsRequest,ListSessionsResponse> listSessionsCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
DatabaseName database = DatabaseName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]");
ListSessionsRequest request = ListSessionsRequest.newBuilder()
.setDatabase(database.toString())
.build();
while (true) {
ListSessionsResponse response = spannerClient.listSessionsCallable().call(request);
for (Session element : response.getSessionsList()) {
// doThingsWith(element);
}
String nextPageToken = response.getNextPageToken();
if (!Strings.isNullOrEmpty(nextPageToken)) {
request = request.toBuilder().setPageToken(nextPageToken).build();
} else {
break;
}
}
}
public final void deleteSession(SessionName name)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
spannerClient.deleteSession(name);
}
name
- Required. The name of the session to delete.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final void deleteSession(String name)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
spannerClient.deleteSession(name.toString());
}
name
- Required. The name of the session to delete.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final void deleteSession(DeleteSessionRequest request)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
DeleteSessionRequest request = DeleteSessionRequest.newBuilder()
.setName(name.toString())
.build();
spannerClient.deleteSession(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<DeleteSessionRequest,Empty> deleteSessionCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName name = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
DeleteSessionRequest request = DeleteSessionRequest.newBuilder()
.setName(name.toString())
.build();
ApiFuture<Void> future = spannerClient.deleteSessionCallable().futureCall(request);
// Do something
future.get();
}
public final ResultSet executeSql(ExecuteSqlRequest request)
Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String sql = "";
ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder()
.setSession(session.toString())
.setSql(sql)
.build();
ResultSet response = spannerClient.executeSql(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<ExecuteSqlRequest,ResultSet> executeSqlCallable()
Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String sql = "";
ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder()
.setSession(session.toString())
.setSql(sql)
.build();
ApiFuture<ResultSet> future = spannerClient.executeSqlCallable().futureCall(request);
// Do something
ResultSet response = future.get();
}
public final com.google.api.gax.rpc.ServerStreamingCallable<ExecuteSqlRequest,PartialResultSet> executeStreamingSqlCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String sql = "";
ExecuteSqlRequest request = ExecuteSqlRequest.newBuilder()
.setSession(session.toString())
.setSql(sql)
.build();
ServerStream<PartialResultSet> stream = spannerClient.executeStreamingSqlCallable().call(request);
for (PartialResultSet response : stream) {
// Do something when receive a response
}
}
public final ExecuteBatchDmlResponse executeBatchDml(ExecuteBatchDmlRequest request)
Statements are executed in sequential order. A request can succeed even if a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements are not executed.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionSelector transaction = TransactionSelector.newBuilder().build();
List<ExecuteBatchDmlRequest.Statement> statements = new ArrayList<>();
long seqno = 0L;
ExecuteBatchDmlRequest request = ExecuteBatchDmlRequest.newBuilder()
.setSession(session.toString())
.setTransaction(transaction)
.addAllStatements(statements)
.setSeqno(seqno)
.build();
ExecuteBatchDmlResponse response = spannerClient.executeBatchDml(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<ExecuteBatchDmlRequest,ExecuteBatchDmlResponse> executeBatchDmlCallable()
Statements are executed in sequential order. A request can succeed even if a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred.
Execution stops after the first failed statement; the remaining statements are not executed.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionSelector transaction = TransactionSelector.newBuilder().build();
List<ExecuteBatchDmlRequest.Statement> statements = new ArrayList<>();
long seqno = 0L;
ExecuteBatchDmlRequest request = ExecuteBatchDmlRequest.newBuilder()
.setSession(session.toString())
.setTransaction(transaction)
.addAllStatements(statements)
.setSeqno(seqno)
.build();
ApiFuture<ExecuteBatchDmlResponse> future = spannerClient.executeBatchDmlCallable().futureCall(request);
// Do something
ExecuteBatchDmlResponse response = future.get();
}
public final ResultSet read(ReadRequest request)
Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String table = "";
List<String> columns = new ArrayList<>();
KeySet keySet = KeySet.newBuilder().build();
ReadRequest request = ReadRequest.newBuilder()
.setSession(session.toString())
.setTable(table)
.addAllColumns(columns)
.setKeySet(keySet)
.build();
ResultSet response = spannerClient.read(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<ReadRequest,ResultSet> readCallable()
Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String table = "";
List<String> columns = new ArrayList<>();
KeySet keySet = KeySet.newBuilder().build();
ReadRequest request = ReadRequest.newBuilder()
.setSession(session.toString())
.setTable(table)
.addAllColumns(columns)
.setKeySet(keySet)
.build();
ApiFuture<ResultSet> future = spannerClient.readCallable().futureCall(request);
// Do something
ResultSet response = future.get();
}
public final com.google.api.gax.rpc.ServerStreamingCallable<ReadRequest,PartialResultSet> streamingReadCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String table = "";
List<String> columns = new ArrayList<>();
KeySet keySet = KeySet.newBuilder().build();
ReadRequest request = ReadRequest.newBuilder()
.setSession(session.toString())
.setTable(table)
.addAllColumns(columns)
.setKeySet(keySet)
.build();
ServerStream<PartialResultSet> stream = spannerClient.streamingReadCallable().call(request);
for (PartialResultSet response : stream) {
// Do something when receive a response
}
}
public final Transaction beginTransaction(SessionName session, TransactionOptions options)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = TransactionOptions.newBuilder().build();
Transaction response = spannerClient.beginTransaction(session, options);
}
session
- Required. The session in which the transaction runs.options
- Required. Options for the new transaction.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Transaction beginTransaction(String session, TransactionOptions options)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = TransactionOptions.newBuilder().build();
Transaction response = spannerClient.beginTransaction(session.toString(), options);
}
session
- Required. The session in which the transaction runs.options
- Required. Options for the new transaction.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final Transaction beginTransaction(BeginTransactionRequest request)
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = TransactionOptions.newBuilder().build();
BeginTransactionRequest request = BeginTransactionRequest.newBuilder()
.setSession(session.toString())
.setOptions(options)
.build();
Transaction response = spannerClient.beginTransaction(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<BeginTransactionRequest,Transaction> beginTransactionCallable()
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = TransactionOptions.newBuilder().build();
BeginTransactionRequest request = BeginTransactionRequest.newBuilder()
.setSession(session.toString())
.setOptions(options)
.build();
ApiFuture<Transaction> future = spannerClient.beginTransactionCallable().futureCall(request);
// Do something
Transaction response = future.get();
}
public final CommitResponse commit(SessionName session, ByteString transactionId, List<Mutation> mutations)
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
List<Mutation> mutations = new ArrayList<>();
CommitResponse response = spannerClient.commit(session, transactionId, mutations);
}
session
- Required. The session in which the transaction to be committed is running.transactionId
- Commit a previously-started transaction.mutations
- The mutations to be executed when this transaction commits. All mutations are
applied atomically, in the order they appear in this list.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final CommitResponse commit(String session, ByteString transactionId, List<Mutation> mutations)
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
List<Mutation> mutations = new ArrayList<>();
CommitResponse response = spannerClient.commit(session.toString(), transactionId, mutations);
}
session
- Required. The session in which the transaction to be committed is running.transactionId
- Commit a previously-started transaction.mutations
- The mutations to be executed when this transaction commits. All mutations are
applied atomically, in the order they appear in this list.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final CommitResponse commit(SessionName session, TransactionOptions singleUseTransaction, List<Mutation> mutations)
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = TransactionOptions.newBuilder().build();
List<Mutation> mutations = new ArrayList<>();
CommitResponse response = spannerClient.commit(session, singleUseTransaction, mutations);
}
session
- Required. The session in which the transaction to be committed is running.singleUseTransaction
- Execute mutations in a temporary transaction. Note that unlike
commit of a previously-started transaction, commit with a temporary transaction is
non-idempotent. That is, if the `CommitRequest` is sent to Cloud Spanner more than once
(for instance, due to retries in the application, or in the transport library), it is
possible that the mutations are executed more than once. If this is undesirable, use
[BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and
[Commit][google.spanner.v1.Spanner.Commit] instead.mutations
- The mutations to be executed when this transaction commits. All mutations are
applied atomically, in the order they appear in this list.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final CommitResponse commit(String session, TransactionOptions singleUseTransaction, List<Mutation> mutations)
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = TransactionOptions.newBuilder().build();
List<Mutation> mutations = new ArrayList<>();
CommitResponse response = spannerClient.commit(session.toString(), singleUseTransaction, mutations);
}
session
- Required. The session in which the transaction to be committed is running.singleUseTransaction
- Execute mutations in a temporary transaction. Note that unlike
commit of a previously-started transaction, commit with a temporary transaction is
non-idempotent. That is, if the `CommitRequest` is sent to Cloud Spanner more than once
(for instance, due to retries in the application, or in the transport library), it is
possible that the mutations are executed more than once. If this is undesirable, use
[BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] and
[Commit][google.spanner.v1.Spanner.Commit] instead.mutations
- The mutations to be executed when this transaction commits. All mutations are
applied atomically, in the order they appear in this list.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final CommitResponse commit(CommitRequest request)
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
CommitRequest request = CommitRequest.newBuilder()
.setSession(session.toString())
.build();
CommitResponse response = spannerClient.commit(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<CommitRequest,CommitResponse> commitCallable()
`Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
CommitRequest request = CommitRequest.newBuilder()
.setSession(session.toString())
.build();
ApiFuture<CommitResponse> future = spannerClient.commitCallable().futureCall(request);
// Do something
CommitResponse response = future.get();
}
public final void rollback(SessionName session, ByteString transactionId)
`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
spannerClient.rollback(session, transactionId);
}
session
- Required. The session in which the transaction to roll back is running.transactionId
- Required. The transaction to roll back.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final void rollback(String session, ByteString transactionId)
`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
spannerClient.rollback(session.toString(), transactionId);
}
session
- Required. The session in which the transaction to roll back is running.transactionId
- Required. The transaction to roll back.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final void rollback(RollbackRequest request)
`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
RollbackRequest request = RollbackRequest.newBuilder()
.setSession(session.toString())
.setTransactionId(transactionId)
.build();
spannerClient.rollback(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<RollbackRequest,Empty> rollbackCallable()
`Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.copyFromUtf8("");
RollbackRequest request = RollbackRequest.newBuilder()
.setSession(session.toString())
.setTransactionId(transactionId)
.build();
ApiFuture<Void> future = spannerClient.rollbackCallable().futureCall(request);
// Do something
future.get();
}
public final PartitionResponse partitionQuery(PartitionQueryRequest request)
Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String sql = "";
PartitionQueryRequest request = PartitionQueryRequest.newBuilder()
.setSession(session.toString())
.setSql(sql)
.build();
PartitionResponse response = spannerClient.partitionQuery(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<PartitionQueryRequest,PartitionResponse> partitionQueryCallable()
Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String sql = "";
PartitionQueryRequest request = PartitionQueryRequest.newBuilder()
.setSession(session.toString())
.setSql(sql)
.build();
ApiFuture<PartitionResponse> future = spannerClient.partitionQueryCallable().futureCall(request);
// Do something
PartitionResponse response = future.get();
}
public final PartitionResponse partitionRead(PartitionReadRequest request)
Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String table = "";
KeySet keySet = KeySet.newBuilder().build();
PartitionReadRequest request = PartitionReadRequest.newBuilder()
.setSession(session.toString())
.setTable(table)
.setKeySet(keySet)
.build();
PartitionResponse response = spannerClient.partitionRead(request);
}
request
- The request object containing all of the parameters for the API call.com.google.api.gax.rpc.ApiException
- if the remote call failspublic final com.google.api.gax.rpc.UnaryCallable<PartitionReadRequest,PartitionResponse> partitionReadCallable()
Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning.
Sample code:
try (SpannerClient spannerClient = SpannerClient.create()) {
SessionName session = SessionName.of("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
String table = "";
KeySet keySet = KeySet.newBuilder().build();
PartitionReadRequest request = PartitionReadRequest.newBuilder()
.setSession(session.toString())
.setTable(table)
.setKeySet(keySet)
.build();
ApiFuture<PartitionResponse> future = spannerClient.partitionReadCallable().futureCall(request);
// Do something
PartitionResponse response = future.get();
}
public final void close()
close
in interface AutoCloseable
public void shutdown()
shutdown
in interface com.google.api.gax.core.BackgroundResource
public boolean isShutdown()
isShutdown
in interface com.google.api.gax.core.BackgroundResource
public boolean isTerminated()
isTerminated
in interface com.google.api.gax.core.BackgroundResource
public void shutdownNow()
shutdownNow
in interface com.google.api.gax.core.BackgroundResource
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException
awaitTermination
in interface com.google.api.gax.core.BackgroundResource
InterruptedException
Copyright © 2019 Google LLC. All rights reserved.