• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
using transactions

#1
I've read the docs on db transactions and also the db driver reference to try and get a grip on how transactions work in CodeIgniter and, although I have often used MySQL transactions, I'm still a bit confused.

In particular, it doesn't look like CI doesn't offer any function to force a ROLLBACK. I understand from the docs that "queries will all be committed or rolled back based on success or failure of any given query" but I do not see how I might force a rollback based on some non-query condition. Can someone explain how I can force a rollback?

The docs refer to trans_begin but this function is not documented in the db driver reference.

Most importantly, I want to know how to use transactions in my registration handler. When a user registers, I need to run some functions and insert records into 3 different db tables and I need to check some other stuff too. My transaction section looks something like this:
PHP Code:
try {
    
// i'd like to start the transaction here

    
$user = new User($userData);
    if (!
$user->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user record");
    }
    
$userProfile = new UserProfile($userProfileData);
    if (!
$userProfile->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user profile record");
    }
    
$userPhone = new UserProfile($userPhone);
    if (!
$userPhone->create_db_record($this->db)) {
        throw new 
Exception("Unable to create user phone record");
    }

    if (
$foo != $bar) {
        
// note this has nothing at all to do with any queries
        
throw new Exception("OH DANG ARBITRARY FAIL!");
    }

    
// i'd like to commit the transaction here

} catch (Exception $e) {
    
// oh no! might need to rollback that transaction if any was started
    
show_error("An exception was caught");


Can someone help me understand how to use transactions in this context?
Reply

#2
You probably need to run the transactions manually in this context. In other words, you start with trans_begin() instead of trans_start(), then use trans_rollback() and trans_commit() to control whether the transaction is rolled back or committed. You also don't use trans_complete() for manual transactions.

When running the transactions manually, remember to check trans_status() before calling trans_commit(). Essentially, this is what trans_complete() normally does (chooses whether to call trans_rollback() or trans_commit() based on the result of trans_status()), but controlling the transactions manually allows you to rollback or commit the transaction based on your own logic.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.