Welcome Guest, Not a member yet? Register   Sign In
transactions and data integrity question
#1

[eluser]moonbeetle[/eluser]
Hi, according to the manual:

Quote:$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

But how do you use this if your queries must be run conditionally? Example:

Code:
if(SOME CONDITION){
$this->db->trans_start();
   $this->db->query('AN SQL QUERY...');
   $this->db->query('ANOTHER QUERY...');
   $this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
}

if(ANOTHER CONDITION)){
$this->db->trans_start();
   $this->db->query('AN SQL QUERY...');
   $this->db->query('ANOTHER QUERY...');
   $this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();
}

Do the transition delimiters need to be as close to the queries as possible?
Or would this be correct as well? Example:

Code:
$this->db->trans_start();

if(SOME CONDITION){
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
}

if(ANOTHER CONDITION)){
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
}

$this->db->trans_complete();
#2

[eluser]Michael Wales[/eluser]
It doesn't matter either way - the latter saves you typing 2 lines though. Big Grin
#3

[eluser]moonbeetle[/eluser]
There is a difference though. If I can put the transaction delimiters outside my conditions, I will not only save a few lines of code I will also safeguard data integrity for ALL queries. This is important if all conditional blocks are part of 1 method like a complex cascading delete.
#4

[eluser]Michael Wales[/eluser]
You know - when I looked at your code I saw an If... Else for some reason, thinking "this condition, or this one" not possibly both.

From the Transactions documentation:
Quote:You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure of any given query.

So yes, you can drop your transaction out to the widest level and run multiple queries within it, maintaining your data integrity.

I would be mindful of how far you drop it out though and only create a transaction to perform a particular "function" (let's say, adding a post to a blog). Sure, it may take 4 queries to do so, but we want that to be one transaction - we definitely don't want to make posting to a blog, updating user login info, and running some statistics parsing all one transaction.




Theme © iAndrew 2016 - Forum software by © MyBB