改进主从数据库的事务支持

This commit is contained in:
thinkphp
2016-04-29 14:41:20 +08:00
parent 494b0dce2b
commit 11769ed15c

View File

@@ -35,6 +35,8 @@ abstract class Connection
protected $lastInsID;
// 返回或者影响记录数
protected $numRows = 0;
// 事务的数据库连接
protected $transPDO;
// 事务指令数
protected $transTimes = 0;
// 事务标识
@@ -450,6 +452,9 @@ abstract class Connection
if (0 == $this->transTimes) {
$this->transLabel = $label;
$this->linkID->beginTransaction();
if (1 == $this->config['deploy']) {
$this->transPDO = $this->linkID;
}
}
$this->transTimes++;
return;
@@ -467,6 +472,9 @@ abstract class Connection
try {
$this->linkID->commit();
$this->transTimes = 0;
if (1 == $this->config['deploy']) {
$this->transPDO = null;
}
} catch (\PDOException $e) {
throw new PDOException($e, $this->config, $this->queryStr);
}
@@ -485,6 +493,9 @@ abstract class Connection
try {
$this->linkID->rollback();
$this->transTimes = 0;
if (1 == $this->config['deploy']) {
$this->transPDO = null;
}
} catch (\PDOException $e) {
throw new PDOException($e, $this->config, $this->queryStr);
}
@@ -505,13 +516,13 @@ abstract class Connection
return false;
}
// 自动启动事务支持
$this->startTrans();
$this->startTrans(NOW_TIME);
try {
foreach ($sql as $_sql) {
$result = $this->execute($_sql);
}
// 提交事务
$this->commit();
$this->commit(NOW_TIME);
} catch (\PDOException $e) {
$this->rollback();
return false;
@@ -689,8 +700,13 @@ abstract class Connection
protected function initConnect($master = true)
{
if (!empty($this->config['deploy'])) {
// 采用分布式数据库
$this->linkID = $this->multiConnect($master);
if ($this->transPDO) {
// 使用事务连接
$this->linkID = $this->transPDO;
} else {
// 采用分布式数据库
$this->linkID = $this->multiConnect($master);
}
} elseif (!$this->linkID) {
// 默认单数据库
$this->linkID = $this->connect();