google-cloud-spanner
Google Cloud Platform GCE spanner library.
Installation
[dependencies]
google-cloud-spanner = 0.1.0
Quick Start
Create Client and call transaction API same as Google Cloud Go.
use Client;
async
Example
Here is the example with using Warp.
Performance
Result of the 24 hours Load Test.
| Metrics | This library | Google Cloud Go |
|---|---|---|
| RPS | 438.4 | 443.4 |
| Used vCPU | 0.37 ~ 0.42 | 0.65 ~ 0.70 |
- This Library : Performance report / CPU Usage
- Google Cloud Go : Performance report / CPU Usage
Test condition
- 2.0 vCPU GKE Autopilot Pod
- 1 Node spanner database server
- 100 Users
- Here is the application for Load Test.
Documentation
Overview
- Creating a Client
- Simple Reads and Writes
- Keys
- KeyRanges
- KeySets
- Transactions
- Single Reads
- Statements
- Rows
- Multiple Reads
- Timestamps and Timestamp Bounds
- Mutations
- Writes
- Structs
- DML and Partitioned DML
Package spanner provides a client for reading and writing to Cloud Spanner databases. See the packages under admin for clients that operate on databases and instances.
Creating a Client
To start working with this package, create a client that refers to the database of interest:
use Client;
const DATABASE: &str = "projects/your_projects/instances/your-instance/databases/your-database";
let mut client = match new.await ;
client.close;
Remember to close the client after use to free up the sessions in the session pool.
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:
use Client;
// Set SPANNER_EMULATOR_HOST environment variable.
set_var;
// Create client as usual.
const DATABASE: &str = "projects/your_projects/instances/your-instance/databases/your-database";
let mut client = match new.await ;
Simple Reads and Writes
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:
use insert;
use Key;
use CommitTimestamp;
use ToKind;
let mutation = insert;
let commit_timestamp = client.apply.await?;
let row = client.single.await?.read_row.await?;
All the methods used above are discussed in more detail below.
Keys
Every Cloud Spanner row has a unique key, composed of one or more columns. Construct keys with a literal of type Key:
use Key;
let key1 = one;
KeyRanges
The keys of a Cloud Spanner table are ordered. You can specify ranges of keys using the KeyRange type:
use ;
let range1 = new;
let range2 = new;
let range3 = new;
let range4 = new;
KeySets
A KeySet represents a set of keys. A single Key or KeyRange can act as a KeySet.
use Key;
use ToKind;
let key1 = new;
let key2 = new;
let keys = vec! ;
let composite_keys = vec!;
all_keys returns a KeySet that refers to all the keys in a table:
use all_keys;
let ks = all_keys;
Transactions
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.
Single Reads
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.
When you only want one row whose key you know, use ReadRow. Provide the table name, key, and the columns you want to read:
use Key;
let row = client.single.await?.read_row.await?;
Read multiple rows with the Read method. It takes a table name, KeySet, and list of columns:
use Key;
use ToKind;
let iter1 = client.single.await?.read.await?;
RowIterator also follows the standard pattern for the Google Cloud Client Libraries:
use Key;
let iter = client.single.await?.read.await?;
loop ;
-
The used session is returned to the drop timing session pool, so unlike Go, there is no need to call Stop.
-
To read rows with an index, use
client.read_with_option.
Statements
The most general form of reading uses SQL statements. Construct a Statement with NewStatement, setting any parameters using the Statement's Params map:
use Statement;
let mut stmt = new;
stmt.add_param;
You can also construct a Statement directly with a struct literal, providing your own map of parameters.
Use the Query method to run the statement and obtain an iterator:
let iter = client.single.await?.query.await?;
Rows
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.
You can extract by column position or name:
let value = row.?;
let nullable_value = row.?;
let array_value = row.?;
let struct_data = row.?;
Or you can define a Rust struct that corresponds to your columns, and extract into that:
TryFromStructtrait is required
use TryFromStruct;
use Struct;
Multiple Reads
To perform more than one read in a transaction, use ReadOnlyTransaction:
use Statement;
use Key;
let tx = client.read_only_transaction.await?;
let mut stmt = new;
stmt.add_param;
let mut reader = tx.query.await?;
loop
let mut reader2 = tx.read.await?;
// iterate reader2 ...
let mut reader3 = tx.read.await?;
// iterate reader3 ...
- The used session is returned to the drop timing session pool, so unlike Go, there is no need to call txn Close.
Timestamps and Timestamp Bounds
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.
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. 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
use TimestampBound;
let tx = client.single_with_timestamp_bound.await?;
See the documentation of TimestampBound for more details.
Mutations
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.
One takes lists of columns and values along with the table name:
use insert;
use CommitTimestamp;
use ToKind;
let mutation = insert;
And the third accepts a struct value, and determines the columns from the struct field names:
ToStructtrait is required
use Kinds;
use Types;
use ToStruct;
use ToKind;
use CommitTimestamp;
use Uuid;
use insert_or_update_struct;
let new_user = User ;
let new_user2 = User ;
let m1 = insert_or_update_struct;
let m2 = insert_or_update_struct;
Writes
To apply a list of mutations to the database, use Apply:
use insert;
use delete;
use all_keys;
use ToKind;
let m1 = delete;
let m2 = insert;
let commit_timestamp = client.apply.await?;
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:
The Error of the read_write_transaction must implements
- From<google_cloud_googleapis::Status>
- From<google_cloud_spanner::session::SessionError>
- google_cloud_gax::invoke::TryAs<google_cloud_googleapis::Status>
use TryAs;
use Status;
use update;
use Key;
use Timestamp;
let tx_result: = client.read_write_transaction.await;
DML and Partitioned DML
Spanner supports DML statements like INSERT, UPDATE and DELETE. Use ReadWriteTransaction.Update to run DML statements. It returns the number of rows affected. (You can call use ReadWriteTransaction.Query with a DML statement. The first call to Next on the resulting RowIterator will return iterator.Done, and the RowCount field of the iterator will hold the number of affected rows.)
For large databases, it may be more efficient to partition the DML statement. Use client.PartitionedUpdate to run a DML statement in this way. Not all DML statements can be partitioned.
use Client;
use Statement;
let client = new.await?;
let stmt = new;
let result = client.partitioned_update.await?;