Google App Engine
Last edited June 7, 2008
More by Ian Lewis »
Transactions - Google App Engine - Google Code
code.google.com/appengine/docs/datastore/transacti...

Using Transactions

A transaction is a datastore operation or a set of datastore operations that either succeed completely, or fail completely. If the transaction succeeds, then all of its intended effects are applied to the datastore. If the transaction fails, then none of the effects are applied.

Every datastore write operation is atomic. A put() or delete() either happens, or it doesn't. An operation may fail due to a high rate of contention, with too many users trying to modify an entity at the same time. Or an operation may fail due to the application reaching a quota limit. Or there may be an internal error with the datastore. In all cases, the operation's effects are not applied, and the datastore API raises an exception.

An application can execute a set of statements and datastore operations in a single transaction, such that if any statement or operation raises an exception, none of the datastore operations in the set are applied. The application defines the actions to perform in the transaction using a Python function, then calls db.run_in_transaction() with the function as an argument:

from google.appengine.ext import db

class Accumulator(db.Model):
  counter
= db.IntegerProperty()

def increment_counter(key, amount):
  obj
= db.get(key)
  obj
.counter += amount
  obj
.put()

q
= db.GqlQuery("SELECT * FROM Accumulator")
acc
= q.get()

db
.run_in_transaction(increment_counter, acc.key(), 5)

db.run_in_transaction() takes the function object, and positional and keyword arguments to pass to the function. If the function returns a value, db.run_in_transaction() will return the value.

If the function returns, the transaction is committed, and all effects of datastore operations are applied. If the function raises an exception, the transaction is "rolled back," and the effects are not applied.

If the function raises the Rollback exception, db.run_in_transaction() returns None. For any other exception, db.run_in_transaction() re-raises the exception.

The content on this page is provided by a Google Notebook user, and Google assumes no responsibility for this content.