google_cloud_spanner/
lib.rs

1//! # google-cloud-spanner
2//!
3//! Google Cloud Platform spanner library.
4//!
5//! * [About Cloud Spanner](https://cloud.google.com/spanner/)
6//! * [Spanner API Documentation](https://cloud.google.com/spanner/docs)
7//! * [Rust client Documentation](#Documentation)
8//!
9//! ## Quickstart
10//! Create `Client` and call transaction API same as [Google Cloud Go](https://github.com/googleapis/google-cloud-go/tree/main/spanner).
11//!
12//! ```
13//! use google_cloud_spanner::client::Client;
14//! use google_cloud_spanner::mutation::insert_or_update;
15//! use google_cloud_spanner::statement::Statement;
16//! use google_cloud_spanner::value::CommitTimestamp;
17//! use google_cloud_spanner::client::Error;
18//! use google_cloud_spanner::client::ClientConfig;
19//! use google_cloud_gax::grpc::Status;
20//!
21//! async fn run(config: ClientConfig) -> Result<(), Error>{
22//!
23//!     const DATABASE: &str = "projects/local-project/instances/test-instance/databases/local-database";
24//!
25//!     // Create spanner client
26//!     let mut client = Client::new(DATABASE, config).await?;
27//!
28//!     // Insert or update
29//!     let mutation = insert_or_update("Guild", &["GuildId", "OwnerUserID", "UpdatedAt"], &[&"guildId", &"ownerId", &CommitTimestamp::new()]);
30//!     let commit_timestamp = client.apply(vec![mutation]).await?;
31//!
32//!     // Read with query
33//!     let mut stmt = Statement::new("SELECT GuildId FROM Guild WHERE OwnerUserID = @OwnerUserID");
34//!     stmt.add_param("OwnerUserID",&"ownerId");
35//!     let mut tx = client.single().await?;
36//!     let mut iter = tx.query(stmt).await?;
37//!     while let Some(row) = iter.next().await? {
38//!         let guild_id = row.column_by_name::<String>("GuildId");
39//!         // do something
40//!     }
41//!
42//!     // Remove all the sessions.
43//!     client.close().await;
44//!     Ok(())
45//! }
46//! ```
47//!
48//! ## Related project
49//! * [google-cloud-spanner-derive](https://github.com/yoshidan/google-cloud-rust/spanner-derive)
50//!
51//! ## <a name="Documentation"></a>Documentation
52//!
53//! ### Overview
54//! * [Creating a Client](#CreatingAClient)
55//! * [Authentication](#Authentication)
56//! * [Simple Reads and Writes](#SimpleReadsAndWrites)
57//! * [Keys](#Keys)
58//! * [KeyRanges](#KeyRanges)
59//! * [KeySets](#KeySets)
60//! * [Transactions](#Transactions)
61//! * [Single Reads](#SingleReads)
62//! * [Statements](#Statements)
63//! * [Rows](#Rows)
64//! * [Multiple Reads](#MultipleReads)
65//! * [Timestamps and Timestamp Bounds](#TimestampsAndTimestampBounds)
66//! * [Mutations](#Mutations)
67//! * [Writes](#Writes)
68//! * [Structs](#Structs)
69//! * [DML and Partitioned DML](#DMLAndPartitionedDML)
70//!
71//! Package spanner provides a client for reading and writing to Cloud Spanner databases.
72//! See the packages under admin for clients that operate on databases and instances.
73//!
74//! ### <a name="CreatingAClient"></a>Creating a Client
75//!
76//! To start working with this package, create a client that refers to the database of interest:
77//!
78//! ```
79//! use google_cloud_spanner::client::Client;
80//! use google_cloud_spanner::client::ClientConfig;
81//!
82//! async fn run() {
83//!     const DATABASE: &str = "projects/local-project/instances/test-instance/databases/local-database";
84//!
85//!     // google_cloud_default provides default ClientConfig with credentials source
86//!     let config = ClientConfig::default().with_auth().await.unwrap();
87//!     let mut client = Client::new(DATABASE, config).await.unwrap();
88//!
89//!     client.close().await;
90//! }
91//! ```
92//!
93//! Remember to close the client after use to free up the sessions in the session pool.
94//!
95//! To use an emulator with this library, you can set the SPANNER_EMULATOR_HOST environment variable to the address at which your emulator is running. This will send requests to that address instead of to Cloud Spanner.   You can then create and use a client as usual:
96//!
97//! ```
98//! use google_cloud_spanner::client::Client;
99//! use google_cloud_spanner::client::ClientConfig;
100//! use google_cloud_spanner::client::Error;
101//!
102//! #[tokio::main]
103//! async fn main() -> Result<(), Error>{
104//!     // Set SPANNER_EMULATOR_HOST environment variable.
105//!     std::env::set_var("SPANNER_EMULATOR_HOST", "localhost:9010");
106//!
107//!     // Create client as usual.
108//!     const DATABASE: &str = "projects/local-project/instances/test-instance/databases/local-database";
109//!     let client = Client::new(DATABASE, ClientConfig::default()).await?;
110//!     Ok(())
111//! }
112//! ```
113//!
114//! ### <a name="Authentication"></a>Authentication
115//!
116//! There are two ways to create a client that is authenticated against the google cloud.
117//!
118//! #### Automatically
119//!
120//! The function `with_auth()` will try and read the credentials from a file specified in the environment variable `GOOGLE_APPLICATION_CREDENTIALS`, `GOOGLE_APPLICATION_CREDENTIALS_JSON` or
121//! from a metadata server.
122//!
123//! This is also described in [google-cloud-auth](https://github.com/yoshidan/google-cloud-rust/blob/main/foundation/auth/README.md)
124//!
125//! ```
126//! use google_cloud_spanner::client::{ClientConfig, Client};
127//!
128//! async fn run() {
129//!     let config = ClientConfig::default().with_auth().await.unwrap();
130//!     let client = Client::new("projects/project/instances/instance/databases/database",config).await.unwrap();
131//! }
132//! ```
133//!
134//! ### Manually
135//!
136//! When you can't use the `gcloud` authentication but you have a different way to get your credentials (e.g a different environment variable)
137//! you can parse your own version of the 'credentials-file' and use it like that:
138//!
139//! ```
140//! use google_cloud_auth::credentials::CredentialsFile;
141//! // or google_cloud_spanner::client::google_cloud_auth::credentials::CredentialsFile
142//! use google_cloud_spanner::client::{ClientConfig, Client};
143//!
144//! async fn run(cred: CredentialsFile) {
145//!     let config = ClientConfig::default().with_credentials(cred).await.unwrap();
146//!     let client = Client::new("projects/project/instances/instance/databases/database",config).await.unwrap();
147//! }
148//! ```
149//!
150//! ### <a name="SimpleReadsAndWrites"></a>Simple Reads and Writes
151//! Two Client methods, Apply and Single, work well for simple reads and writes. As a quick introduction, here we write a new row to the database and read it back:
152//!
153//! ```
154//! use google_cloud_spanner::mutation::insert;
155//! use google_cloud_spanner::key::Key;
156//! use google_cloud_spanner::value::CommitTimestamp;
157//! use google_cloud_spanner::statement::ToKind;
158//! use google_cloud_spanner::client::{Client, Error};
159//! use google_cloud_spanner::mutation::insert_or_update;
160//!
161//! async fn run(client: Client) -> Result<(), Error>{
162//!     let mutation = insert_or_update("Guild", &["GuildId", "OwnerUserID", "UpdatedAt"], &[&"guildId1", &"ownerId1", &CommitTimestamp::new()]);
163//!     let commit_timestamp = client.apply(vec![mutation]).await?;
164//!
165//!     let mut tx = client.single().await?;
166//!     let row = tx.read_row( "Guild", &["GuildId", "OwnerUserID", "UpdatedAt"], Key::new(&"guildId1")).await?;
167//!     Ok(())
168//! }
169//! ```
170//!
171//! All the methods used above are discussed in more detail below.
172//!
173//! ### <a name="Keys"></a>Keys
174//!
175//! Every Cloud Spanner row has a unique key, composed of one or more columns. Construct keys with a literal of type Key:
176//!
177//! ```
178//! use google_cloud_spanner::key::Key;
179//!
180//! let key1 = Key::new(&"key");
181//! ```
182//!
183//! ### <a name="KeyRanges"></a>KeyRanges
184//!
185//! The keys of a Cloud Spanner table are ordered. You can specify ranges of keys using the KeyRange type:
186//!
187//! ```
188//! use google_cloud_spanner::key::{Key,KeyRange,RangeKind};
189//!
190//! let range1 = KeyRange::new(Key::new(&1), Key::new(&100), RangeKind::ClosedClosed);
191//! let range2 = KeyRange::new(Key::new(&1), Key::new(&100), RangeKind::ClosedOpen);
192//! let range3 = KeyRange::new(Key::new(&1), Key::new(&100), RangeKind::OpenOpen);
193//! let range4 = KeyRange::new(Key::new(&1), Key::new(&100), RangeKind::OpenClosed);
194//! ```
195//!
196//! ### <a name="KeySets"></a>KeySets
197//!
198//! A KeySet represents a set of keys. A single Key or KeyRange can act as a KeySet.
199//!
200//! ```
201//! use google_cloud_spanner::key::Key;
202//! use google_cloud_spanner::statement::ToKind;
203//!
204//! let key1 = Key::composite(&[&"Bob", &"2014-09-23"]);
205//! let key2 = Key::composite(&[&"Alfred", &"2015-06-12"]);
206//! let keys  = vec![key1,key2] ;
207//! let composite_keys = vec![
208//!     Key::composite(&[&"composite-pk-1-1",&"composite-pk-1-2"]),
209//!     Key::composite(&[&"composite-pk-2-1",&"composite-pk-2-2"])
210//! ];
211//! ```
212//!
213//! all_keys returns a KeySet that refers to all the keys in a table:
214//!
215//! ```
216//! use google_cloud_spanner::key::all_keys;
217//!
218//! let ks = all_keys();
219//! ```
220//!
221//! ### <a name="Transactions"></a>Transactions
222//!
223//! All Cloud Spanner reads and writes occur inside transactions. There are two types of transactions, read-only and read-write. Read-only transactions cannot change the database, do not acquire locks, and may access either the current database state or states in the past. Read-write transactions can read the database before writing to it, and always apply to the most recent database state.
224//!
225//! ### <a name="SingleReads"></a>Single Reads
226//! The simplest and fastest transaction is a ReadOnlyTransaction that supports a single read operation. Use Client.Single to create such a transaction. You can chain the call to Single with a call to a Read method.
227//!
228//! When you only want one row whose key you know, use ReadRow. Provide the table name, key, and the columns you want to read:
229//!
230//! ```
231//! use google_cloud_spanner::key::Key;
232//! use google_cloud_spanner::client::{Client, Error};
233//!
234//! async fn run(client: Client) -> Result<(), Error>{
235//!     let mut tx = client.single().await?;
236//!     let row = tx.read_row("Guild", &["GuildID", "OwnerUserID"], Key::new(&"guild1")).await;
237//!     Ok(())
238//! }
239//! ```
240//!
241//! Read multiple rows with the Read method. It takes a table name, KeySet, and list of columns:
242//!
243//! ```
244//! use google_cloud_spanner::key::Key;
245//! use google_cloud_spanner::statement::ToKind;
246//! use google_cloud_spanner::client::Client;
247//! use google_cloud_spanner::client::Error;
248//!
249//! async fn run(client: Client) -> Result<(), Error>{
250//!     let mut tx = client.single().await?;
251//!     let iter1 = tx.read("Guild",&["GuildID", "OwnerUserID"], vec![
252//!         Key::new(&"pk1"),
253//!         Key::new(&"pk2")
254//!     ]).await?;
255//!     Ok(())
256//! }
257//! ```
258//!
259//! RowIterator also follows the standard pattern for the Google Cloud Client Libraries:
260//!
261//! ```
262//! use google_cloud_spanner::key::Key;
263//! use google_cloud_spanner::client::Client;
264//! use google_cloud_spanner::client::Error;
265//!
266//! #[tokio::main]
267//! async fn run(client: Client) -> Result<(), Error>{
268//!     let mut tx = client.single().await?;
269//!     let mut iter = tx.read("Guild", &["GuildID", "OwnerUserID"], vec![
270//!         Key::new(&"pk1"),
271//!         Key::new(&"pk2")
272//!     ]).await.unwrap();
273//!
274//!     while let Some(row) = iter.next().await? {
275//!         let guild_id = row.column_by_name::<String>("GuildID");
276//!         //do something
277//!     };
278//!     Ok(())
279//! }
280//! ```
281//!
282//! * The used session is returned to the drop timing session pool, so unlike Go, there is no need to call Stop.
283//!
284//! * To read rows with an index, use `client.read_with_option`.
285//!
286//! ### <a name="Statements"></a>Statements
287//!
288//! The most general form of reading uses SQL statements. Construct a Statement with NewStatement, setting any parameters using the Statement's Params map:
289//!
290//! ```
291//! use google_cloud_spanner::statement::Statement;
292//!
293//! let mut stmt = Statement::new("SELECT * FROM User WHERE UserId = @UserID");
294//! stmt.add_param("UserId", &"user_id");
295//! ```
296//!
297//! You can also construct a Statement directly with a struct literal, providing your own map of parameters.
298//!
299//! Use the Query method to run the statement and obtain an iterator:
300//!
301//! ```
302//! use google_cloud_spanner::client::{Client, Error};
303//! use google_cloud_spanner::statement::Statement;
304//!
305//! async fn run(client: Client) -> Result<(), Error>{
306//!     let mut stmt = Statement::new("SELECT * FROM Guild WHERE OwnerUserID = @OwnerUserID");
307//!     stmt.add_param("OwnerUserID", &"key");
308//!     let mut tx = client.single().await?;
309//!     let iter = tx.query(stmt).await?;
310//!     Ok(())
311//! }
312//! ```
313//!
314//! ### <a name="Rows"></a>Rows
315//! Once you have a Row, via an iterator or a call to read_row, you can extract column values in several ways. Pass in a pointer to a Rust variable of the appropriate type when you extract a value.
316//!
317//! You can extract by column position or name:
318//!
319//! ```ignore
320//! let value           = row.column::<String>(0)?;
321//! let nullable_value  = row.column::<Option<String>>(1)?;
322//! let array_value     = row.column_by_name::<Vec<i64>>("array")?;
323//! let struct_data     = row.column_by_name::<Vec<User>>("struct_data")?;
324//! ```
325//!
326//! Or you can define a Rust struct that corresponds to your columns, and extract into that:
327//! * `TryFromStruct` trait is required
328//!
329//! ```
330//! use google_cloud_spanner::row::TryFromStruct;
331//! use google_cloud_spanner::row::Struct;
332//! use google_cloud_spanner::row::Error;
333//!
334//! pub struct User {
335//!     pub user_id: String,
336//!     pub premium: bool,
337//!     pub updated_at: time::OffsetDateTime,
338//! }
339//!
340//! impl TryFromStruct for User {
341//!     fn try_from_struct(s: Struct<'_>) -> Result<Self, Error> {
342//!         Ok(User {
343//!             user_id: s.column_by_name("UserId")?,
344//!             premium: s.column_by_name("Premium")?,
345//!             updated_at: s.column_by_name("UpdatedAt")?,
346//!         })
347//!     }
348//! }
349//! ```
350//!
351//! ### <a name="MultipleReads"></a>Multiple Reads
352//!
353//! To perform more than one read in a transaction, use ReadOnlyTransaction:
354//!
355//! ```ignore
356//! use google_cloud_spanner::client::{Client, Error};
357//! use google_cloud_spanner::statement::Statement;
358//! use google_cloud_spanner::key::Key;
359//!
360//! async fn run(client: Client) -> Result<(), Error> {
361//!     let mut tx = client.read_only_transaction().await?;
362//!
363//!     let mut stmt = Statement::new("SELECT * , \
364//!             ARRAY (SELECT AS STRUCT * FROM UserItem WHERE UserId = @Param1 ) AS UserItem, \
365//!             ARRAY (SELECT AS STRUCT * FROM UserCharacter WHERE UserId = @Param1 ) AS UserCharacter  \
366//!             FROM User \
367//!             WHERE UserId = @Param1");
368//!
369//!     stmt.add_param("Param1", user_id);
370//!     let mut reader = tx.query(stmt).await?;
371//!     let mut data = vec![];
372//!     while let Some(row) = reader.next().await? {
373//!         let user_id= row.column_by_name::<String>("UserId")?;
374//!         let user_items= row.column_by_name::<Vec<model::UserItem>>("UserItem")?;
375//!         let user_characters = row.column_by_name::<Vec<model::UserCharacter>>("UserCharacter")?;
376//!         data.push(user_id);
377//!     }
378//!
379//!     let mut reader2 = tx.read("User", &["UserId"], vec![
380//!         Key::new(&"user-1"),
381//!         Key::new(&"user-2")
382//!     ]).await?;
383//!
384//!     // iterate reader2 ...
385//!
386//!     let mut reader3 = tx.read("Table", &["col1", "col2"], vec![
387//!         Key::composite(&[&"composite-pk-1-1",&"composite-pk-1-2"]),
388//!         Key::composite(&[&"composite-pk-2-1",&"composite-pk-2-2"])
389//!     ]).await?;
390//!
391//!     Ok(())
392//! }
393//! // iterate reader3 ...
394//! ```
395//!
396//! * The used session is returned to the drop timing session pool, so unlike Go, there is no need to call txn Close.
397//!
398//! ### <a name="TimestampsAndTimestampBounds"></a>Timestamps and Timestamp Bounds
399//!
400//! Cloud Spanner read-only transactions conceptually perform all their reads at a single moment in time, called the transaction's read timestamp. Once a read has started, you can call ReadOnlyTransaction's Timestamp method to obtain the read timestamp.
401//!
402//! By default, a transaction will pick the most recent time (a time where all previously committed transactions are visible) for its reads. This provides the freshest data, but may involve some delay. You can often get a quicker response if you are willing to tolerate "stale" data.
403//! You can control the read timestamp selected by a transaction. For example, to perform a query on data that is at most one minute stale, use
404//!
405//! ```
406//! use google_cloud_spanner::client::{Client, Error};
407//! use google_cloud_spanner::value::TimestampBound;
408//!
409//! pub async fn run(client: Client) -> Result<(), Error>{
410//!     let tx = client.single_with_timestamp_bound(TimestampBound::max_staleness(std::time::Duration::from_secs(60))).await?;
411//!     Ok(())
412//! }
413//! ```
414//!
415//! See the documentation of TimestampBound for more details.
416//!
417//! ### <a name="Mutations"></a>Mutations
418//!
419//! To write values to a Cloud Spanner database, construct a Mutation. The spanner package has functions for inserting, updating and deleting rows. Except for the Delete methods, which take a Key or KeyRange, each mutation-building function comes in three varieties.
420//!
421//! One takes lists of columns and values along with the table name:
422//!
423//! ```
424//! use google_cloud_spanner::mutation::insert_or_update;
425//! use google_cloud_spanner::mutation::insert_or_update_map;
426//! use google_cloud_spanner::value::CommitTimestamp;
427//! use google_cloud_spanner::client::Client;
428//!
429//! fn run(client: Client) {
430//!     let mutation = insert_or_update("Guild",
431//!         &[&"GuildID", &"OwnerUserID", &"UpdatedAt"], // columns
432//!         &[&"gid", &"owner", &CommitTimestamp::new()] // values
433//!     );
434//!     // or use insert_map
435//!     let mutation2 = insert_or_update_map("Guild",
436//!         &[("GuildId", &"gid"), ("OwnerUserID", &"owner"), (&"UpdatedAt",&CommitTimestamp::new())]
437//!     );
438//! }
439//! ```
440//!
441//! And the third accepts a struct value, and determines the columns from the struct field names:
442//!
443//! * `ToStruct` trait is required
444//!
445//! ```
446//! use google_cloud_spanner::statement::Kinds;
447//! use google_cloud_spanner::statement::Types;
448//! use google_cloud_spanner::statement::ToStruct;
449//! use google_cloud_spanner::statement::ToKind;
450//! use google_cloud_spanner::value::CommitTimestamp;
451//! use google_cloud_spanner::mutation::insert_or_update_struct;
452//!
453//! pub struct User {
454//!     pub user_id: String,
455//!     pub premium: bool,
456//!     pub updated_at: time::OffsetDateTime,
457//! }
458//!
459//! impl ToStruct for User {
460//!     fn to_kinds(&self) -> Kinds {
461//!         vec![
462//!             ("UserId", self.user_id.to_kind()),
463//!             ("Premium", self.premium.to_kind()),
464//!             ("UpdatedAt", CommitTimestamp::new().to_kind())
465//!         ]
466//!     }
467//!
468//!     fn get_types() -> Types {
469//!         vec![
470//!             ("UserId", String::get_type()),
471//!             ("Premium", bool::get_type()),
472//!             ("UpdatedAt", CommitTimestamp::get_type())
473//!         ]
474//!     }
475//! }
476//!
477//! let new_user = User {
478//!     user_id: "user_id".to_string(),
479//!     premium: true,
480//!     updated_at: time::OffsetDateTime::now_utc(),
481//! };
482//! let m1 = insert_or_update_struct("User", &new_user);
483//! ```
484//!
485//! ### <a name="Writes"></a>Writes
486//!
487//! To apply a list of mutations to the database, use Apply:
488//! ```
489//! use google_cloud_spanner::mutation::insert;
490//! use google_cloud_spanner::mutation::delete;
491//! use google_cloud_spanner::key::all_keys;
492//! use google_cloud_spanner::statement::ToKind;
493//! use google_cloud_spanner::value::CommitTimestamp;
494//! use google_cloud_spanner::client::{Client, Error};
495//!
496//! async fn run(client: Client) -> Result<(), Error>{
497//!     let m1 = delete("Guild", all_keys());
498//!     let m2 = insert("Guild", &["GuildID", "OwnerUserID", "UpdatedAt"], &[&"1", &"2", &CommitTimestamp::new()]);
499//!     let commit_timestamp = client.apply(vec![m1,m2]).await?;
500//!     Ok(())
501//! }
502//! ```
503//!
504//! If you need to read before writing in a single transaction, use a ReadWriteTransaction. ReadWriteTransactions may be aborted automatically by the backend and need to be retried. You pass in a function to ReadWriteTransaction, and the client will handle the retries automatically. Use the transaction's BufferWrite method to buffer mutations, which will all be executed at the end of the transaction:
505//!
506//! ```
507//! use google_cloud_spanner::mutation::update;
508//! use google_cloud_spanner::key::Key;
509//! use google_cloud_spanner::value::Timestamp;
510//! use google_cloud_spanner::client::Error;
511//! use google_cloud_spanner::client::Client;
512//!
513//! async fn run(client: Client) ->Result<(Option<Timestamp>,()), Error> {
514//!     client.read_write_transaction(|tx| {
515//!         Box::pin(async move {
516//!             // The transaction function will be called again if the error code
517//!             // of this error is Aborted. The backend may automatically abort
518//!             // any read/write transaction if it detects a deadlock or other problems.
519//!             let key = Key::new(&"user1");
520//!             let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
521//!             let mut ms = vec![];
522//!             while let Some(row) = reader.next().await? {
523//!                 let user_id = row.column_by_name::<i64>("UserId")?;
524//!                 let item_id = row.column_by_name::<i64>("ItemId")?;
525//!                 let quantity = row.column_by_name::<i64>("Quantity")? + 1;
526//!                 let m = update("UserItem", &["UserId", "ItemId", "Quantity"], &[&user_id, &item_id, &quantity]);
527//!                 ms.push(m);
528//!             }
529//!             // The buffered mutation will be committed.  If the commit
530//!             // fails with an Aborted error, this function will be called again
531//!             tx.buffer_write(ms);
532//!             Ok(())
533//!         })
534//!     }).await
535//! }
536//! ```
537//!
538//! You can customize error. The Error of the `read_write_transaction` must implements
539//! * `From<google_cloud_googleapis::Status>`
540//! * `From<google_cloud_spanner::session::SessionError>`
541//! * `google_cloud_gax::invoke::TryAs<google_cloud_googleapis::Status>`
542//! ```
543//! use google_cloud_gax::grpc::Status;
544//! use google_cloud_gax::retry::TryAs;
545//! use google_cloud_spanner::client::Error;
546//! use google_cloud_spanner::session::SessionError;
547//!
548//! #[derive(thiserror::Error, Debug)]
549//! pub enum DomainError {
550//!     #[error("invalid")]
551//!     OtherError,
552//!     #[error(transparent)]
553//!     Tx(#[from] Error),
554//! }
555//!
556//! impl TryAs<Status> for DomainError {
557//! fn try_as(&self) -> Option<&Status> {
558//!     match self {
559//!         DomainError::Tx(Error::GRPC(status)) => Some(status),
560//!         _ => None,
561//!     }
562//!  }
563//! }
564//! impl From<Status> for DomainError {
565//!     fn from(status: Status) -> Self {
566//!         Self::Tx(Error::GRPC(status))
567//!     }
568//! }
569//! impl From<SessionError> for DomainError {
570//!     fn from(se: SessionError) -> Self {
571//!         Self::Tx(Error::InvalidSession(se))
572//!     }
573//!  }
574//! ```
575//!
576//! You can begin transaction  by `begin_read_write_transaction`.
577//! It is necessary to write retry processing for transaction abort
578//! ```
579//! use google_cloud_spanner::mutation::update;
580//! use google_cloud_spanner::key::{Key, all_keys};
581//! use google_cloud_spanner::value::Timestamp;
582//! use google_cloud_spanner::client::Error;
583//! use google_cloud_spanner::client::Client;
584//! use google_cloud_spanner::transaction_rw::ReadWriteTransaction;
585//! use google_cloud_googleapis::spanner::v1::execute_batch_dml_request::Statement;
586//! use google_cloud_spanner::retry::TransactionRetry;
587//!
588//! async fn run(client: Client) -> Result<(), Error> {
589//!     let retry = &mut TransactionRetry::new();
590//!     loop {
591//!         let tx = &mut client.begin_read_write_transaction().await?;
592//!
593//!         let result = run_in_transaction(tx).await;
594//!
595//!         // try to commit or rollback transaction.
596//!         match tx.end(result, None).await {
597//!             Ok((_commit_timestamp, success)) => return Ok(success),
598//!             Err(err) => retry.next(err).await? // check retry
599//!         }
600//!     }
601//! }
602//!
603//! async fn run_in_transaction(tx: &mut ReadWriteTransaction) -> Result<(), Error> {
604//!     let key = all_keys();
605//!     let mut reader = tx.read("UserItem", &["UserId", "ItemId", "Quantity"], key).await?;
606//!     let mut ms = vec![];
607//!     while let Some(row) = reader.next().await? {
608//!         let user_id = row.column_by_name::<String>("UserId")?;
609//!         let item_id = row.column_by_name::<i64>("ItemId")?;
610//!         let quantity = row.column_by_name::<i64>("Quantity")? + 1;
611//!         let m = update("UserItem", &["UserId", "ItemId", "Quantity"], &[&user_id, &item_id, &quantity]);
612//!         ms.push(m);
613//!     }
614//!     tx.buffer_write(ms);
615//!     Ok(())
616//! }
617//! ```
618//!
619//! ### <a name="DMLAndPartitionedDML"></a>DML and Partitioned DML
620//! For large databases, it may be more efficient to partition the DML statement.
621//! Use client.partitioned_update to run a DML statement in this way. Not all DML statements can be partitioned.
622//!
623//! ```
624//! use google_cloud_spanner::client::{Client, Error};
625//! use google_cloud_spanner::statement::Statement;
626//!
627//! #[tokio::main]
628//! async fn run(client:Client) -> Result<(), Error>{
629//!     let stmt = Statement::new("UPDATE User SET NullableString = 'aaa' WHERE NullableString IS NOT NULL");
630//!     let result = client.partitioned_update(stmt).await?;
631//!     Ok(())
632//! }
633//! ```
634pub mod admin;
635pub mod apiv1;
636pub mod client;
637pub mod key;
638pub mod mutation;
639pub mod reader;
640pub mod retry;
641pub mod row;
642pub mod session;
643pub mod statement;
644pub mod transaction;
645pub mod transaction_ro;
646pub mod transaction_rw;
647pub mod value;
648pub use bigdecimal;