Google Cloud Spanner C++ Client  1.40.2
A C++ Client Library for Google Cloud Spanner
client.h
Go to the documentation of this file.
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_CLIENT_H
16 #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_CLIENT_H
17 
18 #include "google/cloud/spanner/batch_dml_result.h"
19 #include "google/cloud/spanner/client_options.h"
20 #include "google/cloud/spanner/commit_options.h"
21 #include "google/cloud/spanner/commit_result.h"
22 #include "google/cloud/spanner/connection.h"
23 #include "google/cloud/spanner/connection_options.h"
24 #include "google/cloud/spanner/database.h"
25 #include "google/cloud/spanner/internal/defaults.h"
26 #include "google/cloud/spanner/keys.h"
27 #include "google/cloud/spanner/mutations.h"
28 #include "google/cloud/spanner/partition_options.h"
29 #include "google/cloud/spanner/query_options.h"
30 #include "google/cloud/spanner/query_partition.h"
31 #include "google/cloud/spanner/read_options.h"
32 #include "google/cloud/spanner/read_partition.h"
33 #include "google/cloud/spanner/results.h"
34 #include "google/cloud/spanner/retry_policy.h"
35 #include "google/cloud/spanner/session_pool_options.h"
36 #include "google/cloud/spanner/sql_statement.h"
37 #include "google/cloud/spanner/transaction.h"
38 #include "google/cloud/spanner/version.h"
39 #include "google/cloud/backoff_policy.h"
40 #include "google/cloud/internal/non_constructible.h"
41 #include "google/cloud/options.h"
42 #include "google/cloud/status.h"
43 #include "google/cloud/status_or.h"
44 #include <google/spanner/v1/spanner.pb.h>
45 #include <grpcpp/grpcpp.h>
46 #include <functional>
47 #include <initializer_list>
48 #include <memory>
49 #include <string>
50 #include <vector>
51 
52 namespace google {
53 namespace cloud {
54 namespace spanner {
56 
57 // clang-format off
58 /**
59  * Performs database client operations on Spanner.
60  *
61  * Applications use this class to perform operations on
62  * [Spanner Databases][spanner-doc-link].
63  *
64  * @par Performance
65  *
66  * `Client` objects are relatively cheap to create, copy, and move. However,
67  * each `Client` object must be created with a `std::shared_ptr<Connection>`,
68  * which itself is relatively expensive to create. Therefore, connection
69  * instances should be shared when possible. See the `MakeConnection()` method
70  * and the `Connection` interface for more details.
71  *
72  * @par Thread Safety
73  *
74  * Instances of this class created via copy-construction or copy-assignment
75  * share the underlying pool of connections. Access to these copies via multiple
76  * threads is guaranteed to work. Two threads operating on the same instance of
77  * this class is not guaranteed to work.
78  *
79  * @par Error Handling
80  *
81  * This class uses `StatusOr<T>` to report errors. When an operation fails to
82  * perform its work the returned `StatusOr<T>` contains the error details. If
83  * the `ok()` member function in the `StatusOr<T>` returns `true` then it
84  * contains the expected result. Please consult the
85  * [`StatusOr<T>` documentation](#google::cloud::v0::StatusOr) for more details.
86  *
87  * @code
88  * namespace spanner = ::google::cloud::spanner;
89  *
90  * auto db = spanner::Database("my_project", "my_instance", "my_db_id"));
91  * auto conn = spanner::MakeConnection(db);
92  * auto client = spanner::Client(conn);
93  *
94  * auto rows = client.Read(...);
95  * using RowType = std::tuple<std::int64_t, std::string>;
96  * for (auto const& row : spanner::StreamOf<RowType>(rows)) {
97  * // ...
98  * }
99  * @endcode
100  *
101  * @par Query Options
102  *
103  * Most operations that take an `SqlStatement` may also be modified with
104  * query `Options`. These options can be set at various levels, with more
105  * specific levels taking precedence over broader ones. For example,
106  * `Options` that are passed directly to `Client::ExecuteQuery()` will
107  * take precedence over the `Client`-level defaults (if any), which will
108  * themselves take precedence over any environment variables. The following
109  * table shows the environment variables that may optionally be set and the
110  * query `Options` setting that they affect.
111  *
112  * Environment Variable | Options setting
113  * -------------------------------------- | --------------------
114  * `SPANNER_OPTIMIZER_VERSION` | `QueryOptimizerVersionOption`
115  * `SPANNER_OPTIMIZER_STATISTICS_PACKAGE` | `QueryOptimizerStatisticsPackageOption`
116  *
117  * @see https://cloud.google.com/spanner/docs/reference/rest/v1/QueryOptions
118  * @see http://cloud/spanner/docs/query-optimizer/manage-query-optimizer
119  *
120  * [spanner-doc-link]:
121  * https://cloud.google.com/spanner/docs/api-libraries-overview
122  */
123 // clang-format on
124 class Client {
125  public:
126  /**
127  * Constructs a `Client` object using the specified @p conn and @p opts.
128  *
129  * See `MakeConnection()` for how to create a connection to Spanner. To help
130  * with unit testing, callers may create fake/mock `Connection` objects that
131  * are injected into the `Client`.
132  */
133  explicit Client(std::shared_ptr<Connection> conn, Options opts = {})
134  : conn_(std::move(conn)),
135  opts_(internal::MergeOptions(
136  std::move(opts),
137  spanner_internal::DefaultOptions(conn_->options()))) {}
138 
139  /// @name Backwards compatibility for `ClientOptions`.
140  ///@{
141  explicit Client(std::shared_ptr<Connection> conn, ClientOptions const& opts)
142  : Client(std::move(conn), Options(opts)) {}
143  explicit Client(std::shared_ptr<Connection> conn,
144  std::initializer_list<internal::NonConstructible>)
145  : Client(std::move(conn)) {}
146  ///@}
147 
148  /// No default construction.
149  Client() = delete;
150 
151  //@{
152  // @name Copy and move support
153  Client(Client const&) = default;
154  Client& operator=(Client const&) = default;
155  Client(Client&&) = default;
156  Client& operator=(Client&&) = default;
157  //@}
158 
159  //@{
160  // @name Equality
161  friend bool operator==(Client const& a, Client const& b) {
162  return a.conn_ == b.conn_;
163  }
164  friend bool operator!=(Client const& a, Client const& b) { return !(a == b); }
165  //@}
166 
167  //@{
168  /**
169  * Reads rows from the database using key lookups and scans, as a simple
170  * key/value style alternative to `ExecuteQuery()`.
171  *
172  * Callers can optionally supply a `Transaction` or
173  * `Transaction::SingleUseOptions` used to create a single-use transaction -
174  * or neither, in which case a single-use transaction with default options
175  * is used.
176  *
177  * @param table The name of the table in the database to be read.
178  * @param keys Identifies the rows to be yielded. If `read_options.index_name`
179  * is set, names keys in that index; otherwise names keys in the primary
180  * index of `table`. It is not an error for `keys` to name rows that do
181  * not exist in the database; `Read` yields nothing for nonexistent rows.
182  * @param columns The columns of `table` to be returned for each row matching
183  * this request.
184  * @param opts `Options` used for this request.
185  *
186  * @par Example
187  * @snippet samples.cc read-data
188  *
189  * @note No individual row in the `ReadResult` can exceed 100 MiB, and no
190  * column value can exceed 10 MiB.
191  */
192  RowStream Read(std::string table, KeySet keys,
193  std::vector<std::string> columns, Options opts = {});
194 
195  /**
196  * @copydoc Read
197  *
198  * @param transaction_options Execute this read in a single-use transaction
199  * with these options.
200  */
202  std::string table, KeySet keys,
203  std::vector<std::string> columns, Options opts = {});
204 
205  /**
206  * @copydoc Read
207  *
208  * @param transaction Execute this read as part of an existing transaction.
209  */
210  RowStream Read(Transaction transaction, std::string table, KeySet keys,
211  std::vector<std::string> columns, Options opts = {});
212  //@}
213 
214  /// @name Backwards compatibility for `ReadOptions`.
215  ///@{
216  RowStream Read(std::string table, KeySet keys,
217  std::vector<std::string> columns,
218  ReadOptions const& read_options) {
219  return Read(std::move(table), std::move(keys), std::move(columns),
220  ToOptions(read_options));
221  }
222  RowStream Read(std::string table, KeySet keys,
223  std::vector<std::string> columns,
224  std::initializer_list<internal::NonConstructible>) {
225  return Read(std::move(table), std::move(keys), std::move(columns));
226  }
228  std::string table, KeySet keys,
229  std::vector<std::string> columns,
230  ReadOptions const& read_options) {
231  return Read(std::move(transaction_options), std::move(table),
232  std::move(keys), std::move(columns), ToOptions(read_options));
233  }
235  std::string table, KeySet keys,
236  std::vector<std::string> columns,
237  std::initializer_list<internal::NonConstructible>) {
238  return Read(std::move(transaction_options), std::move(table),
239  std::move(keys), std::move(columns));
240  }
241  RowStream Read(Transaction transaction, std::string table, KeySet keys,
242  std::vector<std::string> columns,
243  ReadOptions const& read_options) {
244  return Read(std::move(transaction), std::move(table), std::move(keys),
245  std::move(columns), ToOptions(read_options));
246  }
247  RowStream Read(Transaction transaction, std::string table, KeySet keys,
248  std::vector<std::string> columns,
249  std::initializer_list<internal::NonConstructible>) {
250  return Read(std::move(transaction), std::move(table), std::move(keys),
251  std::move(columns));
252  }
253  ///@}
254 
255  /**
256  * Reads rows from a subset of rows in a database. Requires a prior call
257  * to `PartitionRead` to obtain the partition information; see the
258  * documentation of that method for full details.
259  *
260  * @param partition A `ReadPartition`, obtained by calling `PartitionRead`.
261  * @param opts `Options` used for this request.
262  *
263  * @note No individual row in the `ReadResult` can exceed 100 MiB, and no
264  * column value can exceed 10 MiB.
265  *
266  * @par Example
267  * @snippet samples.cc read-read-partition
268  */
269  RowStream Read(ReadPartition const& partition, Options opts = {});
270 
271  /**
272  * Creates a set of partitions that can be used to execute a read
273  * operation in parallel. Each of the returned partitions can be passed
274  * to `Read` to specify a subset of the read result to read.
275  *
276  * There are no ordering guarantees on rows returned among the returned
277  * partition, or even within each individual `Read` call issued with a given
278  * partition.
279  *
280  * Partitions become invalid when the session used to create them is deleted,
281  * is idle for too long, begins a new transaction, or becomes too old. When
282  * any of these happen, it is not possible to resume the read, and the whole
283  * operation must be restarted from the beginning.
284  *
285  * @param transaction The transaction to execute the operation in.
286  * **Must** be a read-only snapshot transaction.
287  * @param table The name of the table in the database to be read.
288  * @param keys Identifies the rows to be yielded. If `read_options.index_name`
289  * is set, names keys in that index; otherwise names keys in the primary
290  * index of `table`. It is not an error for `keys` to name rows that do
291  * not exist in the database; `Read` yields nothing for nonexistent rows.
292  * @param columns The columns of `table` to be returned for each row matching
293  * this request.
294  * @param opts `Options` used for this request.
295  *
296  * @return A `StatusOr` containing a vector of `ReadPartition` or error
297  * status on failure.
298  *
299  * @par Example
300  * @snippet samples.cc partition-read
301  */
302  StatusOr<std::vector<ReadPartition>> PartitionRead(
303  Transaction transaction, std::string table, KeySet keys,
304  std::vector<std::string> columns, Options opts = {});
305 
306  /// @name Backwards compatibility for `ReadOptions` and `PartitionOptions`.
307  ///@{
308  StatusOr<std::vector<ReadPartition>> PartitionRead(
309  Transaction transaction, std::string table, KeySet keys,
310  std::vector<std::string> columns, ReadOptions const& read_options,
311  PartitionOptions const& partition_options) {
312  return PartitionRead(std::move(transaction), std::move(table),
313  std::move(keys), std::move(columns),
314  internal::MergeOptions(ToOptions(read_options),
315  ToOptions(partition_options)));
316  }
317  StatusOr<std::vector<ReadPartition>> PartitionRead(
318  Transaction transaction, std::string table, KeySet keys,
319  std::vector<std::string> columns,
320  std::initializer_list<internal::NonConstructible>) {
321  return PartitionRead(std::move(transaction), std::move(table),
322  std::move(keys), std::move(columns));
323  }
324  ///@}
325 
326  //@{
327  /**
328  * Executes a SQL query.
329  *
330  * Operations inside read-write transactions might return `ABORTED`. If this
331  * occurs, the application should restart the transaction from the beginning.
332  *
333  * Callers can optionally supply a `Transaction` or
334  * `Transaction::SingleUseOptions` used to create a single-use transaction -
335  * or neither, in which case a single-use transaction with default options
336  * is used.
337  *
338  * `SELECT * ...` queries are supported, but there's no guarantee about the
339  * order, nor number, of returned columns. Therefore, the caller must look up
340  * the wanted values in each row by column name. When the desired column
341  * names are known in advance, it is better to list them explicitly in the
342  * query's SELECT statement, so that unnecessary values are not
343  * returned/ignored, and the column order is known. This enables more
344  * efficient and simpler code.
345  *
346  * @par Example with explicitly selected columns.
347  * @snippet samples.cc spanner-query-data
348  *
349  * @par Example using SELECT *
350  * @snippet samples.cc spanner-query-data-select-star
351  *
352  * @param statement The SQL statement to execute.
353  * @param opts (optional) The `Options` to use for this call. If given,
354  * these will take precedence over the options set at the client and
355  * environment levels.
356  *
357  * @note No individual row in the `RowStream` can exceed 100 MiB, and no
358  * column value can exceed 10 MiB.
359  */
361 
362  /**
363  * @copydoc ExecuteQuery(SqlStatement, Options)
364  *
365  * @param transaction_options Execute this query in a single-use transaction
366  * with these options.
367  */
369  SqlStatement statement, Options opts = {});
370 
371  /**
372  * @copydoc ExecuteQuery(SqlStatement, Options)
373  *
374  * @param transaction Execute this query as part of an existing transaction.
375  */
377  Options opts = {});
378 
379  /**
380  * Executes a SQL query on a subset of rows in a database. Requires a prior
381  * call to `PartitionQuery` to obtain the partition information; see the
382  * documentation of that method for full details.
383  *
384  * @param partition A `QueryPartition`, obtained by calling `PartitionQuery`.
385  * @param opts (optional) The `Options` to use for this call. If given,
386  * these will take precedence over the options set at the client and
387  * environment levels.
388  *
389  * @note No individual row in the `RowStream` can exceed 100 MiB, and no
390  * column value can exceed 10 MiB.
391  *
392  * @par Example
393  * @snippet samples.cc execute-sql-query-partition
394  */
395  RowStream ExecuteQuery(QueryPartition const& partition, Options opts = {});
396  //@}
397 
398  /// @name Backwards compatibility for `QueryOptions`.
399  ///@{
401  return ExecuteQuery(std::move(statement), Options(opts));
402  }
404  std::initializer_list<internal::NonConstructible>) {
405  return ExecuteQuery(std::move(statement));
406  }
408  SqlStatement statement, QueryOptions const& opts) {
409  return ExecuteQuery(std::move(transaction_options), std::move(statement),
410  Options(opts));
411  }
413  SqlStatement statement,
414  std::initializer_list<internal::NonConstructible>) {
415  return ExecuteQuery(std::move(transaction_options), std::move(statement));
416  }
418  QueryOptions const& opts) {
419  return ExecuteQuery(std::move(transaction), std::move(statement),
420  Options(opts));
421  }
423  std::initializer_list<internal::NonConstructible>) {
424  return ExecuteQuery(std::move(transaction), std::move(statement));
425  }
427  QueryOptions const& opts) {
428  return ExecuteQuery(partition, Options(opts));
429  }
431  std::initializer_list<internal::NonConstructible>) {
432  return ExecuteQuery(partition);
433  }
434  ///@}
435 
436  //@{
437  /**
438  * Profiles a SQL query.
439  *
440  * Profiling executes the query, provides the resulting rows, `ExecutionPlan`,
441  * and execution statistics.
442  *
443  * Operations inside read-write transactions might return `kAborted`. If this
444  * occurs, the application should restart the transaction from the beginning.
445  *
446  * Callers can optionally supply a `Transaction` or
447  * `Transaction::SingleUseOptions` used to create a single-use transaction -
448  * or neither, in which case a single-use transaction with default options
449  * is used.
450  *
451  * @note Callers must consume all rows from the result before execution
452  * statistics and `ExecutionPlan` are available.
453  *
454  * @param statement The SQL statement to execute.
455  * @param opts (optional) The `Options` to use for this call. If given,
456  * these will take precedence over the options set at the client and
457  * environment levels.
458  *
459  * @note No individual row in the `ProfileQueryResult` can exceed 100 MiB, and
460  * no column value can exceed 10 MiB.
461  *
462  * @par Example
463  * @snippet samples.cc profile-query
464  */
466 
467  /**
468  * @copydoc ProfileQuery(SqlStatement, Options)
469  *
470  * @param transaction_options Execute this query in a single-use transaction
471  * with these options.
472  */
474  Transaction::SingleUseOptions transaction_options, SqlStatement statement,
475  Options opts = {});
476 
477  /**
478  * @copydoc ProfileQuery(SqlStatement, Options)
479  *
480  * @param transaction Execute this query as part of an existing transaction.
481  */
483  SqlStatement statement, Options opts = {});
484  //@}
485 
486  /// @name Backwards compatibility for `QueryOptions`.
487  ///@{
489  QueryOptions const& opts) {
490  return ProfileQuery(std::move(statement), Options(opts));
491  }
493  SqlStatement statement,
494  std::initializer_list<internal::NonConstructible>) {
495  return ProfileQuery(std::move(statement));
496  }
498  Transaction::SingleUseOptions transaction_options, SqlStatement statement,
499  QueryOptions const& opts) {
500  return ProfileQuery(std::move(transaction_options), std::move(statement),
501  Options(opts));
502  }
504  Transaction::SingleUseOptions transaction_options, SqlStatement statement,
505  std::initializer_list<internal::NonConstructible>) {
506  return ProfileQuery(std::move(transaction_options), std::move(statement));
507  }
509  SqlStatement statement,
510  QueryOptions const& opts) {
511  return ProfileQuery(std::move(transaction), std::move(statement),
512  Options(opts));
513  }
515  Transaction transaction, SqlStatement statement,
516  std::initializer_list<internal::NonConstructible>) {
517  return ProfileQuery(std::move(transaction), std::move(statement));
518  }
519  ///@}
520 
521  /**
522  * Creates a set of partitions that can be used to execute a query
523  * operation in parallel. Each of the returned partitions can be passed
524  * to `ExecuteQuery` to specify a subset of the query result to read.
525  *
526  * Partitions become invalid when the session used to create them is deleted,
527  * is idle for too long, begins a new transaction, or becomes too old. When
528  * any of these happen, it is not possible to resume the query, and the whole
529  * operation must be restarted from the beginning.
530  *
531  * @param transaction The transaction to execute the operation in.
532  * **Must** be a read-only snapshot transaction.
533  * @param statement The SQL statement to execute.
534  * @param opts `Options` used for this request.
535  *
536  * @return A `StatusOr` containing a vector of `QueryPartition`s or error
537  * status on failure.
538  *
539  * @par Example
540  * @snippet samples.cc partition-query
541  */
542  StatusOr<std::vector<QueryPartition>> PartitionQuery(
543  Transaction transaction, SqlStatement statement,
544  Options opts = Options{});
545 
546  /// @name Backwards compatibility for `PartitionOptions`.
547  ///@{
548  StatusOr<std::vector<QueryPartition>> PartitionQuery(
549  Transaction transaction, SqlStatement statement,
550  PartitionOptions const& partition_options) {
551  return PartitionQuery(std::move(transaction), std::move(statement),
552  ToOptions(partition_options));
553  }
554  StatusOr<std::vector<QueryPartition>> PartitionQuery(
555  Transaction transaction, SqlStatement statement,
556  std::initializer_list<internal::NonConstructible>) {
557  return PartitionQuery(std::move(transaction), std::move(statement));
558  }
559  ///@}
560 
561  /**
562  * Executes a SQL DML statement.
563  *
564  * Operations inside read-write transactions might return `ABORTED`. If this
565  * occurs, the application should restart the transaction from the beginning.
566  *
567  * @note Single-use transactions are not supported with DML statements.
568  *
569  * @param transaction Execute this query as part of an existing transaction.
570  * @param statement The SQL statement to execute.
571  * @param opts (optional) The `Options` to use for this call. If given,
572  * these will take precedence over the options set at the client and
573  * environment levels.
574  *
575  * @par Example
576  * @snippet samples.cc execute-dml
577  */
578  StatusOr<DmlResult> ExecuteDml(Transaction transaction,
579  SqlStatement statement, Options opts = {});
580 
581  /// @name Backwards compatibility for `QueryOptions`.
582  ///@{
583  StatusOr<DmlResult> ExecuteDml(Transaction transaction,
584  SqlStatement statement,
585  QueryOptions const& opts) {
586  return ExecuteDml(std::move(transaction), std::move(statement),
587  Options(opts));
588  }
590  Transaction transaction, SqlStatement statement,
591  std::initializer_list<internal::NonConstructible>) {
592  return ExecuteDml(std::move(transaction), std::move(statement));
593  }
594  ///@}
595 
596  /**
597  * Profiles a SQL DML statement.
598  *
599  * Profiling executes the DML statement, provides the modified row count,
600  * `ExecutionPlan`, and execution statistics.
601  *
602  * Operations inside read-write transactions might return `ABORTED`. If this
603  * occurs, the application should restart the transaction from the beginning.
604  *
605  * @note Single-use transactions are not supported with DML statements.
606  *
607  * @param transaction Execute this query as part of an existing transaction.
608  * @param statement The SQL statement to execute.
609  * @param opts (optional) The `Options` to use for this call. If given,
610  * these will take precedence over the options set at the client and
611  * environment levels.
612  *
613  * @par Example:
614  * @snippet samples.cc profile-dml
615  */
616  StatusOr<ProfileDmlResult> ProfileDml(Transaction transaction,
617  SqlStatement statement,
618  Options opts = {});
619 
620  /// @name Backwards compatibility for `QueryOptions`.
621  ///@{
622  StatusOr<ProfileDmlResult> ProfileDml(Transaction transaction,
623  SqlStatement statement,
624  QueryOptions const& opts) {
625  return ProfileDml(std::move(transaction), std::move(statement),
626  Options(opts));
627  }
629  Transaction transaction, SqlStatement statement,
630  std::initializer_list<internal::NonConstructible>) {
631  return ProfileDml(std::move(transaction), std::move(statement));
632  }
633  ///@}
634 
635  /**
636  * Analyzes the execution plan of a SQL statement.
637  *
638  * Analyzing provides the `ExecutionPlan`, but does not execute the SQL
639  * statement.
640  *
641  * Operations inside read-write transactions might return `ABORTED`. If this
642  * occurs, the application should restart the transaction from the beginning.
643  *
644  * @note Single-use transactions are not supported with DML statements.
645  *
646  * @param transaction Execute this query as part of an existing transaction.
647  * @param statement The SQL statement to execute.
648  * @param opts (optional) The `Options` to use for this call. If given,
649  * these will take precedence over the options set at the client and
650  * environment levels.
651  *
652  * @par Example:
653  * @snippet samples.cc analyze-query
654  */
655  StatusOr<ExecutionPlan> AnalyzeSql(Transaction transaction,
656  SqlStatement statement, Options opts = {});
657 
658  /// @name Backwards compatibility for `QueryOptions`.
659  ///@{
660  StatusOr<ExecutionPlan> AnalyzeSql(Transaction transaction,
661  SqlStatement statement,
662  QueryOptions const& opts) {
663  return AnalyzeSql(std::move(transaction), std::move(statement),
664  Options(opts));
665  }
666  StatusOr<ExecutionPlan> AnalyzeSql(
667  Transaction transaction, SqlStatement statement,
668  std::initializer_list<internal::NonConstructible>) {
669  return AnalyzeSql(std::move(transaction), std::move(statement));
670  }
671  ///@}
672 
673  /**
674  * Executes a batch of SQL DML statements. This method allows many statements
675  * to be run with lower latency than submitting them sequentially with
676  * `ExecuteDml`.
677  *
678  * Statements are executed in order, sequentially. Execution will stop at the
679  * first failed statement; the remaining statements will not run.
680  *
681  * As with all read-write transactions, the results will not be visible
682  * outside of the transaction until it is committed. For that reason, it is
683  * advisable to run this method from a `Commit` mutator.
684  *
685  * @warning A returned status of OK from this function does not imply that
686  * all the statements were executed successfully. For that, you need to
687  * inspect the `BatchDmlResult::status` field.
688  *
689  * @param transaction The read-write transaction to execute the operation in.
690  * @param statements The list of statements to execute in this batch.
691  * Statements are executed serially, such that the effects of statement i
692  * are visible to statement i+1. Each statement must be a DML statement.
693  * Execution will stop at the first failed statement; the remaining
694  * statements will not run. Must not be empty.
695  * @param opts (optional) The options to use for this call. Expected options
696  * are any of the types in the following option lists.
697  * - `google::cloud::RequestOptionList`
698  *
699  * @par Example
700  * @snippet samples.cc execute-batch-dml
701  */
703  std::vector<SqlStatement> statements,
704  Options opts = {});
705 
706  /**
707  * Commits a read-write transaction.
708  *
709  * Calls the @p mutator in the context of a new read-write transaction.
710  * The @p mutator can execute read/write operations using the transaction,
711  * and returns any additional `Mutations` to commit.
712  *
713  * If the @p mutator succeeds and the transaction commits, then `Commit()`
714  * returns the `CommitResult`.
715  *
716  * If the @p mutator returns a non-rerunnable status (according to the
717  * @p rerun_policy), the transaction is rolled back and that status is
718  * returned. Similarly, if the transaction fails to commit with a non-
719  * rerunnable status, that status is returned.
720  *
721  * Otherwise the whole process repeats (subject to @p rerun_policy and
722  * @p backoff_policy), by building a new transaction and re-running the
723  * @p mutator. The lock priority of the operation increases after each
724  * rerun, meaning that the next attempt has a slightly better chance of
725  * success.
726  *
727  * Note that the @p mutator should only return a rerunnable status when
728  * the transaction is no longer usable (e.g., it was aborted). Otherwise
729  * the transaction will be leaked.
730  *
731  * @param mutator the function called to create mutations
732  * @param rerun_policy controls for how long (or how many times) the mutator
733  * will be rerun after the transaction aborts.
734  * @param backoff_policy controls how long `Commit` waits between reruns.
735  * @param opts (optional) The options to use for this call. Expected options
736  * include any of the following types:
737  * - `google::cloud::spanner::CommitReturnStatsOption`
738  * - `google::cloud::spanner::RequestPriorityOption`
739  * - `google::cloud::spanner::TransactionTagOption`
740  *
741  * @throw Rethrows any exception thrown by @p `mutator` (after rolling back
742  * the transaction). However, a `RuntimeStatusError` exception is
743  * instead consumed and converted into a `mutator` return value of the
744  * enclosed `Status`.
745  *
746  * @par Example
747  * @snippet samples.cc commit-with-policies
748  */
749  StatusOr<CommitResult> Commit(
750  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
751  std::unique_ptr<TransactionRerunPolicy> rerun_policy,
752  std::unique_ptr<BackoffPolicy> backoff_policy, Options opts = {});
753 
754  /// @name Backwards compatibility for `CommitOptions`.
755  ///@{
756  StatusOr<CommitResult> Commit(
757  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
758  std::unique_ptr<TransactionRerunPolicy> rerun_policy,
759  std::unique_ptr<BackoffPolicy> backoff_policy,
760  CommitOptions const& commit_options) {
761  return Commit(mutator, std::move(rerun_policy), std::move(backoff_policy),
762  Options(commit_options));
763  }
764  StatusOr<CommitResult> Commit(
765  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
766  std::unique_ptr<TransactionRerunPolicy> rerun_policy,
767  std::unique_ptr<BackoffPolicy> backoff_policy,
768  std::initializer_list<internal::NonConstructible>) {
769  return Commit(mutator, std::move(rerun_policy), std::move(backoff_policy));
770  }
771  ///@}
772 
773  /**
774  * Commits a read-write transaction.
775  *
776  * Same as above, but uses the default rerun and backoff policies.
777  *
778  * @param mutator the function called to create mutations
779  * @param opts (optional) The options to use for this call.
780  *
781  * @par Example
782  * @snippet samples.cc commit-with-mutator
783  */
784  StatusOr<CommitResult> Commit(
785  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
786  Options opts = {});
787 
788  /// @name Backwards compatibility for `CommitOptions`.
789  ///@{
790  StatusOr<CommitResult> Commit(
791  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
792  CommitOptions const& commit_options) {
793  return Commit(mutator, Options(commit_options));
794  }
795  StatusOr<CommitResult> Commit(
796  std::function<StatusOr<Mutations>(Transaction)> const& mutator,
797  std::initializer_list<internal::NonConstructible>) {
798  return Commit(mutator);
799  }
800  ///@}
801 
802  /**
803  * Commits the @p mutations, using the @p options, atomically in order.
804  *
805  * This function uses the re-run loop described above with the default
806  * policies.
807  *
808  * @par Example
809  * @snippet samples.cc commit-with-mutations
810  */
811  StatusOr<CommitResult> Commit(Mutations mutations, Options opts = {});
812 
813  /// @name Backwards compatibility for `CommitOptions`.
814  ///@{
815  StatusOr<CommitResult> Commit(Mutations mutations,
816  CommitOptions const& commit_options) {
817  return Commit(std::move(mutations), Options(commit_options));
818  }
819  StatusOr<CommitResult> Commit(
820  Mutations mutations, std::initializer_list<internal::NonConstructible>) {
821  return Commit(std::move(mutations));
822  }
823  ///@}
824 
825  /**
826  * Commits a read-write transaction.
827  *
828  * The commit might return a `kAborted` error. This can occur at any time.
829  * Commonly the cause is conflicts with concurrent transactions, however
830  * it can also happen for a variety of other reasons. If `Commit` returns
831  * `kAborted`, the caller may try to reapply the mutations within a new
832  * read-write transaction (which should share lock priority with the aborted
833  * transaction so that the new attempt has a slightly better chance of
834  * success).
835  *
836  * @note Prefer the previous `Commit` overloads if you want to simply reapply
837  * mutations after a `kAborted` error.
838  *
839  * @warning It is an error to call `Commit` with a read-only transaction.
840  *
841  * @param transaction The transaction to commit.
842  * @param mutations The mutations to be executed when this transaction
843  * commits. All mutations are applied atomically, in the order they appear
844  * in this list.
845  * @param opts (optional) The options to use for this call.
846  *
847  * @return A `StatusOr` containing the result of the commit or error status
848  * on failure.
849  */
850  StatusOr<CommitResult> Commit(Transaction transaction, Mutations mutations,
851  Options opts = {});
852 
853  /// @name Backwards compatibility for `CommitOptions`.
854  ///@{
855  StatusOr<CommitResult> Commit(Transaction transaction, Mutations mutations,
856  CommitOptions const& commit_options) {
857  return Commit(std::move(transaction), std::move(mutations),
858  Options(commit_options));
859  }
860  StatusOr<CommitResult> Commit(
861  Transaction transaction, Mutations mutations,
862  std::initializer_list<internal::NonConstructible>) {
863  return Commit(std::move(transaction), std::move(mutations));
864  }
865  ///@}
866 
867  /**
868  * Rolls back a read-write transaction, releasing any locks it holds.
869  *
870  * At any time before `Commit`, the client can call `Rollback` to abort the
871  * transaction. It is a good idea to call this for any read-write transaction
872  * that includes one or more `Read`, `ExecuteQuery`, or `ExecuteDml` requests
873  * and ultimately decides not to commit.
874  *
875  * @warning It is an error to call `Rollback` with a read-only transaction.
876  *
877  * @param transaction The transaction to roll back.
878  * @param opts (optional) The options to use for this call.
879  *
880  * @return The error status of the rollback.
881  */
882  Status Rollback(Transaction transaction, Options opts = {});
883 
884  /**
885  * Executes a Partitioned DML SQL query.
886  *
887  * @param statement the SQL statement to execute. Please see the
888  * [spanner documentation][dml-partitioned] for the restrictions on the
889  * SQL statements supported by this function.
890  * @param opts (optional) The `Options` to use for this call. If given,
891  * these will take precedence over the options set at the client and
892  * environment levels.
893  *
894  * @par Example
895  * @snippet samples.cc execute-sql-partitioned
896  *
897  * @see [Partitioned DML Transactions][txn-partitioned] for an overview of
898  * Partitioned DML transactions.
899  * @see [Partitioned DML][dml-partitioned] for a description of which SQL
900  * statements are supported in Partitioned DML transactions.
901  * [txn-partitioned]:
902  * https://cloud.google.com/spanner/docs/transactions#partitioned_dml_transactions
903  * [dml-partitioned]: https://cloud.google.com/spanner/docs/dml-partitioned
904  */
906  Options opts = {});
907 
908  /// @name Backwards compatibility for `QueryOptions`.
909  ///@{
911  SqlStatement statement, QueryOptions const& opts) {
912  return ExecutePartitionedDml(std::move(statement), Options(opts));
913  }
915  SqlStatement statement,
916  std::initializer_list<internal::NonConstructible>) {
917  return ExecutePartitionedDml(std::move(statement));
918  }
919  ///@}
920 
921  private:
922  std::shared_ptr<Connection> conn_;
923  Options opts_;
924 };
925 
926 /**
927  * Returns a Connection object that can be used for interacting with Spanner.
928  *
929  * The returned connection object should not be used directly; instead it
930  * should be given to a `Client` instance, and methods should be invoked on
931  * `Client`.
932  *
933  * The optional @p opts argument may be used to configure aspects of the
934  * returned `Connection`. Expected options are any of the types in the
935  * following option lists.
936  *
937  * - `google::cloud::CommonOptionList`
938  * - `google::cloud::GrpcOptionList`
939  * - `google::cloud::spanner::SpannerPolicyOptionList`
940  * - `google::cloud::spanner::SessionPoolOptionList`
941  *
942  * @note Unrecognized options will be ignored. To debug issues with options set
943  * `GOOGLE_CLOUD_CPP_ENABLE_CLOG=yes` in the environment and unexpected
944  * options will be logged.
945  *
946  * @see `Connection`
947  *
948  * @param db See `Database`.
949  * @param opts (optional) Configure the `Connection` created by this function.
950  */
951 std::shared_ptr<spanner::Connection> MakeConnection(spanner::Database const& db,
952  Options opts = {});
953 
954 /**
955  * Returns a Connection object that can be used for interacting with Spanner.
956  *
957  * The returned connection object should not be used directly, rather it should
958  * be given to a `Client` instance, and methods should be invoked on `Client`.
959  *
960  * @note Prefer using the `MakeConnection()` overload that accepts
961  * `google::cloud::Options`.
962  *
963  * @see `Connection`
964  *
965  * @param db See `Database`.
966  * @param connection_options configure the `Connection` created by this
967  * function.
968  * @param session_pool_options (optional) configure the `SessionPool` created
969  * by the `Connection`.
970  */
971 std::shared_ptr<Connection> MakeConnection(
972  Database const& db, ConnectionOptions const& connection_options,
973  SessionPoolOptions session_pool_options = SessionPoolOptions());
974 
975 /**
976  * @copydoc MakeConnection(Database const&, ConnectionOptions const&, SessionPoolOptions)
977  *
978  * @note Prefer using the `MakeConnection()` overload that accepts
979  * `google::cloud::Options`.
980  *
981  * @param retry_policy override the default `RetryPolicy`, controls how long
982  * the returned `Connection` object retries requests on transient
983  * failures.
984  * @param backoff_policy override the default `BackoffPolicy`, controls how
985  * long the `Connection` object waits before retrying a failed request.
986  *
987  * @par Example
988  * @snippet samples.cc custom-retry-policy
989  */
990 std::shared_ptr<Connection> MakeConnection(
991  Database const& db, ConnectionOptions const& connection_options,
992  SessionPoolOptions session_pool_options,
993  std::unique_ptr<RetryPolicy> retry_policy,
994  std::unique_ptr<BackoffPolicy> backoff_policy);
995 
997 } // namespace spanner
998 } // namespace cloud
999 } // namespace google
1000 
1001 #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_CLIENT_H