As of January 1, 2020 this library no longer supports Python 2 on the latest released version. Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.

Session API

Wrapper for Cloud Spanner Session objects.

google.cloud.spanner_v1.session.DEFAULT_RETRY_TIMEOUT_SECS = 30

Default timeout used by Session.run_in_transaction().

class google.cloud.spanner_v1.session.Session(database, labels=None, database_role=None)[source]

Bases: object

Representation of a Cloud Spanner Session.

We can use a Session to:

  • create() the session

  • Use exists() to check for the existence of the session

  • drop() the session

Parameters
  • database (Database) – The database to which the session is bound.

  • labels (dict (str -> str)) – (Optional) User-assigned labels for the session.

  • database_role (str) – (Optional) user-assigned database_role for the session.

batch()[source]

Factory to create a batch for this session.

Return type

Batch

Returns

a batch bound to this session

Raises

ValueError – if the session has not yet been created.

create()[source]

Create this session, bound to its database.

See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.CreateSession

Raises

ValueError – if session_id is already set.

property database_role

User-assigned database-role for the session.

Return type

str

Returns

the database role str (None if no database role were assigned).

delete()[source]

Delete this session.

See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.GetSession

Raises
execute_sql(sql, params=None, param_types=None, query_mode=None, query_options=None, request_options=None, retry=_MethodDefault._DEFAULT_VALUE, timeout=_MethodDefault._DEFAULT_VALUE, column_info=None)[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 -> TypeCode}) – (Optional) explicit types for one or more param values; overrides default type detection on the back-end.

  • query_mode (QueryMode) – Mode governing return of results / query plan. See: QueryMode.

  • query_options (QueryOptions or dict) – (Optional) Options that are provided for query plan stability.

  • request_options (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.

  • retry (Retry) – (Optional) The retry settings for this request.

  • timeout (float) – (Optional) The timeout for this request.

  • column_info (dict) – (Optional) dict of mapping between column names and additional column information. An object where column names as keys and custom objects as corresponding values for deserialization. It’s specifically useful for data types like protobuf where deserialization logic is on user-specific code. When provided, the custom object enables deserialization of backend-received column data. If not provided, data remains serialized as bytes for Proto Messages and integer for Proto Enums.

Return type

StreamedResultSet

Returns

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

exists()[source]

Test for the existence of this session.

See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.GetSession

Return type

bool

Returns

True if the session exists on the back-end, else False.

property labels

User-assigned labels for the session.

Return type

dict (str -> str)

Returns

the labels dict (empty if no labels were assigned.

property name

Session name used in requests.

Note

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

The session name is of the form

"projects/../instances/../databases/../sessions/{session_id}"

Return type

str

Returns

The session name.

Raises

ValueError – if session is not yet created

ping()[source]

Ping the session to keep it alive by executing “SELECT 1”.

Raises

ValueError – if session_id is not already set.

read(table, columns, keyset, index='', limit=0, column_info=None)[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) maximum number of rows to return

  • column_info (dict) – (Optional) dict of mapping between column names and additional column information. An object where column names as keys and custom objects as corresponding values for deserialization. It’s specifically useful for data types like protobuf where deserialization logic is on user-specific code. When provided, the custom object enables deserialization of backend-received column data. If not provided, data remains serialized as bytes for Proto Messages and integer for Proto Enums.

Return type

StreamedResultSet

Returns

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

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 retry timeout which defines maximum timestamp to continue retrying the transaction. “commit_request_options” will be removed and used to set the request options for the commit request. “max_commit_delay” will be removed and used to set the max commit delay for the request. “transaction_tag” will be removed and used to set the transaction tag for the request. “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.

Return type

Any

Returns

The return value of func.

Raises

Exception – reraises any non-ABORT exceptions raised by func.

property session_id

Read-only ID, set by the back-end during create().

snapshot(**kw)[source]

Create a snapshot to perform a set of reads with shared staleness.

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

Parameters

kw (dict) – Passed through to Snapshot ctor.

Return type

Snapshot

Returns

a snapshot bound to this session

Raises

ValueError – if the session has not yet been created.

transaction()[source]

Create a transaction to perform a set of reads with shared staleness.

Return type

Transaction

Returns

a transaction bound to this session

Raises

ValueError – if the session has not yet been created.

Session Pools API

Pools managing shared Session objects.

class google.cloud.spanner_v1.pool.AbstractSessionPool(labels=None, database_role=None)[source]

Bases: object

Specifies required API for concrete session pool implementations.

Parameters
  • labels (dict (str -> str) or None) – (Optional) user-assigned labels for sessions created by the pool.

  • database_role (str) – (Optional) user-assigned database_role for the session.

bind(database)[source]

Associate the pool with a database.

Parameters

database (Database) – database used by the pool to create sessions when needed.

Concrete implementations of this method may pre-fill the pool using the database.

Raises

NotImplementedError – abstract method

clear()[source]

Delete all sessions in the pool.

Concrete implementations of this method are allowed to raise an error to signal that the pool is full, or to block until it is not full.

Raises

NotImplementedError – abstract method

property database_role

User-assigned database_role for sessions created by the pool.

Return type

str

Returns

database_role assigned by the user

get()[source]

Check a session out from the pool.

Concrete implementations of this method are allowed to raise an error to signal that the pool is exhausted, or to block until a session is available.

Raises

NotImplementedError – abstract method

property labels

User-assigned labels for sessions created by the pool.

Return type

dict (str -> str)

Returns

labels assigned by the user

put(session)[source]

Return a session to the pool.

Parameters

session (Session) – the session being returned.

Concrete implementations of this method are allowed to raise an error to signal that the pool is full, or to block until it is not full.

Raises

NotImplementedError – abstract method

session(**kwargs)[source]

Check out a session from the pool.

Parameters

kwargs – (optional) keyword arguments, passed through to the returned checkout.

Return type

SessionCheckout

Returns

a checkout instance, to be used as a context manager for accessing the session and returning it to the pool.

class google.cloud.spanner_v1.pool.BurstyPool(target_size=10, labels=None, database_role=None)[source]

Bases: google.cloud.spanner_v1.pool.AbstractSessionPool

Concrete session pool implementation:

  • “Pings” existing sessions via session.exists() before returning them.

  • Creates a new session, rather than blocking, when get() is called on an empty pool.

  • Discards the returned session, rather than blocking, when put() is called on a full pool.

Parameters
  • target_size (int) – max pool size

  • labels (dict (str -> str) or None) – (Optional) user-assigned labels for sessions created by the pool.

  • database_role (str) – (Optional) user-assigned database_role for the session.

bind(database)[source]

Associate the pool with a database.

Parameters

database (Database) – database used by the pool to create sessions when needed.

clear()[source]

Delete all sessions in the pool.

get()[source]

Check a session out from the pool.

Return type

Session

Returns

an existing session from the pool, or a newly-created session.

put(session)[source]

Return a session to the pool.

Never blocks: if the pool is full, the returned session is discarded.

Parameters

session (Session) – the session being returned.

class google.cloud.spanner_v1.pool.FixedSizePool(size=10, default_timeout=10, labels=None, database_role=None)[source]

Bases: google.cloud.spanner_v1.pool.AbstractSessionPool

Concrete session pool implementation:

  • Pre-allocates / creates a fixed number of sessions.

  • “Pings” existing sessions via session.exists() before returning them, and replaces expired sessions.

  • Blocks, with a timeout, when get() is called on an empty pool. Raises after timing out.

  • Raises when put() is called on a full pool. That error is never expected in normal practice, as users should be calling get() followed by put() whenever in need of a session.

Parameters
  • size (int) – fixed pool size

  • default_timeout (int) – default timeout, in seconds, to wait for a returned session.

  • labels (dict (str -> str) or None) – (Optional) user-assigned labels for sessions created by the pool.

  • database_role (str) – (Optional) user-assigned database_role for the session.

bind(database)[source]

Associate the pool with a database.

Parameters

database (Database) – database used by the pool to used to create sessions when needed.

clear()[source]

Delete all sessions in the pool.

get(timeout=None)[source]

Check a session out from the pool.

Parameters

timeout (int) – seconds to block waiting for an available session

Return type

Session

Returns

an existing session from the pool, or a newly-created session.

Raises

queue.Empty if the queue is empty.

put(session)[source]

Return a session to the pool.

Never blocks: if the pool is full, raises.

Parameters

session (Session) – the session being returned.

Raises

queue.Full if the queue is full.

class google.cloud.spanner_v1.pool.PingingPool(size=10, default_timeout=10, ping_interval=3000, labels=None, database_role=None)[source]

Bases: google.cloud.spanner_v1.pool.AbstractSessionPool

Concrete session pool implementation:

  • Pre-allocates / creates a fixed number of sessions.

  • Sessions are used in “round-robin” order (LRU first).

  • “Pings” existing sessions in the background after a specified interval via an API call (session.ping()).

  • Blocks, with a timeout, when get() is called on an empty pool. Raises after timing out.

  • Raises when put() is called on a full pool. That error is never expected in normal practice, as users should be calling get() followed by put() whenever in need of a session.

The application is responsible for calling ping() at appropriate times, e.g. from a background thread.

Parameters
  • size (int) – fixed pool size

  • default_timeout (int) – default timeout, in seconds, to wait for a returned session.

  • ping_interval (int) – interval at which to ping sessions.

  • labels (dict (str -> str) or None) – (Optional) user-assigned labels for sessions created by the pool.

  • database_role (str) – (Optional) user-assigned database_role for the session.

bind(database)[source]

Associate the pool with a database.

Parameters

database (Database) – database used by the pool to create sessions when needed.

clear()[source]

Delete all sessions in the pool.

get(timeout=None)[source]

Check a session out from the pool.

Parameters

timeout (int) – seconds to block waiting for an available session

Return type

Session

Returns

an existing session from the pool, or a newly-created session.

Raises

queue.Empty if the queue is empty.

ping()[source]

Refresh maybe-expired sessions in the pool.

This method is designed to be called from a background thread, or during the “idle” phase of an event loop.

put(session)[source]

Return a session to the pool.

Never blocks: if the pool is full, raises.

Parameters

session (Session) – the session being returned.

Raises

queue.Full if the queue is full.

class google.cloud.spanner_v1.pool.SessionCheckout(pool, **kwargs)[source]

Bases: object

Context manager: hold session checked out from a pool.

Parameters
  • pool (concrete subclass of AbstractSessionPool) – Pool from which to check out a session.

  • kwargs – extra keyword arguments to be passed to pool.get().

class google.cloud.spanner_v1.pool.TransactionPingingPool(size=10, default_timeout=10, ping_interval=3000, labels=None, database_role=None)[source]

Bases: google.cloud.spanner_v1.pool.PingingPool

Concrete session pool implementation:

Deprecated: TransactionPingingPool no longer begins a transaction for each of its sessions at startup. Hence the TransactionPingingPool is same as PingingPool and maybe removed in the future.

In addition to the features of PingingPool, this class creates and begins a transaction for each of its sessions at startup.

When a session is returned to the pool, if its transaction has been committed or rolled back, the pool creates a new transaction for the session and pushes the transaction onto a separate queue of “transactions to begin.” The application is responsible for flushing this queue as appropriate via the pool’s begin_pending_transactions() method.

Parameters
  • size (int) – fixed pool size

  • default_timeout (int) – default timeout, in seconds, to wait for a returned session.

  • ping_interval (int) – interval at which to ping sessions.

  • labels (dict (str -> str) or None) – (Optional) user-assigned labels for sessions created by the pool.

  • database_role (str) – (Optional) user-assigned database_role for the session.

This throws a deprecation warning on initialization.

begin_pending_transactions()[source]

Begin all transactions for sessions added to the pool.

bind(database)[source]

Associate the pool with a database.

Parameters

database (Database) – database used by the pool to create sessions when needed.

put(session)[source]

Return a session to the pool.

Never blocks: if the pool is full, raises.

Parameters

session (Session) – the session being returned.

Raises

queue.Full if the queue is full.