Getting started with Spanner in Rust

Objectives

This tutorial walks you through the following steps using the Spanner client library for Rust:

  • Create a Spanner instance and database.
  • Write, read, and execute SQL queries on data in the database.
  • Update the database schema.
  • Update data using a read-write transaction.
  • Add a secondary index to the database.
  • Use the index to read and execute SQL queries on data.
  • Retrieve data using a read-only transaction.

Costs

This tutorial uses Spanner, which is a billable component of the Google Cloud. For information on the cost of using Spanner, see Pricing.

Before you begin

Complete the steps described in Set up, which cover creating and setting a default Google Cloud project, enabling billing, enabling the Cloud Spanner API, and setting up OAuth 2.0 to get authentication credentials to use the Cloud Spanner API.

In particular, make sure that you run gcloud auth application-default login to set up your local development environment with authentication credentials.

Prepare your local Rust environment

  1. Install Rust (download) on your development machine if it is not already installed.

  2. Clone the sample app repository to your local machine:

    git clone https://github.com/googleapis/google-cloud-rust.git
    
  3. Change to the directory that contains the Spanner sample code:

    cd google-cloud-rust/src/spanner/examples
    
  4. Build the sample applications:

    cargo build
    

Create an instance

When you first use Spanner, you must create an instance, which is an allocation of resources that are used by Spanner databases. When you create an instance, you choose an instance configuration, which determines where your data is stored, and also the number of nodes to use, which determines the amount of serving and storage resources in your instance.

See Create an instance to learn how to create a Spanner instance using any of the following methods. You can name your instance test-instance to use it with other topics in this document that reference an instance named test-instance.

  • The Google Cloud CLI
  • The Google Cloud console
  • A client library (C++, C#, Go, Java, Node.js, PHP, Python, Ruby, or Rust)

Look through sample files

The samples repository contains a sample that shows how to use Spanner with Rust.

Take a look through the src/spanner/examples/src/lib.rs file, which shows how to use Spanner. The code shows how to create and use a new database. The data uses the example schema shown in the Schema and data model page.

Create a database

GoogleSQL

cargo run --bin spanner_sample -- \
    createdatabase test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    createpgdatabase test-instance example-db

You should see:

Created database [projects/PROJECT_ID/instances/test-instance/databases/example-db] successfully.
The following code creates a database and two tables in the database.

GoogleSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(
    admin_client: &DatabaseAdmin,
    instance_name: &str,
    database_id: &str,
) -> anyhow::Result<()> {
    let create_statement = format!("CREATE DATABASE `{database_id}`");
    let extra_statements = vec![
        r#"CREATE TABLE Singers (
            SingerId INT64 NOT NULL,
            FirstName STRING(1024),
            LastName STRING(1024),
            SingerInfo BYTES(MAX),
            FullName STRING(2048) AS (ARRAY_TO_STRING([FirstName, LastName], " ")) STORED
         ) PRIMARY KEY (SingerId)"#
            .to_string(),
        r#"CREATE TABLE Albums (
            SingerId INT64 NOT NULL,
            AlbumId INT64 NOT NULL,
            AlbumTitle STRING(MAX)
         ) PRIMARY KEY (SingerId, AlbumId),
         INTERLEAVE IN PARENT Singers ON DELETE CASCADE"#
            .to_string(),
    ];

    println!("Creating database {database_id}...");
    let database = admin_client
        .create_database()
        .set_parent(instance_name.to_string())
        .set_create_statement(create_statement)
        .set_extra_statements(extra_statements)
        .poller()
        .until_done()
        .await?;

    println!("Created database [{}] successfully.", database.name);
    Ok(())
}

PostgreSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;
use google_cloud_spanner_admin_database_v1::model::DatabaseDialect;

pub async fn sample(
    admin_client: &DatabaseAdmin,
    instance_name: &str,
    database_id: &str,
) -> anyhow::Result<()> {
    let create_statement = format!("CREATE DATABASE \"{database_id}\"");

    println!("Creating PostgreSQL dialect database {database_id}...");
    let database = admin_client
        .create_database()
        .set_parent(instance_name.to_string())
        .set_create_statement(create_statement)
        .set_database_dialect(DatabaseDialect::Postgresql)
        .poller()
        .until_done()
        .await?;

    println!(
        "Created PostgreSQL dialect database [{}] successfully.",
        database.name
    );

    // Note: PostgreSQL dialect databases do not support adding extra statements
    // in the CreateDatabase operations. We must create the database first,
    // and then apply any schema DDL updates.
    let ddl_statements = vec![
        r#"CREATE TABLE Singers (
            SingerId   bigint NOT NULL,
            FirstName  character varying(1024),
            LastName   character varying(1024),
            SingerInfo bytea,
            FullName character varying(2048) GENERATED ALWAYS AS (FirstName || ' ' || LastName) STORED,
            PRIMARY KEY (SingerId)
         )"#
        .to_string(),
        r#"CREATE TABLE Albums (
            SingerId     bigint NOT NULL,
            AlbumId      bigint NOT NULL,
            AlbumTitle   character varying(1024),
            PRIMARY KEY (SingerId, AlbumId)
         ) INTERLEAVE IN PARENT Singers ON DELETE CASCADE"#
        .to_string(),
    ];

    println!(
        "Creating Singers and Albums tables in PostgreSQL database {}...",
        database.name
    );
    admin_client
        .update_database_ddl()
        .set_database(database.name.clone())
        .set_statements(ddl_statements)
        .poller()
        .until_done()
        .await?;

    println!("Created tables successfully.");
    Ok(())
}

The next step is to write data to your database.

Create a database client

Before you can do reads or writes, you must create a DatabaseClient:

use google_cloud_spanner::client::{DatabaseClient, Spanner};
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(database_name: &str) -> anyhow::Result<(DatabaseClient, DatabaseAdmin)> {
    // The builder automatically handles SPANNER_EMULATOR_HOST if set in the environment.
    let client = Spanner::builder().build().await?;

    // Creates a client that can be used to execute queries and transactions on a specific database.
    let database_client = client.database_client(database_name).build().await?;

    // Creates a client that can be used to execute DDL and other administrative operations on databases.
    let admin_client = client.database_admin_builder().build().await?;

    Ok((database_client, admin_client))
}

You can think of a DatabaseClient as a long-lived database connection: all of your interactions with Spanner must go through a DatabaseClient. Typically you create a DatabaseClient when your application starts up, then you re-use that DatabaseClient to read, write, and execute transactions. The client manages a long-lived multiplexed session under the hood.

Read more in the DatabaseClient reference.

Write data with DML

You can insert data using Data Manipulation Language (DML) in a read-write transaction.

You can execute DML statements using DatabaseClient and Statement.

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let runner = client.read_write_transaction().build();

    runner
        .run(async |transaction| {
            let sql = r#"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES
                       (12, 'Melissa', 'Garcia'),
                       (13, 'Russell', 'Morales'),
                       (14, 'Jacqueline', 'Long'),
                       (15, 'Dylan', 'Shaw')"#;
            let statement = Statement::builder(sql).build();
            let row_count = transaction.execute_update(statement).await?;
            println!("{row_count} records inserted.");
            Ok(())
        })
        .await?;

    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let runner = client.read_write_transaction().build();

    runner
        .run(async |transaction| {
            let sql = r#"INSERT INTO Singers (SingerId, FirstName, LastName) VALUES
                       (12, 'Melissa', 'Garcia'),
                       (13, 'Russell', 'Morales'),
                       (14, 'Jacqueline', 'Long'),
                       (15, 'Dylan', 'Shaw')"#;
            let statement = Statement::builder(sql).build();
            let row_count = transaction.execute_update(statement).await?;
            println!("{row_count} records inserted.");
            Ok(())
        })
        .await?;

    Ok(())
}

Run the sample using the writeusingdml argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    writeusingdml test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    writeusingdml test-instance example-db

Write data with mutations

You can also insert data using mutations.

Query data using SQL

Spanner supports a SQL interface for reading data, which you can access on the command line using the Google Cloud CLI or programmatically using the Spanner client library for Rust.

On the command line

Execute the following SQL statement to read the values of all columns from the Albums table:

GoogleSQL

gcloud spanner databases execute-sql example-db --instance=test-instance \
    --sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'

GoogleSQL Pipe syntax

gcloud spanner databases execute-sql example-db --instance=test-instance \
    --sql='FROM Albums |> SELECT SingerId, AlbumId, AlbumTitle'

The result shows:

SingerId AlbumId AlbumTitle
1        1       Total Junk
1        2       Go, Go, Go
2        1       Green
2        2       Forever Hold Your Peace
2        3       Terrified

Use the Spanner client library for Rust

In addition to executing a SQL statement on the command line, you can issue the same SQL statement programmatically using the Spanner client library for Rust.

You can execute SQL queries using DatabaseClient::single_use() and Statement.

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement = Statement::builder("SELECT SingerId, AlbumId, AlbumTitle FROM Albums").build();
    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    println!("Listing albums:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let album_id: i64 = row.get("AlbumId")?;
        let album_title: String = row.get("AlbumTitle")?;
        println!("SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}");
    }
    println!("Done listing albums.");
    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement = Statement::builder(
        r#"SELECT singerid AS "SingerId", firstname as "FirstName", lastname as "LastName"
         FROM Singers"#,
    )
    .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let first_name: String = row.get("FirstName")?;
        let last_name: String = row.get("LastName")?;
        println!("{singer_id} {first_name} {last_name}");
    }
    Ok(())
}

Run the sample using the query argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    query test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    query test-instance example-db

Query using a SQL parameter

If your application has a frequently executed query, you can improve its performance by parameterizing it. The resulting parametric query can be cached and reused, which reduces compilation costs. For more information, see Use query parameters to speed up frequently executed queries.

Here is an example of using a parameter in the WHERE clause to query records containing a specific value for LastName.

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement = Statement::builder(
        "SELECT SingerId, FirstName, LastName \
         FROM Singers \
         WHERE LastName = @lastName",
    )
    .add_param("lastName", "Garcia")
    .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let first_name: String = row.get("FirstName")?;
        let last_name: String = row.get("LastName")?;
        println!("{singer_id} {first_name} {last_name}");
    }
    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement = Statement::builder(
        r#"SELECT singerid AS "SingerId", firstname as "FirstName", lastname as "LastName"
         FROM Singers
         WHERE LastName = $1"#,
    )
    .add_param("p1", "Garcia")
    .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let first_name: String = row.get("FirstName")?;
        let last_name: String = row.get("LastName")?;
        println!("{singer_id} {first_name} {last_name}");
    }
    Ok(())
}

Run the sample using the querywithparameter argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    querywithparameter test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    querywithparameter test-instance example-db

Read data using the read API

In addition to Spanner's SQL interface, Spanner also supports a read interface.

Use the DatabaseClient::single_use() method with ReadOperation to read rows from the database. Use a KeySet object to define a collection of keys and key ranges to read.

Here's how to read the data:

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    // Build a read request to read all rows in the Albums table
    let read_request = ReadRequest::builder("Albums", ["SingerId", "AlbumId", "AlbumTitle"])
        .with_keys(KeySet::all())
        .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_read(read_request).await?;

    println!("Reading albums data:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let album_id: i64 = row.get("AlbumId")?;
        let album_title: String = row.get("AlbumTitle")?;
        println!("SingerId: {singer_id}, AlbumId: {album_id}, AlbumTitle: {album_title}");
    }
    println!("Done reading albums.");

    Ok(())
}

Run the sample using the read argument.

cargo run --bin spanner_sample -- \
    read test-instance example-db

Update the database schema

Assume you need to add a new column called MarketingBudget to the Albums table. Adding a new column to an existing table requires an update to your database schema. Spanner supports schema updates to a database while the database continues to serve traffic. Schema updates don't require taking the database offline and they don't lock entire tables or columns; you can continue writing data to the database during the schema update. Read more about supported schema updates and schema change performance in Make schema updates.

Add a column

You can add a column on the command line using the Google Cloud CLI or programmatically using the Spanner client library for Rust.

On the command line

Use the following ALTER TABLE command to add the new column to the table:

GoogleSQL

gcloud spanner databases ddl update example-db --instance=test-instance \
    --ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'

PostgreSQL

gcloud spanner databases ddl update example-db --instance=test-instance \
    --ddl='ALTER TABLE Albums ADD COLUMN MarketingBudget BIGINT'

You should see:

Schema updating...done.

Use the Spanner client library for Rust

GoogleSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements = vec!["ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added MarketingBudget column");
    Ok(())
}

PostgreSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements = vec!["ALTER TABLE Albums ADD COLUMN MarketingBudget bigint"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added MarketingBudget column");
    Ok(())
}

Run the sample using the addmarketingbudget argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    addmarketingbudget test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    addmarketingbudget test-instance example-db

You should see:

Added MarketingBudget column.

Write data to the new column

The following code writes data to the new column. It sets MarketingBudget to 100000 for the row keyed by Albums(1, 1) and to 500000 for the row keyed by Albums(2, 2).

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::mutation::Mutation;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let mutations = vec![
        Mutation::new_update_builder("Albums")
            .set("SingerId")
            .to(1)
            .set("AlbumId")
            .to(1)
            .set("MarketingBudget")
            .to(100000)
            .build(),
        Mutation::new_update_builder("Albums")
            .set("SingerId")
            .to(2)
            .set("AlbumId")
            .to(2)
            .set("MarketingBudget")
            .to(500000)
            .build(),
    ];

    println!("Updating MarketingBudget on Albums...");
    let write_transaction = client.write_only_transaction().build();
    write_transaction.write(mutations).await?;
    println!("Updated budget successfully.");

    Ok(())
}

Run the sample using the update argument.

cargo run --bin spanner_sample -- \
    update test-instance example-db

You can also execute a SQL query or a read call to fetch the values that you just wrote.

Here's the code to execute the query:

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement =
        Statement::builder("SELECT SingerId, AlbumId, MarketingBudget FROM Albums").build();
    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let album_id: i64 = row.get("AlbumId")?;
        let marketing_budget: Option<i64> = row.get("MarketingBudget")?;

        match marketing_budget {
            Some(budget) => println!("{singer_id} {album_id} {budget}"),
            None => println!("{singer_id} {album_id} NULL"),
        }
    }
    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let statement = Statement::builder(
        r#"SELECT singerid as "SingerId", albumid as "AlbumId", marketingbudget as "MarketingBudget"
         FROM Albums"#,
    )
    .build();
    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_query(statement).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get("SingerId")?;
        let album_id: i64 = row.get("AlbumId")?;
        let marketing_budget: Option<i64> = row.get("MarketingBudget")?;

        match marketing_budget {
            Some(budget) => println!("{singer_id} {album_id} {budget}"),
            None => println!("{singer_id} {album_id} NULL"),
        }
    }
    Ok(())
}

To execute this query, run the sample using the querymarketingbudget argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    querymarketingbudget test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    querymarketingbudget test-instance example-db

Update data

You can update data using DML in a read-write transaction.

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let runner = client.read_write_transaction().build();

    runner
        .run(async |transaction| {
            // Transfer marketing budget from one album to another. We do it in a transaction to
            // ensure that the transfer is atomic.
            let select_statement1 = Statement::builder(
                r#"SELECT MarketingBudget
                 FROM Albums
                 WHERE SingerId = 2 AND AlbumId = 2"#,
            )
            .build();
            let mut result_set1 = transaction.execute_query(select_statement1).await?;
            let mut album2_budget = 0i64;
            if let Some(row) = result_set1.next().await.transpose()? {
                album2_budget = row.get("MarketingBudget")?;
            }

            let transfer = 200000i64;
            if album2_budget < transfer {
                return Ok(());
            }

            let select_statement2 = Statement::builder(
                r#"SELECT MarketingBudget
                 FROM Albums
                 WHERE SingerId = 1 AND AlbumId = 1"#,
            )
            .build();
            let mut result_set2 = transaction.execute_query(select_statement2).await?;
            let mut album1_budget = 0i64;
            if let Some(row) = result_set2.next().await.transpose()? {
                album1_budget = row.get("MarketingBudget")?;
            }

            album1_budget += transfer;
            album2_budget -= transfer;

            let update_statement1 = Statement::builder(
                r#"UPDATE Albums
                 SET MarketingBudget = @AlbumBudget
                 WHERE SingerId = 1 AND AlbumId = 1"#,
            )
            .add_param("AlbumBudget", album1_budget)
            .build();
            transaction.execute_update(update_statement1).await?;

            let update_statement2 = Statement::builder(
                r#"UPDATE Albums
                 SET MarketingBudget = @AlbumBudget
                 WHERE SingerId = 2 AND AlbumId = 2"#,
            )
            .add_param("AlbumBudget", album2_budget)
            .build();
            transaction.execute_update(update_statement2).await?;

            Ok(())
        })
        .await?;

    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let runner = client.read_write_transaction().build();

    runner
        .run(async |transaction| {
            // Transfer marketing budget from one album to another. We do it in a transaction to
            // ensure that the transfer is atomic.
            let select_statement1 = Statement::builder(
                r#"SELECT MarketingBudget as "MarketingBudget"
                 FROM Albums
                 WHERE SingerId = 2 AND AlbumId = 2"#,
            )
            .build();
            let mut result_set1 = transaction.execute_query(select_statement1).await?;
            let mut album2_budget = 0i64;
            if let Some(row) = result_set1.next().await.transpose()? {
                album2_budget = row.get("MarketingBudget")?;
            }

            let transfer = 200000i64;
            if album2_budget < transfer {
                return Ok(());
            }

            let select_statement2 = Statement::builder(
                r#"SELECT MarketingBudget as "MarketingBudget"
                 FROM Albums
                 WHERE SingerId = 1 AND AlbumId = 1"#,
            )
            .build();
            let mut result_set2 = transaction.execute_query(select_statement2).await?;
            let mut album1_budget = 0i64;
            if let Some(row) = result_set2.next().await.transpose()? {
                album1_budget = row.get("MarketingBudget")?;
            }

            album1_budget += transfer;
            album2_budget -= transfer;

            let update_statement1 = Statement::builder(
                r#"UPDATE Albums
                 SET MarketingBudget = $1
                 WHERE SingerId = 1 AND AlbumId = 1"#,
            )
            .add_param("p1", album1_budget)
            .build();
            transaction.execute_update(update_statement1).await?;

            let update_statement2 = Statement::builder(
                r#"UPDATE Albums
                 SET MarketingBudget = $1
                 WHERE SingerId = 2 AND AlbumId = 2"#,
            )
            .add_param("p1", album2_budget)
            .build();
            transaction.execute_update(update_statement2).await?;

            Ok(())
        })
        .await?;

    Ok(())
}

Run the sample using the updateusingdml argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    updateusingdml test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    updateusingdml test-instance example-db

Use a secondary index

Suppose you wanted to fetch all rows of Albums that have AlbumTitle values in a certain range. You could read all values from the AlbumTitle column using a SQL statement or a read call, and then discard the rows that don't meet the criteria, but doing this full table scan is expensive, especially for tables with a lot of rows. Instead you can speed up the retrieval of rows when searching by non-primary key columns by creating a secondary index on the table.

Adding a secondary index to an existing table requires a schema update. Like other schema updates, Spanner supports adding an index while the database continues to serve traffic. Spanner automatically backfills the index with your existing data. Backfills might take a few minutes to complete, but you don't need to take the database offline or avoid writing to the indexed table during this process. For more details, see Add a secondary index.

After you add a secondary index, Spanner automatically uses it for SQL queries that are likely to run faster with the index. If you use the read interface, you must specify the index that you want to use.

Add a secondary index

You can add an index on the command line using the gcloud CLI or programmatically using the Spanner client library for Rust.

On the command line

Use the following CREATE INDEX command to add an index to the database:

gcloud spanner databases ddl update example-db --instance=test-instance \
    --ddl='CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'

You should see:

Schema updating...done.

Using the Spanner client library for Rust

GoogleSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements = vec!["CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added AlbumsByAlbumTitle index");
    Ok(())
}

PostgreSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements = vec!["CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added AlbumsByAlbumTitle index");
    Ok(())
}

Run the sample using the addindex argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    addindex test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    addindex test-instance example-db

Adding an index can take a few minutes. After the index is added, you should see:

Added index.

Read using the index

For SQL queries, Spanner automatically uses an appropriate index. In the read interface, you must specify the index in your request.

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let read_request = ReadRequest::builder("Albums", ["AlbumId", "AlbumTitle"])
        .with_index("AlbumsByAlbumTitle", KeySet::all())
        .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_read(read_request).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let album_id: i64 = row.get(0)?;
        let album_title: String = row.get(1)?;
        println!("{album_id} {album_title}");
    }

    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let read_request = ReadRequest::builder("Albums", ["AlbumId", "AlbumTitle"])
        .with_index("AlbumsByAlbumTitle", KeySet::all())
        .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_read(read_request).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let album_id: i64 = row.get(0)?;
        let album_title: String = row.get(1)?;
        println!("{album_id} {album_title}");
    }

    Ok(())
}

Run the sample using the readindex argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    readindex test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    readindex test-instance example-db

Add an index for index-only reads

You might have noticed that the previous read example doesn't include reading the MarketingBudget column. This is because Spanner's read interface doesn't support the ability to join an index with a data table to look up values that are not stored in the index.

Create an alternate definition of AlbumsByAlbumTitle that stores a copy of MarketingBudget in the index.

On the command line

GoogleSQL

gcloud spanner databases ddl update example-db --instance=test-instance \
    --ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)

PostgreSQL

gcloud spanner databases ddl update example-db --instance=test-instance \
    --ddl='CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) INCLUDE (MarketingBudget)

Adding an index can take a few minutes. After the index is added, you should see:

Schema updating...done.

Using the Spanner client library for Rust

GoogleSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements =
        vec!["CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added AlbumsByAlbumTitle2 index");
    Ok(())
}

PostgreSQL

use google_cloud_lro::Poller;
use google_cloud_spanner_admin_database_v1::client::DatabaseAdmin;

pub async fn sample(admin_client: &DatabaseAdmin, database_name: &str) -> anyhow::Result<()> {
    let statements =
        vec!["CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) INCLUDE (MarketingBudget)"];

    admin_client
        .update_database_ddl()
        .set_database(database_name)
        .set_statements(statements)
        .poller()
        .until_done()
        .await?;

    println!("Added AlbumsByAlbumTitle2 index");
    Ok(())
}

Run the sample using the addstoringindex argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    addstoringindex test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    addstoringindex test-instance example-db

Adding an index can take a few minutes.

Now you can execute a read that fetches all AlbumId, AlbumTitle, and MarketingBudget columns from the AlbumsByAlbumTitle2 index:

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let read_request = ReadRequest::builder("Albums", ["AlbumId", "AlbumTitle", "MarketingBudget"])
        .with_index("AlbumsByAlbumTitle2", KeySet::all())
        .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_read(read_request).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let album_id: i64 = row.get(0)?;
        let album_title: String = row.get(1)?;
        let marketing_budget: Option<i64> = row.get(2)?;

        match marketing_budget {
            Some(budget) => println!("{album_id} {album_title} {budget}"),
            None => println!("{album_id} {album_title} NULL"),
        }
    }

    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let read_request = ReadRequest::builder("Albums", ["AlbumId", "AlbumTitle", "MarketingBudget"])
        .with_index("AlbumsByAlbumTitle2", KeySet::all())
        .build();

    let transaction = client.single_use().build();
    let mut result_set = transaction.execute_read(read_request).await?;

    while let Some(row) = result_set.next().await.transpose()? {
        let album_id: i64 = row.get(0)?;
        let album_title: String = row.get(1)?;
        let marketing_budget: Option<i64> = row.get(2)?;

        match marketing_budget {
            Some(budget) => println!("{album_id} {album_title} {budget}"),
            None => println!("{album_id} {album_title} NULL"),
        }
    }

    Ok(())
}

Run the sample using the readstoringindex argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    readstoringindex test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    readstoringindex test-instance example-db

Retrieve data using read-only transactions

Suppose you want to execute more than one read at the same timestamp. Read-only transactions observe a consistent prefix of the transaction commit history, so your application always gets consistent data.

The following shows how to run a query and perform a read in the same read-only transaction:

GoogleSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let transaction = client.read_only_transaction().build().await?;

    // 1. Execute a query using the read-only transaction
    let statement = Statement::builder("SELECT SingerId, AlbumId, AlbumTitle FROM Albums").build();
    let mut result_set = transaction.execute_query(statement).await?;
    println!("Results from query:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get(0)?;
        let album_id: i64 = row.get(1)?;
        let album_title: String = row.get(2)?;
        println!("{singer_id} {album_id} {album_title}");
    }

    // 2. Execute a read using the same read-only transaction
    let read_request = ReadRequest::builder("Albums", ["SingerId", "AlbumId", "AlbumTitle"])
        .with_keys(KeySet::all())
        .build();
    let mut result_set = transaction.execute_read(read_request).await?;
    println!("Results from read:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get(0)?;
        let album_id: i64 = row.get(1)?;
        let album_title: String = row.get(2)?;
        println!("{singer_id} {album_id} {album_title}");
    }

    Ok(())
}

PostgreSQL

use google_cloud_spanner::client::DatabaseClient;
use google_cloud_spanner::key::KeySet;
use google_cloud_spanner::read::ReadRequest;
use google_cloud_spanner::statement::Statement;

pub async fn sample(client: &DatabaseClient) -> anyhow::Result<()> {
    let transaction = client.read_only_transaction().build().await?;

    // 1. Execute a query using the read-only transaction
    let statement = Statement::builder("SELECT SingerId, AlbumId, AlbumTitle FROM Albums").build();
    let mut result_set = transaction.execute_query(statement).await?;
    println!("Results from query:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get(0)?;
        let album_id: i64 = row.get(1)?;
        let album_title: String = row.get(2)?;
        println!("{singer_id} {album_id} {album_title}");
    }

    // 2. Execute a read using the same read-only transaction
    let read_request = ReadRequest::builder("Albums", ["SingerId", "AlbumId", "AlbumTitle"])
        .with_keys(KeySet::all())
        .build();
    let mut result_set = transaction.execute_read(read_request).await?;
    println!("Results from read:");
    while let Some(row) = result_set.next().await.transpose()? {
        let singer_id: i64 = row.get(0)?;
        let album_id: i64 = row.get(1)?;
        let album_title: String = row.get(2)?;
        println!("{singer_id} {album_id} {album_title}");
    }

    Ok(())
}

Run the sample using the readonlytransaction argument.

GoogleSQL

cargo run --bin spanner_sample -- \
    readonlytransaction test-instance example-db

PostgreSQL

cargo run --bin pg_spanner_sample -- \
    readonlytransaction test-instance example-db

Cleanup

To avoid incurring additional charges to your Cloud Billing account for the resources used in this tutorial, drop the database and delete the instance that you created.

Delete the database

If you delete an instance, all databases within it are automatically deleted. This step shows how to delete a database without deleting an instance (you would still incur charges for the instance).

On the command line

gcloud spanner databases delete example-db --instance=test-instance

Using the Google Cloud console

  1. Go to the Spanner Instances page in the Google Cloud console.

    Go to the Instances page

  2. Click the instance.

  3. Click the database that you want to delete.

  4. In the Database details page, click Delete.

  5. Confirm that you want to delete the database and click Delete.

Delete the instance

Deleting an instance automatically drops all databases created in that instance.

On the command line

gcloud spanner instances delete test-instance

Using the Google Cloud console

  1. Go to the Spanner Instances page in the Google Cloud console.

    Go to the Instances page

  2. Click your instance.

  3. Click Delete.

  4. Confirm that you want to delete the instance and click Delete.

What's next