PDO在提交/回滚之前丢失事务

时间:2014-09-23 14:17:24

标签: php mysql sql pdo transactions

我正在尝试使用PDO使用mysql进行交易来完成工作。我遇到的问题是在进入提交之前事务已经崩溃。我知道这是因为我在连接上回显了inTransaction()函数。

在我看来,原因是我正在实例化一个PDODatabase类,然后在实际执行任何查询之前我做了一些其他编码工作,此时我丢失了这个事务。

实例化我的课程

$pdo = new PdoDatabase;
$pdo->beginTransaction();
echo "first ".$pdo->transactionStarted()."<br />";

PdoDatabase类

public function __construct(){
    $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
    $options = array(PDO::ATTR_PERSISTENT => TRUE, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    try{
        $this->_connection = new PDO($dsn, DB_USER, BD_PASS, $options);
    } catch (PDOException $e){
        $this->_error = $e->getMessage();
    }
}

public function query($q){
    if($this->_error != ''){
        echo $this->_error;
    } else {
        $this->_stmt = $this->_connection->prepare($q);
    }
}

public function bind($param, $value, $type = null){
    //echo "<br>".$value."<br>";
    if (is_null($type)) {
      switch (true) {
        case is_int($value):
          $type = PDO::PARAM_INT;
          break;
        case is_bool($value):
          $type = PDO::PARAM_BOOL;
          break;
        case is_null($value):
          $type = PDO::PARAM_NULL;
          break;
        default:
          $type = PDO::PARAM_STR;
      }
    }
    $this->_stmt->bindValue($param, $value, $type);
}

public function execute($class = null){
    $object_array = array();

    if($class !== null){
        if($this->_stmt->execute()){
            $this->_stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, $class, null);
            while($row = $this->returnRow()){
                $object_array[] = $class::instantiate($row);
            }
        }
        return $object_array;
    } else {

        return $this->_stmt->execute();
    }
}

public function transactionStarted(){
    return $this->_connection->inTransaction();
}

我如何使用它(部分)

if(isset($_POST['id']) && $_POST['id'] != ''){
                echo "id exists ".$pdo->transactionStarted()."<br />";
                $bidder->getBidderById($_POST['id']);
                echo "step 1 ".$pdo->transactionStarted()."<br />";
                $bidder = $bidder->getList(0);
                echo "step 2 ".$pdo->transactionStarted()."<br />";
                $old_bidder = clone $bidder;
                echo "step 3 ".$pdo->transactionStarted()."<br />";

                $bidder_phones->getPhones($_POST['id']);
                echo "step 4 ".$pdo->transactionStarted()."<br />";
                $bidder_phones = $bidder_phones->getList();
                echo "step 5 ".$pdo->transactionStarted()."<br />";
                if($_POST['phone'] == ''){
                    // check to see if there are any phone numbers in the database already and delete if there is
                    foreach($bidder_phones as $bp){
                        $q = "delete from bidder_phones where id = :id";
                        $pdo->query($q);
                        $pdo->bind(":id", $bp->getId());
                        $pdo->execute();
                        //$bp->remove();
                    }
                } else {
                    echo "phone to check ".$pdo->transactionStarted()."<br />";
                    $old_phone_numbers = array();
                    $new_phone_numbers = explode(',', $_POST['phone']);
                    foreach($bidder_phones as $bp){
                        // remove any unused phone numbers
                        if(!in_array($bp, $new_phone_numbers)){
                            $q = "delete from bidder_phones where id = :id";
                            $pdo->query($q);
                            $pdo->bind(":id", $bp->getId());
                            $pdo->execute();
                            //$bp->remove();
                        }
                        // push to an array to test the new numbers
                        array_push($old_phone_numbers, $bp->getPhone());
                    }
                    foreach($new_phone_numbers as $phone){
                        // adding new phone numbers
                        if(!in_array($phone, $old_phone_numbers)){
                            $new_phone = new BidderPhone;
                            $new_phone->setPhone($phone);
                            $new_phone->setBidderId($_POST['id']);
                            $pdo->save('BidderPhones', $new_phone);
                            //$new_phone->save();
                        }
                    }
                }

正如您所看到的,我多次回应$ pdo-&gt; transactionStarted()。这是试图查看我何时丢失交易。我期望看到的是我的消息后跟1表示交易仍处于活动状态。这就是我得到的:

first 1
id exists 1
step 1
step 2
step 3
step 4
step 5
phone to check
in save
before create

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'clickbid.bidder_phoneses' doesn't exist' in /var/www/classes/PdoDatabase.php:59 Stack trace: #0 /var/www/classes/PdoDatabase.php(59): PDOStatement->execute() #1 /var/www/classes/PdoDatabase.php(158): PdoDatabase->execute() #2 /var/www/classes/PdoDatabase.php(187): PdoDatabase->getFields('BidderPhones') #3 /var/www/classes/PdoDatabase.php(176): PdoDatabase->create('BidderPhones', Object(BidderPhone), false) #4 /var/www/admin/data/post_data.php(284): PdoDatabase->save('BidderPhones', Object(BidderPhone)) #5 {main} thrown in /var/www/classes/PdoDatabase.php on line 59

所以我在id存在之后就丢失了这个事务,这是因为我正在做其他编程而不是准备查询并执行它们?我还缺少一些我不知道的东西吗?在过去2天的大部分时间里,我一直在努力解决这个问题。问题是我真的需要能够在实际执行某些查询之前开始我的事务并做一些工作。有没有办法可以做到这一点?

提前感谢您的帮助。

EDIT 因此,我对代码进行了一些重大更改,并且能够在丢失活动事务时更加确定。

我的保存方法如下所示

public function save($table, $object, $old_object = null){
    echo "in save ".$this->transactionStarted()."<br />";
    if($object->_id != ''){
        echo "before update ".$this->transactionStarted()."<br />";
        //return $this->update($table, $object, $old_object, $transaction);
        if($this->update($table, $object, $old_object)){
            echo "update true ".$this->transactionStarted()."<br />";
            return true;
        } else {
            echo "update false ".$this->transactionStarted()."<br />";
            return false;
        }
    } else {
        echo "before create ".$this->transactionStarted()."<br />";
        //return $this->create($table, $object, $transaction);
        if($this->create($table, $object)){
            echo "create true ".$this->transactionStarted()."<br />";
            return true;
        } else {
            echo "create false ".$this->transactionStarted()."<br />";
            return false;
        }
    }
}

在这种特殊情况下,有一个来自对象的_id所以$ this-&gt; update是我们在这里调试的更新方法

private function update($table, $object, $old){
    echo "in update ".$this->transactionStarted()."<br />";
    $audit = new PdoDatabase;
    echo "after new ".$this->transactionStarted()."<br />";
    $aq = "insert into audit_trails 
            (table_name, table_id, user_id, field_name, original_value, new_value) values
            (:table_name, :table_id, :user_id, :field_name, :original_value, :new_value)";
    echo "before query ".$this->transactionStarted()."<br />";
    $audit->query($aq);
    echo "after query ".$this->transactionStarted()."<br />";
    //$update = new PdoDatabase;    

    $binding = array();
    echo "before field_names ".$this->transactionStarted()."<br />";
    $field_names = self::getFields($table);
    echo "after field_names ".$this->transactionStarted()."<br />";

    $uc = new UserConfig;
    $uc->getConfig();
    $user = $uc->getList(0);
    echo "before foreach ".$this->transactionStarted()."<br />";
    foreach($field_names as $field){
        $thisField = "_".$field['Field']."<br>";
        $getField = 'get'.self::to_camel_case($field['Field']);
        $method = $getField;
        $class = self::to_camel_case($table);
        $field_list = '';

        if($field['Field'] == 'id'){
            $where = 'where id = :id';
            $binding[':id'] = ($object->$getField());
        } else {

            if(method_exists($class, $method)){
                if($object->$getField() != $old->$getField()){
                    $field_list .= $field['Field']."= :".$field['Field'].", ";
                    $binding[':'.$field['Field']] = $object->$getField();

                    $audit->bind(':table_name', $table);
                    $audit->bind(':table_id', $object->getId());
                    $audit->bind(':user_id', $user->getUserId());
                    $audit->bind(':field_name', $thisField);
                    $audit->bind(':original_value', $object->$getField());
                    $audit->bind(':new_value', $old->$getField());

                    echo "before audit execute ".$this->transactionStarted()."<br />";
                    $audit->execute();
                    echo "after audit execute ".$this->transactionStarted()."<br />";

                }
            }
        }
    }
    echo "before binding ".$this->transactionStarted()."<br />";
    if(count($binding) > 1){
        $q = "update ".self::singularToPlural($table)." set ";
        foreach($binding as $key => $value){
            if($key != ':id'){
                $q .= str_replace(':', '', $key)." = ".$key.", ";
            }
        }
        $q = rtrim($q, ", ");
        $q .= ' '.$where;

        //$update->query($q);
        echo "before this query ".$this->transactionStarted()."<br />";
        $this->query($q);
        echo "after this query ".$this->transactionStarted()."<br />";
        /*if($transaction && !$this->_stmt->inTransaction()){
            $this->_stmt->beginTransaction();
        }*/

        foreach($binding as $key => $value){
            //$update->bind($key, $value);
            $this->bind($key, $value);
        }
        //$update->bind($id);
        //return $update->execute();
        echo "before this execute ".$this->transactionStarted()."<br />";
        $stupid = $this->execute();
        echo "after this execute ".$this->transactionStarted()."<br />";
        return $stupid;
    } else {
        echo "before return true ".$this->transactionStarted()."<br />";
        return true;
    }

}

,输出

first 1
in save 1
before update 1
in update 1
after new 1
before query 1
after query 1
before field_names 1
before execute 1
after execute 1
after field_names 1
before foreach 1
before audit execute 1
before execute 1
after execute 1
after audit execute 1
before binding 1
before this query 1
after this query 1
before this execute 1
before execute 1
after execute 1
after this execute 1
update true
the save 1
second
after save
before commit

Fatal error: Uncaught exception 'PDOException' with message 'There is no active transaction' in /var/www/classes/PdoDatabase.php:86 Stack trace: #0 /var/www/classes/PdoDatabase.php(86): PDO->commit() #1 /var/www/admin/data/post_data.php(403): PdoDatabase->commit() #2 {main} thrown in /var/www/classes/PdoDatabase.php on line 86

从这里我可以看到当我们从更新返回到保存方法时,活动事务会丢失,我只是不确定为什么会这样。

再次感谢。

编辑添加getBidderById函数

public function getBidderById($bidder_id){
    $pdo = new PdoDatabase;

    $q = "select *
            from bidders Bidder
            where Bidder.id = :bidder_id
            limit 1";

    $pdo->query($q);
    $pdo->bind(":bidder_id", $bidder_id);
    $this->_bidders = $pdo->execute('Bidder');

    if(!empty($this->_bidders)){
        return true;
    } else {
        return false;
    }
}

编辑添加创建方法

private function create($table, $object){
    //$insert = new PdoDatabase;

    $field_names = self::getFields($table);

    foreach($field_names as $field){
        $getField = 'get'.self::to_camel_case($field['Field']);
        $method = $getField;
        $class = self::to_camel_case($table);

        if(method_exists($class, $method)){
            if($field['Field'] != 'id'){
                $fields = $field['Field'].", ";
                $binding_fields = ":".$field['Field'].", ";
                $binding[':'.$field['Field']] = $object->$getField();
            }
        }
    }
    $fields = rtrim($fields, ", ");
    $binding_fields = rtrim($binding_fields, ", ");

    $iq = "insert into ".self::singularToPlural($table)." 
            (".$fields.") values 
            (".$binding_fields.")";
    $this->query($iq);
    /*if($transaction && !$this->_stmt->inTransaction()){
        $this->_stmt->beginTransaction();
    }*/

    foreach($binding as $key => $value){
        $this->bind($key, $value);
    }

    if($this->execute()){
        $object->setId($this->getConnection()->lastInsertId());
        return true;
    } else {
        return false;
    }

}

2 个答案:

答案 0 :(得分:0)

Hmz,我注意到你在一个函数中实例化了PdoDatabase并使用了$ this-&gt; transactionStarted()。

原来不是问题,但由于您使用持久连接,因此可能会在其他某个类中启动新事务,从而导致正在运行的事务的隐式提交。

    if($this->create($table, $object)){
        echo "create true ".$this->transactionStarted()."<br />";
        return true;
    }

如果在此函数中使用DDL语句(CREATE,ALTER,DROP,TRUNCATE等),也将应用提交

答案 1 :(得分:0)

MySQL中的一些语句会导致隐式提交。您正在进行的任何交易都已提交。例如,所有DDL语句都这样做。有关详细信息,请参阅https://dev.mysql.com/doc/refman/5.6/en/implicit-commit.html

很难知道您的会话中是否有活动交易。在导致隐式提交的语句和查询可以是“COMMIT”(不通过任何commit()函数,而是通过query()函数)的可能性之间,客户端无法确定它们是否仍然存在交易正在进行中。

这个问题是尝试创建可重用DBAL的开发人员的祸根。

另请参阅我对How do detect that transaction has already been started?

的回答

评论:

对于MySQL,PDO::inTransaction() 可靠,因为PDO mysql驱动程序没有实现方法mysql_handle_in_transaction()MySQL C API中没有支持询问当前会话的交易状态。

因此,当您致电$dbh->beginTransaction()时,PDO课程会尝试使用设为1的内部变量进行最佳猜测,并在致电$dbh->commit()$dbh->rollback()时设为0 。

但是如果DDL语句导致隐式提交,则驱动程序没有任何关于事务结束的通知。因此,PDO中的内部变量可能与现实不同步。如果您调用$dbh->query('COMMIT'),绕过用于事务控制的PDO函数,也会发生这种情况。

其他PDO驱动程序,例如PostgreSQL驱动程序,确实实现了获取当前事务状态的方法。


在这种情况下,我不是说这是你问题的原因。但是尝试检测客户端中的事务状态并不是一直有效。

我不知道你的情况发生了什么。您仍然有几行调试输出尚未共享代码。