Class Database (3.46.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,
)

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 Instance

The instance that owns the database.

ddl_statements list of string

(Optional) DDL statements, excluding the CREATE DATABASE statement.

pool concrete subclass of AbstractSessionPool.

(Optional) session pool to be used by database. If not passed, the database will construct an instance of 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 EncryptionConfig or 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 or RestoreDatabaseEncryptionConfig

database_dialect 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.

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
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.

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

Returns
Type Description
str The database name.

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

spanner_api

Helper for session-related API calls.

state

State of this database.

Returns
Type Description
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)

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 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.

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.

Returns
Type Description
BatchCheckout new wrapper

batch_snapshot

batch_snapshot(
    read_timestamp=None, exact_staleness=None, session_id=None, transaction_id=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
BatchSnapshot new wrapper

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()

execute_partitioned_dml

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

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 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

request_options RequestOptions

(Optional) Common options for this request. If a dict is provided, it must be of the same form as the protobuf message RequestOptions. Please note, the transactionTag setting will be ignored as it is not supported for partitioned DML.

Returns
Type Description
int Count of rows affected by the DML statement.

exists

exists()
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 Instance

A instance protobuf object.

instance Instance

The instance that owns the database.

pool concrete subclass of 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

mutation_groups

mutation_groups()

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
MutationGroupsCheckout new wrapper

reload

reload()
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
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.

func callable

takes a required positional argument, the transaction, and additional positional / keyword arguments as supplied by the caller.

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.

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
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 constructor.

Returns
Type Description
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
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

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="")
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

Exceptions
Type Description
NotFound if the database does not exist
Returns
Type Description
google.api_core.operation.Operation an operation instance