Contains all the Cloud Spanner C++ client types and functions.
Classes BackupThis class identifies a Cloud Spanner Backup.
BytesA representation of the Spanner BYTES type: variable-length binary data.
ClientPerforms database client operations on Spanner.
ClientOptionsClientOptions allows the caller to set a variety of options when constructing a Client
instance.
Set options on calls to spanner::Client::Commit()
.
A connection to a Spanner database instance.
CreateInstanceRequestBuilderCreateInstanceRequestBuilder is a builder class for google::spanner::admin::instance::v1::CreateInstanceRequest
Use encryption with encryption_key
.
This class identifies a Cloud Spanner Database.
DatabaseAdminClientPerforms database administration operations on Spanner.
DatabaseAdminConnectionA connection to the Cloud Spanner instance administration service.
Decimal<>A representation of the Spanner NUMERIC type: an exact decimal value with a maximum integer precision (kIntPrecision) and rounding to a maximum fractional precision (kFracPrecision).
DefaultEncryptionUse the per-operation default encryption:
DmlResultRepresents the result of a data modifying operation using spanner::Client::ExecuteDml()
.
An ExcludeReplicas
contains a list of ReplicaSelection
s that should be excluded from serving requests.
Use Google default encryption.
IncludeReplicasAn IncludeReplicas
contains an ordered list of ReplicaSelection
s that should be considered when serving requests.
This class identifies a Cloud Spanner Instance.
InstanceAdminClientPerforms instance administration operations on Cloud Spanner.
InstanceAdminConnectionA connection to the Cloud Spanner instance administration service.
IntervalA representation of the Spanner INTERVAL type: The difference between two date/time values.
JsonA simple representation for the Spanner JSON type: a lightweight, text-based, language-independent data interchange format.
JsonBJsonB
is a variant of Json
(see above).
The KeyBound
class is a regular type that represents an open or closed endpoint for a range of keys.
The KeySet
class is a regular type that represents a collection of Key
s.
A retry policy for the Spanner library based on counting errors.
LimitedErrorCountTransactionRerunPolicyA transaction rerun policy based on counting errors.
LimitedTimeRetryPolicyA retry policy for the Spanner library based on elapsed time.
LimitedTimeTransactionRerunPolicyA transaction rerun policy based on elapsed time.
MutationA wrapper for Cloud Spanner mutations.
PgOidA representation of the PostgreSQL Object Identifier (OID) type: used as primary keys for various system tables in the PostgreSQL dialect.
ProfileDmlResultRepresents the result and profile stats of a data modifying operation using spanner::Client::ProfileDml()
.
Represents the stream of Rows
and profile stats returned from spanner::Client::ProfileQuery()
.
A representation of the Spanner ENUM type: a protobuf enumeration.
ProtoMessage<M>A representation of the Spanner PROTO type: a protobuf message.
QueryOptionsThese QueryOptions allow users to configure features about how their SQL queries executes on the server.
QueryPartitionThe QueryPartition
class is a regular type that represents a single slice of a parallel SQL read.
The ReadPartition
class is a regular type that represents a single slice of a parallel Read operation.
The directed-read replica selector.
ResultSourceInterfaceDefines the interface for RowStream
implementations.
The base class for the Spanner library retry policies.
RowA Row
is a sequence of columns each with a name and an associated Value
.
Represents the stream of Rows
returned from spanner::Client::Read()
or spanner::Client::ExecuteQuery()
.
A RowStreamIterator
is an Input Iterator (see below) that returns a sequence of StatusOr
<
Row
>
objects.
Controls the session pool maintained by a spanner::Client
.
Represents a potentially parameterized SQL statement.
TimestampA representation of the Spanner TIMESTAMP type: An instant in time.
TransactionThe representation of a Cloud Spanner transaction.
TransactionRerunPolicyThe base class for the Spanner library transaction rerun policies.
TupleStream<Tuple>A TupleStream
<Tuple>
defines a range that parses Tuple
objects from the given range of RowStreamIterator
s.
A TupleStreamIterator
<Tuple>
is an "Input Iterator" that wraps a RowStreamIterator
, parsing its elements into a sequence of StatusOr
<Tuple>
objects.
UpdateInstanceRequestBuilder is a builder class for google::spanner::admin::instance::v1::UpdateInstanceRequest
A representation of the Spanner UUID type: A 16-byte value that can be represented as a 32-digit hexadecimal string.
ValueThe Value class represents a type-safe, nullable Spanner value.
Structs BatchDmlResultThe result of executing a batch of DML statements.
BatchedCommitResultThe result of committing a Transaction containing a batch of mutation groups.
CommitResultThe result of committing a Transaction.
CommitReturnStatsOptionOption for google::cloud::Options
to return additional statistics about the committed transaction in a spanner::CommitResult
.
Statistics returned for a committed Transaction.
CommitTimestampA sentinel type used to update a commit timestamp column.
ConnectionOptionsTraitsThe traits to configure ConnectionOptions<T>
for Cloud Spanner.
Option for google::cloud::Options
to indicate which replicas or regions should be used for reads/queries in read-only or single-use transactions.
Option for google::cloud::Options
to use Multiplexed sessions in lieu of pooled sessions.
Option for google::cloud::Options
to control when transaction mutations will not be recorded in change streams that track columns modified by the transaction.
Option for google::cloud::Options
to set the lock hint mechanism for reads done within a transaction.
Option for google::cloud::Options
to set the amount of latency this request is willing to incur in order to improve throughput.
Option for google::cloud::Options
to set the order in which the rows are returned from a read request.
Option for google::cloud::Options
to use "data boost" in the partitions returned from Client::PartitionRead()
or PartitionQuery()
.
The result of executing a Partitioned DML query.
PartitionOptionsOptions passed to Client::PartitionRead
or Client::PartitionQuery
.
Option for google::cloud::Options
to set the desired partition size to be generated by Client::PartitionRead()
or PartitionQuery()
.
Option for google::cloud::Options
to set the desired maximum number of partitions to return from Client::PartitionRead()
or PartitionQuery()
.
Option for google::cloud::Options
to set the optimizer statistics package used in an SQL query.
Option for google::cloud::Options
to set the optimizer version used in an SQL query.
Option for google::cloud::Options
to set the name of an index on a database table.
Options passed to Client::Read
or Client::PartitionRead
.
Option for google::cloud::Options
to set a limit on the number of rows to yield from Client::Read()
.
Option for google::cloud::Options
to set a spanner::RequestPriority
.
Option for google::cloud::Options
to set a per-request tag.
Control "route to leader region" headers.
SessionCreatorRoleOptionOption for google::cloud::Options
to set the database role used for session creation.
Option for google::cloud::Options
to set the action to take when attempting to allocate a session when the pool is exhausted.
Option for google::cloud::Options
to set the interval at which we refresh sessions so they don't get collected by the backend GC.
Option for google::cloud::Options
to set the labels used when creating sessions within the pool.
Option for google::cloud::Options
to set the maximum number of sessions to keep in the pool in an idle state.
Option for google::cloud::Options
to set the maximum number of sessions to create on each channel.
Option for google::cloud::Options
to set the minimum number of sessions to keep in the pool.
Option for google::cloud::Options
to set a spanner::BackoffPolicy
.
Option for google::cloud::Options
to set a spanner::PollingPolicy
.
Option for google::cloud::Options
to set a spanner::RetryPolicy
.
Option for google::cloud::Options
to set a limit on how much data will be buffered to guarantee resumability of a streaming read or SQL query.
Option for google::cloud::Options
to set a per-transaction tag.
Indicates the type of replica.
LockHint DecimalMode ActionOnExhaustionAction to take when the session pool is exhausted.
OrderBy RequestPriority Functions ToInteger(Decimal< Mode > const &, int)Conversion to the nearest integer value, scaled by 10^exponent
.
Rounds halfway cases away from zero. Fails when the destination type cannot hold that value.
Exampleauto d =
spanner::MakeDecimal<spanner::DecimalMode::kGoogleSQL>(123456789, -2)
.value();
assert(d.ToString() == "1234567.89");
assert(spanner::ToInteger<int>(d).value() == 1234568);
assert(spanner::ToInteger<int>(d, 2).value() == 123456789);
Parameters Name Description d
Decimal< Mode > const &
exponent
int
typename T
DecimalMode
StatusOr< T >
MakeNumeric(std::string)
MakeNumeric()
factory functions for Numeric
.
s
std::string
StatusOr< Numeric >
MakeNumeric(double)
MakeNumeric()
factory functions for Numeric
.
d
double
StatusOr< Numeric >
MakeNumeric(T, int)
MakeNumeric()
factory functions for Numeric
.
i
T
exponent
int
typename T
StatusOr< Numeric >
MakePgNumeric(std::string)
MakePgNumeric()
factory functions for PgNumeric
.
s
std::string
StatusOr< PgNumeric >
MakePgNumeric(double)
MakePgNumeric()
factory functions for PgNumeric
.
d
double
StatusOr< PgNumeric >
MakePgNumeric(T, int)
MakePgNumeric()
factory functions for PgNumeric
.
i
T
exponent
int
typename T
StatusOr< PgNumeric >
MakeBackup(std::string const &)
Constructs a Backup
from the given full_name
.
Returns a non-OK Status if full_name
is improperly formed.
full_name
std::string const &
StatusOr< Backup >
MakeConnection(spanner::Database const &, Options)
Returns a Connection object that can be used for interacting with Spanner.
Parameters Name Descriptiondb
spanner::Database const &
See Database
.
opts
Options
(optional) Configure the Connection
created by this function.
std::shared_ptr< spanner::Connection >
MakeConnection(Database const &, ConnectionOptions const &, SessionPoolOptions)
Returns a Connection object that can be used for interacting with Spanner.
Parameters Name Descriptiondb
Database const &
See Database
.
connection_options
ConnectionOptions const &
configure the Connection
created by this function.
session_pool_options
SessionPoolOptions
(optional) configure the SessionPool
created by the Connection
.
std::shared_ptr< Connection >
MakeConnection(Database const &, ConnectionOptions const &, SessionPoolOptions, std::unique_ptr< RetryPolicy >, std::unique_ptr< BackoffPolicy >)
Returns a Connection object that can be used for interacting with Spanner.
The returned connection object should not be used directly, rather it should be given to a Client
instance, and methods should be invoked on Client
.
MakeConnection()
overload that accepts google::cloud::Options
instead. See Also
Deprecated:
Please use the MakeConnection()
overload that accepts google::cloud::Options
instead.
namespace spanner = ::google::cloud::spanner;
using ::google::cloud::StatusOr;
[](std::string const& project_id, std::string const& instance_id,
std::string const& database_id) {
// Use a truncated exponential backoff with jitter to wait between
// retries:
// https://en.wikipedia.org/wiki/Exponential_backoff
// https://cloud.google.com/storage/docs/exponential-backoff
auto client = spanner::Client(spanner::MakeConnection(
spanner::Database(project_id, instance_id, database_id),
google::cloud::Options{}
.set<spanner::SpannerRetryPolicyOption>(
std::make_shared<spanner::LimitedTimeRetryPolicy>(
/*maximum_duration=*/std::chrono::seconds(60)))
.set<spanner::SpannerBackoffPolicyOption>(
std::make_shared<spanner::ExponentialBackoffPolicy>(
/*initial_delay=*/std::chrono::milliseconds(500),
/*maximum_delay=*/std::chrono::seconds(16),
/*scaling=*/1.5))));
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),
spanner::SqlStatement(
"INSERT INTO Singers (SingerId, FirstName, LastName)"
" VALUES (20, 'George', 'Washington')"));
if (!insert) return std::move(insert).status();
rows_inserted = insert->RowsModified();
return spanner::Mutations{};
});
if (!commit_result) throw std::move(commit_result).status();
std::cout << "Rows inserted: " << rows_inserted;
}
Parameters Name Description db
Database const &
See Database
.
connection_options
ConnectionOptions const &
configure the Connection
created by this function.
session_pool_options
SessionPoolOptions
(optional) configure the SessionPool
created by the Connection
.
retry_policy
std::unique_ptr< RetryPolicy >
backoff_policy
std::unique_ptr< BackoffPolicy >
std::shared_ptr< Connection >
MakeDatabase(std::string const &)
Constructs a Database
from the given full_name
.
Returns a non-OK Status if full_name
is improperly formed.
full_name
std::string const &
StatusOr< Database >
MakeDatabaseAdminConnection(Options)
Returns a DatabaseAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
Returns Type Descriptionstd::shared_ptr< spanner::DatabaseAdminConnection >
MakeDatabaseAdminConnection(ConnectionOptions const &)
Returns a DatabaseAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
Parameter Name Descriptionoptions
ConnectionOptions const &
configure the DatabaseAdminConnection
created by this function.
std::shared_ptr< DatabaseAdminConnection >
MakeDatabaseAdminConnection(ConnectionOptions const &, std::unique_ptr< RetryPolicy >, std::unique_ptr< BackoffPolicy >, std::unique_ptr< PollingPolicy >)
Returns a DatabaseAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
The returned connection object should not be used directly, rather it should be given to a DatabaseAdminClient
instance.
MakeDatabaseAdminConnection()
overload that accepts google::cloud::Options
. Example
namespace spanner = ::google::cloud::spanner;
[](std::string const& project_id, std::string const& instance_id) {
// A database admin client is controlled by three policies. The retry
// policy determines for how long the client will retry transient failures.
auto retry_policy =
google::cloud::spanner_admin::DatabaseAdminLimitedTimeRetryPolicy(
/*maximum_duration=*/std::chrono::minutes(25))
.clone();
// The backoff policy controls how long does the client waits to retry after
// a transient failure. Here we configure a truncated exponential backoff
// with jitter:
// https://en.wikipedia.org/wiki/Exponential_backoff
// https://cloud.google.com/storage/docs/exponential-backoff
auto backoff_policy = spanner::ExponentialBackoffPolicy(
/*initial_delay=*/std::chrono::seconds(2),
/*maximum_delay=*/std::chrono::minutes(10),
/*scaling=*/2.0)
.clone();
// The polling policy controls how the client waits for long-running
// operations (such as creating new instances). `GenericPollingPolicy<>`
// combines existing policies. In this case, keep polling until the
// operation completes (with success or error) or 45 minutes, whichever
// happens first. Initially pause for 10 seconds between polling requests,
// increasing the pause by a factor of 4 until it becomes 2 minutes.
auto polling_policy =
spanner::GenericPollingPolicy<>(
spanner::LimitedTimeRetryPolicy(
/*maximum_duration=*/std::chrono::minutes(45)),
spanner::ExponentialBackoffPolicy(
/*initial_delay=*/std::chrono::seconds(10),
/*maximum_delay=*/std::chrono::minutes(2),
/*scaling=*/4.0))
.clone();
auto client = google::cloud::spanner_admin::DatabaseAdminClient(
google::cloud::spanner_admin::MakeDatabaseAdminConnection(),
google::cloud::Options{}
.set<google::cloud::spanner_admin::DatabaseAdminRetryPolicyOption>(
std::move(retry_policy))
.set<
google::cloud::spanner_admin::DatabaseAdminBackoffPolicyOption>(
std::move(backoff_policy))
.set<
google::cloud::spanner_admin::DatabaseAdminPollingPolicyOption>(
std::move(polling_policy)));
// Use the client as usual.
spanner::Instance instance(project_id, instance_id);
std::cout << "Available databases for instance " << instance << "\n";
for (auto& db : client.ListDatabases(instance.FullName())) {
if (!db) throw std::move(db).status();
std::cout << db->name() << "\n";
}
std::cout << "End of available databases\n";
}
Parameters Name Description options
ConnectionOptions const &
configure the DatabaseAdminConnection
created by this function.
retry_policy
std::unique_ptr< RetryPolicy >
control for how long (or how many times) are retryable RPCs attempted
backoff_policy
std::unique_ptr< BackoffPolicy >
controls the backoff behavior between retry attempts, typically some form of exponential backoff with jitter
polling_policy
std::unique_ptr< PollingPolicy >
controls for how often, and how quickly, are long running checked for completion
Returns Type Descriptionstd::shared_ptr< DatabaseAdminConnection >
MakeInstance(std::string const &)
Constructs an Instance
from the given full_name
.
Returns a non-OK Status if full_name
is improperly formed.
full_name
std::string const &
StatusOr< Instance >
MakeInstanceAdminConnection(Options)
Returns an InstanceAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
Returns Type Descriptionstd::shared_ptr< spanner::InstanceAdminConnection >
MakeInstanceAdminConnection(ConnectionOptions const &)
Returns an InstanceAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
Parameter Name Descriptionoptions
ConnectionOptions const &
configure the InstanceAdminConnection
created by this function.
std::shared_ptr< InstanceAdminConnection >
MakeInstanceAdminConnection(ConnectionOptions const &, std::unique_ptr< RetryPolicy >, std::unique_ptr< BackoffPolicy >, std::unique_ptr< PollingPolicy >)
Returns an InstanceAdminConnection object that can be used for interacting with Cloud Spanner's admin APIs.
The returned connection object should not be used directly, rather it should be given to a InstanceAdminClient
instance.
MakeInstanceAdminConnection()
overload that accepts google::cloud::Options
. Example
namespace spanner = ::google::cloud::spanner;
[](std::string const& project_id) {
// An instance admin client is controlled by three policies. The retry
// policy determines for how long the client will retry transient failures.
auto retry_policy =
google::cloud::spanner_admin::InstanceAdminLimitedTimeRetryPolicy(
/*maximum_duration=*/std::chrono::minutes(25))
.clone();
// The backoff policy controls how long does the client waits to retry after
// a transient failure. Here we configure a truncated exponential backoff
// with jitter:
// https://en.wikipedia.org/wiki/Exponential_backoff
// https://cloud.google.com/storage/docs/exponential-backoff
auto backoff_policy = spanner::ExponentialBackoffPolicy(
/*initial_delay=*/std::chrono::seconds(2),
/*maximum_delay=*/std::chrono::minutes(10),
/*scaling=*/2.0)
.clone();
// The polling policy controls how the client waits for long-running
// operations (such as creating new instances). `GenericPollingPolicy<>`
// combines existing policies. In this case, keep polling until the
// operation completes (with success or error) or 45 minutes, whichever
// happens first. Initially pause for 10 seconds between polling requests,
// increasing the pause by a factor of 4 until it becomes 2 minutes.
auto polling_policy =
spanner::GenericPollingPolicy<>(
spanner::LimitedTimeRetryPolicy(
/*maximum_duration=*/std::chrono::minutes(45)),
spanner::ExponentialBackoffPolicy(
/*initial_delay=*/std::chrono::seconds(10),
/*maximum_delay=*/std::chrono::minutes(2),
/*scaling=*/4.0))
.clone();
auto client = google::cloud::spanner_admin::InstanceAdminClient(
google::cloud::spanner_admin::MakeInstanceAdminConnection(),
google::cloud::Options{}
.set<google::cloud::spanner_admin::InstanceAdminRetryPolicyOption>(
std::move(retry_policy))
.set<
google::cloud::spanner_admin::InstanceAdminBackoffPolicyOption>(
std::move(backoff_policy))
.set<
google::cloud::spanner_admin::InstanceAdminPollingPolicyOption>(
std::move(polling_policy)));
// Use the client as usual.
std::cout << "Available configs for project " << project_id << "\n";
auto project = google::cloud::Project(project_id);
for (auto& cfg : client.ListInstanceConfigs(project.FullName())) {
if (!cfg) throw std::move(cfg).status();
std::cout << cfg->name() << "\n";
}
std::cout << "End of available configs\n";
}
Parameters Name Description options
ConnectionOptions const &
configure the InstanceAdminConnection
created by this function.
retry_policy
std::unique_ptr< RetryPolicy >
control for how long (or how many times) are retryable RPCs attempted
backoff_policy
std::unique_ptr< BackoffPolicy >
controls the backoff behavior between retry attempts, typically some form of exponential backoff with jitter
polling_policy
std::unique_ptr< PollingPolicy >
controls for how often, and how quickly, are long running checked for completion
Returns Type Descriptionstd::shared_ptr< InstanceAdminConnection >
MakeInterval(absl::string_view)
Construct an Interval
from a string.
At least handles the format produced by Interval::operator std::string()
.
absl::string_view
StatusOr< Interval >
JustifyDays(Interval)
Adjust the interval so that 30-day periods are represented as months.
For example, maps "35 days" to "1 month 5 days".
Parameter Name Description
Interval
Interval
JustifyHours(Interval)
Adjust the interval so that 24-hour periods are represented as days.
For example, maps "27 hours" to "1 day 3 hours".
Parameter Name Description
Interval
Interval
JustifyInterval(Interval)
Adjust the interval using both JustifyDays() and JustifyHours().
For example, maps "1 month -1 hour" to "29 days 23 hours".
Parameter Name Description
Interval
Interval
MakeKey(Ts &&...)
Constructs a Key
from the given arguments.
auto delete_albums = spanner::DeleteMutationBuilder(
"Albums", spanner::KeySet()
.AddKey(spanner::MakeKey(2, 1))
.AddKey(spanner::MakeKey(2, 3)))
.Build();
Parameters Name Description ts
Ts &&...
typename...
Key
MakeKeyBoundClosed(Ts &&...)
Returns a "closed" KeyBound
with a Key
constructed from the given arguments.
auto delete_singers_range =
spanner::DeleteMutationBuilder(
"Singers", spanner::KeySet().AddRange(spanner::MakeKeyBoundClosed(3),
spanner::MakeKeyBoundOpen(5)))
.Build();
Parameters Name Description ts
Ts &&...
typename...
KeyBound
MakeKeyBoundOpen(Ts &&...)
Returns an "open" KeyBound
with a Key
constructed from the given arguments.
auto key_set = spanner::KeySet().AddRange(spanner::MakeKeyBoundOpen(0),
spanner::MakeKeyBoundOpen(11));
Parameters Name Description ts
Ts &&...
typename...
KeyBound
MakeInsertMutation(std::string, std::vector< std::string >, Ts &&...)
Creates a simple insert mutation for the values in values
.
void MakeInsertMutation(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
// Delete each of the albums by individual key, then delete all the singers
// using a key range.
auto commit_result = client.Commit(spanner::Mutations{
spanner::InsertOrUpdateMutationBuilder(
"Performances",
{"SingerId", "VenueId", "EventDate", "Revenue", "LastUpdateTime"})
.EmplaceRow(1, 4, absl::CivilDay(2017, 10, 5), 11000,
spanner::CommitTimestamp{})
.EmplaceRow(1, 19, absl::CivilDay(2017, 11, 2), 15000,
spanner::CommitTimestamp{})
.Build()});
if (!commit_result) throw std::move(commit_result).status();
std::cout << "make-insert-mutation was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
Parameters Name Descriptiontable_name
std::string
columns
std::vector< std::string >
values
Ts &&...
typename...
Mutation
MakeUpdateMutation(std::string, std::vector< std::string >, Ts &&...)
Creates a simple update mutation for the values in values
.
void MakeUpdateMutation(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::MakeUpdateMutation(
"Albums", {"SingerId", "AlbumId", "MarketingBudget"}, 1, 1, 200000),
});
if (!commit) throw std::move(commit).status();
std::cout << "make-update-mutation was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
Parameters Name Descriptiontable_name
std::string
columns
std::vector< std::string >
values
Ts &&...
typename...
Mutation
MakeInsertOrUpdateMutation(std::string, std::vector< std::string >, Ts &&...)
Creates a simple "insert or update" mutation for the values in values
.
void MakeInsertOrUpdateMutation(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::MakeInsertOrUpdateMutation(
"Albums", {"SingerId", "AlbumId", "AlbumTitle", "MarketingBudget"}, 1,
1, "Total Junk", 200000),
});
if (!commit) throw std::move(commit).status();
std::cout << "make-insert-or-update-mutation was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
Parameters Name Descriptiontable_name
std::string
columns
std::vector< std::string >
values
Ts &&...
typename...
Mutation
MakeReplaceMutation(std::string, std::vector< std::string >, Ts &&...)
Creates a simple "replace" mutation for the values in values
.
void MakeReplaceMutation(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::MakeReplaceMutation(
"Albums", {"SingerId", "AlbumId", "AlbumTitle", "MarketingBudget"}, 1,
1, "Go, Go, Go", 600000),
});
if (!commit) throw std::move(commit).status();
std::cout << "make-replace-mutation was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
Parameters Name Descriptiontable_name
std::string
columns
std::vector< std::string >
values
Ts &&...
typename...
Mutation
MakeDeleteMutation(std::string, KeySet)
Creates a simple "delete" mutation for the values in keys
.
void MakeDeleteMutation(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::MakeDeleteMutation("Albums", spanner::KeySet::All()),
});
if (!commit) throw std::move(commit).status();
std::cout << "make-delete-mutation was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
Parameters Name Descriptiontable_name
std::string
keys
KeySet
Mutation
MakeDecimal(std::string)
Construction from a string, in decimal fixed- or floating-point formats.
For example, "0", "-999", "3.141592654", "299792458", "6.02214076e23", etc. There must be digits either before or after any decimal point.
Fails on syntax errors or if the conversion would yield a value outside the NUMERIC range. If the argument has more than kFracPrecision
digits after the decimal point it will be rounded, with halfway cases rounding away from zero.
s
std::string
DecimalMode
StatusOr< Decimal< Mode > >
MakeDecimal(double)
Construction from a double.
Fails on NaN or any argument outside the NUMERIC value range (including infinities). If the argument has more than kFracPrecision
digits after the decimal point it will be rounded, with halfway cases rounding away from zero.
d
double
DecimalMode
StatusOr< Decimal< Mode > >
MakeDecimal(T, int)
Construction from an integer i
, scaled by 10^exponent
.
Fails on any (scaled) argument outside the NUMERIC value range.
Parameters Name Descriptioni
T
exponent
int
typename T
DecimalMode
StatusOr< Decimal< Mode > >
ToDouble(Decimal< Mode > const &)
Conversion to the closest double value, with possible loss of precision.
Always succeeds (i.e., can never overflow, assuming a double can hold values up to 10^(kIntPrecision+1)).
Parameters Name Descriptiond
Decimal< Mode > const &
DecimalMode
double
ToOptions(PartitionOptions const &)
Converts PartitionOptions
to common Options
.
PartitionOptions const &
Options
ToPartitionOptions(Options const &)
Converts common Options
to PartitionOptions
.
Options const &
PartitionOptions
SerializeQueryPartition(QueryPartition const &)
Serializes an instance of QueryPartition
to a string of bytes.
The serialized string of bytes is suitable for writing to disk or transmission to another process.
Note: The serialized string may contain NUL and other non-printable characters. Therefore, callers should avoid formatted IO functions that may incorrectly reformat the string data. Example namespace spanner = ::google::cloud::spanner;
google::cloud::StatusOr<std::string> serialized_partition =
spanner::SerializeQueryPartition(partition);
if (!serialized_partition) throw std::move(serialized_partition).status();
std::string const& bytes = *serialized_partition;
// `bytes` contains the serialized data, which may contain NULs and other
// non-printable characters.
SendBinaryStringData(bytes);
Parameter Name Description query_partition
QueryPartition const &
StatusOr< std::string >
DeserializeQueryPartition(std::string const &)
Deserializes the provided string into a QueryPartition
.
The serialized_query_partition
argument must be a string that was previously returned by a call to SerializeQueryPartition()
.
google::cloud::StatusOr<google::cloud::spanner::QueryPartition>
ReceiveQueryPartitionFromRemoteMachine() {
std::string serialized_partition = Receive();
return google::cloud::spanner::DeserializeQueryPartition(
serialized_partition);
}
Parameter Name Description serialized_query_partition
std::string const &
StatusOr< QueryPartition >
ToOptions(ReadOptions const &)
Converts ReadOptions
to common Options
.
ReadOptions const &
Options
ToReadOptions(Options const &)
Converts common Options
to ReadOptions
.
Options const &
ReadOptions
SerializeReadPartition(ReadPartition const &)
Serializes an instance of ReadPartition
to a string of bytes.
The serialized string of bytes is suitable for writing to disk or transmission to another process.
Note: The serialized string may contain NUL and other non-printable characters. Therefore, callers should avoid formatted IO functions that may incorrectly reformat the string data. Example namespace spanner = ::google::cloud::spanner;
google::cloud::StatusOr<std::string> serialized_partition =
spanner::SerializeReadPartition(partition);
if (!serialized_partition) throw std::move(serialized_partition).status();
std::string const& bytes = *serialized_partition;
// `bytes` contains the serialized data, which may contain NULs and other
// non-printable characters.
SendBinaryStringData(bytes);
Parameter Name Description read_partition
ReadPartition const &
StatusOr< std::string >
DeserializeReadPartition(std::string const &)
Deserializes the provided string into a ReadPartition
.
The serialized_read_partition
argument must be a string that was previously returned by a call to SerializeReadPartition()
.
google::cloud::StatusOr<google::cloud::spanner::ReadPartition>
ReceiveReadPartitionFromRemoteMachine() {
std::string serialized_partition = Receive();
return google::cloud::spanner::DeserializeReadPartition(
serialized_partition);
}
Parameter Name Description serialized_read_partition
std::string const &
StatusOr< ReadPartition >
MakeTestRow(std::vector< std::pair< std::string, Value > >)
Creates a Row
with the specified column names and values.
This overload accepts a vector of pairs, allowing the caller to specify both the column names and the Value
that goes in each column.
This function is intended for application developers who are mocking the results of a Client::ExecuteQuery
call.
pairs
std::vector< std::pair< std::string, Value > >
Row
MakeTestRow(Ts &&...)
Creates a Row
with Value
s created from the given arguments and with auto-generated column names.
This overload accepts a variadic list of arguments that will be used to create the Value
s in the row. The column names will be implicitly generated, the first column being "0", the second "1", and so on, corresponding to the argument's position.
This function is intended for application developers who are mocking the results of a Client::ExecuteQuery
call.
ts
Ts &&...
typename...
Row
StreamOf(RowRange &&)
A factory that creates a TupleStream
<Tuple>
by wrapping the given range
.
The RowRange
must be a range defined by RowStreamIterator
objects.
void StreamOf(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
std::cout << "Querying the Singers table:\n";
auto query = client.ExecuteQuery(spanner::SqlStatement(
"SELECT SingerId, FirstName, LastName FROM Singers"));
using RowType = std::tuple<std::int64_t, std::string, std::string>;
for (auto& row : spanner::StreamOf<RowType>(query)) {
if (!row) throw std::move(row).status();
std::cout << " SingerId: " << std::get<0>(*row) << "\n"
<< " FirstName: " << std::get<1>(*row) << "\n"
<< " LastName: " << std::get<2>(*row) << "\n";
}
std::cout << "end of results\n";
}
Note: Ownership of the range
is not transferred, so it must outlive the returned TupleStream
. Parameters Name Description range
RowRange &&
typename Tuple
typename RowRange
must be a range defined by RowStreamIterator
s.
TupleStream< Tuple >
GetSingularRow(RowRange)
Returns the only row from a range that contains exactly one row.
An error is returned if the given range does not contain exactly one row. This is a convenience function that may be useful when the caller knows that a range should contain exactly one row, such as when LIMIT 1
is used in an SQL query, or when a read is performed on a guaranteed unique key such that only a single row could possibly match. In cases where the caller does not know how many rows may be returned, they should instead consume the range in a loop.
void GetSingularRow(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto query = client.ExecuteQuery(spanner::SqlStatement(
"SELECT FirstName, LastName FROM Singers WHERE SingerId = @singer_id",
{{"singer_id", spanner::Value(2)}}));
// `SingerId` is the primary key for the `Singers` table, the `GetSingularRow`
// helper returns a single row or an error:
using RowType = std::tuple<std::string, std::string>;
auto row = GetSingularRow(spanner::StreamOf<RowType>(query));
if (!row) throw std::move(row).status();
std::cout << "FirstName: " << std::get<0>(*row)
<< "\nLastName: " << std::get<1>(*row) << "\n";
}
Parameters Name Description range
RowRange
typename RowRange
std::decay_t< decltype(*range.begin())>
MakeTimestamp(absl::Time)
Construct a Timestamp
from an absl::Time
.
May produce out-of-range errors if the given time is beyond the range supported by Timestamp
(see class comments above).
absl::Time
StatusOr< Timestamp >
MakeTimestamp(protobuf::Timestamp const &)
Construct a Timestamp
from a google::protobuf::Timestamp
.
May produce out-of-range errors if the given protobuf is beyond the range supported by Timestamp
(which a valid protobuf never will).
protobuf::Timestamp const &
StatusOr< Timestamp >
MakeTimestamp(sys_time< Duration > const &)
Construct a Timestamp
from a std::chrono::time_point
on the system clock.
May produce out-of-range errors, depending on the properties of Duration
and the std::chrono::system_clock
epoch. Duration::rep
may not be wider than std::int64_t
. Requires that Duration::period
is no more precise than std::nano
.
tp
sys_time< Duration > const &
typename Duration
StatusOr< Timestamp >
MakeReadOnlyTransaction(Transaction::ReadOnlyOptions)
Create a read-only transaction configured with opts
.
Transaction
object. Instead, the first request to the server (for example as part of a ExecuteQuery()
call) will also create the transaction.
opts
Transaction::ReadOnlyOptions
Transaction
MakeReadWriteTransaction(Transaction::ReadWriteOptions)
Create a read-write transaction configured with opts
.
Transaction
object. Instead, the first request to the server (for example as part of a ExecuteQuery()
call) will also create the transaction.
opts
Transaction::ReadWriteOptions
Transaction
MakeReadWriteTransaction(Transaction const &, Transaction::ReadWriteOptions)
Create a read-write transaction configured with opts
, and sharing lock priority with txn
.
This should be used when rerunning an aborted transaction, so that the new attempt has a slightly better chance of success.
Parameters Name Descriptiontxn
Transaction const &
opts
Transaction::ReadWriteOptions
Transaction
MakeUuid(absl::string_view)
Parses a textual representation a Uuid
from a string of hexadecimal digits.
Returns an error if unable to parse the given input.
Acceptable input strings must consist of 32 hexadecimal digits: [0-9a-fA-F]. Optional curly braces are allowed around the entire sequence of digits as are hyphens between any pair of hexadecimal digits.
Example acceptable inputs:
s
absl::string_view
StatusOr< Uuid >
MakeNullValue()
Factory to construct a "null" Value of the specified type T
.
This is equivalent to passing an absl::optional<T>
without a value to the constructor, though this factory may be easier to invoke and result in clearer code at the call site.
typename T
Value
VersionMajor()
The Cloud Spanner C++ Client major version.
Returns Type Descriptionint constexpr
VersionMinor()
The Cloud Spanner C++ Client minor version.
Returns Type Descriptionint constexpr
VersionPatch()
The Cloud Spanner C++ Client patch version.
Returns Type Descriptionint constexpr
VersionPreRelease()
The Cloud Spanner C++ Client pre-release version.
Returns Type Descriptionchar const *
Version()
A single integer representing the Major/Minor/Patch version.
Returns Type Descriptionint constexpr
VersionString()
The version as a string, in MAJOR.MINOR.PATCH[-PRE][+gitrev] format.
Returns Type Descriptionstd::string
Type Aliases Numeric
Alias Of: Decimal< DecimalMode::kGoogleSQL >
Most users only need the Numeric
or PgNumeric
specializations of Decimal
.
For example:
auto n = spanner::MakeNumeric(42).value();
assert(n.ToString() == "42");
assert(spanner::ToInteger<int>(n).value() == 42);
PgNumeric
Alias Of: Decimal< DecimalMode::kPostgreSQL >
Most users only need the Numeric
or PgNumeric
specializations of Decimal
.
For example:
auto n = spanner::MakeNumeric(42).value();
assert(n.ToString() == "42");
assert(spanner::ToInteger<int>(n).value() == 42);
BackoffPolicy
Alias Of: ::google::cloud::internal::BackoffPolicy
The base class for backoff policies.
ExponentialBackoffPolicyAlias Of: google::cloud::internal::ExponentialBackoffPolicy
A truncated exponential backoff policy with randomized periods.
BatchedCommitResultStreamAlias Of: StreamRange< BatchedCommitResult >
Represents the stream of BatchedCommitResult
objects returned from the batched Client::CommitAtLeastOnce()
.
Alias Of: google::cloud::ConnectionOptions< ConnectionOptionsTraits >
The options for Cloud Spanner connections.
ListDatabaseRangeAlias Of: ::google::cloud::internal::PaginationRange< google::spanner::admin::database::v1::Database >
An input range to stream all the databases in a Cloud Spanner instance.
This type models an input range of google::spanner::admin::v1::Database
objects. Applications can make a single pass through the results.
Alias Of: google::cloud::internal::PaginationRange< google::longrunning::Operation >
An input range to stream backup operations in Cloud Spanner instance.
This type models an input range of google::longrunning::Operation
objects. Applications can make a single pass through the results.
Alias Of: google::cloud::internal::PaginationRange< google::longrunning::Operation >
An input range to stream database operations in Cloud Spanner instance.
This type models an input range of google::longrunning::Operation
objects. Applications can make a single pass through the results.
Alias Of: ::google::cloud::internal::PaginationRange< google::spanner::admin::database::v1::Backup >
An input range to stream backups in Cloud Spanner instance.
This type models an input range of google::longrunning::Operation
objects. Applications can make a single pass through the results.
Alias Of: ::absl::CivilDay
Represents a date in the proleptic Gregorian calendar as a triple of year, month (1-12), and day (1-31).
EncryptionConfigAlias Of: absl::variant< DefaultEncryption, GoogleEncryption, CustomerManagedEncryption >
Specify the encryption configuration for any of the following operations:
IamUpdaterAlias Of: ::google::cloud::IamUpdater
Type alias for google::cloud::IamUpdater
.
Used in the SetIamPolicy()
read-modify-write cycle of the Spanner admin clients, DatabaseAdminClient
and InstanceAdminClient
, in order to avoid race conditions.
The updater is called with a recently fetched policy, and should either return an empty optional if no changes are required, or return a new policy to be set. In the latter case the control loop will always set the etag
of the new policy to that of the recently fetched one. A failure to update then indicates a race, and the process will repeat.
Alias Of: ::google::cloud::internal::PaginationRange< google::spanner::admin::instance::v1::Instance >
An input range to stream all the instances in a Cloud project.
This type models an input range of google::spanner::admin::v1::Instance
objects. Applications can make a single pass through the results.
Alias Of: ::google::cloud::internal::PaginationRange< google::spanner::admin::instance::v1::InstanceConfig >
An input range to stream all the instance configs in a Cloud project.
This type models an input range of google::spanner::admin::v1::Instance
objects. Applications can make a single pass through the results.
Alias Of: std::vector< Value >
A Key
is a collection of Value
objects where the i'th value corresponds to the i'th component of the table or primary index key.
In C++, this is implemented as a std::vector<
Value
>
. See the MakeKey
factory function below for an easy way to construct a valid Key
instance.
Alias Of: std::vector< Mutation >
An ordered sequence of mutations to pass to Client::Commit()
or return from the Client::Commit()
mutator.
Alias Of: spanner_internal::WriteMutationBuilder< spanner_internal::InsertOp >
A helper class to construct "insert" mutations.
Examplevoid InsertMutationBuilder(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(
spanner::Mutations{spanner::InsertMutationBuilder(
"Singers", {"SingerId", "FirstName", "LastName"})
.EmplaceRow(1, "Marc", "Richards")
.EmplaceRow(2, "Catalina", "Smith")
.EmplaceRow(3, "Alice", "Trentor")
.EmplaceRow(4, "Lea", "Martin")
.EmplaceRow(5, "David", "Lomond")
.Build(),
spanner::InsertMutationBuilder(
"Albums", {"SingerId", "AlbumId", "AlbumTitle"})
.EmplaceRow(1, 1, "Total Junk")
.EmplaceRow(1, 2, "Go, Go, Go")
.EmplaceRow(2, 1, "Green")
.EmplaceRow(2, 2, "Forever Hold Your Peace")
.EmplaceRow(2, 3, "Terrified")
.Build()});
if (!commit) throw std::move(commit).status();
std::cout << "insert-mutation-builder was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
UpdateMutationBuilderAlias Of: spanner_internal::WriteMutationBuilder< spanner_internal::UpdateOp >
A helper class to construct "update" mutations.
Examplevoid UpdateMutationBuilder(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::UpdateMutationBuilder("Albums",
{"SingerId", "AlbumId", "MarketingBudget"})
.EmplaceRow(1, 1, 100000)
.EmplaceRow(2, 2, 500000)
.Build()});
if (!commit) throw std::move(commit).status();
std::cout << "update-mutation-builder was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
InsertOrUpdateMutationBuilderAlias Of: spanner_internal::WriteMutationBuilder< spanner_internal::InsertOrUpdateOp >
A helper class to construct "insert_or_update" mutations.
Examplevoid InsertOrUpdateMutationBuilder(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::InsertOrUpdateMutationBuilder(
"Albums", {"SingerId", "AlbumId", "AlbumTitle", "MarketingBudget"})
.EmplaceRow(1, 1, "Total Junk", 100000)
.EmplaceRow(1, 2, "Go, Go, Go", 200000)
.EmplaceRow(2, 1, "Green", 300000)
.EmplaceRow(2, 2, "Forever Hold Your Peace", 400000)
.EmplaceRow(2, 3, "Terrified", 500000)
.Build()});
if (!commit) throw std::move(commit).status();
std::cout << "insert-or-update-mutation-builder was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
ReplaceMutationBuilderAlias Of: spanner_internal::WriteMutationBuilder< spanner_internal::ReplaceOp >
A helper class to construct "replace" mutations.
Examplevoid ReplaceMutationBuilder(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(spanner::Mutations{
spanner::ReplaceMutationBuilder(
"Albums", {"SingerId", "AlbumId", "AlbumTitle", "MarketingBudget"})
.EmplaceRow(1, 1, "Total Junk", 500000)
.EmplaceRow(1, 2, "Go, Go, Go", 400000)
.EmplaceRow(2, 1, "Green", 300000)
.Build()});
if (!commit) throw std::move(commit).status();
std::cout << "replace-mutation-builder was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
DeleteMutationBuilderAlias Of: spanner_internal::DeleteMutationBuilder
A helper class to construct "delete" mutations.
Examplevoid DeleteMutationBuilder(google::cloud::spanner::Client client) {
namespace spanner = ::google::cloud::spanner;
auto commit = client.Commit(
spanner::Mutations{spanner::DeleteMutationBuilder(
"Albums", spanner::KeySet()
.AddKey(spanner::MakeKey(1, 1))
.AddKey(spanner::MakeKey(1, 2)))
.Build()});
if (!commit) throw std::move(commit).status();
std::cout << "delete-mutation-builder was successful\n";
}
See Also
The Mutation class documentation for an overview of the Cloud Spanner mutation API
See Alsohttps://cloud.google.com/spanner/docs/modify-mutation-api for more information about the Cloud Spanner mutation API.
SpannerPolicyOptionListAlias Of: OptionList< SpannerRetryPolicyOption, SpannerBackoffPolicyOption, SpannerPollingPolicyOption >
List of all "policy" options.
SessionPoolOptionListAlias Of: OptionList< RouteToLeaderOption, SessionCreatorRoleOption, SessionPoolMinSessionsOption, SessionPoolMaxSessionsPerChannelOption, SessionPoolMaxIdleSessionsOption, SessionPoolActionOnExhaustionOption, SessionPoolKeepAliveIntervalOption, SessionPoolLabelsOption, EnableMultiplexedSessionOption >
List of all SessionPool options.
Pass to spanner::MakeConnection()
.
Alias Of: OptionList< RequestPriorityOption, RequestTagOption >
List of Request options for client::ExecuteBatchDml()
.
Alias Of: ::google::cloud::PollingPolicy
Alias Of: ::google::cloud::GenericPollingPolicy< Retry, Backoff >
Alias Of: ::google::spanner::v1::QueryPlan
Contains a hierarchical representation of the operations the database server performs in order to execute a particular SQL statement.
Example: // For a SQL query to be partitionable, it has to satisfy some conditions.
// For example, if it has a Distributed Union operator, the Distributed
// Union operator must be the first operator in the `ExecutionPlan`.
// For detailed definition, please refer to
// https://cloud.google.com/spanner/docs/reads#read_data_in_parallel
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(
spanner::MakeReadOnlyTransaction(),
spanner::SqlStatement(
"SELECT SingerId, FirstName, LastName FROM Singers"));
if (!plan) throw std::move(plan).status();
if (!is_partitionable(*plan)) {
throw std::runtime_error("Query is not partitionable");
}
sys_time
Alias Of: std::chrono::time_point< std::chrono::system_clock, Duration >
Convenience alias.
std::chrono::sys_time
since C++20.
Alias Of: ::google::cloud::TracingOptions
The configuration parameters for RPC/protobuf tracing.
The default options are:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4