Session API#

Wrapper for Cloud Spanner Session objects.

google.cloud.spanner.session.DEFAULT_RETRY_TIMEOUT_SECS = 30#

Default timeout used by Session.run_in_transaction().

class google.cloud.spanner.session.Session(database)[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.
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.
delete()[source]#

Delete this session.

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

Raises:ValueError if session_id is not already set.
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 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.
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.
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.

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

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

snapshot(read_timestamp=None, min_read_timestamp=None, max_staleness=None, exact_staleness=None)[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

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.

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.pool.AbstractSessionPool[source]#

Bases: object

Specifies required API for concrete session pool implementations.

bind(database)[source]#

Associate the pool with a database.

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

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

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.

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.

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.

session(**kwargs)[source]#

Check out a session from the pool.

Parameters:kwargs (dict) – (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.pool.BurstyPool(target_size=10)[source]#

Bases: google.cloud.spanner.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
bind(database)[source]#

Associate the pool with a database.

Parameters:database (Database) – database used by the pool: used 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.pool.FixedSizePool(size=10, default_timeout=10)[source]#

Bases: google.cloud.spanner.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.
bind(database)[source]#

Associate the pool with a database.

Parameters:database (Database) – database used by the pool: 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:six.moves.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:six.moves.queue.Full if the queue is full.
class google.cloud.spanner.pool.PingingPool(size=10, default_timeout=10, ping_interval=3000)[source]#

Bases: google.cloud.spanner.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.exists()).
  • 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.
bind(database)[source]#

Associate the pool with a database.

Parameters:database (Database) – database used by the pool: 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:six.moves.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:six.moves.queue.Full if the queue is full.
class google.cloud.spanner.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 (dict) – extra keyword arguments to be passed to pool.get().
class google.cloud.spanner.pool.TransactionPingingPool(size=10, default_timeout=10, ping_interval=3000)[source]#

Bases: google.cloud.spanner.pool.PingingPool

Concrete session pool implementation:

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.
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: used 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:six.moves.queue.Full if the queue is full.