### Quickstart: Execute a Query with Cloud Spanner Go Client Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries This Go example demonstrates connecting to a Cloud Spanner database and executing a simple query. ```go // Sample spanner_quickstart is a basic program that uses Cloud Spanner. package main import ( "context" "fmt" "log" "cloud.google.com/go/spanner" "google.golang.org/api/iterator" ) func main() { ctx := context.Background() // This database must exist. databaseName := "projects/your-project-id/instances/your-instance-id/databases/your-database-id" client, err := spanner.NewClient(ctx, databaseName) if err != nil { log.Fatalf("Failed to create client %v", err) } defer client.Close() stmt := spanner.Statement{SQL: "SELECT 1"} iter := client.Single().Query(ctx, stmt) defer iter.Stop() for { row, err := iter.Next() if err == iterator.Done { fmt.Println("Done") return } if err != nil { log.Fatalf("Query failed with %v", err) } var i int64 if row.Columns(&i) != nil { log.Fatalf("Failed to parse row %v", err) } fmt.Printf("Got value %v\n", i) } } ``` -------------------------------- ### Quickstart: Execute a Query with Cloud Spanner Client Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries This C++ example demonstrates how to connect to a Cloud Spanner database and execute a simple query to retrieve 'Hello World'. ```cpp #include "google/cloud/spanner/client.h" void Quickstart(std::string const& project_id, std::string const& instance_id, std::string const& database_id) { namespace spanner = ::google::cloud::spanner; auto database = spanner::Database(project_id, instance_id, database_id); auto connection = spanner::MakeConnection(database); auto client = spanner::Client(connection); auto rows = client.ExecuteQuery(spanner::SqlStatement("SELECT 'Hello World'")); using RowType = std::tuple; for (auto& row : spanner::StreamOf(rows)) { if (!row) throw std::move(row).status(); std::cout << std::get<0>(*row) << "\n"; } } ``` -------------------------------- ### Quickstart: Execute a Query with Cloud Spanner .NET Client Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries This C# example shows how to connect to a Cloud Spanner database and execute a query to retrieve 'Hello World' using the .NET client library. ```csharp using Google.Cloud.Spanner.Data; using System; using System.Threading.Tasks; namespace GoogleCloudSamples.Spanner { public class QuickStart { static async Task MainAsync() { string projectId = "YOUR-PROJECT-ID"; string instanceId = "my-instance"; string databaseId = "my-database"; string connectionString = $"Data Source=projects/{projectId}/instances/{instanceId}/" \ + $"databases/{databaseId}"; // Create connection to Cloud Spanner. using (var connection = new SpannerConnection(connectionString)) { // Execute a simple SQL statement. var cmd = connection.CreateSelectCommand( @"SELECT \"Hello World\" as test"); using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { Console.WriteLine( reader.GetFieldValue("test")); } } } } public static void Main(string[] args) { MainAsync().Wait(); } } } ``` -------------------------------- ### Execute DDL Batch Example Source: https://docs.cloud.google.com/spanner/docs/pgadapter-session-mgmt-commands Demonstrates starting a DDL batch, buffering CREATE TABLE statements, and then executing them as a single batch using RUN BATCH. ```sql -- Start a DDL batch. All following statements must be DDL statements. START BATCH DDL; -- This statement is buffered locally until RUN BATCH is executed. CREATE TABLE singers ( id bigint primary key, first_name varchar, last_name varchar ); -- This statement is buffered locally until RUN BATCH is executed. CREATE TABLE albums ( id bigint primary key, title varchar, singer_id bigint, constraint fk_albums_singers foreign key (singer_id) references singers (id) ); -- This runs the DDL statements as one batch. RUN BATCH; ``` -------------------------------- ### Example: Begin Transaction Source: https://docs.cloud.google.com/spanner/docs/jdbc-session-mgmt-commands Shows how to start read-write and read-only transactions, including setting the default READONLY mode and explicitly setting transaction types after BEGIN. ```sql -- This starts a transaction using the current defaults of this connection. -- The value of READONLY determines whether the transaction is a -- read-write or a read-only transaction. BEGIN; INSERT INTO T (id, col_a, col_b) VALUES (1, 100, 1); COMMIT; -- Set READONLY to TRUE to use read-only transactions by default. SET READONLY=TRUE; -- This starts a read-only transaction. BEGIN; SELECT FirstName, LastName FROM Singers ORDER BY LastName; COMMIT; -- Execute 'SET TRANSACTION READ WRITE' or 'SET TRANSACTION READ ONLY' directly -- after the BEGIN statement to override the current default of the connection. SET READONLY=FALSE; BEGIN; SET TRANSACTION READ ONLY; SELECT FirstName, LastName FROM Singers ORDER BY LastName; COMMIT; ``` -------------------------------- ### Install Go Spanner Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries Use 'go get' to install the Spanner client library for Go. Refer to the Go development environment setup guide for more details. ```go go get cloud.google.com/go/spanner/... ``` -------------------------------- ### Install Node.js Spanner Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries Use npm to install the Google Cloud Spanner client library for Node.js. Refer to the Node.js development environment setup guide for more details. ```javascript npm install @google-cloud/spanner ``` -------------------------------- ### Example Encryption Info Output Source: https://docs.cloud.google.com/spanner/docs/use-cmek This is an example of the output you might see when describing a Spanner database, showing the encryption type and KMS key version. ```yaml name: projects/my-project/instances/test-instance/databases/example-db encryptionInfo: - encryptionType: CUSTOMER_MANAGED_ENCRYPTION kmsKeyVersion: projects/my-kms-project/locations/my-kms-key1-location/keyRings/my-kms-key-ring1/cryptoKeys/my-kms-key1/cryptoKeyVersions/1 - encryptionType: CUSTOMER_MANAGED_ENCRYPTION kmsKeyVersion: projects/my-kms-project/locations/my-kms-key2-location/keyRings/my-kms-key-ring2/cryptoKeys/my-kms-key2/cryptoKeyVersions/1 ``` -------------------------------- ### Install Ruby Spanner Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries Use the 'gem' command to install the Google Cloud Spanner client library for Ruby. Refer to the Ruby development environment setup guide for more details. ```ruby gem install google-cloud-spanner ``` -------------------------------- ### Create a Free Trial Instance using gcloud CLI (Example) Source: https://docs.cloud.google.com/spanner/docs/free-trial-quickstart Example command to create a free trial instance with specific parameters. Ensure the instance ID is unique and the configuration is valid. ```bash gcloud spanner instances create trial-instance --config=regional-us-east5 \ --instance-type=free-instance --description="Trial Instance" ``` -------------------------------- ### Install Python Spanner Library Source: https://docs.cloud.google.com/spanner/docs/reference/libraries Use pip to install or upgrade the Google Cloud Spanner client library for Python. Refer to the Python development environment setup guide for more details. ```python pip install --upgrade google-cloud-spanner ``` -------------------------------- ### create Source: https://docs.cloud.google.com/spanner/docs/reference/rest/v1/projects.instances Creates an instance and begins preparing it to begin serving. ```APIDOC ## create ### Description Creates an instance and begins preparing it to begin serving. ### Method POST ### Endpoint /v1/projects/{projectId}/instances ### Parameters #### Path Parameters - **projectId** (string) - Required - The ID of the project in which the instance should be created. #### Request Body - **instance** (Instance) - Required - The instance to create. The name of the instance is not required. The instance's `config` field is required. ### Response #### Success Response (200) - **instance** (Instance) - The created instance, which will be in a `CREATING` state. ### Response Example { "instance": { "name": "projects/my-project/instances/my-instance", "config": "projects/my-project/instanceConfigs/regional-us-central1", "displayName": "My Instance", "nodeCount": 1, "state": "CREATING" } } ``` -------------------------------- ### Clone Sample App Repository Source: https://docs.cloud.google.com/spanner/docs/getting-started/ruby Clone the sample application repository to your local machine to get started with Cloud Spanner examples in Ruby. ```bash git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples ``` -------------------------------- ### Create CMEK backup (Ruby) Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this Ruby snippet to create a CMEK-enabled backup for a database in a regional Spanner instance configuration. Ensure you have the necessary Google Cloud Spanner client libraries installed. ```ruby # project_id = "Your Google Cloud project ID" # instance_id = "Your Spanner instance ID" # database_id = "Your Spanner database ID" # backup_id = "Your Spanner backup ID" # kms_key_name = "Your backup encryption database KMS key" require "google/cloud/spanner" require "google/cloud/spanner/admin/database" database_admin_client = Google::Cloud::Spanner::Admin::Database.database_admin instance_path = database_admin_client.instance_path project: project_id, instance: instance_id db_path = database_admin_client.database_path project: project_id, instance: instance_id, database: database_id backup_path = database_admin_client.backup_path project: project_id, instance: instance_id, backup: backup_id expire_time = Time.now + (14 * 24 * 3600) # 14 days from now encryption_config = { encryption_type: :CUSTOMER_MANAGED_ENCRYPTION, kms_key_name: kms_key_name } job = database_admin_client.create_backup parent: instance_path, backup_id: backup_id, backup: { database: db_path, expire_time: expire_time }, encryption_config: encryption_config puts "Backup operation in progress" job.wait_until_done! backup = database_admin_client.get_backup name: backup_path puts "Backup #{backup_id} of size #{backup.size_bytes} bytes was created at #{backup.create_time} using encryption key #{kms_key_name} ``` -------------------------------- ### Create a Free Trial Instance using gcloud CLI (Template) Source: https://docs.cloud.google.com/spanner/docs/free-trial-quickstart Use this command template to create a free trial instance. Replace placeholders with your specific instance details. ```bash gcloud spanner instances create INSTANCE_ID \ --instance-type=free-instance --config=INSTANCE_CONFIG \ --description=INSTANCE_DESCRIPTION ``` -------------------------------- ### Start Antigravity CLI Source: https://docs.cloud.google.com/spanner/docs/build-context-gemini-cli Start the Antigravity CLI after installing the context engineering agent plugin. ```bash agy ``` -------------------------------- ### Get Current Query Start Time with mysql.NOW Source: https://docs.cloud.google.com/spanner/docs/reference/mysql/timestamp_functions Returns the TIMESTAMP at which the current query statement started to run. This function is an alias for mysql.LOCALTIME() and mysql.LOCALTIMESTAMP(). ```sql SELECT mysql.NOW() as current_query_time; /* +-------------------------------+ | current_query_time | +-------------------------------+ | 2025-06-03 12:28:32.123456+00 | +-------------------------------+ */ ``` -------------------------------- ### Create Instance Partition Source: https://docs.cloud.google.com/spanner/docs/reference/rest Creates an instance partition and begins preparing it to be used. ```APIDOC ## POST /v1/{parent=projects/*/instances/*}/instancePartitions ### Description Creates an instance partition and begins preparing it to be used. ### Method POST ### Endpoint /v1/{parent=projects/*/instances/*}/instancePartitions ``` -------------------------------- ### Create CMEK-enabled database (Multi-region) Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this Python snippet to create a Spanner database with multiple KMS keys for encryption in a multi-region instance. Ensure the google-cloud-spanner library is installed. ```python def create_database_with_multiple_kms_keys(instance_id, database_id, kms_key_names): """Creates a database with tables using multiple KMS keys(CMEK).""" from google.cloud.spanner_admin_database_v1 import EncryptionConfig from google.cloud.spanner_admin_database_v1.types import spanner_database_admin spanner_client = spanner.Client() database_admin_api = spanner_client.database_admin_api request = spanner_database_admin.CreateDatabaseRequest( parent=database_admin_api.instance_path(spanner_client.project, instance_id), create_statement=f"CREATE DATABASE `{database_id}`", extra_statements=[ "CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId)", "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", ], encryption_config=EncryptionConfig(kms_key_names=kms_key_names), ) operation = database_admin_api.create_database(request=request) print("Waiting for operation to complete...") database = operation.result(OPERATION_TIMEOUT_SECONDS) print( "Database {} created with multiple KMS keys {}".format( database.name, database.encryption_config.kms_key_names ) ) ``` -------------------------------- ### Create CMEK-enabled backup (multi-region) Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this C# snippet to create a CMEK-enabled backup for a multi-region Cloud Spanner instance. Ensure you have the necessary Google Cloud client libraries installed. ```csharp using Google.Cloud.Spanner.Admin.Database.V1; using Google.Cloud.Spanner.Common.V1; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Threading.Tasks; public class CreateBackupWithMultiRegionEncryptionAsyncSample { public async Task CreateBackupWithMultiRegionEncryptionAsync(string projectId, string instanceId, string databaseId, string backupId, IEnumerable kmsKeyNames) { // Create a DatabaseAdminClient instance. DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); // Create the CreateBackupRequest with encryption configuration. CreateBackupRequest request = new CreateBackupRequest { ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId), BackupId = backupId, Backup = new Backup { DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId), ExpireTime = DateTime.UtcNow.AddDays(14).ToTimestamp(), }, EncryptionConfig = new CreateBackupEncryptionConfig { EncryptionType = CreateBackupEncryptionConfig.Types.EncryptionType.CustomerManagedEncryption, KmsKeyNamesAsCryptoKeyNames = { kmsKeyNames }, }, }; // Execute the CreateBackup request. var operation = await databaseAdminClient.CreateBackupAsync(request); Console.WriteLine("Waiting for the operation to finish."); // Poll until the returned long-running operation is complete. var completedResponse = await operation.PollUntilCompletedAsync(); if (completedResponse.IsFaulted) { Console.WriteLine($"Error while creating backup: {completedResponse.Exception}"); throw completedResponse.Exception; } var backup = completedResponse.Result; Console.WriteLine($"Backup {backup.Name} of size {backup.SizeBytes} bytes was created with encryption keys {string.Join(", ", kmsKeyNames)} at {backup.CreateTime}"); return backup; } } ``` -------------------------------- ### Get Current Query Start Time with mysql.LOCALTIME Source: https://docs.cloud.google.com/spanner/docs/reference/mysql/timestamp_functions Returns the TIMESTAMP when the current query statement started to run. This function is an alias for mysql.NOW() and mysql.LOCALTIMESTAMP(). ```sql SELECT mysql.LOCALTIME() as current_query_time; /* +-------------------------------+ | current_query_time | +-------------------------------+ | 2025-06-03 12:28:32.123456+00 | +-------------------------------+ */ ``` -------------------------------- ### Run Partitioned DML Example (GoogleSQL) Source: https://docs.cloud.google.com/spanner/docs/getting-started/ado_net Command to execute the Partitioned DML example using the GoogleSQL dialect. Ensure you replace PROJECT_ID and the database path with your specific details. ```bash dotnet run pdml projects/PROJECT_ID/instances/test-instance/databases/example-db ``` -------------------------------- ### Run the C# Sample Source: https://docs.cloud.google.com/spanner/docs/getting-started/csharp This command shows how to execute the C# sample code from the command line. Ensure you have the necessary environment variables set for project ID. ```bash dotnet run queryDataWithTransaction $env:PROJECT_ID test-instance example-db ``` -------------------------------- ### Install SQLAlchemy Spanner Dialect from Source Source: https://docs.cloud.google.com/spanner/docs/use-sqlalchemy Alternatively, install the dialect by cloning the GitHub repository and running the setup script. This is useful for development or when needing the latest unreleased changes. ```bash git clone https://github.com/googleapis/python-spanner-sqlalchemy.git cd python-spanner-sqlalchemy python setup.py install ``` -------------------------------- ### Run PGAdapter Emulator with Docker Source: https://docs.cloud.google.com/spanner/docs/getting-started/pgadapter Start PGAdapter with an embedded Spanner emulator using Docker. This setup automatically creates instances and databases, simplifying local development without manual setup. ```bash docker pull gcr.io/cloud-spanner-pg-adapter/pgadapter-emulator docker run \ --name pgadapter-emulator \ --rm -d \ -p 5432:5432 \ -p 9010:9010 \ -p 9020:9020 \ gcr.io/cloud-spanner-pg-adapter/pgadapter-emulator ``` -------------------------------- ### Example: Create Custom Configuration with Read-Only Replicas Source: https://docs.cloud.google.com/spanner/docs/create-manage-configurations This example demonstrates creating a custom instance configuration by cloning the 'eur6' base configuration and adding two read-only replicas in 'us-east1'. ```bash gcloud spanner instance-configs create custom-eur6 --clone-config=eur6 \ --add-replicas=location=us-east1,type=READ_ONLY:location=us-east1,type=READ_ONLY ``` -------------------------------- ### Create or Get Spanner Service Agent Source: https://docs.cloud.google.com/spanner/docs/use-cmek This command creates or retrieves the service agent that Spanner uses to access Cloud KMS keys on your behalf. Ensure the gcloud Beta Commands component is installed if prompted. ```bash gcloud beta services identity create --service=spanner.googleapis.com \ --project=PROJECT_ID ``` -------------------------------- ### Example output for a CMEK-enabled Spanner database description Source: https://docs.cloud.google.com/spanner/docs/use-cmek This output shows the "encryptionConfig" field, indicating that the Spanner database is CMEK-enabled. It includes the KMS key name used for encryption. ```yaml encryptionConfig: kmsKeyNames:projects/my-kms-project/locations/eur5/keyRings/my-kms-key-ring/cryptoKeys/my-kms-key name: projects/my-spanner-project/instances/my-instance/databases/my-db state: READY ``` -------------------------------- ### Copy CMEK-enabled backup with multiple KMS keys (Ruby) Source: https://docs.cloud.google.com/spanner/docs/use-cmek This Ruby snippet demonstrates how to copy a CMEK-enabled backup, specifying multiple KMS key names. Ensure the Google Cloud Spanner client libraries for Ruby are installed and configured. ```ruby # project_id = "Your Google Cloud project ID" # instance_id = "The ID of the destination instance that will contain the backup copy" # backup_id = "The ID of the backup copy" # source_backup = "The source backup to be copied" # kms_key_names = ["key1", "key2", "key3"] require "google/cloud/spanner" require "google/cloud/spanner/admin/database" database_admin_client = Google::Cloud::Spanner::Admin::Database.database_admin instance_path = database_admin_client.instance_path( project: project_id, instance: instance_id ) backup_path = database_admin_client.backup_path project: project_id, instance: instance_id, backup: backup_id source_backup = database_admin_client.backup_path project: project_id, instance: instance_id, backup: source_backup_id expire_time = Time.now + (14 * 24 * 3600) # 14 days from now encryption_config = { encryption_type: :CUSTOMER_MANAGED_ENCRYPTION, kms_key_names: kms_key_names } job = database_admin_client.copy_backup parent: instance_path, backup_id: backup_id, source_backup: source_backup, expire_time: expire_time, encryption_config: encryption_config puts "Copy backup operation in progress" job.wait_until_done! backup = database_admin_client.get_backup name: backup_path puts "Backup #{backup_id} of size #{backup.size_bytes} bytes was copied at " \ "#{backup.create_time}" from #{source_backup} for version " \ "#{backup.version_time} using encryption keys #{kms_key_names} ``` -------------------------------- ### UNIX_DATE Function Example Source: https://docs.cloud.google.com/spanner/docs/reference/standard-sql/date_functions Demonstrates how to use the UNIX_DATE function to get the number of days since 1970-01-01. ```sql SELECT UNIX_DATE(DATE '2008-12-25') AS days_from_epoch; /*-----------------+ | days_from_epoch | +-----------------+ | 14238 | +-----------------*/ ``` -------------------------------- ### v1.projects.instances.create Source: https://docs.cloud.google.com/spanner/docs/reference/rest Creates a new instance and prepares it for serving. ```APIDOC ## POST /v1/{parent=projects/*}/instances ### Description Creates an instance and begins preparing it to begin serving. ### Method POST ### Endpoint /v1/{parent=projects/*}/instances ``` -------------------------------- ### Get Spanner Instance Locations Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this command to retrieve a list of replica locations for your Spanner instance configuration. This is useful for ensuring your Cloud KMS key ring location matches your Spanner instance configuration. ```bash gcloud spanner instances get-locations INSTANCE_ID ``` -------------------------------- ### Get Database DDL Statements (Node.js) Source: https://docs.cloud.google.com/spanner/docs/modifying-leader-region Retrieves the schema definition of a Spanner database. Ensure the Spanner client library is installed and configured. ```javascript // TODO(developer): Uncomment the following lines before running the sample. // const projectId = 'my-project-id'; // const instanceId = 'my-instance-id'; // const databaseId = 'my-database-id'; // Imports the Google Cloud client library const { Spanner } = require('@google-cloud/spanner'); // creates a client const spanner = new Spanner({ projectId: projectId, }); const databaseAdminClient = spanner.getDatabaseAdminClient(); async function getDatabaseDdl() { // Get the schema definition of the database. const [ddlStatements] = await databaseAdminClient.getDatabaseDdl({ database: databaseAdminClient.databasePath( projectId, instanceId, databaseId, ), }); console.log( `Retrieved database DDL for ${databaseAdminClient.databasePath( projectId, instanceId, databaseId, )}:`, ); ddlStatements.statements.forEach(element => { console.log(element); }); } getDatabaseDdl(); ``` -------------------------------- ### v1.projects.instanceConfigs.create Source: https://docs.cloud.google.com/spanner/docs/reference/rest Creates a new instance configuration and initiates its preparation. ```APIDOC ## POST /v1/{parent=projects/*}/instanceConfigs ### Description Creates an instance configuration and begins preparing it to be used. ### Method POST ### Endpoint /v1/{parent=projects/*}/instanceConfigs ``` -------------------------------- ### Create CMEK-enabled database (Regional) Source: https://docs.cloud.google.com/spanner/docs/use-cmek This Ruby snippet creates a Spanner database with a single KMS key for encryption in a regional instance. Ensure the google-cloud-spanner and google-cloud-spanner-admin-database gems are installed. ```ruby # project_id = "Your Google Cloud project ID" # instance_id = "Your Spanner instance ID" # database_id = "Your Spanner database ID" # kms_key_name = "Database eencryption KMS key" require "google/cloud/spanner" require "google/cloud/spanner/admin/database" database_admin_client = Google::Cloud::Spanner::Admin::Database.database_admin instance_path = database_admin_client.instance_path project: project_id, instance: instance_id db_path = database_admin_client.database_path project: project_id, instance: instance_id, database: database_id job = database_admin_client.create_database parent: instance_path, create_statement: "CREATE DATABASE `#{database_id}`", extra_statements: [ "CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId)", "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" ], encryption_config: { kms_key_name: kms_key_name } puts "Waiting for create database operation to complete" job.wait_until_done! database = database_admin_client.get_database name: db_path puts "Database #{database_id} created with encryption key #{database.encryption_config.kms_key_name}" ``` -------------------------------- ### Run Go Sample Source: https://docs.cloud.google.com/spanner/docs/getting-started/go This command shows how to execute the Go sample code for read-only transactions. Replace PROJECT_ID and other placeholders with your actual Spanner instance and database details. ```bash go run snippet.go readonlytransaction projects/PROJECT_ID/instances/test-instance/databases/example-db ``` -------------------------------- ### SPLIT_SUBSTR with multi-character delimiter and overlapping matches (example 2) Source: https://docs.cloud.google.com/spanner/docs/reference/standard-sql/string_functions Demonstrates SPLIT_SUBSTR with a multi-character delimiter ('**') and overlapping matches, starting the split from the second position. ```sql SELECT SPLIT_SUBSTR('aaa***bbb***ccc', '**', 2, 2) AS example /*------------+ | example | +------------+ | *bbb***ccc | +-----------*/ ``` -------------------------------- ### Create CMEK-enabled backup with multiple KMS keys Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this snippet to create a backup of a Cloud Spanner database that is encrypted using multiple Customer-Managed Encryption Keys (CMEK). Ensure the necessary Google Cloud client libraries are installed and authenticated. ```javascript /** * TODO(developer): Uncomment the following lines before running the sample. */ // const projectId = 'my-project-id'; // const instanceId = 'my-instance'; // const databaseId = 'my-database'; // const backupId = 'my-backup'; // const kmsKeyNames = // 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key1, // 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key2'; // Imports the Google Cloud client library const {Spanner, protos} = require('@google-cloud/spanner'); const {PreciseDate} = require('@google-cloud/precise-date'); // Creates a client const spanner = new Spanner({ projectId: projectId, }); // Gets a reference to a Cloud Spanner Database Admin Client object const databaseAdminClient = spanner.getDatabaseAdminClient(); async function createBackupWithMultipleKmsKeys() { // Creates a new backup of the database try { console.log( `Creating backup of database ${databaseAdminClient.databasePath( projectId, instanceId, databaseId, )}.`, ); // Expire backup 14 days in the future const expireTime = Date.now() + 1000 * 60 * 60 * 24 * 14; // Create a backup of the state of the database at the current time. const [operation] = await databaseAdminClient.createBackup({ parent: databaseAdminClient.instancePath(projectId, instanceId), backupId: backupId, backup: (protos.google.spanner.admin.database.v1.Backup = { database: databaseAdminClient.databasePath( projectId, instanceId, databaseId, ), expireTime: Spanner.timestamp(expireTime).toStruct(), name: databaseAdminClient.backupPath(projectId, instanceId, backupId), }), encryptionConfig: { encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', kmsKeyNames: kmsKeyNames.split(','), }, }); console.log( `Waiting for backup ${databaseAdminClient.backupPath( projectId, instanceId, backupId, )} to complete...`, ); await operation.promise(); // Verify backup is ready const [backupInfo] = await databaseAdminClient.getBackup({ name: databaseAdminClient.backupPath(projectId, instanceId, backupId), }); const kmsKeyVersions = backupInfo.encryptionInformation .map(encryptionInfo => encryptionInfo.kmsKeyVersion) .join(', '); if (backupInfo.state === 'READY') { console.log( `Backup ${backupInfo.name} of size ` + `${backupInfo.sizeBytes} bytes was created at ` + `${new PreciseDate(backupInfo.createTime).toISOString()} ` + `using encryption key ${kmsKeyVersions}`, ); } else { console.error('ERROR: Backup is not ready.'); } } catch (err) { console.error('ERROR:', err); } finally { // Close the spanner client when finished. // The databaseAdminClient does not require explicit closure. The closure of the Spanner client will automatically close the databaseAdminClient. spanner.close(); } } createBackupWithMultipleKmsKeys(); ``` -------------------------------- ### Run Data Boost Example (CLI) Source: https://docs.cloud.google.com/spanner/docs/getting-started/pgadapter Execute a Data Boost example using the command line for a specified database. ```bash dotnet run databoost example-db ``` ```bash php data_boost.php example-db ``` -------------------------------- ### KeyRange Example: All Events for Bob Source: https://docs.cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1 Defines a key range to retrieve all events for a specific user ('Bob'). This range is inclusive of the start and end keys. ```json { "start_closed": ["Bob"] "end_closed": ["Bob"] } ``` -------------------------------- ### Restore CMEK Backup to Regional Instance (Python) Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this Python snippet to restore a CMEK-encrypted backup to a Spanner instance in a regional configuration. Ensure the `google-cloud-spanner` library is installed. ```python def restore_database_with_encryption_key( instance_id, new_database_id, backup_id, kms_key_name ): """Restores a database from a backup using a Customer Managed Encryption Key (CMEK).""" from google.cloud.spanner_admin_database_v1 import ( RestoreDatabaseEncryptionConfig, RestoreDatabaseRequest, ) spanner_client = spanner.Client() database_admin_api = spanner_client.database_admin_api # Start restoring an existing backup to a new database. encryption_config = { "encryption_type": RestoreDatabaseEncryptionConfig.EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, "kms_key_name": kms_key_name, } request = RestoreDatabaseRequest( parent=database_admin_api.instance_path(spanner_client.project, instance_id), database_id=new_database_id, backup=database_admin_api.backup_path( spanner_client.project, instance_id, backup_id ), encryption_config=encryption_config, ) operation = database_admin_api.restore_database(request) # Wait for restore operation to complete. db = operation.result(1600) # Newly created database has restore information. restore_info = db.restore_info print( "Database {} restored to {} from backup {} with using encryption key {}.".format( restore_info.backup_info.source_database, new_database_id, restore_info.backup_info.backup, db.encryption_config.kms_key_name, ) ) ``` -------------------------------- ### Restore CMEK-enabled Backup in Multi-Region Instance (C#) Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this C# code to restore a CMEK-enabled backup to a multi-region Cloud Spanner instance. Ensure you have the necessary Google Cloud client libraries installed. ```csharp using Google.Cloud.Spanner.Admin.Database.V1; using Google.Cloud.Spanner.Common.V1; using System; using System.Collections.Generic; using System.Threading.Tasks; public class RestoreDatabaseWithMultiRegionEncryptionAsyncSample { public async Task RestoreDatabaseWithMultiRegionEncryptionAsync(string projectId, string instanceId, string databaseId, string backupId, IEnumerable kmsKeyNames) { // Create a DatabaseAdminClient instance. DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); // Create the RestoreDatabaseRequest with encryption configuration. RestoreDatabaseRequest request = new RestoreDatabaseRequest { ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId), DatabaseId = databaseId, BackupAsBackupName = BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId), EncryptionConfig = new RestoreDatabaseEncryptionConfig { EncryptionType = RestoreDatabaseEncryptionConfig.Types.EncryptionType.CustomerManagedEncryption, KmsKeyNamesAsCryptoKeyNames = { kmsKeyNames }, } }; // Execute the RestoreDatabase request. var operation = await databaseAdminClient.RestoreDatabaseAsync(request); Console.WriteLine("Waiting for the operation to finish."); // Poll until the returned long-running operation is complete. var completedResponse = await operation.PollUntilCompletedAsync(); if (completedResponse.IsFaulted) { Console.WriteLine($"Error while restoring database: {completedResponse.Exception}"); throw completedResponse.Exception; } var database = completedResponse.Result; var restoreInfo = database.RestoreInfo; Console.WriteLine($"Database {restoreInfo.BackupInfo.SourceDatabase} restored to {database.Name} from backup {restoreInfo.BackupInfo.Backup} using encryption keys {string.Join(", ", kmsKeyNames)}"); return database; } } ``` -------------------------------- ### Restore CMEK Backup to Regional Instance (Ruby) Source: https://docs.cloud.google.com/spanner/docs/use-cmek This Ruby snippet demonstrates how to restore a CMEK-encrypted backup to a Spanner instance in a regional configuration. Ensure you have the `google-cloud-spanner` gem installed. ```ruby # project_id = "Your Google Cloud project ID" # instance_id = "Your Spanner instance ID" # database_id = "Your Spanner database ID of where to restore" # backup_id = "Your Spanner backup ID" # kms_key_name = "Your backup encryption database KMS key" require "google/cloud/spanner" require "google/cloud/spanner/admin/database" database_admin_client = Google::Cloud::Spanner::Admin::Database.database_admin instance_path = database_admin_client.instance_path project: project_id, instance: instance_id db_path = database_admin_client.database_path project: project_id, instance: instance_id, database: database_id backup_path = database_admin_client.backup_path project: project_id, instance: instance_id, backup: backup_id encryption_config = { encryption_type: :CUSTOMER_MANAGED_ENCRYPTION, kms_key_name: kms_key_name } job = database_admin_client.restore_database parent: instance_path, database_id: database_id, backup: backup_path, encryption_config: encryption_config puts "Waiting for restore backup operation to complete" job.wait_until_done! database = database_admin_client.get_database name: db_path restore_info = database.restore_info puts "Database #{restore_info.backup_info.source_database} was restored to #{database_id} from backup #{restore_info.backup_info.backup} using encryption key #{database.encryption_config.kms_key_name} ``` -------------------------------- ### Get Current Date in Specified Time Zone (America/Los_Angeles) Source: https://docs.cloud.google.com/spanner/docs/reference/standard-sql/date_functions Retrieves the current date for a specific time zone. The date is set at the start of the query. ```sql SELECT CURRENT_DATE('America/Los_Angeles') AS the_date; ``` -------------------------------- ### Run Partitioned DML Example (PostgreSQL) Source: https://docs.cloud.google.com/spanner/docs/getting-started/ado_net Command to execute the Partitioned DML example using the PostgreSQL dialect. Ensure you replace PROJECT_ID and the database path with your specific details. ```bash dotnet run pdmlpg projects/PROJECT_ID/instances/test-instance/databases/example-db ``` -------------------------------- ### Create Regional CMEK Database (Python) Source: https://docs.cloud.google.com/spanner/docs/use-cmek This Python snippet creates a regional Cloud Spanner database with CMEK. It requires the instance ID, database ID, and the KMS key name for encryption. The example includes table definitions for Singers and Albums. ```python def create_database_with_encryption_key(instance_id, database_id, kms_key_name): """Creates a database with tables using a Customer Managed Encryption Key (CMEK).""" from google.cloud.spanner_admin_database_v1 import EncryptionConfig from google.cloud.spanner_admin_database_v1.types import spanner_database_admin spanner_client = spanner.Client() database_admin_api = spanner_client.database_admin_api request = spanner_database_admin.CreateDatabaseRequest( parent=database_admin_api.instance_path(spanner_client.project, instance_id), create_statement=f"CREATE DATABASE `{database_id}`", extra_statements=[ """CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX) ) PRIMARY KEY (SingerId)""", """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""", ], encryption_config=EncryptionConfig(kms_key_name=kms_key_name), ) operation = database_admin_api.create_database(request=request) print("Waiting for operation to complete...") database = operation.result(OPERATION_TIMEOUT_SECONDS) print( "Database {} created with encryption key {}".format( database.name, database.encryption_config.kms_key_name ) ) ``` -------------------------------- ### Create CMEK-enabled backup in Cloud Spanner Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this PHP function to create a backup for a Cloud Spanner database that is encrypted with a Customer-Managed Encryption Key (CMEK). Ensure you have the necessary Google Cloud client libraries installed and authenticated. ```PHP use Google\Cloud\Spanner\Admin\Database\V1\Backup; use \Google\Cloud\Spanner\Admin\Database\V1\Backup\State; use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Database\V1\CreateBackupEncryptionConfig; use Google\Cloud\Spanner\Admin\Database\V1\CreateBackupRequest; use Google\Cloud\Spanner\Admin\Database\V1\GetBackupRequest; use Google\Protobuf\Timestamp; /** * Create an encrypted backup. * Example: * ``` * create_backup_with_encryption_key($projectId, $instanceId, $databaseId, $backupId, $kmsKeyName); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. * @param string $backupId The Spanner backup ID. * @param string $kmsKeyName The KMS key used for encryption. */ function create_backup_with_encryption_key( string $projectId, string $instanceId, string $databaseId, string $backupId, string $kmsKeyName ): void { $databaseAdminClient = new DatabaseAdminClient(); $instanceFullName = DatabaseAdminClient::instanceName($projectId, $instanceId); $databaseFullName = DatabaseAdminClient::databaseName($projectId, $instanceId, $databaseId); $expireTime = new Timestamp(); $expireTime->setSeconds((new DateTime('+14 days'))->getTimestamp()); $request = new CreateBackupRequest([ 'parent' => $instanceFullName, 'backup_id' => $backupId, 'encryption_config' => new CreateBackupEncryptionConfig([ 'kms_key_name' => $kmsKeyName, 'encryption_type' => CreateBackupEncryptionConfig\EncryptionType::CUSTOMER_MANAGED_ENCRYPTION ]), 'backup' => new Backup([ 'database' => $databaseFullName, 'expire_time' => $expireTime ]) ]); $operation = $databaseAdminClient->createBackup($request); print('Waiting for operation to complete...' . PHP_EOL); $operation->pollUntilComplete(); $request = new GetBackupRequest(); $request->setName($databaseAdminClient->backupName($projectId, $instanceId, $backupId)); $info = $databaseAdminClient->getBackup($request); if (State::name($info->getState()) == 'READY') { printf( 'Backup %s of size %d bytes was created at %d using encryption key %s' . PHP_EOL, basename($info->getName()), $info->getSizeBytes(), $info->getCreateTime()->getSeconds(), $info->getEncryptionInfo()->getKmsKeyVersion() ); } else { print('Backup is not ready!' . PHP_EOL); } } ``` -------------------------------- ### Copy CMEK-enabled backup with C# Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this C# code to copy a CMEK-enabled backup in a multi-region Spanner instance. Ensure you have the necessary Google Cloud Spanner Admin Database client library installed. ```csharp using Google.Cloud.Spanner.Admin.Database.V1; using Google.Cloud.Spanner.Common.V1; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Threading.Tasks; public class CopyBackupWithMultiRegionEncryptionAsyncSample { public async Task CopyBackupWithMultiRegionEncryptionAsync( string sourceProjectId, string sourceInstanceId, string sourceBackupId, string targetProjectId, string targetInstanceId, string targetBackupId, DateTimeOffset expireTime, IEnumerable kmsKeyNames) { DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); var request = new CopyBackupRequest { SourceBackupAsBackupName = new BackupName(sourceProjectId, sourceInstanceId, sourceBackupId), ParentAsInstanceName = new InstanceName(targetProjectId, targetInstanceId), BackupId = targetBackupId, ExpireTime = Timestamp.FromDateTimeOffset(expireTime), EncryptionConfig = new CopyBackupEncryptionConfig { EncryptionType = CopyBackupEncryptionConfig.Types.EncryptionType.CustomerManagedEncryption, KmsKeyNamesAsCryptoKeyNames = { kmsKeyNames }, } }; // Execute the CopyBackup request. var operation = await databaseAdminClient.CopyBackupAsync(request); Console.WriteLine("Waiting for the operation to finish."); // Poll until the returned long-running operation is complete. var completedResponse = await operation.PollUntilCompletedAsync(); if (completedResponse.IsFaulted) { Console.WriteLine($"Error while copying backup: {completedResponse.Exception}"); throw completedResponse.Exception; } Backup backup = completedResponse.Result; Console.WriteLine("Backup copied successfully."); Console.WriteLine($"Backup with Id {sourceBackupId} has been copied from {sourceProjectId}/{sourceInstanceId} to {targetProjectId}/{targetInstanceId} Backup {targetBackupId}"); Console.WriteLine($"Backup {backup.Name} of size {backup.SizeBytes} bytes was created with encryption keys {string.Join(", ", kmsKeyNames)} at {backup.CreateTime} from {backup.Database} and is in state {backup.State} and has version time {backup.VersionTime}"); return backup; } } ``` -------------------------------- ### Invalid PostgreSQL Identifiers Source: https://docs.cloud.google.com/spanner/docs/reference/postgresql/lexical Examples of invalid identifiers in PostgreSQL due to starting with a number, containing invalid characters, or being a reserved keyword without quotes. ```sql 5Customers _dataField! GROUP ``` -------------------------------- ### Run DML Write Sample from Command Line Source: https://docs.cloud.google.com/spanner/docs/getting-started/csharp Demonstrates how to execute the C# DML write sample using the .NET CLI. Replace placeholder values with your actual project ID, instance ID, and database ID. ```bash dotnet run writeUsingDml $env:PROJECT_ID test-instance example-db ``` -------------------------------- ### Create CMEK-enabled Cloud Spanner Database Backup Source: https://docs.cloud.google.com/spanner/docs/use-cmek Use this Node.js snippet to create a CMEK-enabled backup of a Cloud Spanner database. Ensure you have the necessary Google Cloud client libraries installed and have uncommented the project, instance, database, backup IDs, and KMS key name variables. ```javascript // Imports the Google Cloud client library const {Spanner, protos} = require('@google-cloud/spanner'); const {PreciseDate} = require('@google-cloud/precise-date'); /** * TODO(developer): Uncomment the following lines before running the sample. */ // const projectId = 'my-project-id'; // const instanceId = 'my-instance'; // const databaseId = 'my-database'; // const backupId = 'my-backup'; // const keyName = // 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key'; // Creates a client const spanner = new Spanner({ projectId: projectId, }); // Gets a reference to a Cloud Spanner Database Admin Client object const databaseAdminClient = spanner.getDatabaseAdminClient(); // Creates a new backup of the database try { console.log( `Creating backup of database ${databaseAdminClient.databasePath( projectId, instanceId, databaseId, )}.`, ); // Expire backup 14 days in the future const expireTime = Date.now() + 1000 * 60 * 60 * 24 * 14; // Create a backup of the state of the database at the current time. const [operation] = await databaseAdminClient.createBackup({ parent: databaseAdminClient.instancePath(projectId, instanceId), backupId: backupId, backup: (protos.google.spanner.admin.database.v1.Backup = { database: databaseAdminClient.databasePath( projectId, instanceId, databaseId, ), expireTime: Spanner.timestamp(expireTime).toStruct(), name: databaseAdminClient.backupPath(projectId, instanceId, backupId), }), encryptionConfig: { encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', kmsKeyName: keyName, }, }); console.log( `Waiting for backup ${databaseAdminClient.backupPath( projectId, instanceId, backupId, )} to complete...`, ); await operation.promise(); // Verify backup is ready const [backupInfo] = await databaseAdminClient.getBackup({ name: databaseAdminClient.backupPath(projectId, instanceId, backupId), }); if (backupInfo.state === 'READY') { console.log( `Backup ${backupInfo.name} of size ` + `${backupInfo.sizeBytes} bytes was created at ` + `${new PreciseDate(backupInfo.createTime).toISOString()} ` + `using encryption key ${backupInfo.encryptionInfo.kmsKeyVersion}`, ); } else { console.error('ERROR: Backup is not ready.'); } } catch (err) { console.error('ERROR:', err); } finally { // Close the spanner client when finished. // The databaseAdminClient does not require explicit closure. The closure of the Spanner client will automatically close the databaseAdminClient. spanner.close(); } ``` -------------------------------- ### CreateInstance Source: https://docs.cloud.google.com/spanner/docs/reference/rpc Creates an instance and begins preparing it to begin serving. ```APIDOC ## CreateInstance ### Description Creates an instance and begins preparing it to begin serving. ### Method Not specified (RPC method) ### Endpoint Not specified (RPC method) ### Parameters Not specified ### Request Example Not specified ### Response Not specified ```