I'm trying to figure out how transactions work in twisted's adbapi module. I am currently using runOperation() in order to execute INSERT and UPDATE statements. The documentation, which I will link to below, makes it appear that it supports transactions, but it doesn't seem to in the way that I would like. Here is some example code (its running inside a cyclone web server, but hopefully that's not relevant):
class OperationHandler(cyclone.web.RequestHandler):
@cyclone.web.asynchronous
def get(self, *args, **kwargs):
d = conn.runOperation("INSERT INTO Table1 (Field1, Field2) VALUES ('a', 'b')")
d.addCallback(self.next1)
def next1(self, rows):
d = conn.runOperation("UPDATE Table1 SET Field1 = 'c'")
d.addCallback(self.next2)
def next2(self, rows):
raise Exception("rollback")
self.finish("done")
In this case even though an exception is raised in the last callback, both the INSERT and UPDATE statement are executed. Not what I want.
I tried converting over to use the runInteraction() method, but I'm not sure I'm doing it correctly.
class InteractionHandler(cyclone.web.RequestHandler):
@cyclone.web.asynchronous
def get(self, *args, **kwargs):
d = conn.runInteraction(self.someTransaction)
d.addCallback(self.done)
def someTransaction(self, txn):
txn.execute("INSERT INTO Table1 (Field1, Field2) VALUES ('a', 'b')")
txn.execute("UPDATE Table1 SET Field1 = 'c'")
txn.execute("UPDATE Table1 SET Field1 = 'd'")
raise Exception("rollback")
def done(self, rows):
print rows
self.finish("done")
In this case I get the effect I want in which everything is rolled back, but as you can see the code is quite different. Instead of chaining callbacks together, where each callback runs one query, I'm just executing everything in one big method.
Is the way this has to be done in order to support transactions?
Here are links to the documentation:
http://twistedmatrix.com/documents/current/core/howto/rdbms.html
http://twistedmatrix.com/documents/12.0.0/api/twisted.enterprise.adbapi.ConnectionPool.html#runInteraction
Yes. Your runInteraction
-based rewrite is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With