Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction support in twisted adbapi

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

like image 957
d512 Avatar asked Jul 18 '12 05:07

d512


1 Answers

Yes. Your runInteraction-based rewrite is correct.

like image 124
Jean-Paul Calderone Avatar answered Sep 22 '22 12:09

Jean-Paul Calderone