Database API#

User friendly container for Cloud Spanner Database.

class google.cloud.spanner.database.BatchCheckout(database)[source]#

Bases: object

Context manager for using a batch from a database.

Inside the context manager, checks out a session from the database, creates a batch from it, making the batch available.

Caller must not use the batch to perform API requests outside the scope of the context manager.

Parameters:database (Database) – database to use
class google.cloud.spanner.database.Database(database_id, instance, ddl_statements=(), pool=None)[source]#

Bases: object

Representation of a Cloud Spanner Database.

We can use a Database to:

Parameters:
  • 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.
batch()[source]#

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.

Return type:BatchCheckout
Returns:new wrapper
create()[source]#

Create this database within its instance

Inclues 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

ddl_statements#

DDL Statements used to define database schema.

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

Return type:sequence of string
Returns:the statements
drop()[source]#

Drop this database.

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

execute_sql(sql, params=None, param_types=None, query_mode=None, resume_token='')[source]#

Perform an ExecuteStreamingSql API request.

Parameters:
  • sql (str) – SQL query statement
  • params (dict, {str -> column value}) – values for parameter replacement. Keys must match the names used in sql.
  • param_types (dict, {str -> google.spanner.v1.type_pb2.TypeCode}) – (Optional) explicit types for one or more param values; overrides default type detection on the back-end.
  • query_mode (google.spanner.v1.spanner_pb2.ExecuteSqlRequest.QueryMode) – Mode governing return of results / query plan. See: https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1
  • resume_token (bytes) – token for resuming previously-interrupted query
Return type:

StreamedResultSet

Returns:

a result set instance which can be used to consume rows.

exists()[source]#

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

classmethod from_pb(database_pb, instance, pool=None)[source]#

Creates an instance of this class from a protobuf.

Parameters:
  • database_pb (google.spanner.v2.spanner_instance_admin_pb2.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.
Return type:

Database

Returns:

The database parsed from the protobuf response.

Raises:

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.

name#

Database name used in requests.

Note

This property will not change if database_id does not, but the return value is not cached.

The database name is of the form

"projects/../instances/../databases/{database_id}"
Return type:str
Returns:The database name.
read(table, columns, keyset, index='', limit=0, resume_token='')[source]#

Perform a StreamingRead API request for rows in a table.

Parameters:
  • table (str) – name of the table from which to fetch data
  • columns (list of str) – names of columns to be retrieved
  • keyset (KeySet) – keys / ranges identifying rows to be retrieved
  • index (str) – (Optional) name of index to use, rather than the table’s primary key
  • limit (int) – (Optional) maxiumn number of rows to return
  • resume_token (bytes) – token for resuming previously-interrupted read
Return type:

StreamedResultSet

Returns:

a result set instance which can be used to consume rows.

reload()[source]#

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

run_in_transaction(func, *args, **kw)[source]#

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

Parameters:
  • 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 timeout.
Return type:

datetime.datetime

Returns:

timestamp of committed transaction

session()[source]#

Factory to create a session for this database.

Return type:Session
Returns:a session bound to this database.
snapshot(read_timestamp=None, min_read_timestamp=None, max_staleness=None, exact_staleness=None)[source]#

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

If no options are passed, reads will use the strong model, reading at a timestamp where all previously committed transactions are visible.

Parameters:
  • read_timestamp (datetime.datetime) – Execute all reads at the given timestamp.
  • min_read_timestamp (datetime.datetime) – Execute all reads at a timestamp >= min_read_timestamp.
  • max_staleness (datetime.timedelta) – Read data at a timestamp >= NOW - max_staleness seconds.
  • exact_staleness (datetime.timedelta) – Execute all reads at a timestamp that is exact_staleness old.
Return type:

Snapshot

Returns:

a snapshot bound to this session

Raises:

ValueError if the session has not yet been created.

Return type:

SnapshotCheckout

Returns:

new wrapper

spanner_api#

Helper for session-related API calls.

update_ddl(ddl_statements)[source]#

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

Return type:google.cloud.operation.Operation
Returns:an operation instance
class google.cloud.spanner.database.SnapshotCheckout(database, read_timestamp=None, min_read_timestamp=None, max_staleness=None, exact_staleness=None)[source]#

Bases: object

Context manager for using a snapshot from a database.

Inside the context manager, checks out a session from the database, creates a snapshot from it, making the snapshot available.

Caller must not use the snapshot to perform API requests outside the scope of the context manager.

Parameters:
  • database (Database) – database to use
  • read_timestamp (datetime.datetime) – Execute all reads at the given timestamp.
  • min_read_timestamp (datetime.datetime) – Execute all reads at a timestamp >= min_read_timestamp.
  • max_staleness (datetime.timedelta) – Read data at a timestamp >= NOW - max_staleness seconds.
  • exact_staleness (datetime.timedelta) – Execute all reads at a timestamp that is exact_staleness old.