2.14.1 (latest) 2.14.0 2.13.1 2.12.0 2.11.0 2.10.0 2.9.0 2.8.0 2.7.1 2.6.0 2.5.0 2.4.0 2.3.1 2.2.4 Reference documentation and code samples for the Firestore in Datastore mode API class Google::Cloud::Datastore::Transaction.

## Transaction

Special Connection instance for running transactions.

See [Dataset#transaction](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset.md.txt#Google__Cloud__Datastore__Dataset_transaction_instance_ "Google::Cloud::Datastore::Dataset#transaction (method)")

## Inherits

- [Google::Cloud::Datastore::Dataset](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset.md.txt)

## Example

Transactional update:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

def transfer_funds from_key, to_key, amount
  datastore.transaction do |tx|
    from = tx.find from_key
    from["balance"] -= amount
    to = tx.find to_key
    to["balance"] += amount
    tx.save from, to
  end
end
```

## Methods

### #begin_transaction

```ruby
def begin_transaction()
```
**Alias Of** : [#start](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_start_instance_) Begins a transaction.
This method is run when a new Transaction is created.
**Raises**

- ([TransactionError](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-TransactionError.md.txt))

### #commit

```ruby
def commit() { |commit| ... }
```
Commits a transaction.
**Yields**

- (commit) --- an optional block for making changes
**Yield Parameter**

- **commit** ([Commit](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Commit.md.txt)) --- The object that changes are made on
**Examples**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task = datastore.entity "Task" do |t|
  t["type"] = "Personal"
  t["done"] = false
  t["priority"] = 4
  t["description"] = "Learn Cloud Datastore"
end

tx = datastore.transaction
begin
  if tx.find(task.key).nil?
    tx.save task
  end
  tx.commit
rescue
  tx.rollback
end
```

Commit can be passed a block, same as [Dataset#commit](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset.md.txt#Google__Cloud__Datastore__Dataset_commit_instance_ "Google::Cloud::Datastore::Dataset#commit (method)"):

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

tx = datastore.transaction
begin
  tx.commit do |c|
  c.save task3, task4
  c.delete task1, task2
  end
rescue
  tx.rollback
end
```

### #delete

```ruby
def delete(*entities_or_keys)
```
Remove entities in a transaction.
**Example**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  if tx.find(task_list.key).nil?
    tx.delete task1, task2
  end
end
```

### #find

```ruby
def find(key_or_kind, id_or_name = nil) -> Google::Cloud::Datastore::Entity, nil
```
**Aliases**

- [#get](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_get_instance_)
Retrieve an entity by providing key information. The lookup is run
within the transaction.
**Parameter**

- **key_or_kind** ([Key](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Key.md.txt), String) --- A Key object or `kind` string value.
**Returns**

- ([Google::Cloud::Datastore::Entity](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Entity.md.txt), nil)
**Examples**

Finding an entity with a key:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"
task = datastore.find task_key
```

Finding an entity with a `kind` and `id`/`name`:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task = datastore.find "Task", "sampleTask"
```

### #find_all

```ruby
def find_all(*keys) -> Google::Cloud::Datastore::Dataset::LookupResults
```
**Aliases**

- [#lookup](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_lookup_instance_)
Retrieve the entities for the provided keys. The lookup is run within
the transaction.
**Parameter**

- **keys** ([Key](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Key.md.txt)) --- One or more Key objects to find records for.
**Returns**

- ([Google::Cloud::Datastore::Dataset::LookupResults](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset-LookupResults.md.txt))
**Example**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key1 = datastore.key "Task", 123456
task_key2 = datastore.key "Task", 987654
tasks = datastore.find_all task_key1, task_key2
```

### #get

```ruby
def get(key_or_kind, id_or_name = nil) -> Google::Cloud::Datastore::Entity, nil
```
**Alias Of** : [#find](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_find_instance_) Retrieve an entity by providing key information. The lookup is run
within the transaction.
**Parameter**

- **key_or_kind** ([Key](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Key.md.txt), String) --- A Key object or `kind` string value.
**Returns**

- ([Google::Cloud::Datastore::Entity](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Entity.md.txt), nil)
**Examples**

Finding an entity with a key:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"
task = datastore.find task_key
```

Finding an entity with a `kind` and `id`/`name`:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task = datastore.find "Task", "sampleTask"
```

### #id

```ruby
def id() -> String
```
The identifier of the transaction.
**Returns**

- (String) --- the current value of id

### #insert

```ruby
def insert(*entities)
```
Insert entities in a transaction. An InvalidArgumentError will raised
if the entities cannot be inserted.
**Example**

Transactional insert:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"

task = nil
datastore.transaction do |tx|
  task = tx.find task_key
  if task.nil?
    task = datastore.entity task_key do |t|
      t["type"] = "Personal"
      t["done"] = false
      t["priority"] = 4
      t["description"] = "Learn Cloud Datastore"
    end
    tx.insert task
  end
end
```

### #lookup

```ruby
def lookup(*keys) -> Google::Cloud::Datastore::Dataset::LookupResults
```
**Alias Of** : [#find_all](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_find_all_instance_) Retrieve the entities for the provided keys. The lookup is run within
the transaction.
**Parameter**

- **keys** ([Key](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Key.md.txt)) --- One or more Key objects to find records for.
**Returns**

- ([Google::Cloud::Datastore::Dataset::LookupResults](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset-LookupResults.md.txt))
**Example**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key1 = datastore.key "Task", 123456
task_key2 = datastore.key "Task", 987654
tasks = datastore.find_all task_key1, task_key2
```

### #reset!

```ruby
def reset!()
```
Reset the transaction.
[#start](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_start_instance_ "Google::Cloud::Datastore::Transaction#start (method)") must be called afterwards.

### #rollback

```ruby
def rollback()
```
Rolls a transaction back.
**Example**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task = datastore.entity "Task" do |t|
  t["type"] = "Personal"
  t["done"] = false
  t["priority"] = 4
  t["description"] = "Learn Cloud Datastore"
end

tx = datastore.transaction
begin
  if tx.find(task.key).nil?
    tx.save task
  end
  tx.commit
rescue
  tx.rollback
end
```

### #run

```ruby
def run(query, namespace: nil, explain_options: nil) -> Google::Cloud::Datastore::Dataset::QueryResults
```
**Aliases**

- [#run_query](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_run_query_instance_)
Retrieve entities specified by a Query. The query is run within the
transaction.
**Parameters**

- **query** ([Query](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Query.md.txt), [GqlQuery](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-GqlQuery.md.txt)) --- The query with the search criteria.
- **namespace** (String) *(defaults to: nil)* --- The namespace the query is to run within.
- **explain_options** (Hash, Google::Cloud::Datastore::V1::ExplainOptions) *(defaults to: nil)* --- The options for query explanation. See V1::ExplainOptions for details. Optional.
**Returns**

- ([Google::Cloud::Datastore::Dataset::QueryResults](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset-QueryResults.md.txt))
**Examples**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  tasks = tx.run query
end
```

Run the query within a namespace with the `namespace` option:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

query = Google::Cloud::Datastore::Query.new.kind("Task").
  where("done", "=", false)
datastore.transaction do |tx|
  tasks = tx.run query, namespace: "example-ns"
end
```

Run the query with explain options:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  results = tx.run query, explain_options: { analyze: true }

  # You must iterate through all pages of results to get the metrics.
  loop do
    break unless results.next?
    results = results.next
  end

  if results.explain_metrics
    stats = results.explain_metrics.execution_stats
    puts "Read operations: #{stats.read_operations}"
  end
end
```

Run the query with explain options using a `Google::Cloud::Datastore::V1::ExplainOptions` object.

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  explain_options = Google::Cloud::Datastore::V1::ExplainOptions.new
  results = tx.run query, explain_options: explain_options

  # You must iterate through all pages of results to get the metrics.
  loop do
    break unless results.next?
    results = results.next
  end

  if results.explain_metrics
    stats = results.explain_metrics.execution_stats
    puts "Read operations: #{stats.read_operations}"
  end
end
```

### #run_aggregation

```ruby
def run_aggregation(aggregate_query, namespace: nil, explain_options: nil) -> Google::Cloud::Datastore::Dataset::AggregateQueryResults
```
Retrieve aggregate query results specified by an AggregateQuery. The query is run within the
transaction.
**Parameters**

- **aggregate_query** ([AggregateQuery](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-AggregateQuery.md.txt), [GqlQuery](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-GqlQuery.md.txt)) --- The Query object with the search criteria.
- **namespace** (String) *(defaults to: nil)* --- The namespace the query is to run within.
- **explain_options** (Hash, Google::Cloud::Datastore::V1::ExplainOptions) *(defaults to: nil)* --- The options for query explanation. See V1::ExplainOptions for details. Optional.
**Returns**

- ([Google::Cloud::Datastore::Dataset::AggregateQueryResults](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset-AggregateQueryResults.md.txt))
**Examples**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = tx.query("Task")
            .where("done", "=", false)
  aggregate_query = query.aggregate_query
                         .add_count
  res = tx.run_aggregation aggregate_query
end
```

Run the aggregate query with explain options:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = tx.query("Task")
  aggregate_query = query.aggregate_query.add_count aggregate_alias: "total"
  results = tx.run_aggregation aggregate_query, explain_options: { analyze: true }

  if results.explain_metrics
    stats = results.explain_metrics.execution_stats
    puts "Read operations: #{stats.read_operations}"
  end
end
```

### #run_query

```ruby
def run_query(query, namespace: nil, explain_options: nil) -> Google::Cloud::Datastore::Dataset::QueryResults
```
**Alias Of** : [#run](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_run_instance_) Retrieve entities specified by a Query. The query is run within the
transaction.
**Parameters**

- **query** ([Query](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Query.md.txt), [GqlQuery](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-GqlQuery.md.txt)) --- The query with the search criteria.
- **namespace** (String) *(defaults to: nil)* --- The namespace the query is to run within.
- **explain_options** (Hash, Google::Cloud::Datastore::V1::ExplainOptions) *(defaults to: nil)* --- The options for query explanation. See V1::ExplainOptions for details. Optional.
**Returns**

- ([Google::Cloud::Datastore::Dataset::QueryResults](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Dataset-QueryResults.md.txt))
**Examples**

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  tasks = tx.run query
end
```

Run the query within a namespace with the `namespace` option:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

query = Google::Cloud::Datastore::Query.new.kind("Task").
  where("done", "=", false)
datastore.transaction do |tx|
  tasks = tx.run query, namespace: "example-ns"
end
```

Run the query with explain options:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  results = tx.run query, explain_options: { analyze: true }

  # You must iterate through all pages of results to get the metrics.
  loop do
    break unless results.next?
    results = results.next
  end

  if results.explain_metrics
    stats = results.explain_metrics.execution_stats
    puts "Read operations: #{stats.read_operations}"
  end
end
```

Run the query with explain options using a `Google::Cloud::Datastore::V1::ExplainOptions` object.

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

datastore.transaction do |tx|
  query = datastore.query("Task")
  explain_options = Google::Cloud::Datastore::V1::ExplainOptions.new
  results = tx.run query, explain_options: explain_options

  # You must iterate through all pages of results to get the metrics.
  loop do
    break unless results.next?
    results = results.next
  end

  if results.explain_metrics
    stats = results.explain_metrics.execution_stats
    puts "Read operations: #{stats.read_operations}"
  end
end
```

### #save

```ruby
def save(*entities)
```
**Aliases**

- [#upsert](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_upsert_instance_)
Persist entities in a transaction.
**Example**

Transactional get or create:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"

task = nil
datastore.transaction do |tx|
  task = tx.find task_key
  if task.nil?
    task = datastore.entity task_key do |t|
      t["type"] = "Personal"
      t["done"] = false
      t["priority"] = 4
      t["description"] = "Learn Cloud Datastore"
    end
    tx.save task
  end
end
```

### #start

```ruby
def start()
```
**Aliases**

- [#begin_transaction](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_begin_transaction_instance_)
Begins a transaction.
This method is run when a new Transaction is created.
**Raises**

- ([TransactionError](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-TransactionError.md.txt))

### #update

```ruby
def update(*entities)
```
Update entities in a transaction. An InvalidArgumentError will raised
if the entities cannot be updated.
**Example**

Transactional update:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"

task = nil
datastore.transaction do |tx|
  task = tx.find task_key
  if task
    task["done"] = true
    tx.update task
  end
end
```

### #upsert

```ruby
def upsert(*entities)
```
**Alias Of** : [#save](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-datastore/latest/Google-Cloud-Datastore-Transaction.md.txt#Google__Cloud__Datastore__Transaction_save_instance_) Persist entities in a transaction.
**Example**

Transactional get or create:

```ruby
require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

task_key = datastore.key "Task", "sampleTask"

task = nil
datastore.transaction do |tx|
  task = tx.find task_key
  if task.nil?
    task = datastore.entity task_key do |t|
      t["type"] = "Personal"
      t["done"] = false
      t["priority"] = 4
      t["description"] = "Learn Cloud Datastore"
    end
    tx.save task
  end
end
```