# Class Database (3.68.0)

3.68.0 (latest) 3.67.0 3.66.0 3.65.0 3.64.0 3.63.0 3.62.0 3.61.0 3.60.0 3.59.0 3.58.0 3.57.0 3.56.0 3.55.0 3.54.0 3.53.0 3.52.0 3.51.0 3.50.1 3.46.0 3.45.0 3.44.0 3.43.0 3.42.0 3.41.0 3.40.1 3.39.0 3.38.0 3.37.0 3.36.0 3.35.1 3.34.0 3.33.0 3.32.0 3.31.0 3.30.0 3.29.0 3.28.0 3.27.1 3.26.0 3.25.0 3.24.0 3.23.0 3.22.2 3.21.0 3.20.0 3.19.0 3.18.0 3.17.0 3.16.0 3.15.1 3.14.1 3.13.0 3.12.1 3.11.1 3.10.0 3.9.0 3.8.0 3.7.0 3.6.0 3.5.0 3.4.0 3.3.0 3.2.0 3.1.0 3.0.0 2.1.1 2.0.0 1.19.3 1.18.0 1.17.1 1.16.0 1.15.1 1.14.0 1.13.0 1.12.0 1.11.0 1.10.0

    Database(
        database_id,
        instance,
        ddl_statements=(),
        pool=None,
        logger=None,
        encryption_config=None,
        database_dialect=DatabaseDialect.DATABASE_DIALECT_UNSPECIFIED,
        database_role=None,
        enable_drop_protection=False,
        proto_descriptors=None,
    )

Representation of a Cloud Spanner Database.

We can use a `Database` to:

- `create` the database
- `reload` the database
- `update` the database
- `drop` the database

| ## Parameters ||
|---|---|
| **Name** | **Description** |
| `database_id` | `str` The ID of the database. |
| `instance` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.instance.Instance` The instance that owns the database. |
| `ddl_statements` | `list of string` (Optional) DDL statements, excluding the CREATE DATABASE statement. |
| `pool` | `concrete subclass of https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.pool.AbstractSessionPool.` (Optional) session pool to be used by database. If not passed, the database will construct an instance of [BurstyPool](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.pool.BurstyPool). |
| `logger` | `` `logging.Logger` `` (Optional) a custom logger that is used if `log_commit_stats` is `True` to log commit statistics. If not passed, a logger will be created when needed that will log the commit statistics to stdout. |
| `encryption_config` | `` https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.EncryptionConfig or https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.RestoreDatabaseEncryptionConfig or `dict` `` (Optional) Encryption configuration for the database. If a dict is provided, it must be of the same form as either of the protobuf messages [EncryptionConfig](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.EncryptionConfig) or [RestoreDatabaseEncryptionConfig](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.RestoreDatabaseEncryptionConfig) |
| `database_dialect` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.DatabaseDialect` (Optional) database dialect for the database |
| `database_role` | `str or None` (Optional) user-assigned database_role for the session. |
| `enable_drop_protection` | `boolean` (Optional) Represents whether the database has drop protection enabled or not. |
| `proto_descriptors` | `bytes` (Optional) Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements in 'ddl_statements' above. |

## Properties

### create_time

Create time of this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `datetime.datetime` `` | a datetime object representing the create time of this database |

### database_dialect

DDL Statements used to define database schema.

See
cloud.google.com/spanner/docs/data-definition-language

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.DatabaseDialect` | the dialect of the database |

### database_role

User-assigned database_role for sessions created by the pool.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `str` | a str with the name of the database role. |

### ddl_statements

DDL Statements used to define database schema.

See
cloud.google.com/spanner/docs/data-definition-language

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `sequence of string` | the statements |

### default_leader

The read-write region which contains the database's leader replicas.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `str` | a string representing the read-write region |

### default_schema_name

Default schema name for this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `str` | "" for GoogleSQL and "public" for PostgreSQL |

### earliest_version_time

The earliest time at which older versions of the data can be read.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `datetime.datetime` `` | a datetime object representing the earliest version time |

### enable_drop_protection

Whether the database has drop protection enabled.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `boolean` | a boolean representing whether the database has drop protection enabled |

### encryption_config

Encryption config for this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `EncryptionConfig` | an object representing the encryption config for this database |

### encryption_info

Encryption info for this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `a list of EncryptionInfo` | a list of objects representing encryption info for this database |

### logger

Logger used by the database.

The default logger will log commit stats at the log level INFO using
`sys.stderr`.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `logging.Logger` or `None` `` | the logger |

### name

Database name used in requests.

<br />

> [!NOTE]
> **Note:** This property will not change if `database_id` does not, but the return value is not cached.

`"projects/../instances/../databases/{database_id}"`

<br />

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `str` | The database name. |

### observability_options

Returns the observability options that you set when creating
the SpannerClient.

### proto_descriptors

Proto Descriptors for this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `bytes` | bytes representing the proto descriptors for this database |

### reconciling

Whether the database is currently reconciling.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `boolean` | a boolean representing whether the database is reconciling |

### restore_info

Restore info for this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `RestoreInfo` | an object representing the restore info for this database |

### sessions_manager

Returns the database sessions manager.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `DatabaseSessionsManager` | The sessions manager for this database. |

### spanner_api

Helper for session-related API calls.

### state

State of this database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_database_v1.types.Database.State` | an enum describing the state of the database |

### version_retention_period

The period in which Cloud Spanner retains all versions of data
for the database.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `str` | a string representing the duration of the version retention period |

## Methods

### batch

    batch(
        request_options=None,
        max_commit_delay=None,
        exclude_txn_from_change_streams=False,
        isolation_level=IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
        read_lock_mode=ReadLockMode.READ_LOCK_MODE_UNSPECIFIED,
        client_context=None,
        **kw
    )

Return an object which wraps a batch.

The wrapper *must* be used as a context manager, with the batch
as the value returned by the wrapper.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `request_options` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.RequestOptions` (Optional) Common options for the commit request. If a dict is provided, it must be of the same form as the protobuf message [RequestOptions](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.RequestOptions). |
| `max_commit_delay` | `` `datetime.timedelta` `` (Optional) The amount of latency this request is willing to incur in order to improve throughput. Value must be between 0ms and 500ms. |
| `exclude_txn_from_change_streams` | `bool` (Optional) If true, instructs the transaction to be excluded from being recorded in change streams with the DDL option `allow_txn_exclusion=true`. This does not exclude the transaction from being recorded in the change streams with the DDL option `allow_txn_exclusion` being false or unset. |
| `isolation_level` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.TransactionOptions.IsolationLevel` (Optional) Sets the isolation level for this transaction. This overrides any default isolation level set for the client. |
| `read_lock_mode` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.TransactionOptions.ReadWrite.ReadLockMode` (Optional) Sets the read lock mode for this transaction. This overrides any default read lock mode set for the client. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.database.BatchCheckout` | new wrapper |

### batch_snapshot

    batch_snapshot(
        read_timestamp=None,
        exact_staleness=None,
        session_id=None,
        transaction_id=None,
        client_context=None,
    )

Return an object which wraps a batch read / query.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `read_timestamp` | `` `datetime.datetime` `` Execute all reads at the given timestamp. |
| `exact_staleness` | `` `datetime.timedelta` `` Execute all reads at a timestamp that is `exact_staleness` old. |
| `session_id` | `str` id of the session used in transaction |
| `transaction_id` | `str` id of the transaction |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.database.BatchSnapshot` | new wrapper |

### close

    close()

Clean up underlying session manager and background tasks.

### create

    create()

Create this database within its instance

Includes any configured schema assigned to `ddl_statements`.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase>

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `Conflict` | if the database already exists |
| `NotFound` | if the instance owning the database does not exist |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.api_core.operation.Operation` `` | a future used to poll the status of the create request |

### drop

    drop()

Drop this database.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase>

### execute_partitioned_dml

    execute_partitioned_dml(
        dml,
        params=None,
        param_types=None,
        query_options=None,
        request_options=None,
        exclude_txn_from_change_streams=False,
    )

Execute a partitionable DML statement.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `dml` | `str` DML statement |
| `params` | `dict, {str -> column value}` values for parameter replacement. Keys must match the names used in `dml`. |
| `param_types` | `dict[str -> Union[dict, .types.Type]]` (Optional) maps explicit types for one or more param values; required if parameters are passed. |
| `query_options` | `` https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryOptions or `dict` `` (Optional) Query optimizer configuration to use for the given query. If a dict is provided, it must be of the same form as the protobuf message [QueryOptions](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryOptions) |
| `request_options` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.RequestOptions` (Optional) Common options for this request. If a dict is provided, it must be of the same form as the protobuf message [RequestOptions](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.types.RequestOptions). Please note, the `transactionTag` setting will be ignored as it is not supported for partitioned DML. |
| `exclude_txn_from_change_streams` | `bool` (Optional) If true, instructs the transaction to be excluded from being recorded in change streams with the DDL option `allow_txn_exclusion=true`. This does not exclude the transaction from being recorded in the change streams with the DDL option `allow_txn_exclusion` being false or unset. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `int` | Count of rows affected by the DML statement. |

### exists

    exists()

Test whether this database exists.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL>

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `bool` | True if the database exists, else false. |

### from_pb

    from_pb(database_pb, instance, pool=None)

Creates an instance of this class from a protobuf.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `database_pb` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_instance_v1.types.Instance` A instance protobuf object. |
| `instance` | `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_admin_instance_v1.types.Instance` The instance that owns the database. |
| `pool` | `concrete subclass of https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.pool.AbstractSessionPool.` (Optional) session pool to be used by database. |

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `ValueError` | if the instance name does not match the expected format or if the parsed project ID does not match the project ID on the instance's client, or if the parsed instance ID does not match the instance's ID. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `Database` `` | The database parsed from the protobuf response. |

### get_iam_policy

    get_iam_policy(policy_version=None)

Gets the access control policy for a database resource.

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `policy_version` | `int` (Optional) the maximum policy version that will be used to format the policy. Valid values are 0, 1 ,3. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.iam.v1.policy_pb2.Policy` `` | returns an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. |

### is_optimized

    is_optimized()

Test whether this database has finished optimizing.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `bool` | True if the database state is READY, else False. |

### is_ready

    is_ready()

Test whether this database is ready for use.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `bool` | True if the database state is READY_OPTIMIZING or READY, else False. |

### list_database_operations

    list_database_operations(filter_="", page_size=None)

List database operations for the database.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `filter_` | `str` Optional. A string specifying a filter for which database operations to list. |
| `page_size` | `int` Optional. The maximum number of operations in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type: `google.api_core.page_iterator.Iterator` |

### list_database_roles

    list_database_roles(page_size=None)

Lists Cloud Spanner database roles.

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `page_size` | `int` Optional. The maximum number of database roles in each page of results from this request. Non-positive values are ignored. Defaults to a sensible value set by the API. :type: Iterable |

### list_tables

    list_tables(schema="_default")

List tables within the database.

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `schema` | `str` The schema to search for tables, or None for all schemas. Use the special string "_default" to search for tables in the default schema of the database. :type: Iterable |

### metadata_and_request_id

    metadata_and_request_id(nth_request, nth_attempt, prior_metadata=[], span=None)

Return metadata and request ID string.

This method returns both the gRPC metadata with request ID header
and the request ID string itself, which can be used to augment errors.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `tuple` | (metadata_list, request_id_string) |

### mutation_groups

    mutation_groups(client_context=None)

Return an object which wraps a mutation_group.

The wrapper *must* be used as a context manager, with the mutation group
as the value returned by the wrapper.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.database.MutationGroupsCheckout` | new wrapper |

### reload

    reload()

Reload this database.

Refresh any configured schema into `ddl_statements`.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL>

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `NotFound` | if the database does not exist |

### restore

    restore(source)

Restore from a backup to this database.

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `source` | `Backup` the path of the source being restored from. |

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `Conflict` | if the database already exists |
| `NotFound` | if the instance owning the database does not exist, or if the backup being restored from does not exist |
| `ValueError` | if backup is not set |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.api_core.operation.Operation` `` | a future used to poll the status of the create request |

### run_in_transaction

    run_in_transaction(func, *args, **kw)

Perform a unit of work in a transaction, retrying on abort.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `func` | `callable` takes a required positional argument, the transaction, and additional positional / keyword arguments as supplied by the caller. |
| `args` | `tuple` additional positional arguments to be passed to `func`. |
| `kw` | `dict` (Optional) keyword arguments to be passed to `func`. If passed, "timeout_secs" will be removed and used to override the default retry timeout which defines maximum timestamp to continue retrying the transaction. "max_commit_delay" will be removed and used to set the max_commit_delay for the request. Value must be between 0ms and 500ms. "exclude_txn_from_change_streams" if true, instructs the transaction to be excluded from being recorded in change streams with the DDL option `allow_txn_exclusion=true`. This does not exclude the transaction from being recorded in the change streams with the DDL option `allow_txn_exclusion` being false or unset. "isolation_level" sets the isolation level for the transaction. "read_lock_mode" sets the read lock mode for the transaction. |

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `Exception` | reraises any non-ABORT exceptions raised by `func`. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `Any` | The return value of `func`. |

### session

    session(labels=None, database_role=None)

Factory to create a session for this database.

Deprecated. Sessions should be checked out indirectly using context
managers or xref_run_in_transaction,
rather than built directly from the database.

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `labels` | `dict (str -> str) or None` (Optional) user-assigned labels for the session. |
| `database_role` | `str` (Optional) user-assigned database_role for the session. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.session.Session` | a session bound to this database. |

### set_iam_policy

    set_iam_policy(policy)

Sets the access control policy on a database resource.
Replaces any existing policy.

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.iam.v1.policy_pb2.Policy` `` | returns the new Identity and Access Management (IAM) policy. |

### snapshot

    snapshot(**kw)

Return an object which wraps a snapshot.

The wrapper *must* be used as a context manager, with the snapshot
as the value returned by the wrapper.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions.ReadOnly>

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `kw` | `dict` Passed through to [Snapshot](https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.snapshot.Snapshot) constructor. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.snapshot.SnapshotCheckout` | new wrapper |

### table

    table(table_id)

Factory to create a table object within this database.

Note: This method does not create a table in Cloud Spanner, but it can
be used to check if a table exists.

    my_table = database.table("my_table")
    if my_table.exists():
        print("Table with ID 'my_table' exists.")
    else:
        print("Table with ID 'my_table' does not exist.")

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `table_id` | `str` The ID of the table. |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `https://docs.cloud.google.com/python/docs/reference/spanner/latest/google.cloud.spanner_v1.table.Table` | a table owned by this database. |

### update

    update(fields)

Update this database.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabase>

> [!NOTE]
> **Note:** Updates the specified fields of a Cloud Spanner database. Currently, only the `enable_drop_protection` field supports updates. To change this value before updating, set it via .. code:: python database.enable_drop_protection = True

| **Parameter** ||
|---|---|
| **Name** | **Description** |
| `fields` | `Sequence[str]` a list of fields to update |

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `NotFound` | if the database does not exist |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.api_core.operation.Operation` `` | an operation instance |

### update_ddl

    update_ddl(ddl_statements, operation_id="", proto_descriptors=None)

Update DDL for this database.

Apply any configured schema from `ddl_statements`.

See
<https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl>

| **Parameters** ||
|---|---|
| **Name** | **Description** |
| `ddl_statements` | `Sequence[str]` a list of DDL statements to use on this database |
| `operation_id` | `str` (optional) a string ID for the long-running operation |
| `proto_descriptors` | `bytes` (optional) Proto descriptors used by CREATE/ALTER PROTO BUNDLE statements |

| **Exceptions** ||
|---|---|
| **Type** | **Description** |
| `NotFound` | if the database does not exist |

| **Returns** ||
|---|---|
| **Type** | **Description** |
| `` `google.api_core.operation.Operation` `` | an operation instance |

### with_error_augmentation

    with_error_augmentation(nth_request, nth_attempt, prior_metadata=[], span=None)

Context manager for gRPC calls with error augmentation.

This context manager provides both metadata with request ID and
automatically augments any exceptions with the request ID.