# Transactions

2.25.0 (latest) 2.24.0 2.23.0 2.22.0 2.21.0 2.20.2 2.19.0 2.18.0 2.17.0 2.16.1 2.15.2 2.14.0 2.13.2 2.12.0 2.11.1 2.10.0 2.9.0 2.8.3 2.7.2 2.6.2 2.5.1 2.4.0 2.3.0 2.2.0 2.1.6 2.0.1 1.15.5 1.14.0 1.13.2 1.12.0 1.11.0 1.10.0 1.9.0 Create / interact with Google Cloud Datastore transactions.

### *class* google.cloud.datastore.transaction.Transaction(client, read_only=False, read_time=None, begin_later=False)

Bases: [`google.cloud.datastore.batch.Batch`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/batches#google.cloud.datastore.batch.Batch)

An abstraction representing datastore Transactions.

Transactions can be used to build up a bulk mutation and ensure all
or none succeed (transactionally).

For example, the following snippet of code will put the two `save`
operations (either `insert` or `upsert`) into the same
mutation, and execute those within a transaction:

    >>> entity1 = datastore.Entity(client.key('EntityKind', 1234))
    >>> entity2 = datastore.Entity(client.key('EntityKind', 2345))
    >>> with client.transaction():
    ...     client.put_multi([entity1, entity2])

Because it derives from [`Batch`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/batches#google.cloud.datastore.batch.Batch),
`Transaction` also provides `put()` and `delete()` methods:

    >>> with client.transaction() as xact:
    ...     xact.put(entity1)
    ...     xact.delete(entity2.key)

By default, the transaction is rolled back if the transaction block
exits with an error:

    >>> def do_some_work():
    ...    return
    >>> class SomeException(Exception):
    ...    pass
    >>> with client.transaction():
    ...     do_some_work()
    ...     raise SomeException  # rolls back
    Traceback (most recent call last):
      ...
    SomeException

If the transaction block exits without an exception, it will commit
by default.

**WARNING**: \> Inside a transaction, automatically assigned IDs for
> entities will not be available at save time! That means, if you
> try:
>
>     >>> with client.transaction():
>     ...     thing1 = datastore.Entity(key=client.key('Thing'))
>     ...     client.put(thing1)

`thing1` won't have a complete key until the transaction is
committed.

Once you exit the transaction (or call `commit()`), the
automatically generated ID will be assigned to the entity:

    >>> with client.transaction():
    ...     thing2 = datastore.Entity(key=client.key('Thing'))
    ...     client.put(thing2)
    ...     print(thing2.key.is_partial)  # There is no ID on this key.
    ...
    True
    >>> print(thing2.key.is_partial)  # There *is* an ID.
    False

If you don't want to use the context manager you can initialize a
transaction manually:

    >>> transaction = client.transaction()
    >>> transaction.begin()
    >>>
    >>> thing3 = datastore.Entity(key=client.key('Thing'))
    >>> transaction.put(thing3)
    >>>
    >>> transaction.commit()

- **Parameters**

  - **client** ([`google.cloud.datastore.client.Client`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/client#google.cloud.datastore.client.Client)) -- the client used to connect to datastore.

  - **read_only** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- indicates the transaction is read only.

  - **read_time** (*datetime* ) -- (Optional) Time at which the transaction reads entities.
    Only allowed when `read_only=True`. This feature is in private preview.

  - **begin_later** ([*bool*](https://docs.python.org/3/library/functions.html#bool)) -- (Optional) If True, the transaction will be started
    lazily (i.e. when the first RPC is made). If False,
    the transaction will be started as soon as the context manager
    is entered. self.begin() can also be called manually to begin
    the transaction at any time. Default is False.

- **Raises**

  [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) if read_time is specified when
  `read_only=False`.

#### begin(retry=None, timeout=None)

Begins a transaction.

This method is called automatically when entering a with
statement, however it can be called explicitly if you don't want
to use a context manager. If used outside a context manager,
client.get calls targeting the transaction and commit/rollback calls
will need to be managed explicitly as well.

- **Parameters**

  - **retry** ([`google.api_core.retry.Retry`](https://googleapis.dev/python/google-api-core/latest/retry.html#google.api_core.retry.Retry)) -- A retry object used to retry requests. If `None` is specified,
    requests will be retried using a default configuration.

  - **timeout** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Time, in seconds, to wait for the request to complete.
    Note that if `retry` is specified, the timeout applies
    to each individual attempt.

- **Raises**

  `ValueError` if the transaction has
  already begun.

#### commit(retry=None, timeout=None)

Commits the transaction.

This is called automatically upon exiting a with statement,
however it can be called explicitly if you don't want to use a
context manager.

This method has necessary side-effects:

- Sets the current transaction's ID to None.

- **Parameters**

  - **retry** ([`google.api_core.retry.Retry`](https://googleapis.dev/python/google-api-core/latest/retry.html#google.api_core.retry.Retry)) -- A retry object used to retry requests. If `None` is specified,
    requests will be retried using a default configuration.

  - **timeout** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Time, in seconds, to wait for the request to complete.
    Note that if `retry` is specified, the timeout applies
    to each individual attempt.

#### current()

Return the topmost transaction.

**NOTE**: If the topmost element on the stack is not a transaction,
returns None.

- **Return type**

  `google.cloud.datastore.transaction.Transaction` or None
- **Returns**

  The current transaction (if any are active).

#### *property* database()

Getter for database in which the batch will run.

- **Return type**

  [`str`](https://docs.python.org/3/library/stdtypes.html#str)
- **Returns**

  The database in which the batch will run.

#### delete(key)

Remember a key to be deleted during `commit()`.

- **Parameters**

  **key** ([`google.cloud.datastore.key.Key`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/keys#google.cloud.datastore.key.Key)) -- the key to be deleted.
- **Raises**

  `ValueError` if the batch is not in
  progress, if key is not complete, or if the key's
  `project` does not match ours.

#### *property* id()

Getter for the transaction ID.

- **Return type**

  [bytes](https://docs.python.org/3/library/stdtypes.html#bytes) or None
- **Returns**

  The ID of the current transaction, or None if not started.

#### *property* mutations()

Getter for the changes accumulated by this batch.

Every batch is committed with a single commit request containing all
the work to be done as mutations. Inside a batch, calling `put()`
with an entity, or `delete()` with a key, builds up the request by
adding a new mutation. This getter returns the protobuf that has been
built-up so far.

- **Return type**

  iterable
- **Returns**

  The list of `datastore_pb2.Mutation`
  protobufs to be sent in the commit request.

#### *property* namespace()

Getter for namespace in which the batch will run.

- **Return type**

  [`str`](https://docs.python.org/3/library/stdtypes.html#str)
- **Returns**

  The namespace in which the batch will run.

#### *property* project()

Getter for project in which the batch will run.

- **Return type**

  [`str`](https://docs.python.org/3/library/stdtypes.html#str)
- **Returns**

  The project in which the batch will run.

#### put(entity)

Adds an entity to be committed.

Ensures the transaction is not marked readonly.
Please see documentation at
[`put()`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/batches#google.cloud.datastore.batch.Batch.put)

- **Parameters**

  **entity** ([`Entity`](https://docs.cloud.google.com/python/docs/reference/datastore/latest/entities#google.cloud.datastore.entity.Entity)) -- the entity to be saved.
- **Raises**

  [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) if the transaction
  is marked ReadOnly

#### rollback(retry=None, timeout=None)

Rolls back the current transaction.

This method has necessary side-effects:

- Sets the current transaction's ID to None.

- **Parameters**

  - **retry** ([`google.api_core.retry.Retry`](https://googleapis.dev/python/google-api-core/latest/retry.html#google.api_core.retry.Retry)) -- A retry object used to retry requests. If `None` is specified,
    requests will be retried using a default configuration.

  - **timeout** ([*float*](https://docs.python.org/3/library/functions.html#float)) -- Time, in seconds, to wait for the request to complete.
    Note that if `retry` is specified, the timeout applies
    to each individual attempt.