Class: Gcloud::Datastore::Transaction

Inherits:
Dataset
  • Object
show all
Defined in:
lib/gcloud/datastore/transaction.rb

Overview

Transaction

Special Connection instance for running transactions.

See Dataset.transaction

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Dataset

#allocate_ids, #entity, #find, #find_all, #key, #project, #query, #run, #transaction

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id


25
26
27
# File 'lib/gcloud/datastore/transaction.rb', line 25

def id
  @id
end

Instance Method Details

#commitObject

Commits a transaction.


83
84
85
86
87
88
89
90
91
# File 'lib/gcloud/datastore/transaction.rb', line 83

def commit
  if @id.nil?
    fail TransactionError, "Cannot commit when not in a transaction."
  end

  response = connection.commit shared_mutation, @id
  auto_id_assign_ids response.mutation_result.insert_auto_id_key
  true
end

#delete(*entities) ⇒ Object

Remove entities in a transaction.

Examples:

dataset.transaction do |tx|
  if tx.find(user.key).nil?
    tx.delete task1, task2
  end
end

62
63
64
65
66
67
68
# File 'lib/gcloud/datastore/transaction.rb', line 62

def delete *entities
  shared_mutation.tap do |m|
    m.delete = entities.map { |entity| entity.key.to_proto }
  end
  # Do not delete yet
  true
end

#reset!Object

Reset the transaction. #start must be called afterwards.


107
108
109
110
111
# File 'lib/gcloud/datastore/transaction.rb', line 107

def reset!
  @shared_mutation = nil
  @id = nil
  @_auto_id_entities = []
end

#rollbackObject

Rolls a transaction back.


95
96
97
98
99
100
101
102
# File 'lib/gcloud/datastore/transaction.rb', line 95

def rollback
  if @id.nil?
    fail TransactionError, "Cannot rollback when not in a transaction."
  end

  connection.rollback @id
  true
end

#save(*entities) ⇒ Object

Persist entities in a transaction.

Examples:

dataset.transaction do |tx|
  if tx.find(user.key).nil?
    tx.save task1, task2
  end
end

46
47
48
49
50
# File 'lib/gcloud/datastore/transaction.rb', line 46

def save *entities
  save_entities_to_mutation entities, shared_mutation
  # Do not save or assign auto_ids yet
  entities
end

#startObject Also known as: begin_transaction

Begins a transaction. This method is run when a new Transaction is created.


73
74
75
76
77
78
# File 'lib/gcloud/datastore/transaction.rb', line 73

def start
  fail TransactionError, "Transaction already opened." unless @id.nil?

  response = connection.begin_transaction
  @id = response.transaction
end