# Cloud Spanner API - Class Google::Cloud::Spanner::Database (v2.36.0)

2.36.0 (latest) 2.35.0 2.34.0 2.33.0 2.32.0 2.31.0 2.30.0 2.29.0 2.28.0 2.27.0 2.26.0 2.25.0 2.24.0 2.23.0 2.22.0 2.21.0 2.20.0 2.19.1 2.18.1 2.17.0 2.16.1 2.15.0 2.14.0 2.13.0 2.12.1 2.11.0 Reference documentation and code samples for the Cloud Spanner API class Google::Cloud::Spanner::Database.

## Database

NOTE: From `google-cloud-spanner/v2.11.0` onwards, new features for
mananging databases will only be available through the
[google-cloud-spanner-admin-database-v1](https://github.com/googleapis/ruby-spanner/tree/main/google-cloud-spanner-admin-database-v1)
client. See the
[README](https://github.com/googleapis/ruby-spanner/tree/main/google-cloud-spanner#google-cloud-spanner)
for further details.

Represents a Cloud Spanner database. To use Cloud Spanner's read and
write operations, you must first create a database. A database belongs
to a [Instance](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Instance "Google::Cloud::Spanner::Instance (class)") and contains tables and indexes. You may create multiple
databases in an [Instance](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Instance "Google::Cloud::Spanner::Instance (class)").

See [Instance#databases](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Instance#Google__Cloud__Spanner__Instance_databases_instance_ "Google::Cloud::Spanner::Instance#databases (method)"),
[Instance#database](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Instance#Google__Cloud__Spanner__Instance_database_instance_ "Google::Cloud::Spanner::Instance#database (method)"), and
[Instance#create_database](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Instance#Google__Cloud__Spanner__Instance_create_database_instance_ "Google::Cloud::Spanner::Instance#create_database (method)").

To read and/or modify data in a Cloud Spanner database, use an instance
of [Client](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Client "Google::Cloud::Spanner::Client (class)"). See
[Project#client](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Project#Google__Cloud__Spanner__Project_client_instance_ "Google::Cloud::Spanner::Project#client (method)").

Admin::Database#database_admin instead.

## Inherits

- Object

## Example

```ruby
require "google/cloud"

spanner = Google::Cloud::Spanner.new
instance = spanner.instance "my-instance"

job = instance.create_database "my-new-database"

job.done? #=> false
job.reload! # API call
job.done? #=> true

if job.error?
  status = job.error
else
  database = job.database
end
```

## Methods

### #backups

    def backups(page_size: nil) -> Array<Google::Cloud::Spanner::Backup>

Retrieves backups belonging to the database.
**Parameter**

- **page_size** (Integer) *(defaults to: nil)* --- Optional. Number of backups to be returned in the response. If 0 or less, defaults to the server's maximum allowed page size.
**Returns**

- (Array\<[Google::Cloud::Spanner::Backup](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Backup)\>) --- Enumerable list of backups. (See [Backup::List](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Backup-List "Google::Cloud::Spanner::Backup::List (class)"))
**Examples**

```ruby
require "google/cloud/spanner"

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

database.backups.all.each do |backup|
  puts backup.backup_id
end
```

List backups by page size

```ruby
require "google/cloud/spanner"

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

database.backups(page_size: 5).all.each do |backup|
  puts backup.backup_id
end
```

### #create_backup

    def create_backup(backup_id, expire_time, version_time: nil, encryption_config: nil) -> Google::Cloud::Spanner::Backup::Job

Creates a database backup.
**Parameters**

- **backup_id** (String) --- The unique identifier for the backup. Values are of the form `[a-z][a-z0-9_\-]*[a-z0-9]` and must be between 2 and 60 characters in length. Required.
- **expire_time** (Time) --- The expiration time of the backup, with microseconds granularity that must be at least 6 hours and at most 366 days from the time the request is received. Required. Once the `expire_time` has passed, Cloud Spanner will delete the backup and free the resources used by the backup. Required.
- **version_time** (Time) *(defaults to: nil)* --- Specifies the time to have an externally consistent copy of the database. If no version time is specified, it will be automatically set to the backup create time. The version time can be as far in the past as specified by the database earliest version time. Optional.
- **encryption_config** (Hash) *(defaults to: nil)* ---

  An encryption configuration describing
  the encryption type and key resources in Cloud KMS. Optional. The
  following settings can be provided:
  - `:kms_key_name` (String) The name of KMS key to use which should be the full path, e.g., `projects/<project>/locations/<location>\
    /keyRings/<key_ring>/cryptoKeys/<kms_key_name>` This field should be set only when encryption type `:CUSTOMER_MANAGED_ENCRYPTION`.
  - `:encryption_type` (Symbol) The encryption type of the backup. Valid values are:
    1. `:USE_DATABASE_ENCRYPTION` - Use the same encryption configuration as the database.
    2. `:GOOGLE_DEFAULT_ENCRYPTION` - Google default encryption.
    3. `:CUSTOMER_MANAGED_ENCRYPTION` - Use customer managed encryption. If specified, `:kms_key_name` must contain a valid Cloud KMS key.
**Returns**

- ([Google::Cloud::Spanner::Backup::Job](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Backup-Job)) --- The job representing the long-running, asynchronous processing of a backup create operation.
**Raises**

- (ArgumentError) --- if `:CUSTOMER_MANAGED_ENCRYPTION` specified without customer managed kms key.
**Examples**

Create backup with expiration time

```ruby
require "google/cloud/spanner"

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

backup_id = "my-backup"
expire_time = Time.now + (24 * 60 * 60) # 1 day from now
version_time = Time.now - (24 * 60 * 60) # 1 day ago (optional)

job = database.create_backup backup_id, expire_time, version_time: version_time

job.done? #=> false
job.reload! # API call
job.done? #=> true

if job.error?
  status = job.error
else
  backup = job.backup
end
```

Create backup with encryption config

```ruby
require "google/cloud/spanner"

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

kms_key_name = "projects/<project>/locations/<location>/keyRings/<key_ring>/cryptoKeys/<kms_key_name>"
encryption_config = {
  kms_key_name: kms_key_name,
  encryption_type: :CUSTOMER_MANAGED_ENCRYPTION
}
job = database.create_backup "my-backup",
                             Time.now + 36000,
                             encryption_config: encryption_config

job.done? #=> false
job.reload! # API call
job.done? #=> true

if job.error?
  status = job.error
else
  backup = job.backup
end
```

### #create_time

    def create_time() -> Time

Time at which the database creation started.
**Returns**

- (Time)

### #creating?

    def creating?() -> Boolean

The database is still being created. Operations on the database may
raise with `FAILED_PRECONDITION` in this state.
**Returns**

- (Boolean)

### #database_id

    def database_id() -> String

The unique identifier for the database.
**Returns**

- (String)

### #database_operations

    def database_operations(filter: nil, page_size: nil) -> Array<Google::Cloud::Spanner::Database::Job>

Retrieves the list of database operations for the given database.
**Parameters**

- **filter** (String) *(defaults to: nil)* ---

  A filter expression that filters what operations are returned in the
  response.

  The response returns a list of
  `Google::Longrunning::Operation` long-running operations whose names
  are prefixed by a database name within the specified instance.
  The long-running operation
  `Google::Longrunning::Operation#metadata` metadata field type
  `metadata.type_url` describes the type of the metadata.

  The filter expression must specify the field name,
  a comparison operator, and the value that you want to use for
  filtering. The value must be a string, a number, or a boolean.
  The comparison operator must be
  \<, \>, \<=, \>=, !=, =, or :. Colon ':' represents a HAS operator
  which is roughly synonymous with equality. Filter rules are case
  insensitive.

  The long-running operation fields eligible for filtering are:
  - `name` --\> The name of the long-running operation
  - `done` --\> False if the operation is in progress, else true.
  - `metadata.type_url` (using filter string `metadata.@type`) and fields in `metadata.value` (using filter string `metadata.<field_name>`, where
  - `error` --\> Error associated with the long-running operation.
  - `response.type_url` (using filter string `response.@type`) and fields in `response.value` (using filter string `response.<field_name>`, where

  To filter on multiple expressions, provide each separate
  expression within parentheses. By default, each expression
  is an AND expression. However, you can include AND, OR, and NOT
  expressions explicitly.

  Some examples of using filters are:
  - `done:true` --\> The operation is complete.
  - `(metadata.@type:type.googleapis.com/google.spanner.admin.\
    database.v1.RestoreDatabaseMetadata)
    AND (metadata.source_type:BACKUP)
    AND (metadata.backup_info.backup:backup_howl)
    AND (metadata.name:restored_howl)
    AND (metadata.progress.start_time < \"2018-03-28T14:50:00Z\")
    AND (error:*)` --\> Return RestoreDatabase operations from backups whose name contains "backup_howl", where the created database name contains the string "restored_howl", the start_time of the restore operation is before 2018-03-28T14:50:00Z, and the operation returned an error.
- **page_size** (Integer) *(defaults to: nil)* --- The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.
**Returns**

- (Array\<[Google::Cloud::Spanner::Database::Job](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database-Job)\>) --- List representing the long-running, asynchronous processing of a database operations. (See [Job::List](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database-Job-List "Google::Cloud::Spanner::Database::Job::List (class)"))
**Examples**

```ruby
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

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

jobs = database.database_operations
jobs.each do |job|
  if job.error?
    p job.error
  else
    p job.database.database_id
  end
end
```

Retrieve all

```ruby
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

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

jobs = database.database_operations
jobs.all do |job|
  if job.error?
    p job.error
  else
    puts job.database.database_id
  end
end
```

List by page size

```ruby
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

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

jobs = database.database_operations page_size: 10
jobs.each do |job|
  if job.error?
    p job.error
  else
    puts job.database.database_id
  end
end
```

Filter and list

```ruby
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new

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

jobs = database.database_operations filter: "done:true"
jobs.each do |job|
  if job.error?
    p job.error
  else
    puts job.database.database_id
  end
end
```

### #ddl

    def ddl(force: nil) -> Array<String>

Retrieve the Data Definition Language (DDL) statements that define
database structures. DDL statements are used to create, update,
and delete tables and indexes.
**Parameter**

- **force** (Boolean) *(defaults to: nil)* --- Force the latest DDL statements to be retrieved from the Spanner service when `true`. Otherwise the DDL statements will be memoized to reduce the number of API calls made to the Spanner service. The default is `false`.
**Returns**

- (Array\<String\>) --- The DDL statements.
**Examples**

statements are memoized to reduce the number of API calls:

```ruby
require "google/cloud/spanner"

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

statements = database.ddl # API call
statements_2 = database.ddl # No API call
```

Use `force` to retrieve the statements from the service:

```ruby
require "google/cloud/spanner"

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

statements = database.ddl force: true # API call
statements_2 = database.ddl force: true # API call
```

### #drop

    def drop() -> Boolean

Drops (deletes) the Cloud Spanner database.
**Returns**

- (Boolean) --- Returns `true` if the database was deleted.
**Example**

```ruby
require "google/cloud/spanner"

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

database.drop
```

### #earliest_version_time

    def earliest_version_time() -> Time

The earliest available version time for a database.
**Returns**

- (Time)

### #encryption_config

    def encryption_config() -> Google::Cloud::Spanner::Admin::Database::V1::EncryptionConfig, nil

An encryption configuration describing the encryption type and key
resources in Cloud KMS.
**Returns**

- (Google::Cloud::Spanner::Admin::Database::V1::EncryptionConfig, nil)

### #encryption_info

    def encryption_info() -> Array<Google::Cloud::Spanner::Admin::Database::V1::EncryptionInfo>

Encryption information for the database.


For databases that are using customer managed encryption, this
field contains the encryption information for the database, such as
encryption state and the Cloud KMS key versions that are in use.

For databases that are using Google default or other types of encryption,
this field is empty.

<br />

This field is propagated lazily from the backend. There might be a delay
from when a key version is being used and when it appears in this field.
**Returns**

- (Array\<Google::Cloud::Spanner::Admin::Database::V1::EncryptionInfo\>)

### #instance_id

    def instance_id() -> String

The unique identifier for the instance.
**Returns**

- (String)

### #path

    def path() -> String

The full path for the database resource. Values are of the form
`projects/<project_id>/instances/<instance_id>/databases/<database_id>`.
**Returns**

- (String)

### #policy

    def policy() { |policy| ... } -> Policy

Gets the [Cloud IAM](https://cloud.google.com/iam/) access control
policy for this database.
**Yields**

- (policy) --- A block for updating the policy. The latest policy will be read from the Spanner service and passed to the block. After the block completes, the modified policy will be written to the service.
**Yield Parameter**

- **policy** ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- the current Cloud IAM Policy for this database
**Returns**

- ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- The current Cloud IAM Policy for this database.
**Examples**

```ruby
require "google/cloud/spanner"

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

policy = database.policy
```

Update the policy by passing a block:

```ruby
require "google/cloud/spanner"

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

database.policy do |p|
  p.add "roles/owner", "user:owner@example.com"
end # 2 API calls
```

### #policy=

    def policy=(new_policy) -> Policy

**Alias Of** : [#update_policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_update_policy_instance_) Updates the [Cloud IAM](https://cloud.google.com/iam/) access control
policy for this database. The policy should be read from [#policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_policy_instance_ "Google::Cloud::Spanner::Database#policy (method)").
See [Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy "Google::Cloud::Spanner::Policy (class)") for an explanation of the policy
`etag` property and how to modify policies.


<br />

You can also update the policy by passing a block to [#policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_policy_instance_ "Google::Cloud::Spanner::Database#policy (method)"), which
will call this method internally after the block completes.
**Parameter**

- **new_policy** ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- a new or modified Cloud IAM Policy for this database
**Returns**

- ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- The policy returned by the API update operation.
**Example**

```ruby
require "google/cloud/spanner"

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

policy = database.policy # API call

policy.add "roles/owner", "user:owner@example.com"

database.update_policy policy # API call
```

### #project_id

    def project_id() -> String

The unique identifier for the project.
**Returns**

- (String)

### #ready?

    def ready?() -> Boolean

The database is fully created and ready for use.
**Returns**

- (Boolean)

### #ready_optimizing?

    def ready_optimizing?() -> Boolean

The database is fully created from backup and optimizing.
**Returns**

- (Boolean)

### #restore_info

    def restore_info() -> Google::Cloud::Spanner::Database::RestoreInfo, nil

Information about the source used to restore the database.
**Returns**

- ([Google::Cloud::Spanner::Database::RestoreInfo](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database-RestoreInfo), nil)

### #state

    def state() -> Symbol

The current database state. Possible values are `:CREATING` and
`:READY`.
**Returns**

- (Symbol)

### #test_permissions

    def test_permissions(*permissions) -> Array<Strings>

Tests the specified permissions against the [Cloud
IAM](https://cloud.google.com/iam/) access control policy.

- spanner.databases.beginPartitionedDmlTransaction
- spanner.databases.create
- spanner.databases.createBackup
- spanner.databases.list
- spanner.databases.update
- spanner.databases.updateDdl
- spanner.databases.get
- spanner.databases.getDdl
- spanner.databases.getIamPolicy
- spanner.databases.setIamPolicy
- spanner.databases.beginReadOnlyTransaction
- spanner.databases.beginOrRollbackReadWriteTransaction
- spanner.databases.read
- spanner.databases.select
- spanner.databases.write
- spanner.databases.drop
**Parameter**

- **permissions** (String, Array\<String\>) --- The set of permissions to check access for. Permissions with wildcards (such as `*` or `storage.*`) are not allowed.


  The permissions that can be checked on a database are:
**Returns**

- (Array\<Strings\>) --- The permissions that have access.
**Example**

```ruby
require "google/cloud/spanner"

spanner = Google::Cloud::Spanner.new
database = spanner.database "my-instance", "my-database"
perms = database.test_permissions "spanner.databases.get",
                                  "spanner.databases.update"
perms.include? "spanner.databases.get" #=> true
perms.include? "spanner.databases.update" #=> false
```

### #update

    def update(statements: [], operation_id: nil, descriptor_set: nil) -> Database::Job

Updates the database schema by adding Data Definition Language (DDL)
statements to create, update, and delete tables and indexes.
**Parameters**

- **statements** (Array\<String\>) *(defaults to: \[\])* --- The DDL statements to be applied to the database.
- **operation_id** (String, nil) *(defaults to: nil)* --- The operation ID used to perform the update. When `nil`, the update request is assigned an automatically-generated operation ID. Specifying an explicit value simplifies determining whether the statements were executed in the event that the update is replayed, or the return value is otherwise lost. This value should be unique within the database, and must be a valid identifier: `[a-z][a-z0-9_]*`. Will raise AlreadyExistsError if the named operation already exists. Optional.
- **descriptor_set** (Google::Protobuf::FileDescriptorSet, String) *(defaults to: nil)* --- The file descriptor set object to be used in the update, or alternatively, an absolute path to the generated file descriptor set. The descriptor set is only used during DDL statements, such as `CREATE PROTO BUNDLE`.
**Returns**

- ([Database::Job](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database-Job)) --- The job representing the long-running, asynchronous processing of a database schema update operation.
**Examples**

```ruby
require "google/cloud/spanner"

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

add_users_table_sql =
  <<~SQL
    CREATE TABLE users (
      id INT64 NOT NULL,
      username STRING(25) NOT NULL,
      name STRING(45) NOT NULL,
      email STRING(128),
    ) PRIMARY KEY(id)
  SQL

database.update statements: [add_users_table_sql]
```

```ruby
require "google/cloud/spanner"

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

create_proto_bundle_sql =
  <<~SQL
    CREATE PROTO BUNDLE (
      `examples.User`
    )
  SQL

create_users_table_sql =
  <<~SQL
    CREATE TABLE users (
      id INT64 NOT NULL,
      user `examples.User` NOT NULL
    ) PRIMARY KEY (id)
  SQL

database.update statements: [create_proto_bundle_sql, create_users_table_sql],
                descriptor_set: "/usr/local/user_descriptors.pb"
```

### #update_policy

    def update_policy(new_policy) -> Policy

**Aliases**

- [#policy=](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_policy=_instance_)
Updates the [Cloud IAM](https://cloud.google.com/iam/) access control
policy for this database. The policy should be read from [#policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_policy_instance_ "Google::Cloud::Spanner::Database#policy (method)").
See [Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy "Google::Cloud::Spanner::Policy (class)") for an explanation of the policy
`etag` property and how to modify policies.


<br />

You can also update the policy by passing a block to [#policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Database#Google__Cloud__Spanner__Database_policy_instance_ "Google::Cloud::Spanner::Database#policy (method)"), which
will call this method internally after the block completes.
**Parameter**

- **new_policy** ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- a new or modified Cloud IAM Policy for this database
**Returns**

- ([Policy](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-spanner/latest/Google-Cloud-Spanner-Policy)) --- The policy returned by the API update operation.
**Example**

```ruby
require "google/cloud/spanner"

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

policy = database.policy # API call

policy.add "roles/owner", "user:owner@example.com"

database.update_policy policy # API call
```

### #version_retention_period

    def version_retention_period() -> String

The version retention period for a database.
**Returns**

- (String)