Google Cloud Spanner C++ Client  1.32.1
A C++ Client Library for Google Cloud Spanner
Public Member Functions | Friends | List of all members
google::cloud::spanner::v1::Client Class Reference

Performs database client operations on Spanner. More...

#include <google/cloud/spanner/client.h>

Public Member Functions

 Client (std::shared_ptr< Connection > conn, ClientOptions opts={})
 Constructs a Client object using the specified conn and opts. More...
 
 Client ()=delete
 No default construction. Use Client(std::shared_ptr<Connection>) More...
 
 Client (Client const &)=default
 
Clientoperator= (Client const &)=default
 
 Client (Client &&)=default
 
Clientoperator= (Client &&)=default
 
RowStream Read (std::string table, KeySet keys, std::vector< std::string > columns, ReadOptions read_options={})
 Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery(). More...
 
RowStream Read (Transaction::SingleUseOptions transaction_options, std::string table, KeySet keys, std::vector< std::string > columns, ReadOptions read_options={})
 Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery(). More...
 
RowStream Read (Transaction transaction, std::string table, KeySet keys, std::vector< std::string > columns, ReadOptions read_options={})
 Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery(). More...
 
RowStream Read (ReadPartition const &partition)
 Reads rows from a subset of rows in a database. More...
 
StatusOr< std::vector< ReadPartition > > PartitionRead (Transaction transaction, std::string table, KeySet keys, std::vector< std::string > columns, ReadOptions read_options={}, PartitionOptions const &partition_options=PartitionOptions{})
 Creates a set of partitions that can be used to execute a read operation in parallel. More...
 
RowStream ExecuteQuery (SqlStatement statement, QueryOptions const &opts={})
 Executes a SQL query. More...
 
RowStream ExecuteQuery (Transaction::SingleUseOptions transaction_options, SqlStatement statement, QueryOptions const &opts={})
 Executes a SQL query. More...
 
RowStream ExecuteQuery (Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
 Executes a SQL query. More...
 
RowStream ExecuteQuery (QueryPartition const &partition, QueryOptions const &opts={})
 Executes a SQL query on a subset of rows in a database. More...
 
ProfileQueryResult ProfileQuery (SqlStatement statement, QueryOptions const &opts={})
 Profiles a SQL query. More...
 
ProfileQueryResult ProfileQuery (Transaction::SingleUseOptions transaction_options, SqlStatement statement, QueryOptions const &opts={})
 Profiles a SQL query. More...
 
ProfileQueryResult ProfileQuery (Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
 Profiles a SQL query. More...
 
StatusOr< std::vector< QueryPartition > > PartitionQuery (Transaction transaction, SqlStatement statement, PartitionOptions const &partition_options=PartitionOptions{})
 Creates a set of partitions that can be used to execute a query operation in parallel. More...
 
StatusOr< DmlResultExecuteDml (Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
 Executes a SQL DML statement. More...
 
StatusOr< ProfileDmlResultProfileDml (Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
 Profiles a SQL DML statement. More...
 
StatusOr< ExecutionPlanAnalyzeSql (Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
 Analyzes the execution plan of a SQL statement. More...
 
StatusOr< BatchDmlResultExecuteBatchDml (Transaction transaction, std::vector< SqlStatement > statements, Options opts={})
 Executes a batch of SQL DML statements. More...
 
StatusOr< CommitResultCommit (std::function< StatusOr< Mutations >(Transaction)> const &mutator, std::unique_ptr< TransactionRerunPolicy > rerun_policy, std::unique_ptr< BackoffPolicy > backoff_policy, CommitOptions const &options={})
 Commits a read-write transaction. More...
 
StatusOr< CommitResultCommit (std::function< StatusOr< Mutations >(Transaction)> const &mutator, CommitOptions const &options={})
 Commits a read-write transaction. More...
 
StatusOr< CommitResultCommit (Mutations mutations, CommitOptions const &options={})
 Commits the mutations, using the options, atomically in order. More...
 
StatusOr< CommitResultCommit (Transaction transaction, Mutations mutations, CommitOptions const &options={})
 Commits a read-write transaction. More...
 
Status Rollback (Transaction transaction)
 Rolls back a read-write transaction, releasing any locks it holds. More...
 
StatusOr< PartitionedDmlResultExecutePartitionedDml (SqlStatement statement, QueryOptions const &opts={})
 Executes a Partitioned DML SQL query. More...
 

Friends

bool operator== (Client const &a, Client const &b)
 
bool operator!= (Client const &a, Client const &b)
 

Detailed Description

Performs database client operations on Spanner.

Applications use this class to perform operations on Spanner Databases.

Performance

Client objects are relatively cheap to create, copy, and move. However, each Client object must be created with a std::shared_ptr<Connection>, which itself is relatively expensive to create. Therefore, connection instances should be shared when possible. See the MakeConnection() method and the Connection interface for more details.

Thread Safety

Instances of this class created via copy-construction or copy-assignment share the underlying pool of connections. Access to these copies via multiple threads is guaranteed to work. Two threads operating on the same instance of this class is not guaranteed to work.

Error Handling

This class uses StatusOr<T> to report errors. When an operation fails to perform its work the returned StatusOr<T> contains the error details. If the ok() member function in the StatusOr<T> returns true then it contains the expected result. Please consult the StatusOr<T> documentation for more details.

namespace spanner = ::google::cloud::spanner;
auto db = spanner::Database("my_project", "my_instance", "my_db_id"));
auto conn = spanner::MakeConnection(db);
auto client = spanner::Client(conn);
auto rows = client.Read(...);
using RowType = std::tuple<std::int64_t, std::string>;
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
// ...
}
Performs database client operations on Spanner.
Definition: client.h:122
This class identifies a Cloud Spanner Database.
Definition: database.h:43
std::shared_ptr< spanner::Connection > MakeConnection(spanner::Database const &db, Options opts)
Returns a Connection object that can be used for interacting with Spanner.
Definition: client.cc:325
Contains all the Cloud Spanner C++ client types and functions.
Definition: backup.cc:21
Query Options

Most operations that take an SqlStatement may also be modified with QueryOptions. These options can be set at various levels, with more specific levels taking precedence over broader ones. For example, QueryOptions that are passed directly to Client::ExecuteQuery() will take precedence over the Client-level defaults (if any), which will themselves take precedence over any environment variables. The following table shows the environment variables that may optionally be set and the QueryOptions setting that they affect.

Environment Variable QueryOptions setting
SPANNER_OPTIMIZER_VERSION QueryOptions::optimizer_version()
SPANNER_OPTIMIZER_STATISTICS_PACKAGE QueryOptions::optimizer_statistics_package()
See also
https://cloud.google.com/spanner/docs/reference/rest/v1/QueryOptions
http://cloud/spanner/docs/query-optimizer/manage-query-optimizer

Definition at line 122 of file client.h.

Constructor & Destructor Documentation

◆ Client() [1/4]

google::cloud::spanner::v1::Client::Client ( std::shared_ptr< Connection conn,
ClientOptions  opts = {} 
)
inlineexplicit

Constructs a Client object using the specified conn and opts.

See MakeConnection() for how to create a connection to Spanner. To help with unit testing, callers may create fake/mock Connection objects that are injected into the Client.

Definition at line 131 of file client.h.

◆ Client() [2/4]

google::cloud::spanner::v1::Client::Client ( )
delete

No default construction. Use Client(std::shared_ptr<Connection>)

◆ Client() [3/4]

google::cloud::spanner::v1::Client::Client ( Client const &  )
default

◆ Client() [4/4]

google::cloud::spanner::v1::Client::Client ( Client &&  )
default

Member Function Documentation

◆ AnalyzeSql()

StatusOr< ExecutionPlan > google::cloud::spanner::v1::Client::AnalyzeSql ( Transaction  transaction,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Analyzes the execution plan of a SQL statement.

Analyzing provides the ExecutionPlan, but does not execute the SQL statement.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Note
Single-use transactions are not supported with DML statements.
Parameters
transactionExecute this query as part of an existing transaction.
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Example:
// Only SQL queries with a Distributed Union as the first operator in the
// `ExecutionPlan` can be partitioned.
auto is_partitionable = [](spanner::ExecutionPlan const& plan) {
return (!plan.plan_nodes().empty() &&
plan.plan_nodes(0).kind() ==
google::spanner::v1::PlanNode::RELATIONAL &&
plan.plan_nodes(0).display_name() == "Distributed Union");
};
google::cloud::StatusOr<spanner::ExecutionPlan> plan = client.AnalyzeSql(
"SELECT SingerId, FirstName, LastName FROM Singers"));
if (!plan) throw std::runtime_error(plan.status().message());
if (!is_partitionable(*plan)) {
throw std::runtime_error("Query is not partitionable");
}
Represents a potentially parameterized SQL statement.
Definition: sql_statement.h:51
::google::spanner::v1::QueryPlan ExecutionPlan
Contains a hierarchical representation of the operations the database server performs in order to exe...
Definition: results.h:56
Transaction MakeReadOnlyTransaction(Transaction::ReadOnlyOptions opts={})
Create a read-only transaction configured with opts.
Definition: transaction.h:180

Definition at line 174 of file client.cc.

◆ Commit() [1/4]

StatusOr< CommitResult > google::cloud::spanner::v1::Client::Commit ( Mutations  mutations,
CommitOptions const &  options = {} 
)

Commits the mutations, using the options, atomically in order.

This function uses the re-run loop described above with the default policies.

Example
namespace spanner = ::google::cloud::spanner;
auto commit_result = client.Commit(spanner::Mutations{
{"SingerId", "AlbumId", "MarketingBudget"})
.EmplaceRow(1, 1, 100000)
.EmplaceRow(2, 2, 500000)
.Build()});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
std::vector< Mutation > Mutations
An ordered sequence of mutations to pass to Client::Commit() or return from the Client::Commit() muta...
Definition: mutations.h:99
spanner_internal::WriteMutationBuilder< spanner_internal::UpdateOp > UpdateMutationBuilder
A helper class to construct "update" mutations.
Definition: mutations.h:249

Definition at line 284 of file client.cc.

◆ Commit() [2/4]

StatusOr< CommitResult > google::cloud::spanner::v1::Client::Commit ( std::function< StatusOr< Mutations >(Transaction)> const &  mutator,
CommitOptions const &  options = {} 
)

Commits a read-write transaction.

Same as above, but uses the default rerun and backoff policies.

Parameters
mutatorthe function called to create mutations
optionsto apply to the commit.
Example
using ::google::cloud::StatusOr;
namespace spanner = ::google::cloud::spanner;
auto commit_result = client.Commit(
[&client](spanner::Transaction txn) -> StatusOr<spanner::Mutations> {
auto update = client.ExecuteDml(
std::move(txn),
"UPDATE Albums SET MarketingBudget = MarketingBudget * 2"
" WHERE SingerId = 1 AND AlbumId = 1"));
if (!update) return update.status();
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
The representation of a Cloud Spanner transaction.
Definition: transaction.h:58

Definition at line 265 of file client.cc.

◆ Commit() [3/4]

StatusOr< CommitResult > google::cloud::spanner::v1::Client::Commit ( std::function< StatusOr< Mutations >(Transaction)> const &  mutator,
std::unique_ptr< TransactionRerunPolicy rerun_policy,
std::unique_ptr< BackoffPolicy backoff_policy,
CommitOptions const &  options = {} 
)

Commits a read-write transaction.

Calls the mutator in the context of a new read-write transaction. The mutator can execute read/write operations using the transaction, and returns any additional Mutations to commit.

If the mutator succeeds and the transaction commits, then Commit() returns the CommitResult.

If the mutator returns a non-rerunnable status (according to the rerun_policy), the transaction is rolled back and that status is returned. Similarly, if the transaction fails to commit with a non- rerunnable status, that status is returned.

Otherwise the whole process repeats (subject to rerun_policy and backoff_policy), by building a new transaction and re-running the mutator. The lock priority of the operation increases after each rerun, meaning that the next attempt has a slightly better chance of success.

Note that the mutator should only return a rerunnable status when the transaction is no longer usable (e.g., it was aborted). Otherwise the transaction will be leaked.

Parameters
mutatorthe function called to create mutations
rerun_policycontrols for how long (or how many times) the mutator will be rerun after the transaction aborts.
backoff_policycontrols how long Commit waits between reruns.
optionsto apply to the commit.
Exceptions
Rethrowsany exception thrown by mutator (after rolling back the transaction). However, a RuntimeStatusError exception is instead consumed and converted into a mutator return value of the enclosed Status.
Example
void CommitWithPolicies(google::cloud::spanner::Client client) {
using ::google::cloud::StatusOr;
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(
[&client](spanner::Transaction txn) -> StatusOr<spanner::Mutations> {
auto update = client.ExecuteDml(
std::move(txn),
"UPDATE Albums SET MarketingBudget = MarketingBudget * 2"
" WHERE SingerId = 1 AND AlbumId = 1"));
if (!update) return update.status();
},
// Retry for up to 42 minutes.
.clone(),
// After a failure backoff for 2 seconds (with jitter), then triple the
// backoff time on each retry, up to 5 minutes.
spanner::ExponentialBackoffPolicy(std::chrono::seconds(2),
std::chrono::minutes(5), 3.0)
.clone());
if (!commit) throw std::runtime_error(commit.status().message());
std::cout << "commit-with-policies was successful\n";
}
StatusOr< DmlResult > ExecuteDml(Transaction transaction, SqlStatement statement, QueryOptions const &opts={})
Executes a SQL DML statement.
Definition: client.cc:156
StatusOr< CommitResult > Commit(std::function< StatusOr< Mutations >(Transaction)> const &mutator, std::unique_ptr< TransactionRerunPolicy > rerun_policy, std::unique_ptr< BackoffPolicy > backoff_policy, CommitOptions const &options={})
Commits a read-write transaction.
Definition: client.cc:191
google::cloud::internal::LimitedTimeRetryPolicy< spanner_internal::SafeTransactionRerun > LimitedTimeTransactionRerunPolicy
A transaction rerun policy that limits the duration of the rerun loop.
Definition: retry_policy.h:97
google::cloud::internal::ExponentialBackoffPolicy ExponentialBackoffPolicy
A truncated exponential backoff policy with randomized periods.

Definition at line 191 of file client.cc.

◆ Commit() [4/4]

StatusOr< CommitResult > google::cloud::spanner::v1::Client::Commit ( Transaction  transaction,
Mutations  mutations,
CommitOptions const &  options = {} 
)

Commits a read-write transaction.

The commit might return a kAborted 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 kAborted, the caller may try to reapply the mutations within a new read-write transaction (which should share lock priority with the aborted transaction so that the new attempt has a slightly better chance of success).

Note
Prefer the previous Commit overloads if you want to simply reapply mutations after a kAborted error.
Warning
It is an error to call Commit with a read-only transaction.
Parameters
transactionThe transaction to commit.
mutationsThe mutations to be executed when this transaction commits. All mutations are applied atomically, in the order they appear in this list.
optionsto apply to the commit.
Returns
A StatusOr containing the result of the commit or error status on failure.

Definition at line 290 of file client.cc.

◆ ExecuteBatchDml()

StatusOr< BatchDmlResult > google::cloud::spanner::v1::Client::ExecuteBatchDml ( Transaction  transaction,
std::vector< SqlStatement statements,
Options  opts = {} 
)

Executes a batch of SQL DML statements.

This method allows many statements to be run with lower latency than submitting them sequentially with ExecuteDml.

Statements are executed in order, sequentially. Execution will stop at the first failed statement; the remaining statements will not run.

As with all read-write transactions, the results will not be visible outside of the transaction until it is committed. For that reason, it is advisable to run this method from a Commit mutator.

Warning
A returned status of OK from this function does not imply that all the statements were executed successfully. For that, you need to inspect the BatchDmlResult::status field.
Parameters
transactionThe read-write transaction to execute the operation in.
statementsThe list of statements to execute in this batch. Statements are executed serially, such that the effects of statement i are visible to statement i+1. Each statement must be a DML statement. Execution will stop at the first failed statement; the remaining statements will not run. Must not be empty.
optsThe options to use for this call. Expected options are any of the types in the following option lists.
  • google::cloud::RequestOptionList
Example
void DmlStructs(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
std::int64_t rows_modified = 0;
auto commit_result =
client.Commit([&client, &rows_modified](spanner::Transaction const& txn)
-> google::cloud::StatusOr<spanner::Mutations> {
auto singer_info = std::make_tuple("Marc", "Richards");
"UPDATE Singers SET FirstName = 'Keith' WHERE "
"STRUCT<FirstName String, LastName String>(FirstName, LastName) "
"= @name",
{{"name", spanner::Value(std::move(singer_info))}});
auto dml_result = client.ExecuteDml(txn, std::move(sql));
if (!dml_result) return dml_result.status();
rows_modified = dml_result->RowsModified();
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
std::cout << rows_modified
<< " update was successful [spanner_dml_structs]\n";
}
The Value class represents a type-safe, nullable Spanner value.
Definition: value.h:168

Definition at line 183 of file client.cc.

◆ ExecuteDml()

StatusOr< DmlResult > google::cloud::spanner::v1::Client::ExecuteDml ( Transaction  transaction,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Executes a SQL DML statement.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Note
Single-use transactions are not supported with DML statements.
Parameters
transactionExecute this query as part of an existing transaction.
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Example
using ::google::cloud::StatusOr;
namespace spanner = ::google::cloud::spanner;
std::int64_t rows_inserted;
auto commit_result = client.Commit(
[&client, &rows_inserted](
spanner::Transaction txn) -> StatusOr<spanner::Mutations> {
auto insert = client.ExecuteDml(
std::move(txn),
"INSERT INTO Singers (SingerId, FirstName, LastName)"
" VALUES (10, 'Virginia', 'Watson')"));
if (!insert) return insert.status();
rows_inserted = insert->RowsModified();
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
std::cout << "Rows inserted: " << rows_inserted;

Definition at line 156 of file client.cc.

◆ ExecutePartitionedDml()

StatusOr< PartitionedDmlResult > google::cloud::spanner::v1::Client::ExecutePartitionedDml ( SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Executes a Partitioned DML SQL query.

Parameters
statementthe SQL statement to execute. Please see the spanner documentation for the restrictions on the SQL statements supported by this function.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Example
void DmlPartitionedDelete(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto result = client.ExecutePartitionedDml(
spanner::SqlStatement("DELETE FROM Singers WHERE SingerId > 10"));
if (!result) throw std::runtime_error(result.status().message());
std::cout << "Delete was successful [spanner_dml_partitioned_delete]\n";
}
StatusOr< PartitionedDmlResult > ExecutePartitionedDml(SqlStatement statement, QueryOptions const &opts={})
Executes a Partitioned DML SQL query.
Definition: client.cc:300
See also
Partitioned DML Transactions for an overview of Partitioned DML transactions.
Partitioned DML for a description of which SQL statements are supported in Partitioned DML transactions.

Definition at line 300 of file client.cc.

◆ ExecuteQuery() [1/4]

RowStream google::cloud::spanner::v1::Client::ExecuteQuery ( QueryPartition const &  partition,
QueryOptions const &  opts = {} 
)

Executes a SQL query on a subset of rows in a database.

Requires a prior call to PartitionQuery to obtain the partition information; see the documentation of that method for full details.

Parameters
partitionA QueryPartition, obtained by calling PartitionQuery.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the RowStream can exceed 100 MiB, and no column value can exceed 10 MiB.
Example
google::cloud::StatusOr<spanner::QueryPartition> partition =
remote_connection.ReceiveQueryPartitionFromRemoteMachine();
if (!partition) throw std::runtime_error(partition.status().message());
auto rows = client.ExecuteQuery(*partition);
for (auto const& row : rows) {
if (!row) throw std::runtime_error(row.status().message());
ProcessRow(*row);
}

Definition at line 114 of file client.cc.

◆ ExecuteQuery() [2/4]

RowStream google::cloud::spanner::v1::Client::ExecuteQuery ( SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Executes a SQL query.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

SELECT * ... queries are supported, but there's no guarantee about the order, nor number, of returned columns. Therefore, the caller must look up the wanted values in each row by column name. When the desired column names are known in advance, it is better to list them explicitly in the query's SELECT statement, so that unnecessary values are not returned/ignored, and the column order is known. This enables more efficient and simpler code.

Example with explicitly selected columns.
void QueryData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
spanner::SqlStatement select("SELECT SingerId, LastName FROM Singers");
using RowType = std::tuple<std::int64_t, std::string>;
auto rows = client.ExecuteQuery(std::move(select));
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "LastName: " << std::get<1>(*row) << "\n";
}
std::cout << "Query completed for [spanner_query_data]\n";
}
RowStream ExecuteQuery(SqlStatement statement, QueryOptions const &opts={})
Executes a SQL query.
Definition: client.cc:87
Example using SELECT *
void QueryDataSelectStar(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
// With a "SELECT *" query, we don't know the order in which the columns will
// be returned (nor the number of columns). Therefore, we look up each value
// based on the column name rather than its position.
spanner::SqlStatement select_star("SELECT * FROM Singers");
auto rows = client.ExecuteQuery(std::move(select_star));
for (auto const& row : rows) {
if (!row) throw std::runtime_error(row.status().message());
if (auto singer_id = row->get<std::int64_t>("SingerId")) {
std::cout << "SingerId: " << *singer_id << "\t";
} else {
std::cerr << singer_id.status();
}
if (auto last_name = row->get<std::string>("LastName")) {
std::cout << "LastName: " << *last_name;
} else {
std::cerr << last_name.status();
}
std::cout << "\n";
}
std::cout << "Query completed for [spanner_query_data_select_star]\n";
}
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the RowStream can exceed 100 MiB, and no column value can exceed 10 MiB.

Definition at line 87 of file client.cc.

◆ ExecuteQuery() [3/4]

RowStream google::cloud::spanner::v1::Client::ExecuteQuery ( Transaction  transaction,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Executes a SQL query.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

SELECT * ... queries are supported, but there's no guarantee about the order, nor number, of returned columns. Therefore, the caller must look up the wanted values in each row by column name. When the desired column names are known in advance, it is better to list them explicitly in the query's SELECT statement, so that unnecessary values are not returned/ignored, and the column order is known. This enables more efficient and simpler code.

Example with explicitly selected columns.
void QueryData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
spanner::SqlStatement select("SELECT SingerId, LastName FROM Singers");
using RowType = std::tuple<std::int64_t, std::string>;
auto rows = client.ExecuteQuery(std::move(select));
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "LastName: " << std::get<1>(*row) << "\n";
}
std::cout << "Query completed for [spanner_query_data]\n";
}
Example using SELECT *
void QueryDataSelectStar(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
// With a "SELECT *" query, we don't know the order in which the columns will
// be returned (nor the number of columns). Therefore, we look up each value
// based on the column name rather than its position.
spanner::SqlStatement select_star("SELECT * FROM Singers");
auto rows = client.ExecuteQuery(std::move(select_star));
for (auto const& row : rows) {
if (!row) throw std::runtime_error(row.status().message());
if (auto singer_id = row->get<std::int64_t>("SingerId")) {
std::cout << "SingerId: " << *singer_id << "\t";
} else {
std::cerr << singer_id.status();
}
if (auto last_name = row->get<std::string>("LastName")) {
std::cout << "LastName: " << *last_name;
} else {
std::cerr << last_name.status();
}
std::cout << "\n";
}
std::cout << "Query completed for [spanner_query_data_select_star]\n";
}
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the RowStream can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameters
transactionExecute this query as part of an existing transaction.

Definition at line 106 of file client.cc.

◆ ExecuteQuery() [4/4]

RowStream google::cloud::spanner::v1::Client::ExecuteQuery ( Transaction::SingleUseOptions  transaction_options,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Executes a SQL query.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

SELECT * ... queries are supported, but there's no guarantee about the order, nor number, of returned columns. Therefore, the caller must look up the wanted values in each row by column name. When the desired column names are known in advance, it is better to list them explicitly in the query's SELECT statement, so that unnecessary values are not returned/ignored, and the column order is known. This enables more efficient and simpler code.

Example with explicitly selected columns.
void QueryData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
spanner::SqlStatement select("SELECT SingerId, LastName FROM Singers");
using RowType = std::tuple<std::int64_t, std::string>;
auto rows = client.ExecuteQuery(std::move(select));
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "LastName: " << std::get<1>(*row) << "\n";
}
std::cout << "Query completed for [spanner_query_data]\n";
}
Example using SELECT *
void QueryDataSelectStar(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
// With a "SELECT *" query, we don't know the order in which the columns will
// be returned (nor the number of columns). Therefore, we look up each value
// based on the column name rather than its position.
spanner::SqlStatement select_star("SELECT * FROM Singers");
auto rows = client.ExecuteQuery(std::move(select_star));
for (auto const& row : rows) {
if (!row) throw std::runtime_error(row.status().message());
if (auto singer_id = row->get<std::int64_t>("SingerId")) {
std::cout << "SingerId: " << *singer_id << "\t";
} else {
std::cerr << singer_id.status();
}
if (auto last_name = row->get<std::string>("LastName")) {
std::cout << "LastName: " << *last_name;
} else {
std::cerr << last_name.status();
}
std::cout << "\n";
}
std::cout << "Query completed for [spanner_query_data_select_star]\n";
}
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the RowStream can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameters
transaction_optionsExecute this query in a single-use transaction with these options.

Definition at line 96 of file client.cc.

◆ operator=() [1/2]

Client& google::cloud::spanner::v1::Client::operator= ( Client &&  )
default

◆ operator=() [2/2]

Client& google::cloud::spanner::v1::Client::operator= ( Client const &  )
default

◆ PartitionQuery()

StatusOr< std::vector< QueryPartition > > google::cloud::spanner::v1::Client::PartitionQuery ( Transaction  transaction,
SqlStatement  statement,
PartitionOptions const &  partition_options = PartitionOptions{} 
)

Creates a set of partitions that can be used to execute a query operation in parallel.

Each of the returned partitions can be passed to ExecuteQuery to specify a subset of the query result to read.

Partitions 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.

Parameters
transactionThe transaction to execute the operation in. Must be a read-only snapshot transaction.
statementThe SQL statement to execute.
partition_optionsPartitionOptions used for this request.
Returns
A StatusOr containing a vector of QueryPartitions or error status on failure.
Example
google::cloud::StatusOr<std::vector<spanner::QueryPartition>> partitions =
client.PartitionQuery(
"SELECT SingerId, FirstName, LastName FROM Singers"));
if (!partitions) throw std::runtime_error(partitions.status().message());
for (auto& partition : *partitions) {
remote_connection.SendPartitionToRemoteMachine(partition);
}

Definition at line 149 of file client.cc.

◆ PartitionRead()

StatusOr< std::vector< ReadPartition > > google::cloud::spanner::v1::Client::PartitionRead ( Transaction  transaction,
std::string  table,
KeySet  keys,
std::vector< std::string >  columns,
ReadOptions  read_options = {},
PartitionOptions const &  partition_options = PartitionOptions{} 
)

Creates a set of partitions that can be used to execute a read operation in parallel.

Each of the returned partitions can be passed to Read to specify a subset of the read result to read.

There are no ordering guarantees on rows returned among the returned partition, or even within each individual Read call issued with a given partition.

Partitions 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.

Parameters
transactionThe transaction to execute the operation in. Must be a read-only snapshot transaction.
tableThe name of the table in the database to be read.
keysIdentifies the rows to be yielded. If read_options.index_name is set, names keys in that index; otherwise names keys in the primary index of table. It is not an error for keys to name rows that do not exist in the database; Read yields nothing for nonexistent rows.
columnsThe columns of table to be returned for each row matching this request.
read_optionsReadOptions used for this request.
partition_optionsPartitionOptions used for this request.
Returns
A StatusOr containing a vector of ReadPartition or error status on failure.
Example
google::cloud::StatusOr<std::vector<spanner::ReadPartition>> partitions =
client.PartitionRead(ro_transaction, "Singers", key_set,
{"SingerId", "FirstName", "LastName"});
if (!partitions) throw std::runtime_error(partitions.status().message());
for (auto& partition : *partitions) {
remote_connection.SendPartitionToRemoteMachine(partition);
}

Definition at line 74 of file client.cc.

◆ ProfileDml()

StatusOr< ProfileDmlResult > google::cloud::spanner::v1::Client::ProfileDml ( Transaction  transaction,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Profiles a SQL DML statement.

Profiling executes the DML statement, provides the modified row count, ExecutionPlan, and execution statistics.

Operations inside read-write transactions might return ABORTED. If this occurs, the application should restart the transaction from the beginning.

Note
Single-use transactions are not supported with DML statements.
Parameters
transactionExecute this query as part of an existing transaction.
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Example:
auto commit_result = client.Commit(
[&client,
&dml_result](spanner::Transaction txn) -> StatusOr<spanner::Mutations> {
auto update = client.ProfileDml(
std::move(txn),
"UPDATE Albums SET MarketingBudget = MarketingBudget * 2"
" WHERE SingerId = 1 AND AlbumId = 1"));
if (!update) return update.status();
dml_result = *std::move(update);
});
if (!commit_result) {
throw std::runtime_error(commit_result.status().message());
}
// Stats only available after statement has been executed.
std::cout << "Rows modified: " << dml_result.RowsModified();
auto execution_stats = dml_result.ExecutionStats();
if (execution_stats) {
for (auto const& stat : *execution_stats) {
std::cout << stat.first << ":\t" << stat.second << "\n";
}
}
Represents the result and profile stats of a data modifying operation using spanner::Client::ProfileD...
Definition: results.h:216
std::int64_t RowsModified() const
Returns the number of rows modified by the DML statement.
Definition: results.cc:81
absl::optional< std::unordered_map< std::string, std::string > > ExecutionStats() const
Returns a collection of key value pair statistics for the SQL statement execution.
Definition: results.cc:96

Definition at line 165 of file client.cc.

◆ ProfileQuery() [1/3]

ProfileQueryResult google::cloud::spanner::v1::Client::ProfileQuery ( SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Profiles a SQL query.

Profiling executes the query, provides the resulting rows, ExecutionPlan, and execution statistics.

Operations inside read-write transactions might return kAborted. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Note
Callers must consume all rows from the result before execution statistics and ExecutionPlan are available.
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the ProfileQueryResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Example
namespace spanner = ::google::cloud::spanner;
"SELECT AlbumId, AlbumTitle, MarketingBudget"
" FROM Albums"
" WHERE AlbumTitle >= 'Aardvark' AND AlbumTitle < 'Goo'");
auto profile_query_result = client.ProfileQuery(std::move(select));
for (auto const& row : profile_query_result) {
if (!row) throw std::runtime_error(row.status().message());
// Discard rows for brevity in this example.
}
// Stats are only available after all rows from the result have been read.
auto execution_stats = profile_query_result.ExecutionStats();
if (execution_stats) {
for (auto const& stat : *execution_stats) {
std::cout << stat.first << ":\t" << stat.second << "\n";
}
}

Definition at line 121 of file client.cc.

◆ ProfileQuery() [2/3]

ProfileQueryResult google::cloud::spanner::v1::Client::ProfileQuery ( Transaction  transaction,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Profiles a SQL query.

Profiling executes the query, provides the resulting rows, ExecutionPlan, and execution statistics.

Operations inside read-write transactions might return kAborted. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Note
Callers must consume all rows from the result before execution statistics and ExecutionPlan are available.
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the ProfileQueryResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Example
namespace spanner = ::google::cloud::spanner;
"SELECT AlbumId, AlbumTitle, MarketingBudget"
" FROM Albums"
" WHERE AlbumTitle >= 'Aardvark' AND AlbumTitle < 'Goo'");
auto profile_query_result = client.ProfileQuery(std::move(select));
for (auto const& row : profile_query_result) {
if (!row) throw std::runtime_error(row.status().message());
// Discard rows for brevity in this example.
}
// Stats are only available after all rows from the result have been read.
auto execution_stats = profile_query_result.ExecutionStats();
if (execution_stats) {
for (auto const& stat : *execution_stats) {
std::cout << stat.first << ":\t" << stat.second << "\n";
}
}
Parameters
transactionExecute this query as part of an existing transaction.

Definition at line 140 of file client.cc.

◆ ProfileQuery() [3/3]

ProfileQueryResult google::cloud::spanner::v1::Client::ProfileQuery ( Transaction::SingleUseOptions  transaction_options,
SqlStatement  statement,
QueryOptions const &  opts = {} 
)

Profiles a SQL query.

Profiling executes the query, provides the resulting rows, ExecutionPlan, and execution statistics.

Operations inside read-write transactions might return kAborted. If this occurs, the application should restart the transaction from the beginning.

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Note
Callers must consume all rows from the result before execution statistics and ExecutionPlan are available.
Parameters
statementThe SQL statement to execute.
optsThe QueryOptions to use for this call. If given, these will take precedence over the options set at the client and environment levels.
Note
No individual row in the ProfileQueryResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Example
namespace spanner = ::google::cloud::spanner;
"SELECT AlbumId, AlbumTitle, MarketingBudget"
" FROM Albums"
" WHERE AlbumTitle >= 'Aardvark' AND AlbumTitle < 'Goo'");
auto profile_query_result = client.ProfileQuery(std::move(select));
for (auto const& row : profile_query_result) {
if (!row) throw std::runtime_error(row.status().message());
// Discard rows for brevity in this example.
}
// Stats are only available after all rows from the result have been read.
auto execution_stats = profile_query_result.ExecutionStats();
if (execution_stats) {
for (auto const& stat : *execution_stats) {
std::cout << stat.first << ":\t" << stat.second << "\n";
}
}
Parameters
transaction_optionsExecute this query in a single-use transaction with these options.

Definition at line 130 of file client.cc.

◆ Read() [1/4]

RowStream google::cloud::spanner::v1::Client::Read ( ReadPartition const &  partition)

Reads rows from a subset of rows in a database.

Requires a prior call to PartitionRead to obtain the partition information; see the documentation of that method for full details.

Parameters
partitionA ReadPartition, obtained by calling PartitionRead.
Note
No individual row in the ReadResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Example
google::cloud::StatusOr<spanner::ReadPartition> partition =
remote_connection.ReceiveReadPartitionFromRemoteMachine();
if (!partition) throw std::runtime_error(partition.status().message());
auto rows = client.Read(*partition);
for (auto const& row : rows) {
if (!row) throw std::runtime_error(row.status().message());
ProcessRow(*row);
}

Definition at line 70 of file client.cc.

◆ Read() [2/4]

RowStream google::cloud::spanner::v1::Client::Read ( std::string  table,
KeySet  keys,
std::vector< std::string >  columns,
ReadOptions  read_options = {} 
)

Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery().

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Parameters
tableThe name of the table in the database to be read.
keysIdentifies the rows to be yielded. If read_options.index_name is set, names keys in that index; otherwise names keys in the primary index of table. It is not an error for keys to name rows that do not exist in the database; Read yields nothing for nonexistent rows.
columnsThe columns of table to be returned for each row matching this request.
read_optionsReadOptions used for this request.
Example
void ReadData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto rows = client.Read("Albums", google::cloud::spanner::KeySet::All(),
{"SingerId", "AlbumId", "AlbumTitle"});
using RowType = std::tuple<std::int64_t, std::int64_t, std::string>;
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "AlbumId: " << std::get<1>(*row) << "\t";
std::cout << "AlbumTitle: " << std::get<2>(*row) << "\n";
}
std::cout << "Read completed for [spanner_read_data]\n";
}
RowStream Read(std::string table, KeySet keys, std::vector< std::string > columns, ReadOptions read_options={})
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ...
Definition: client.cc:34
Note
No individual row in the ReadResult can exceed 100 MiB, and no column value can exceed 10 MiB.

Definition at line 34 of file client.cc.

◆ Read() [3/4]

RowStream google::cloud::spanner::v1::Client::Read ( Transaction  transaction,
std::string  table,
KeySet  keys,
std::vector< std::string >  columns,
ReadOptions  read_options = {} 
)

Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery().

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Parameters
tableThe name of the table in the database to be read.
keysIdentifies the rows to be yielded. If read_options.index_name is set, names keys in that index; otherwise names keys in the primary index of table. It is not an error for keys to name rows that do not exist in the database; Read yields nothing for nonexistent rows.
columnsThe columns of table to be returned for each row matching this request.
read_optionsReadOptions used for this request.
Example
void ReadData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto rows = client.Read("Albums", google::cloud::spanner::KeySet::All(),
{"SingerId", "AlbumId", "AlbumTitle"});
using RowType = std::tuple<std::int64_t, std::int64_t, std::string>;
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "AlbumId: " << std::get<1>(*row) << "\t";
std::cout << "AlbumTitle: " << std::get<2>(*row) << "\n";
}
std::cout << "Read completed for [spanner_read_data]\n";
}
Note
No individual row in the ReadResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameters
transactionExecute this read as part of an existing transaction.

Definition at line 59 of file client.cc.

◆ Read() [4/4]

RowStream google::cloud::spanner::v1::Client::Read ( Transaction::SingleUseOptions  transaction_options,
std::string  table,
KeySet  keys,
std::vector< std::string >  columns,
ReadOptions  read_options = {} 
)

Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteQuery().

Callers can optionally supply a Transaction or Transaction::SingleUseOptions used to create a single-use transaction - or neither, in which case a single-use transaction with default options is used.

Parameters
tableThe name of the table in the database to be read.
keysIdentifies the rows to be yielded. If read_options.index_name is set, names keys in that index; otherwise names keys in the primary index of table. It is not an error for keys to name rows that do not exist in the database; Read yields nothing for nonexistent rows.
columnsThe columns of table to be returned for each row matching this request.
read_optionsReadOptions used for this request.
Example
void ReadData(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto rows = client.Read("Albums", google::cloud::spanner::KeySet::All(),
{"SingerId", "AlbumId", "AlbumTitle"});
using RowType = std::tuple<std::int64_t, std::int64_t, std::string>;
for (auto const& row : spanner::StreamOf<RowType>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << "SingerId: " << std::get<0>(*row) << "\t";
std::cout << "AlbumId: " << std::get<1>(*row) << "\t";
std::cout << "AlbumTitle: " << std::get<2>(*row) << "\n";
}
std::cout << "Read completed for [spanner_read_data]\n";
}
Note
No individual row in the ReadResult can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameters
transaction_optionsExecute this read in a single-use transaction with these options.

Definition at line 46 of file client.cc.

◆ Rollback()

Status google::cloud::spanner::v1::Client::Rollback ( Transaction  transaction)

Rolls back a read-write transaction, releasing any locks it holds.

At any time before Commit, the client can call Rollback to abort the transaction. It is a good idea to call this for any read-write transaction that includes one or more Read, ExecuteQuery, or ExecuteDml requests and ultimately decides not to commit.

Warning
It is an error to call Rollback with a read-only transaction.
Parameters
transactionThe transaction to roll back.
Returns
The error status of the rollback.

Definition at line 296 of file client.cc.

Friends And Related Function Documentation

◆ operator!=

bool operator!= ( Client const &  a,
Client const &  b 
)
friend

Definition at line 150 of file client.h.

◆ operator==

bool operator== ( Client const &  a,
Client const &  b 
)
friend

Definition at line 147 of file client.h.