note 109753 modified in pdo.begintransaction by danbrown

From: Date: Fri, 31 Aug 2012 15:55:42 +0000
Subject: note 109753 modified in pdo.begintransaction by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190351@lists.php.net to get a copy of this message
You can generate problems with nested beginTransaction and commit calls.
example:

beginTransaction()
do imprortant stuff
call method
 beginTransaction()
 basic stuff 1
 basic stuff 2
 commit()
do most important stuff
commit()

Won't work and is dangerous since you could close your transaction too early with the nested commit().

There is no need to mess you code and pass like a bool which indicate if transaction is already running. You could just overload the beginTransaction() and commit() in your PDO wrapper like this:

<?php
class Database extends \\PDO
{
	protected $transactionCounter = 0;
	function beginTransaction()
	{
		if(!$this->transactionCounter++)
			return parent::beginTransaction();
	 return $this->transactionCounter >= 0;
	}

	function commit()
	{
	 if(!--$this->transactionCounter)
		 return parent::commit();
	 return $this->transactionCounter >= 0;
	}

	function rollback()
	{
		if($this->transactionCounter >= 0)
		{
			$this->transactionCounter = 0;
			return parent::rollback();
		}
		$this->transactionCounter = 0;
		return false;
	}
//...
}
?> --was-- You can generate problems with nested beginTransaction and commit calls. example: beginTransaction() do imprortant stuff call method beginTransaction() basic stuff 1 basic stuff 2 commit() do most important stuff commit() Won't work and is dangerous since you could close your transaction too early with the nested commit(). There is no need to mess you code and pass like a bool which indicate if transaction is already running. You could just overload the beginTransaction() and commit() in your PDO wrapper like this: class Database extends \PDO { protected $transactionCounter = 0; function beginTransaction() { if(!$this->transactionCounter++) return parent::beginTransaction(); return $this->transactionCounter >= 0; } function commit() { if(!--$this->transactionCounter) return parent::commit(); return $this->transactionCounter >= 0; } function rollback() { if($this->transactionCounter >= 0) { $this->transactionCounter = 0; return parent::rollback(); } $this->transactionCounter = 0; return false; } ... } http://php.net/manual/en/pdo.begintransaction.php

« previous php.notes (#190351) next »