Class Google::Cloud::Spanner::Client (v2.11.0)

Client

A client is used to read and/or modify data in a Cloud Spanner database.

See Project#client.

Inherits

  • Object

Example

require "google/cloud"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query "SELECT * FROM users"

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Methods

#close

def close()

Closes the client connection and releases resources.

#commit

def commit(commit_options: nil, request_options: nil, call_options: nil, &block) { |commit| ... } -> Time, CommitResponse

Creates and commits a transaction for writes that execute atomically at a single logical point in time across columns, rows, and tables in a database.

All changes are accumulated in memory until the block completes. Unlike #transaction, which can also perform reads, this operation accepts only mutations and makes a single API request.

Note: This method does not feature replay protection present in #transaction. This method makes a single RPC, whereas #transaction requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind changes.

Parameters
  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Yields
  • (commit) — The block for mutating the data.
Yield Parameter
Returns
Raises
  • (ArgumentError)
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.commit do |c|
  c.update "users", [{ id: 1, name: "Charlie", active: false }]
  c.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

commit_options = { return_commit_stats: true }
commit_resp = db.commit commit_options: commit_options do |c|
  c.update "users", [{ id: 1, name: "Charlie", active: false }]
  c.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

With request options

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.commit request_options: { priority: :PRIORITY_MEDIUM } do |c|
  c.update "users", [{ id: 1, name: "Charlie", active: false }]
  c.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

Commit using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "BulkManipulate-Users" }
db.commit request_options: request_options do |c|
  c.update "users", [{ id: 1, name: "Charlie", active: false }]
  c.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

#commit_timestamp

def commit_timestamp() -> ColumnValue

Creates a column value object representing setting a field's value to the timestamp of the commit. (See Google::Cloud::Spanner::ColumnValue.commit_timestamp)

This placeholder value can only be used for timestamp columns that have set the option "(allow_commit_timestamp=true)" in the schema.

Returns
  • (ColumnValue) — The commit timestamp column value object.
Example
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

# create column value object
commit_timestamp = db.commit_timestamp

db.commit do |c|
  c.insert "users", [
    { id: 5, name: "Murphy", updated_at: commit_timestamp }
  ]
end

#database

def database() -> Database

The Spanner database connected to.

Returns
  • (Database)

#database_id

def database_id() -> String

The unique identifier for the database.

Returns
  • (String)

#delete

def delete(table, keys = [], commit_options: nil, request_options: nil, call_options: nil) -> Time, CommitResponse

Deletes rows from a table. Succeeds whether or not the specified rows were present.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#delete (See #transaction). This method makes a single RPC, whereas Transaction#delete requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind deletions.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • keys (Object, Array<Object>) — A single, or list of keys or key ranges to match returned data to. Values should have exactly as many elements as there are columns in the primary key.
  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.delete "users", [1, 2, 3]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

commit_options = { return_commit_stats: true }
commit_resp = db.delete "users", [1, 2, 3], commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

With request optinos

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.delete "users", [1, 2, 3], request_options: request_options

Delete using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "BulkDelete-Users" }
db.delete "users", [1, 2, 3], request_options: request_options

#execute

def execute(sql, params: nil, types: nil, single_use: nil, query_options: nil, request_options: nil, call_options: nil) -> Google::Cloud::Spanner::Results
Alias Of: #execute_query

Executes a SQL query.

Parameters
  • sql (String) — The SQL query string. See Query syntax.

    The SQL query string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — SQL parameters for the query string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil) — Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash must be used to specify the SQL type for these values.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Types for STRUCT values (Hash/Data objects) are specified using a Fields object.

    Types are optional.

  • single_use (Hash) (defaults to: nil)

    Perform the read with a single-use snapshot (read-only transaction). (See TransactionOptions.) If no value is specified for this parameter, Cloud Spanner will use a single use read-only transaction with strong timestamp bound as default. The snapshot can be created by providing exactly one of the following options in the hash:

    • Strong
      • :strong (true, false) Read at a timestamp where all previously committed transactions are visible.
    • Exact

      • :timestamp/:read_timestamp (Time, DateTime) Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

      Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.

      • :staleness/:exact_staleness (Numeric) Executes all reads at a timestamp that is exactly the number of seconds provided old. The timestamp is chosen soon after the read is started.

      Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use bounded_staleness.

    • Bounded

      • :bounded_timestamp/:min_read_timestamp (Time, DateTime) Executes all reads at a timestamp greater than the value provided.

      This is useful for requesting fresher data than some previous read, or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.

      • :bounded_staleness/:max_staleness (Numeric) Read data at a timestamp greater than or equal to the number of seconds provided. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading the freshest data available at a nearby replica, while bounding the possible staleness if the local replica has fallen behind.

  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (Symbol) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query "SELECT * FROM users"

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query(
  "SELECT * FROM users WHERE active = @active",
  params: { active: true }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query with a SQL STRUCT query parameter as a Hash:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_hash = { id: 1, name: "Charlie", active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Specify the SQL STRUCT type using Fields object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_hash = { id: 1, name: nil, active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash },
  types: { user_struct: user_type }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Or, query with a SQL STRUCT as a typed Data object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_data = user_type.struct id: 1, name: nil, active: false

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_data }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query \
  "SELECT * FROM users", query_options: {
    optimizer_version: "1",
    optimizer_statistics_package: "auto_20191128_14_47_22UTC"
  }

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

results = db.execute_query \
  "SELECT * FROM users", call_options: call_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Read-Users" }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#execute_partition_update

def execute_partition_update(sql, params: nil, types: nil, query_options: nil, request_options: nil, call_options: nil) -> Integer
Aliases

Executes a Partitioned DML SQL statement.

Partitioned DML is an alternate implementation with looser semantics to enable large-scale changes without running into transaction size limits or (accidentally) locking the entire table in one large transaction. At a high level, it partitions the keyspace and executes the statement on each partition in separate internal transactions.

Partitioned DML does not guarantee database-wide atomicity of the statement - it guarantees row-based atomicity, which includes updates to any indices. Additionally, it does not guarantee that it will execute exactly one time against each row - it guarantees "at least once" semantics.

Where DML statements must be executed using Transaction (see Transaction#execute_update), Partitioned DML statements are executed outside of a read/write transaction.

Not all DML statements can be executed in the Partitioned DML mode and the backend will return an error for the statements which are not supported.

DML statements must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table. InvalidArgumentError is raised if the statement does not qualify.

The method will block until the update is complete. Running a DML statement with this method does not offer exactly once semantics, and therefore the DML statement should be idempotent. The DML statement must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table. This is a Partitioned DML transaction in which a single Partitioned DML statement is executed. Partitioned DML partitions the and runs the DML statement over each partition in parallel using separate, internal transactions that commit independently. Partitioned DML transactions do not need to be committed.

Partitioned DML updates are used to execute a single DML statement with a different execution strategy that provides different, and often better, scalability properties for large, table-wide operations than DML in a Transaction#execute_update transaction. Smaller scoped statements, such as an OLTP workload, should prefer using Transaction#execute_update.

That said, Partitioned DML is not a drop-in replacement for standard DML used in Transaction#execute_update.

  • The DML statement must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table.
  • The statement is not applied atomically to all rows of the table. Rather, the statement is applied atomically to partitions of the table, in independent internal transactions. Secondary index rows are updated atomically with the base table rows.
  • Partitioned DML does not guarantee exactly-once execution semantics against a partition. The statement will be applied at least once to each partition. It is strongly recommended that the DML statement should be idempotent to avoid unexpected results. For instance, it is potentially dangerous to run a statement such as UPDATE table SET column = column + 1 as it could be run multiple times against some rows.
  • The partitions are committed automatically - there is no support for Commit or Rollback. If the call returns an error, or if the client issuing the DML statement dies, it is possible that some rows had the statement executed on them successfully. It is also possible that statement was never executed against other rows.
  • If any error is encountered during the execution of the partitioned DML operation (for instance, a UNIQUE INDEX violation, division by zero, or a value that cannot be stored due to schema constraints), then the operation is stopped at that point and an error is returned. It is possible that at this point, some partitions have been committed (or even committed multiple times), and other partitions have not been run at all.

Given the above, Partitioned DML is good fit for large, database-wide, operations that are idempotent, such as deleting old rows from a very large table.

Parameters
  • sql (String) — The Partitioned DML statement string. See Query syntax.

    The Partitioned DML statement string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — Parameters for the Partitioned DML statement string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil)

    Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash can be used to specify the exact SQL type for some or all of the SQL query parameters.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Nested Structs are specified by providing a Fields object.
  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
  • (Integer) — The lower bound number of rows that were modified.
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false"

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = @active",
 params: { active: false }

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false",
 query_options: {
   optimizer_version: "1",
   optimizer_statistics_package: "auto_20191128_14_47_22UTC"
 }

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false",
 call_options: call_options

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = @active",
 params: { active: false }, request_options: request_options

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

request_options = { tag: "Update-Users" }
row_count = db.execute_partition_update \
  "UPDATE users SET friends = NULL WHERE active = false",
  request_options: request_options

#execute_pdml

def execute_pdml(sql, params: nil, types: nil, query_options: nil, request_options: nil, call_options: nil) -> Integer

Executes a Partitioned DML SQL statement.

Partitioned DML is an alternate implementation with looser semantics to enable large-scale changes without running into transaction size limits or (accidentally) locking the entire table in one large transaction. At a high level, it partitions the keyspace and executes the statement on each partition in separate internal transactions.

Partitioned DML does not guarantee database-wide atomicity of the statement - it guarantees row-based atomicity, which includes updates to any indices. Additionally, it does not guarantee that it will execute exactly one time against each row - it guarantees "at least once" semantics.

Where DML statements must be executed using Transaction (see Transaction#execute_update), Partitioned DML statements are executed outside of a read/write transaction.

Not all DML statements can be executed in the Partitioned DML mode and the backend will return an error for the statements which are not supported.

DML statements must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table. InvalidArgumentError is raised if the statement does not qualify.

The method will block until the update is complete. Running a DML statement with this method does not offer exactly once semantics, and therefore the DML statement should be idempotent. The DML statement must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table. This is a Partitioned DML transaction in which a single Partitioned DML statement is executed. Partitioned DML partitions the and runs the DML statement over each partition in parallel using separate, internal transactions that commit independently. Partitioned DML transactions do not need to be committed.

Partitioned DML updates are used to execute a single DML statement with a different execution strategy that provides different, and often better, scalability properties for large, table-wide operations than DML in a Transaction#execute_update transaction. Smaller scoped statements, such as an OLTP workload, should prefer using Transaction#execute_update.

That said, Partitioned DML is not a drop-in replacement for standard DML used in Transaction#execute_update.

  • The DML statement must be fully-partitionable. Specifically, the statement must be expressible as the union of many statements which each access only a single row of the table.
  • The statement is not applied atomically to all rows of the table. Rather, the statement is applied atomically to partitions of the table, in independent internal transactions. Secondary index rows are updated atomically with the base table rows.
  • Partitioned DML does not guarantee exactly-once execution semantics against a partition. The statement will be applied at least once to each partition. It is strongly recommended that the DML statement should be idempotent to avoid unexpected results. For instance, it is potentially dangerous to run a statement such as UPDATE table SET column = column + 1 as it could be run multiple times against some rows.
  • The partitions are committed automatically - there is no support for Commit or Rollback. If the call returns an error, or if the client issuing the DML statement dies, it is possible that some rows had the statement executed on them successfully. It is also possible that statement was never executed against other rows.
  • If any error is encountered during the execution of the partitioned DML operation (for instance, a UNIQUE INDEX violation, division by zero, or a value that cannot be stored due to schema constraints), then the operation is stopped at that point and an error is returned. It is possible that at this point, some partitions have been committed (or even committed multiple times), and other partitions have not been run at all.

Given the above, Partitioned DML is good fit for large, database-wide, operations that are idempotent, such as deleting old rows from a very large table.

Parameters
  • sql (String) — The Partitioned DML statement string. See Query syntax.

    The Partitioned DML statement string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — Parameters for the Partitioned DML statement string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil)

    Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash can be used to specify the exact SQL type for some or all of the SQL query parameters.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Nested Structs are specified by providing a Fields object.
  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
  • (Integer) — The lower bound number of rows that were modified.
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false"

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = @active",
 params: { active: false }

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false",
 query_options: {
   optimizer_version: "1",
   optimizer_statistics_package: "auto_20191128_14_47_22UTC"
 }

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = false",
 call_options: call_options

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
row_count = db.execute_partition_update \
 "UPDATE users SET friends = NULL WHERE active = @active",
 params: { active: false }, request_options: request_options

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

request_options = { tag: "Update-Users" }
row_count = db.execute_partition_update \
  "UPDATE users SET friends = NULL WHERE active = false",
  request_options: request_options

#execute_query

def execute_query(sql, params: nil, types: nil, single_use: nil, query_options: nil, request_options: nil, call_options: nil) -> Google::Cloud::Spanner::Results

Executes a SQL query.

Parameters
  • sql (String) — The SQL query string. See Query syntax.

    The SQL query string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — SQL parameters for the query string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil) — Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash must be used to specify the SQL type for these values.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Types for STRUCT values (Hash/Data objects) are specified using a Fields object.

    Types are optional.

  • single_use (Hash) (defaults to: nil)

    Perform the read with a single-use snapshot (read-only transaction). (See TransactionOptions.) If no value is specified for this parameter, Cloud Spanner will use a single use read-only transaction with strong timestamp bound as default. The snapshot can be created by providing exactly one of the following options in the hash:

    • Strong
      • :strong (true, false) Read at a timestamp where all previously committed transactions are visible.
    • Exact

      • :timestamp/:read_timestamp (Time, DateTime) Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

      Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.

      • :staleness/:exact_staleness (Numeric) Executes all reads at a timestamp that is exactly the number of seconds provided old. The timestamp is chosen soon after the read is started.

      Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use bounded_staleness.

    • Bounded

      • :bounded_timestamp/:min_read_timestamp (Time, DateTime) Executes all reads at a timestamp greater than the value provided.

      This is useful for requesting fresher data than some previous read, or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.

      • :bounded_staleness/:max_staleness (Numeric) Read data at a timestamp greater than or equal to the number of seconds provided. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading the freshest data available at a nearby replica, while bounding the possible staleness if the local replica has fallen behind.

  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (Symbol) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query "SELECT * FROM users"

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query(
  "SELECT * FROM users WHERE active = @active",
  params: { active: true }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query with a SQL STRUCT query parameter as a Hash:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_hash = { id: 1, name: "Charlie", active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Specify the SQL STRUCT type using Fields object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_hash = { id: 1, name: nil, active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash },
  types: { user_struct: user_type }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Or, query with a SQL STRUCT as a typed Data object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_data = user_type.struct id: 1, name: nil, active: false

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_data }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query \
  "SELECT * FROM users", query_options: {
    optimizer_version: "1",
    optimizer_statistics_package: "auto_20191128_14_47_22UTC"
  }

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

results = db.execute_query \
  "SELECT * FROM users", call_options: call_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Read-Users" }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#execute_sql

def execute_sql(sql, params: nil, types: nil, single_use: nil, query_options: nil, request_options: nil, call_options: nil) -> Google::Cloud::Spanner::Results
Alias Of: #execute_query

Executes a SQL query.

Parameters
  • sql (String) — The SQL query string. See Query syntax.

    The SQL query string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — SQL parameters for the query string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil) — Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash must be used to specify the SQL type for these values.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Types for STRUCT values (Hash/Data objects) are specified using a Fields object.

    Types are optional.

  • single_use (Hash) (defaults to: nil)

    Perform the read with a single-use snapshot (read-only transaction). (See TransactionOptions.) If no value is specified for this parameter, Cloud Spanner will use a single use read-only transaction with strong timestamp bound as default. The snapshot can be created by providing exactly one of the following options in the hash:

    • Strong
      • :strong (true, false) Read at a timestamp where all previously committed transactions are visible.
    • Exact

      • :timestamp/:read_timestamp (Time, DateTime) Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

      Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.

      • :staleness/:exact_staleness (Numeric) Executes all reads at a timestamp that is exactly the number of seconds provided old. The timestamp is chosen soon after the read is started.

      Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use bounded_staleness.

    • Bounded

      • :bounded_timestamp/:min_read_timestamp (Time, DateTime) Executes all reads at a timestamp greater than the value provided.

      This is useful for requesting fresher data than some previous read, or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.

      • :bounded_staleness/:max_staleness (Numeric) Read data at a timestamp greater than or equal to the number of seconds provided. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading the freshest data available at a nearby replica, while bounding the possible staleness if the local replica has fallen behind.

  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (Symbol) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query "SELECT * FROM users"

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query(
  "SELECT * FROM users WHERE active = @active",
  params: { active: true }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query with a SQL STRUCT query parameter as a Hash:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_hash = { id: 1, name: "Charlie", active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Specify the SQL STRUCT type using Fields object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_hash = { id: 1, name: nil, active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash },
  types: { user_struct: user_type }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Or, query with a SQL STRUCT as a typed Data object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_data = user_type.struct id: 1, name: nil, active: false

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_data }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query \
  "SELECT * FROM users", query_options: {
    optimizer_version: "1",
    optimizer_statistics_package: "auto_20191128_14_47_22UTC"
  }

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

results = db.execute_query \
  "SELECT * FROM users", call_options: call_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Read-Users" }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#fields

def fields(types) -> Fields

Creates a configuration object (Fields) that may be provided to queries or used to create STRUCT objects. (The STRUCT will be represented by the Data class.) See #execute and/or Fields#struct.

For more information, see Data Types - Constructing a STRUCT.

Parameter
  • types (Array, Hash) —

    Accepts an array or hash types.

    Arrays can contain just the type value, or a sub-array of the field's name and type value. Hash keys must contain the field name as a Symbol or String, or the field position as an Integer. Hash values must contain the type value. If a Hash is used the fields will be created using the same order as the Hash keys.

    Supported type values include:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Nested Structs are specified by providing a Fields object.
Returns
  • (Fields) — The fields of the given types.
Examples

Create a STRUCT value with named fields using Fields object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

named_type = db.fields(
  { id: :INT64, name: :STRING, active: :BOOL }
)
named_data = named_type.struct(
  { id: 42, name: nil, active: false }
)

Create a STRUCT value with anonymous field names:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

anon_type = db.fields [:INT64, :STRING, :BOOL]
anon_data = anon_type.struct [42, nil, false]

Create a STRUCT value with duplicate field names:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

dup_type = db.fields [[:x, :INT64], [:x, :STRING], [:x, :BOOL]]
dup_data = dup_type.struct [42, nil, false]

#insert

def insert(table, rows, commit_options: nil, request_options: nil) -> Time, CommitResponse

Inserts new rows in a table. If any of the rows already exist, the write or request fails with AlreadyExistsError.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#insert (See #transaction). This method makes a single RPC, whereas Transaction#insert requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind inserts.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • rows (Array<Hash>) — One or more hash objects with the hash keys matching the table's columns, and the hash values matching the table's values.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. |

    See Data types.

  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.insert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

records = [{ id: 1, name: "Charlie", active: false },
           { id: 2, name: "Harvey",  active: true }]
commit_options = { return_commit_stats: true }
commit_resp = db.insert "users", records, commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.insert "users", [{ id: 1, name: "Charlie", active: false }],
                   request_options: request_options

Insert using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "BulkInsert-Users" }
db.insert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }],
                    request_options: request_options

#instance

def instance() -> Instance

The Spanner instance connected to.

Returns
  • (Instance)

#instance_id

def instance_id() -> String

The unique identifier for the instance.

Returns
  • (String)

#project

def project() -> Project

The Spanner project connected to.

Returns

#project_id

def project_id() -> String

The unique identifier for the project.

Returns
  • (String)

#query

def query(sql, params: nil, types: nil, single_use: nil, query_options: nil, request_options: nil, call_options: nil) -> Google::Cloud::Spanner::Results
Alias Of: #execute_query

Executes a SQL query.

Parameters
  • sql (String) — The SQL query string. See Query syntax.

    The SQL query string can contain parameter placeholders. A parameter placeholder consists of "@" followed by the parameter name. Parameter names consist of any combination of letters, numbers, and underscores.

  • params (Hash) (defaults to: nil) — SQL parameters for the query string. The parameter placeholders, minus the "@", are the the hash keys, and the literal values are the hash values. If the query string contains something like "WHERE id > @msg_id", then the params must contain something like :msg_id => 1.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. | | STRUCT | Hash, Data | |

    See Data types.

    See Data Types - Constructing a STRUCT.

  • types (Hash) (defaults to: nil) — Types of the SQL parameters in params. It is not always possible for Cloud Spanner to infer the right SQL type from a value in params. In these cases, the types hash must be used to specify the SQL type for these values.

    The keys of the hash should be query string parameter placeholders, minus the "@". The values of the hash should be Cloud Spanner type codes from the following list:

    • :BOOL
    • :BYTES
    • :DATE
    • :FLOAT64
    • :NUMERIC
    • :INT64
    • :STRING
    • :TIMESTAMP
    • Array - Lists are specified by providing the type code in an array. For example, an array of integers are specified as [:INT64].
    • Fields - Types for STRUCT values (Hash/Data objects) are specified using a Fields object.

    Types are optional.

  • single_use (Hash) (defaults to: nil)

    Perform the read with a single-use snapshot (read-only transaction). (See TransactionOptions.) If no value is specified for this parameter, Cloud Spanner will use a single use read-only transaction with strong timestamp bound as default. The snapshot can be created by providing exactly one of the following options in the hash:

    • Strong
      • :strong (true, false) Read at a timestamp where all previously committed transactions are visible.
    • Exact

      • :timestamp/:read_timestamp (Time, DateTime) Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

      Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.

      • :staleness/:exact_staleness (Numeric) Executes all reads at a timestamp that is exactly the number of seconds provided old. The timestamp is chosen soon after the read is started.

      Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use bounded_staleness.

    • Bounded

      • :bounded_timestamp/:min_read_timestamp (Time, DateTime) Executes all reads at a timestamp greater than the value provided.

      This is useful for requesting fresher data than some previous read, or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.

      • :bounded_staleness/:max_staleness (Numeric) Read data at a timestamp greater than or equal to the number of seconds provided. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading the freshest data available at a nearby replica, while bounding the possible staleness if the local replica has fallen behind.

  • query_options (Hash) (defaults to: nil)

    A hash of values to specify the custom query options for executing SQL query. Query options are optional. The following settings can be provided:

    • :optimizer_version (String) The version of optimizer to use. Empty to use database default. "latest" to use the latest available optimizer version.
    • :optimizer_statistics_package (String) Statistics package to use. Empty to use the database default.
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (Symbol) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query "SELECT * FROM users"

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query parameters:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query(
  "SELECT * FROM users WHERE active = @active",
  params: { active: true }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query with a SQL STRUCT query parameter as a Hash:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_hash = { id: 1, name: "Charlie", active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Specify the SQL STRUCT type using Fields object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_hash = { id: 1, name: nil, active: false }

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_hash },
  types: { user_struct: user_type }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Or, query with a SQL STRUCT as a typed Data object:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

user_type = db.fields id: :INT64, name: :STRING, active: :BOOL
user_data = user_type.struct id: 1, name: nil, active: false

results = db.execute_query(
  "SELECT * FROM users WHERE " \
  "ID = @user_struct.id " \
  "AND name = @user_struct.name " \
  "AND active = @user_struct.active",
  params: { user_struct: user_data }
)

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using query options:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.execute_query \
  "SELECT * FROM users", query_options: {
    optimizer_version: "1",
    optimizer_statistics_package: "auto_20191128_14_47_22UTC"
  }

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using custom timeout and retry policy:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

results = db.execute_query \
  "SELECT * FROM users", call_options: call_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Query using tag for request query statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Read-Users" }
results = db.execute_query "SELECT * FROM users",
                           request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#query_options

def query_options() -> Hash

A hash of values to specify the custom query options for executing SQL query.

Returns
  • (Hash)

#range

def range(beginning, ending, exclude_begin: false, exclude_end: false) -> Google::Cloud::Spanner::Range

Creates a Spanner Range. This can be used in place of a Ruby Range when needing to exclude the beginning value.

Parameters
  • beginning (Object) — The object that defines the beginning of the range.
  • ending (Object) — The object that defines the end of the range.
  • exclude_begin (Boolean) (defaults to: false) — Determines if the range excludes its beginning value. Default is false.
  • exclude_end (Boolean) (defaults to: false) — Determines if the range excludes its ending value. Default is false.
Returns
Example
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

key_range = db.range 1, 100
results = db.read "users", [:id, :name], keys: key_range

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#read

def read(table, columns, keys: nil, index: nil, limit: nil, single_use: nil, request_options: nil, call_options: nil) -> Google::Cloud::Spanner::Results

Read rows from a database table, as a simple alternative to #execute_query.

Parameters
  • table (String) — The name of the table in the database to be read.
  • columns (Array<String, Symbol>) — The columns of table to be returned for each row matching this request.
  • keys (Object, Array<Object>) (defaults to: nil) — A single, or list of keys or key ranges to match returned data to. Values should have exactly as many elements as there are columns in the primary key.
  • index (String) (defaults to: nil) — The name of an index to use instead of the table's primary key when interpreting id and sorting result rows. Optional.
  • limit (Integer) (defaults to: nil) — If greater than zero, no more than this number of rows will be returned. The default is no limit.
  • single_use (Hash) (defaults to: nil)

    Perform the read with a single-use snapshot (read-only transaction). (See TransactionOptions.) If no value is specified for this parameter, Cloud Spanner will use a single use read-only transaction with strong timestamp bound as default. The snapshot can be created by providing exactly one of the following options in the hash:

    • Strong
      • :strong (true, false) Read at a timestamp where all previously committed transactions are visible.
    • Exact

      • :timestamp/:read_timestamp (Time, DateTime) Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

      Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data.

      • :staleness/:exact_staleness (Numeric) Executes all reads at a timestamp that is exactly the number of seconds provided old. The timestamp is chosen soon after the read is started.

      Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use bounded_staleness.

    • Bounded

      • :bounded_timestamp/:min_read_timestamp (Time, DateTime) Executes all reads at a timestamp greater than the value provided.

      This is useful for requesting fresher data than some previous read, or data that is fresh enough to observe the effects of some previously committed transaction whose timestamp is known.

      • :bounded_staleness/:max_staleness (Numeric) Read data at a timestamp greater than or equal to the number of seconds provided. Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

      Useful for reading the freshest data available at a nearby replica, while bounding the possible staleness if the local replica has fallen behind.

  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (Symbol) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A per-request tag which can be applied to queries or reads, used for statistics collection. Tag must be a valid identifier of the form: [a-zA-Z][a-zA-Z0-9_\-] between 2 and 64 characters in length.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.read "users", [:id, :name]

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Use the keys option to pass keys and/or key ranges to read.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

results = db.read "users", [:id, :name], keys: 1..5

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Read using custom timeout and retry.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

timeout = 30.0
retry_policy = {
  initial_delay: 0.25,
  max_delay:     32.0,
  multiplier:    1.3,
  retry_codes:   ["UNAVAILABLE"]
}
call_options = { timeout: timeout, retry_policy: retry_policy }

results = db.read "users", [:id, :name], call_options: call_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
results = db.read "users", [:id, :name],
                  request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

Read using tag for read statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Read-Users-All" }
results = db.read "users", [:id, :name],
                  request_options: request_options

results.rows.each do |row|
  puts "User #{row[:id]} is #{row[:name]}"
end

#replace

def replace(table, rows, commit_options: nil, request_options: nil) -> Time, CommitResponse

Inserts or replaces rows in a table. If any of the rows already exist, it is deleted, and the column values provided are inserted instead. Unlike #upsert, this means any values not explicitly written become NULL.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#replace (See #transaction). This method makes a single RPC, whereas Transaction#replace requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind replaces.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • rows (Array<Hash>) — One or more hash objects with the hash keys matching the table's columns, and the hash values matching the table's values.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. |

    See Data types.

  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.replace "users", [{ id: 1, name: "Charlie", active: false },
                     { id: 2, name: "Harvey",  active: true }]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

records = [{ id: 1, name: "Charlie", active: false },
           { id: 2, name: "Harvey",  active: true }]
commit_options = { return_commit_stats: true }
commit_resp = db.replace "users", records, commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.replace "users", [{ id: 1, name: "Charlie", active: false }],
                    request_options: request_options

Replace using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "BulkReplace-Users" }
db.replace "users", [{ id: 1, name: "Charlie", active: false },
                     { id: 2, name: "Harvey",  active: true }],
                    request_options: request_options

#reset

def reset()

Reset the client sessions.

#save

def save(table, rows, commit_options: nil, request_options: nil) -> Time, CommitResponse
Alias Of: #upsert

Inserts or updates rows in a table. If any of the rows already exist, then its column values are overwritten with the ones provided. Any column values not explicitly written are preserved.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#upsert (See #transaction). This method makes a single RPC, whereas Transaction#upsert requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind upserts.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • rows (Array<Hash>) — One or more hash objects with the hash keys matching the table's columns, and the hash values matching the table's values.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. |

    See Data types.

  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.upsert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

records = [{ id: 1, name: "Charlie", active: false },
           { id: 2, name: "Harvey",  active: true }]
commit_options = { return_commit_stats: true }
commit_resp = db.upsert "users", records, commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.upsert "users", [{ id: 1, name: "Charlie", active: false }],
                   request_options: request_options

Upsert using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Bulk-Upsert" }
db.upsert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }],
                    request_options: request_options

#snapshot

def snapshot(strong: nil, timestamp: nil, read_timestamp: nil, staleness: nil, exact_staleness: nil, call_options: nil) { |snapshot| ... }

Creates a snapshot read-only transaction for reads that execute atomically at a single logical point in time across columns, rows, and tables in a database. For transactions that only read, snapshot read-only transactions provide simpler semantics and are almost always faster than read-write transactions.

Parameters
  • strong (true, false) (defaults to: nil) — Read at a timestamp where all previously committed transactions are visible.
  • timestamp (Time, DateTime) (defaults to: nil) — Executes all reads at the given timestamp. Unlike other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp always returns the same data. If the timestamp is in the future, the read will block until the specified timestamp, modulo the read's deadline.

    Useful for large scale consistent reads such as mapreduces, or for coordinating many reads against a consistent snapshot of the data. (See TransactionOptions.)

  • read_timestamp (Time, DateTime) (defaults to: nil) — Same as timestamp.
  • staleness (Numeric) (defaults to: nil) — Executes all reads at a timestamp that is staleness seconds old. For example, the number 10.1 is translated to 10 seconds and 100 milliseconds.

    Guarantees that all writes that have committed more than the specified number of seconds ago are visible. Because Cloud Spanner chooses the exact timestamp, this mode works even if the client's local clock is substantially skewed from Cloud Spanner commit timestamps.

    Useful for reading at nearby replicas without the distributed timestamp negotiation overhead of single-use staleness. (See TransactionOptions.)

  • exact_staleness (Numeric) (defaults to: nil) — Same as staleness.
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Yields
  • (snapshot) — The block for reading and writing data.
Yield Parameter
Example
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

db.snapshot do |snp|
  results = snp.execute_query "SELECT * FROM users"

  results.rows.each do |row|
    puts "User #{row[:id]} is #{row[:name]}"
  end
end

#transaction

def transaction(deadline: 120, commit_options: nil, request_options: nil, call_options: nil) { |transaction| ... } -> Time, CommitResponse

Creates a transaction for reads and writes that execute atomically at a single logical point in time across columns, rows, and tables in a database.

The transaction will always commit unless an error is raised. If the error raised is Rollback the transaction method will return without passing on the error. All other errors will be passed on.

All changes are accumulated in memory until the block completes. Transactions will be automatically retried when possible, until deadline is reached. This operation makes separate API requests to begin and commit the transaction.

Parameters
  • deadline (Numeric) (defaults to: 120) — The total amount of time in seconds the transaction has to succeed. The default is 120.
  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String)A tag used for statistics collection about transaction. The value of a transaction tag should be the same for all requests belonging to the same transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}
  • call_options (Hash) (defaults to: nil)

    A hash of values to specify the custom call options, e.g., timeout, retries, etc. Call options are optional. The following settings can be provided:

    • :timeout (Numeric) A numeric value of custom timeout in seconds that overrides the default setting.
    • :retry_policy (Hash) A hash of values that overrides the default setting of retry policy with the following keys:
      • :initial_delay (Numeric) - The initial delay in seconds.
      • :max_delay (Numeric) - The max delay in seconds.
      • :multiplier (Numeric) - The incremental backoff multiplier.
      • :retry_codes (Array<String>) - The error codes that should trigger a retry.
Yields
  • (transaction) — The block for reading and writing data.
Yield Parameter
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

db.transaction do |tx|
  results = tx.execute_query "SELECT * FROM users"

  results.rows.each do |row|
    puts "User #{row[:id]} is #{row[:name]}"
  end

  tx.update "users", [{ id: 1, name: "Charlie", active: false }]
  tx.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

Manually rollback the transaction using Rollback:

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

db.transaction do |tx|
  tx.update "users", [{ id: 1, name: "Charlie", active: false }]
  tx.insert "users", [{ id: 2, name: "Harvey",  active: true }]

  if something_wrong?
    # Rollback the transaction without passing on the error
    # outside of the transaction method.
    raise Google::Cloud::Spanner::Rollback
  end
end

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

commit_options = { return_commit_stats: true }
commit_resp = db.transaction commit_options: commit_options do |tx|
  results = tx.execute_query "SELECT * FROM users"

  results.rows.each do |row|
    puts "User #{row[:id]} is #{row[:name]}"
  end

  tx.update "users", [{ id: 1, name: "Charlie", active: false }]
  tx.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

db.transaction request_options: { priority: :PRIORITY_MEDIUM } do |tx|
  tx.update "users", [{ id: 1, name: "Charlie", active: false }]
  tx.insert "users", [{ id: 2, name: "Harvey",  active: true }]

  request_options = { priority: :PRIORITY_LOW }
  results = tx.execute_query "SELECT * FROM users",
                            request_options: request_options
end

Tags for request and transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
db = spanner.client "my-instance", "my-database"

# Transaction tag will be set to "Users-Txn"
db.transaction request_options: { tag: "Users-Txn" } do |tx|
  # The transaction tag set as "Users-Txn"
  # The request tag set as "Users-Txn-1"
  request_options = { tag: "Users-Txn-1" }
  results = tx.execute_query "SELECT * FROM users",
                             request_options: request_options

  results.rows.each do |row|
    puts "User #{row[:id]} is #{row[:name]}"
  end

  # The transaction tag set as "Users-Txn"
  tx.update "users", [{ id: 1, name: "Charlie", active: false }]
  tx.insert "users", [{ id: 2, name: "Harvey",  active: true }]
end

#update

def update(table, rows, commit_options: nil, request_options: nil) -> Time, CommitResponse

Updates existing rows in a table. If any of the rows does not already exist, the request fails with NotFoundError.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#update (See #transaction). This method makes a single RPC, whereas Transaction#update requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind updates.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • rows (Array<Hash>) — One or more hash objects with the hash keys matching the table's columns, and the hash values matching the table's values.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. |

    See Data types.

  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.update "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

records = [{ id: 1, name: "Charlie", active: false },
           { id: 2, name: "Harvey",  active: true }]
commit_options = { return_commit_stats: true }
commit_resp = db.update "users", records, commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.update "users", [{ id: 1, name: "Charlie", active: false }],
                   request_options: request_options

Updte using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "BulkUpdate-Users" }
db.update "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }],
                   request_options: request_options

#upsert

def upsert(table, rows, commit_options: nil, request_options: nil) -> Time, CommitResponse
Aliases

Inserts or updates rows in a table. If any of the rows already exist, then its column values are overwritten with the ones provided. Any column values not explicitly written are preserved.

Changes are made immediately upon calling this method using a single-use transaction. To make multiple changes in the same single-use transaction use #commit. To make changes in a transaction that supports reads and automatic retry protection use #transaction.

Note: This method does not feature replay protection present in Transaction#upsert (See #transaction). This method makes a single RPC, whereas Transaction#upsert requires two RPCs (one of which may be performed in advance), and so this method may be appropriate for latency sensitive and/or high throughput blind upserts.

Parameters
  • table (String) — The name of the table in the database to be modified.
  • rows (Array<Hash>) — One or more hash objects with the hash keys matching the table's columns, and the hash values matching the table's values.

    Ruby types are mapped to Spanner types as follows:

    | Spanner | Ruby | Notes | |-------------|----------------|---| | BOOL | true/false | | | INT64 | Integer | | | FLOAT64 | Float | | | NUMERIC | BigDecimal | | | STRING | String | | | DATE | Date | | | TIMESTAMP | Time, DateTime | | | BYTES | File, IO, StringIO, or similar | | | ARRAY | Array | Nested arrays are not supported. |

    See Data types.

  • commit_options (Hash) (defaults to: nil)

    A hash of commit options. e.g., return_commit_stats. Commit options are optional. The following options can be provided:

    • :return_commit_stats (Boolean) A boolean value. If true, then statistics related to the transaction will be included in CommitResponse. Default value is false
  • request_options (Hash) (defaults to: nil)

    Common request options.

    • :priority (String) The relative priority for requests. The priority acts as a hint to the Cloud Spanner scheduler and does not guarantee priority or order of execution. Valid values are :PRIORITY_LOW, :PRIORITY_MEDIUM, :PRIORITY_HIGH. If priority not set then default is PRIORITY_UNSPECIFIED is equivalent to :PRIORITY_HIGH.
    • :tag (String) A tag used for statistics collection about transaction. A tag must be a valid identifier of the format: [a-zA-Z][a-zA-Z0-9_\-]{0,49}.
Returns
Examples
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

db.upsert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }]

Get commit stats

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

records = [{ id: 1, name: "Charlie", active: false },
           { id: 2, name: "Harvey",  active: true }]
commit_options = { return_commit_stats: true }
commit_resp = db.upsert "users", records, commit_options: commit_options

puts commit_resp.timestamp
puts commit_resp.stats.mutation_count

Using request options.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { priority: :PRIORITY_MEDIUM }
db.upsert "users", [{ id: 1, name: "Charlie", active: false }],
                   request_options: request_options

Upsert using tag for transaction statistics collection.

require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

db = spanner.client "my-instance", "my-database"

request_options = { tag: "Bulk-Upsert" }
db.upsert "users", [{ id: 1, name: "Charlie", active: false },
                    { id: 2, name: "Harvey",  active: true }],
                    request_options: request_options