Session API

Wrapper for Cloud Spanner Session objects.

google.cloud.spanner_v1.session.DEFAULT_RETRY_TIMEOUT_SECS( = 3 )

Default timeout used by Session.run_in_transaction().

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

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

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

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

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.

    • NotFound – if the session does not exist

execute_sql(sql, params=None, param_types=None, query_mode=None, query_options=None, request_options=None, retry=<_MethodDefault._DEFAULT_VALUE:

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.

  • Return type

    StreamedResultSet

  • Returns

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

exists()

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

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)

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

  • Return type

    StreamedResultSet

  • Returns

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

run_in_transaction(func, *args, **kw)

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.

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

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

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)

Bases: object

Specifies required API for concrete session pool implementations.

bind(database)

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.

clear()

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.

property database_role()

User-assigned database_role for sessions created by the pool.

  • Return type

    str

  • Returns

    database_role assigned by the user

get()

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.

property labels()

User-assigned labels for sessions created by the pool.

  • Return type

    dict (str -> str)

  • Returns

    labels assigned by the user

put(session)

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)

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)

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

bind(database)

Associate the pool with a database.

  • Parameters

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

clear()

Delete all sessions in the pool.

get()

Check a session out from the pool.

  • Return type

    Session

  • Returns

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

put(session)

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)

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

bind(database)

Associate the pool with a database.

  • Parameters

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

clear()

Delete all sessions in the pool.

get(timeout=None)

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)

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)

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*](https://python.readthedocs.io/en/latest/library/constants.html#None)) – (Optional) user-assigned labels for sessions created by the pool.

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

bind(database)

Associate the pool with a database.

  • Parameters

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

clear()

Delete all sessions in the pool.

get(timeout=None)

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

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)

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)

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)

Bases: google.cloud.spanner_v1.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.

    • labels (dict* (str -> str) or [None*](https://python.readthedocs.io/en/latest/library/constants.html#None)) – (Optional) user-assigned labels for sessions created by the pool.

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

begin_pending_transactions()

Begin all transactions for sessions added to the pool.

bind(database)

Associate the pool with a database.

  • Parameters

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

put(session)

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.