Skip to content

Commit aa195e7

Browse files
author
remi Taylor
committed
Wrap Datastore insert and update samples in transactions
These samples actually run an upsert because they use `datastore.save` rather than explicitly calling #insert and #update. `datastore.save` is the correct, simple idiomatic sample but these samples execute multiple queries against Datastore rather than one so they should be wrapped in transactions. If either query fails, the entire transaction will be rolled back and an exception will be raised.
1 parent 532c029 commit aa195e7

1 file changed

Lines changed: 14 additions & 9 deletions

File tree

datastore/sample.rb

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -141,17 +141,20 @@ def upsert
141141
end
142142

143143
def insert
144+
task = nil
144145
gcloud = Gcloud.new
145146
datastore = gcloud.datastore
146147

147148
# [START insert]
148-
task = datastore.entity "Task" do |t|
149-
t["category"] = "Personal"
150-
t["done"] = false
151-
t["priority"] = 4
152-
t["description"] = "Learn Cloud Datastore"
149+
datastore.transaction do |tx|
150+
task = datastore.entity "Task" do |t|
151+
t["category"] = "Personal"
152+
t["done"] = false
153+
t["priority"] = 4
154+
t["description"] = "Learn Cloud Datastore"
155+
end
156+
datastore.save task
153157
end
154-
datastore.save task
155158
# [END insert]
156159

157160
task
@@ -182,9 +185,11 @@ def update
182185
datastore.save task
183186

184187
# [START update]
185-
task = datastore.find "Task", "sampleTask"
186-
task["priority"] = 5
187-
datastore.save task
188+
datastore.transaction do |tx|
189+
task = datastore.find "Task", "sampleTask"
190+
task["priority"] = 5
191+
datastore.save task
192+
end
188193
# [END update]
189194

190195
task

0 commit comments

Comments
 (0)