1

I've recently started to work on an application based on the Kohana framework that has been in development for some months, and the code is not using any DB transactions. I've already seen data corruption because of this.

Going through all the code to add transactions manually would be a lengthy and error-prone task, so my plan is to implement something like the declarative transactions in the Java EE and Spring frameworks: simply wrap every controller action in a DB transaction using the before() and after() functions of the project-specific controller superclass. Maybe make it configurable via an overridable property containing the names of actions that require a transaction.

  1. Has this been done before in a reusable way?
  2. How can I deal with exceptions? Is after() called when an exception occurs? If so, how can I find out whether an exception was thrown? If not, how else can I react to them?
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720

2 Answers2

1

It doesn't look like Kohanas ORM has transaction suport but you can still makes the calls manually

$db->query("START TRANSACTION");
$db->query(query1);
$db->query(query2);
$db->query("COMMIT");

I had a look and it seems like the after method is not called if there is an exception, if you have a look in here and search for 'after' you get to some code where you see the catch statement doesn't run the after() method.

Im really not sure what how you can make it global without other trade-offs...

Manatok
  • 5,506
  • 3
  • 23
  • 32
  • Kohana 3 actually has transaction support, see http://stackoverflow.com/a/7690326/16883 - not at the ORM level, but then that wouldn't be very useful anyway. Looks like you're right about the exception handling - no way to do it except at an even higher level, or modify Kohana's Request class. – Michael Borgwardt Mar 01 '12 at 19:01
0

Using the before() and after() functions of the controller base class worked for many cases, but I felt uneasy about not doing an explicit rollback when dealing with exceptions. Then I found that I was also getting an implicit rollback whenever an action called Request::current()->redirect() because that function does anexit, so after() never gets called.

My new and improved solution is to override Kohana's Request class, and I create a Kohana module so everyone can use it easily:

https://github.com/brazzy/kohana-transactional

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720