Transactions - noresources/ns-php-sql GitHub Wiki

Transactions

Examples

Transaction and nested save point

// Start a transaction
$transaction = $connection->newTransactionBlock ('Insert stuff');

// ... Do some stuff

// Add a nested save point
$savepoint = $connection->newTransactionBlock ('update things');

// ... Do things

// Commit or rollback things done between save point and now
if ($everythingGoesWell) {
	$savepoint->commit ();
} else {
	$savepoint->rollback();
}

// ... Do other stuff

// Commit or rollback the whole transaction
if ($everythingStillGoesWell) {
	$transaction->commit ();
} else }
	$transaction->rollback ();
{

Block state propagation

It is not necessary to commit/rollback all save points. If an outer block is ended, its state will be propagated to all the inner blocks.

$one = $connection->newTransactionBlock ('Outer most');
// ... stuff 
$two = $connection->newTransactionBlock ('outer');
// ... things
$three = $connection->newTransactionBlock ('inner');
// ... tasks

Case 1

$two->rollback (); 		// Rollback "outer" and "inner"
$one->commit ();		// Commit stuff done after "outer most" and before "outer"

Case 2

$one->rollback(); 		// Rollback everything, mark "outer" and "inner" as rolled back
$three->rollback(); 	// Silently ignored

Case 3

$one->rollback(); 		// Rollback everything, mark "outer" and "inner" as rolled back
$three->commit(); 		// Throws TransactionBlockException  (INVALID_STATE)