in spanner/spanner_samples.rb [1296:1335]
def write_with_transaction_using_dml project_id:, instance_id:, database_id:
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
transfer_amount = 200_000
client.transaction do |transaction|
first_album = transaction.execute(
"SELECT MarketingBudget from Albums
WHERE SingerId = 1 and AlbumId = 1"
).rows.first
second_album = transaction.execute(
"SELECT MarketingBudget from Albums
WHERE SingerId = 2 and AlbumId = 2"
).rows.first
raise "The second album does not have enough funds to transfer" if second_album[:MarketingBudget] < transfer_amount
new_first_album_budget = first_album[:MarketingBudget] + transfer_amount
new_second_album_budget = second_album[:MarketingBudget] - transfer_amount
transaction.execute_update(
"UPDATE Albums SET MarketingBudget = @albumBudget WHERE SingerId = 1 and AlbumId = 1",
params: { albumBudget: new_first_album_budget }
)
transaction.execute_update(
"UPDATE Albums SET MarketingBudget = @albumBudget WHERE SingerId = 2 and AlbumId = 2",
params: { albumBudget: new_second_album_budget }
)
end
puts "Transaction complete"
end