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

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