Connection.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\db;
  12. use PDO;
  13. use PDOStatement;
  14. use think\Db;
  15. use think\db\exception\BindParamException;
  16. use think\Debug;
  17. use think\Exception;
  18. use think\exception\PDOException;
  19. use think\Log;
  20. /**
  21. * Class Connection
  22. * @package think
  23. * @method Query table(string $table) 指定数据表(含前缀)
  24. * @method Query name(string $name) 指定数据表(不含前缀)
  25. *
  26. */
  27. abstract class Connection
  28. {
  29. /** @var PDOStatement PDO操作实例 */
  30. protected $PDOStatement;
  31. /** @var string 当前SQL指令 */
  32. protected $queryStr = '';
  33. // 返回或者影响记录数
  34. protected $numRows = 0;
  35. // 事务指令数
  36. protected $transTimes = 0;
  37. // 错误信息
  38. protected $error = '';
  39. /** @var PDO[] 数据库连接ID 支持多个连接 */
  40. protected $links = [];
  41. /** @var PDO 当前连接ID */
  42. protected $linkID;
  43. protected $linkRead;
  44. protected $linkWrite;
  45. // 查询结果类型
  46. protected $fetchType = PDO::FETCH_ASSOC;
  47. // 字段属性大小写
  48. protected $attrCase = PDO::CASE_LOWER;
  49. // 监听回调
  50. protected static $event = [];
  51. // 使用Builder类
  52. protected $builder;
  53. // 数据库连接参数配置
  54. protected $config = [
  55. // 数据库类型
  56. 'type' => '',
  57. // 服务器地址
  58. 'hostname' => '',
  59. // 数据库名
  60. 'database' => '',
  61. // 用户名
  62. 'username' => '',
  63. // 密码
  64. 'password' => '',
  65. // 端口
  66. 'hostport' => '',
  67. // 连接dsn
  68. 'dsn' => '',
  69. // 数据库连接参数
  70. 'params' => [],
  71. // 数据库编码默认采用utf8
  72. 'charset' => 'utf8',
  73. // 数据库表前缀
  74. 'prefix' => '',
  75. // 数据库调试模式
  76. 'debug' => false,
  77. // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
  78. 'deploy' => 0,
  79. // 数据库读写是否分离 主从式有效
  80. 'rw_separate' => false,
  81. // 读写分离后 主服务器数量
  82. 'master_num' => 1,
  83. // 指定从服务器序号
  84. 'slave_no' => '',
  85. // 模型写入后自动读取主服务器
  86. 'read_master' => false,
  87. // 是否严格检查字段是否存在
  88. 'fields_strict' => true,
  89. // 数据返回类型
  90. 'result_type' => PDO::FETCH_ASSOC,
  91. // 数据集返回类型
  92. 'resultset_type' => 'array',
  93. // 自动写入时间戳字段
  94. 'auto_timestamp' => false,
  95. // 时间字段取出后的默认时间格式
  96. 'datetime_format' => 'Y-m-d H:i:s',
  97. // 是否需要进行SQL性能分析
  98. 'sql_explain' => false,
  99. // Builder类
  100. 'builder' => '',
  101. // Query类
  102. 'query' => '\\think\\db\\Query',
  103. // 是否需要断线重连
  104. 'break_reconnect' => true,
  105. ];
  106. // PDO连接参数
  107. protected $params = [
  108. PDO::ATTR_CASE => PDO::CASE_NATURAL,
  109. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  110. PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
  111. PDO::ATTR_STRINGIFY_FETCHES => false,
  112. PDO::ATTR_EMULATE_PREPARES => false,
  113. ];
  114. // 绑定参数
  115. protected $bind = [];
  116. /**
  117. * 构造函数 读取数据库配置信息
  118. * @access public
  119. * @param array $config 数据库配置数组
  120. */
  121. public function __construct(array $config = [])
  122. {
  123. if (!empty($config)) {
  124. $this->config = array_merge($this->config, $config);
  125. }
  126. }
  127. /**
  128. * 获取新的查询对象
  129. * @access protected
  130. * @return Query
  131. */
  132. protected function getQuery()
  133. {
  134. $class = $this->config['query'];
  135. return new $class($this);
  136. }
  137. /**
  138. * 获取当前连接器类对应的Builder类
  139. * @access public
  140. * @return string
  141. */
  142. public function getBuilder()
  143. {
  144. if (!empty($this->builder)) {
  145. return $this->builder;
  146. } else {
  147. return $this->getConfig('builder') ?: '\\think\\db\\builder\\' . ucfirst($this->getConfig('type'));
  148. }
  149. }
  150. /**
  151. * 调用Query类的查询方法
  152. * @access public
  153. * @param string $method 方法名称
  154. * @param array $args 调用参数
  155. * @return mixed
  156. */
  157. public function __call($method, $args)
  158. {
  159. return call_user_func_array([$this->getQuery(), $method], $args);
  160. }
  161. /**
  162. * 解析pdo连接的dsn信息
  163. * @access protected
  164. * @param array $config 连接信息
  165. * @return string
  166. */
  167. abstract protected function parseDsn($config);
  168. /**
  169. * 取得数据表的字段信息
  170. * @access public
  171. * @param string $tableName
  172. * @return array
  173. */
  174. abstract public function getFields($tableName);
  175. /**
  176. * 取得数据库的表信息
  177. * @access public
  178. * @param string $dbName
  179. * @return array
  180. */
  181. abstract public function getTables($dbName);
  182. /**
  183. * SQL性能分析
  184. * @access protected
  185. * @param string $sql
  186. * @return array
  187. */
  188. abstract protected function getExplain($sql);
  189. /**
  190. * 对返数据表字段信息进行大小写转换出来
  191. * @access public
  192. * @param array $info 字段信息
  193. * @return array
  194. */
  195. public function fieldCase($info)
  196. {
  197. // 字段大小写转换
  198. switch ($this->attrCase) {
  199. case PDO::CASE_LOWER:
  200. $info = array_change_key_case($info);
  201. break;
  202. case PDO::CASE_UPPER:
  203. $info = array_change_key_case($info, CASE_UPPER);
  204. break;
  205. case PDO::CASE_NATURAL:
  206. default:
  207. // 不做转换
  208. }
  209. return $info;
  210. }
  211. /**
  212. * 获取数据库的配置参数
  213. * @access public
  214. * @param string $config 配置名称
  215. * @return mixed
  216. */
  217. public function getConfig($config = '')
  218. {
  219. return $config ? $this->config[$config] : $this->config;
  220. }
  221. /**
  222. * 设置数据库的配置参数
  223. * @access public
  224. * @param string|array $config 配置名称
  225. * @param mixed $value 配置值
  226. * @return void
  227. */
  228. public function setConfig($config, $value = '')
  229. {
  230. if (is_array($config)) {
  231. $this->config = array_merge($this->config, $config);
  232. } else {
  233. $this->config[$config] = $value;
  234. }
  235. }
  236. /**
  237. * 连接数据库方法
  238. * @access public
  239. * @param array $config 连接参数
  240. * @param integer $linkNum 连接序号
  241. * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式)
  242. * @return PDO
  243. * @throws Exception
  244. */
  245. public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
  246. {
  247. if (!isset($this->links[$linkNum])) {
  248. if (!$config) {
  249. $config = $this->config;
  250. } else {
  251. $config = array_merge($this->config, $config);
  252. }
  253. // 连接参数
  254. if (isset($config['params']) && is_array($config['params'])) {
  255. $params = $config['params'] + $this->params;
  256. } else {
  257. $params = $this->params;
  258. }
  259. // 记录当前字段属性大小写设置
  260. $this->attrCase = $params[PDO::ATTR_CASE];
  261. // 数据返回类型
  262. if (isset($config['result_type'])) {
  263. $this->fetchType = $config['result_type'];
  264. }
  265. try {
  266. if (empty($config['dsn'])) {
  267. $config['dsn'] = $this->parseDsn($config);
  268. }
  269. if ($config['debug']) {
  270. $startTime = microtime(true);
  271. }
  272. $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
  273. if ($config['debug']) {
  274. // 记录数据库连接信息
  275. Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql');
  276. }
  277. } catch (\PDOException $e) {
  278. if ($autoConnection) {
  279. Log::record($e->getMessage(), 'error');
  280. return $this->connect($autoConnection, $linkNum);
  281. } else {
  282. throw $e;
  283. }
  284. }
  285. }
  286. return $this->links[$linkNum];
  287. }
  288. /**
  289. * 释放查询结果
  290. * @access public
  291. */
  292. public function free()
  293. {
  294. try {
  295. $this->PDOStatement = null;
  296. } catch (\Exception $e) {
  297. Log::write("has error when free PDOStatement maybe mysql gone away,skip it:" . $e->getMessage(), log::DEBUG);
  298. }
  299. // $this->PDOStatement = null;
  300. }
  301. /**
  302. * 获取PDO对象
  303. * @access public
  304. * @return \PDO|false
  305. */
  306. public function getPdo()
  307. {
  308. if (!$this->linkID) {
  309. return false;
  310. } else {
  311. return $this->linkID;
  312. }
  313. }
  314. /**
  315. * 执行查询 返回数据集
  316. * @access public
  317. * @param string $sql sql指令
  318. * @param array $bind 参数绑定
  319. * @param bool $master 是否在主服务器读操作
  320. * @param bool $pdo 是否返回PDO对象
  321. * @return mixed
  322. * @throws PDOException
  323. * @throws \Exception
  324. */
  325. public function query($sql, $bind = [], $master = false, $pdo = false)
  326. {
  327. $this->initConnect($master);
  328. if (!$this->linkID) {
  329. return false;
  330. }
  331. // 记录SQL语句
  332. $this->queryStr = $sql;
  333. if ($bind) {
  334. $this->bind = $bind;
  335. }
  336. Db::$queryTimes++;
  337. try {
  338. // 调试开始
  339. $this->debug(true);
  340. // 预处理
  341. $this->PDOStatement = $this->linkID->prepare($sql);
  342. // 是否为存储过程调用
  343. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  344. // 参数绑定
  345. if ($procedure) {
  346. $this->bindParam($bind);
  347. } else {
  348. $this->bindValue($bind);
  349. }
  350. // 执行查询
  351. $this->PDOStatement->execute();
  352. // 调试结束
  353. $this->debug(false, '', $master);
  354. // 返回结果集
  355. return $this->getResult($pdo, $procedure);
  356. } catch (\PDOException $e) {
  357. if ($this->isBreak($e)) {
  358. return $this->close()->query($sql, $bind, $master, $pdo);
  359. }
  360. throw new PDOException($e, $this->config, $this->getLastsql());
  361. } catch (\Throwable $e) {
  362. if ($this->isBreak($e)) {
  363. return $this->close()->query($sql, $bind, $master, $pdo);
  364. }
  365. throw $e;
  366. } catch (\Exception $e) {
  367. if ($this->isBreak($e)) {
  368. return $this->close()->query($sql, $bind, $master, $pdo);
  369. }
  370. throw $e;
  371. }
  372. }
  373. /**
  374. * 执行语句
  375. * @access public
  376. * @param string $sql sql指令
  377. * @param array $bind 参数绑定
  378. * @param Query $query 查询对象
  379. * @return int
  380. * @throws PDOException
  381. * @throws \Exception
  382. */
  383. public function execute($sql, $bind = [], Query $query = null)
  384. {
  385. $this->initConnect(true);
  386. if (!$this->linkID) {
  387. return false;
  388. }
  389. // 记录SQL语句
  390. $this->queryStr = $sql;
  391. if ($bind) {
  392. $this->bind = $bind;
  393. }
  394. Db::$executeTimes++;
  395. try {
  396. // 调试开始
  397. $this->debug(true);
  398. // 预处理
  399. $this->PDOStatement = $this->linkID->prepare($sql);
  400. // 是否为存储过程调用
  401. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  402. // 参数绑定
  403. if ($procedure) {
  404. $this->bindParam($bind);
  405. } else {
  406. $this->bindValue($bind);
  407. }
  408. // 执行语句
  409. $this->PDOStatement->execute();
  410. // 调试结束
  411. $this->debug(false, '', true);
  412. if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) {
  413. $query->readMaster();
  414. }
  415. $this->numRows = $this->PDOStatement->rowCount();
  416. return $this->numRows;
  417. } catch (\PDOException $e) {
  418. if ($this->isBreak($e)) {
  419. return $this->close()->execute($sql, $bind, $query);
  420. }
  421. throw new PDOException($e, $this->config, $this->getLastsql());
  422. } catch (\Throwable $e) {
  423. if ($this->isBreak($e)) {
  424. return $this->close()->execute($sql, $bind, $query);
  425. }
  426. throw $e;
  427. } catch (\Exception $e) {
  428. if ($this->isBreak($e)) {
  429. return $this->close()->execute($sql, $bind, $query);
  430. }
  431. throw $e;
  432. }
  433. }
  434. /**
  435. * 根据参数绑定组装最终的SQL语句 便于调试
  436. * @access public
  437. * @param string $sql 带参数绑定的sql语句
  438. * @param array $bind 参数绑定列表
  439. * @return string
  440. */
  441. public function getRealSql($sql, array $bind = [])
  442. {
  443. if (is_array($sql)) {
  444. $sql = implode(';', $sql);
  445. }
  446. foreach ($bind as $key => $val) {
  447. $value = is_array($val) ? $val[0] : $val;
  448. $type = is_array($val) ? $val[1] : PDO::PARAM_STR;
  449. if (PDO::PARAM_STR == $type) {
  450. $value = $this->quote($value);
  451. } elseif (PDO::PARAM_INT == $type) {
  452. $value = (float) $value;
  453. }
  454. // 判断占位符
  455. $sql = is_numeric($key) ?
  456. substr_replace($sql, $value, strpos($sql, '?'), 1) :
  457. str_replace(
  458. [':' . $key . ')', ':' . $key . ',', ':' . $key . ' ', ':' . $key . PHP_EOL],
  459. [$value . ')', $value . ',', $value . ' ', $value . PHP_EOL],
  460. $sql . ' ');
  461. }
  462. return rtrim($sql);
  463. }
  464. /**
  465. * 参数绑定
  466. * 支持 ['name'=>'value','id'=>123] 对应命名占位符
  467. * 或者 ['value',123] 对应问号占位符
  468. * @access public
  469. * @param array $bind 要绑定的参数列表
  470. * @return void
  471. * @throws BindParamException
  472. */
  473. protected function bindValue(array $bind = [])
  474. {
  475. foreach ($bind as $key => $val) {
  476. // 占位符
  477. $param = is_numeric($key) ? $key + 1 : ':' . $key;
  478. if (is_array($val)) {
  479. if (PDO::PARAM_INT == $val[1] && '' === $val[0]) {
  480. $val[0] = 0;
  481. }
  482. $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]);
  483. } else {
  484. $result = $this->PDOStatement->bindValue($param, $val);
  485. }
  486. if (!$result) {
  487. throw new BindParamException(
  488. "Error occurred when binding parameters '{$param}'",
  489. $this->config,
  490. $this->getLastsql(),
  491. $bind
  492. );
  493. }
  494. }
  495. }
  496. /**
  497. * 存储过程的输入输出参数绑定
  498. * @access public
  499. * @param array $bind 要绑定的参数列表
  500. * @return void
  501. * @throws BindParamException
  502. */
  503. protected function bindParam($bind)
  504. {
  505. foreach ($bind as $key => $val) {
  506. $param = is_numeric($key) ? $key + 1 : ':' . $key;
  507. if (is_array($val)) {
  508. array_unshift($val, $param);
  509. $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val);
  510. } else {
  511. $result = $this->PDOStatement->bindValue($param, $val);
  512. }
  513. if (!$result) {
  514. $param = array_shift($val);
  515. throw new BindParamException(
  516. "Error occurred when binding parameters '{$param}'",
  517. $this->config,
  518. $this->getLastsql(),
  519. $bind
  520. );
  521. }
  522. }
  523. }
  524. /**
  525. * 获得数据集数组
  526. * @access protected
  527. * @param bool $pdo 是否返回PDOStatement
  528. * @param bool $procedure 是否存储过程
  529. * @return PDOStatement|array
  530. */
  531. protected function getResult($pdo = false, $procedure = false)
  532. {
  533. if ($pdo) {
  534. // 返回PDOStatement对象处理
  535. return $this->PDOStatement;
  536. }
  537. if ($procedure) {
  538. // 存储过程返回结果
  539. return $this->procedure();
  540. }
  541. $result = $this->PDOStatement->fetchAll($this->fetchType);
  542. $this->numRows = count($result);
  543. return $result;
  544. }
  545. /**
  546. * 获得存储过程数据集
  547. * @access protected
  548. * @return array
  549. */
  550. protected function procedure()
  551. {
  552. $item = [];
  553. do {
  554. $result = $this->getResult();
  555. if ($result) {
  556. $item[] = $result;
  557. }
  558. } while ($this->PDOStatement->nextRowset());
  559. $this->numRows = count($item);
  560. return $item;
  561. }
  562. /**
  563. * 执行数据库事务
  564. * @access public
  565. * @param callable $callback 数据操作方法回调
  566. * @return mixed
  567. * @throws PDOException
  568. * @throws \Exception
  569. * @throws \Throwable
  570. */
  571. public function transaction($callback)
  572. {
  573. $this->startTrans();
  574. try {
  575. $result = null;
  576. if (is_callable($callback)) {
  577. $result = call_user_func_array($callback, [$this]);
  578. }
  579. $this->commit();
  580. return $result;
  581. } catch (\Exception $e) {
  582. $this->rollback();
  583. throw $e;
  584. } catch (\Throwable $e) {
  585. $this->rollback();
  586. throw $e;
  587. }
  588. }
  589. /**
  590. * 启动事务
  591. * @access public
  592. * @return bool|mixed
  593. * @throws \Exception
  594. */
  595. public function startTrans()
  596. {
  597. $this->initConnect(true);
  598. if (!$this->linkID) {
  599. return false;
  600. }
  601. ++$this->transTimes;
  602. try {
  603. if (1 == $this->transTimes) {
  604. $this->linkID->beginTransaction();
  605. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  606. $this->linkID->exec(
  607. $this->parseSavepoint('trans' . $this->transTimes)
  608. );
  609. }
  610. } catch (\Exception $e) {
  611. if ($this->isBreak($e)) {
  612. --$this->transTimes;
  613. return $this->close()->startTrans();
  614. }
  615. throw $e;
  616. } catch (\Error $e) {
  617. if ($this->isBreak($e)) {
  618. --$this->transTimes;
  619. return $this->close()->startTrans();
  620. }
  621. throw $e;
  622. }
  623. }
  624. /**
  625. * 用于非自动提交状态下面的查询提交
  626. * @access public
  627. * @return void
  628. * @throws PDOException
  629. */
  630. public function commit()
  631. {
  632. $this->initConnect(true);
  633. if (1 == $this->transTimes) {
  634. $this->linkID->commit();
  635. }
  636. --$this->transTimes;
  637. }
  638. /**
  639. * 事务回滚
  640. * @access public
  641. * @return void
  642. * @throws PDOException
  643. */
  644. public function rollback()
  645. {
  646. $this->initConnect(true);
  647. if (1 == $this->transTimes) {
  648. $this->linkID->rollBack();
  649. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  650. $this->linkID->exec(
  651. $this->parseSavepointRollBack('trans' . $this->transTimes)
  652. );
  653. }
  654. $this->transTimes = max(0, $this->transTimes - 1);
  655. }
  656. /**
  657. * 是否支持事务嵌套
  658. * @return bool
  659. */
  660. protected function supportSavepoint()
  661. {
  662. return false;
  663. }
  664. /**
  665. * 生成定义保存点的SQL
  666. * @param $name
  667. * @return string
  668. */
  669. protected function parseSavepoint($name)
  670. {
  671. return 'SAVEPOINT ' . $name;
  672. }
  673. /**
  674. * 生成回滚到保存点的SQL
  675. * @param $name
  676. * @return string
  677. */
  678. protected function parseSavepointRollBack($name)
  679. {
  680. return 'ROLLBACK TO SAVEPOINT ' . $name;
  681. }
  682. /**
  683. * 批处理执行SQL语句
  684. * 批处理的指令都认为是execute操作
  685. * @access public
  686. * @param array $sqlArray SQL批处理指令
  687. * @return boolean
  688. */
  689. public function batchQuery($sqlArray = [], $bind = [], Query $query = null)
  690. {
  691. if (!is_array($sqlArray)) {
  692. return false;
  693. }
  694. // 自动启动事务支持
  695. $this->startTrans();
  696. try {
  697. foreach ($sqlArray as $sql) {
  698. $this->execute($sql, $bind, $query);
  699. }
  700. // 提交事务
  701. $this->commit();
  702. } catch (\Exception $e) {
  703. $this->rollback();
  704. throw $e;
  705. }
  706. return true;
  707. }
  708. /**
  709. * 获得查询次数
  710. * @access public
  711. * @param boolean $execute 是否包含所有查询
  712. * @return integer
  713. */
  714. public function getQueryTimes($execute = false)
  715. {
  716. return $execute ? Db::$queryTimes + Db::$executeTimes : Db::$queryTimes;
  717. }
  718. /**
  719. * 获得执行次数
  720. * @access public
  721. * @return integer
  722. */
  723. public function getExecuteTimes()
  724. {
  725. return Db::$executeTimes;
  726. }
  727. /**
  728. * 关闭数据库(或者重新连接)
  729. * @access public
  730. * @return $this
  731. */
  732. public function close()
  733. {
  734. $this->linkID = null;
  735. $this->linkWrite = null;
  736. $this->linkRead = null;
  737. $this->links = [];
  738. // 释放查询
  739. $this->free();
  740. return $this;
  741. }
  742. /**
  743. * 是否断线
  744. * @access protected
  745. * @param \PDOException|\Exception $e 异常对象
  746. * @return bool
  747. */
  748. protected function isBreak($e)
  749. {
  750. if (!$this->config['break_reconnect']) {
  751. return false;
  752. }
  753. $info = [
  754. 'server has gone away',
  755. 'no connection to the server',
  756. 'Lost connection',
  757. 'is dead or not enabled',
  758. 'Error while sending',
  759. 'decryption failed or bad record mac',
  760. 'server closed the connection unexpectedly',
  761. 'SSL connection has been closed unexpectedly',
  762. 'Error writing data to the connection',
  763. 'Resource deadlock avoided',
  764. 'failed with errno',
  765. 'send of 33 bytes failed with errno=32 Broken pipe',
  766. 'send of 93 bytes failed with errno=110 Connection timed out'
  767. ];
  768. $error = $e->getMessage();
  769. foreach ($info as $msg) {
  770. if (false !== stripos($error, $msg)) {
  771. return true;
  772. }
  773. }
  774. return false;
  775. }
  776. /**
  777. * 获取最近一次查询的sql语句
  778. * @access public
  779. * @return string
  780. */
  781. public function getLastSql()
  782. {
  783. return $this->getRealSql($this->queryStr, $this->bind);
  784. }
  785. /**
  786. * 获取最近插入的ID
  787. * @access public
  788. * @param string $sequence 自增序列名
  789. * @return string
  790. */
  791. public function getLastInsID($sequence = null)
  792. {
  793. return $this->linkID->lastInsertId($sequence);
  794. }
  795. /**
  796. * 获取返回或者影响的记录数
  797. * @access public
  798. * @return integer
  799. */
  800. public function getNumRows()
  801. {
  802. return $this->numRows;
  803. }
  804. /**
  805. * 获取最近的错误信息
  806. * @access public
  807. * @return string
  808. */
  809. public function getError()
  810. {
  811. if ($this->PDOStatement) {
  812. $error = $this->PDOStatement->errorInfo();
  813. $error = $error[1] . ':' . $error[2];
  814. } else {
  815. $error = '';
  816. }
  817. if ('' != $this->queryStr) {
  818. $error .= "\n [ SQL语句 ] : " . $this->getLastsql();
  819. }
  820. return $error;
  821. }
  822. /**
  823. * SQL指令安全过滤
  824. * @access public
  825. * @param string $str SQL字符串
  826. * @param bool $master 是否主库查询
  827. * @return string
  828. */
  829. public function quote($str, $master = true)
  830. {
  831. $this->initConnect($master);
  832. return $this->linkID ? $this->linkID->quote($str) : $str;
  833. }
  834. /**
  835. * 数据库调试 记录当前SQL及分析性能
  836. * @access protected
  837. * @param boolean $start 调试开始标记 true 开始 false 结束
  838. * @param string $sql 执行的SQL语句 留空自动获取
  839. * @param boolean $master 主从标记
  840. * @return void
  841. */
  842. protected function debug($start, $sql = '', $master = false)
  843. {
  844. if (!empty($this->config['debug'])) {
  845. // 开启数据库调试模式
  846. if ($start) {
  847. Debug::remark('queryStartTime', 'time');
  848. } else {
  849. // 记录操作结束时间
  850. Debug::remark('queryEndTime', 'time');
  851. $runtime = Debug::getRangeTime('queryStartTime', 'queryEndTime');
  852. $sql = $sql ?: $this->getLastsql();
  853. $result = [];
  854. // SQL性能分析
  855. if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
  856. $result = $this->getExplain($sql);
  857. }
  858. // SQL监听
  859. $this->trigger($sql, $runtime, $result, $master);
  860. }
  861. }
  862. }
  863. /**
  864. * 监听SQL执行
  865. * @access public
  866. * @param callable $callback 回调方法
  867. * @return void
  868. */
  869. public function listen($callback)
  870. {
  871. self::$event[] = $callback;
  872. }
  873. /**
  874. * 触发SQL事件
  875. * @access protected
  876. * @param string $sql SQL语句
  877. * @param float $runtime SQL运行时间
  878. * @param mixed $explain SQL分析
  879. * @param bool $master 主从标记
  880. * @return void
  881. */
  882. protected function trigger($sql, $runtime, $explain = [], $master = false)
  883. {
  884. if (!empty(self::$event)) {
  885. foreach (self::$event as $callback) {
  886. if (is_callable($callback)) {
  887. call_user_func_array($callback, [$sql, $runtime, $explain, $master]);
  888. }
  889. }
  890. } else {
  891. // 未注册监听则记录到日志中
  892. if ($this->config['deploy']) {
  893. // 分布式记录当前操作的主从
  894. $master = $master ? 'master|' : 'slave|';
  895. } else {
  896. $master = '';
  897. }
  898. Log::record('[ SQL ] ' . $sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]', 'sql');
  899. if (!empty($explain)) {
  900. Log::record('[ EXPLAIN : ' . var_export($explain, true) . ' ]', 'sql');
  901. }
  902. }
  903. }
  904. /**
  905. * 初始化数据库连接
  906. * @access protected
  907. * @param boolean $master 是否主服务器
  908. * @return void
  909. */
  910. protected function initConnect($master = true)
  911. {
  912. if (!empty($this->config['deploy'])) {
  913. // 采用分布式数据库
  914. if ($master || $this->transTimes) {
  915. if (!$this->linkWrite) {
  916. $this->linkWrite = $this->multiConnect(true);
  917. }
  918. $this->linkID = $this->linkWrite;
  919. } else {
  920. if (!$this->linkRead) {
  921. $this->linkRead = $this->multiConnect(false);
  922. }
  923. $this->linkID = $this->linkRead;
  924. }
  925. } elseif (!$this->linkID) {
  926. // 默认单数据库
  927. $this->linkID = $this->connect();
  928. }
  929. }
  930. /**
  931. * 连接分布式服务器
  932. * @access protected
  933. * @param boolean $master 主服务器
  934. * @return PDO
  935. */
  936. protected function multiConnect($master = false)
  937. {
  938. $_config = [];
  939. // 分布式数据库配置解析
  940. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  941. $_config[$name] = explode(',', $this->config[$name]);
  942. }
  943. // 主服务器序号
  944. $m = floor(mt_rand(0, $this->config['master_num'] - 1));
  945. if ($this->config['rw_separate']) {
  946. // 主从式采用读写分离
  947. if ($master) // 主服务器写入
  948. {
  949. $r = $m;
  950. } elseif (is_numeric($this->config['slave_no'])) {
  951. // 指定服务器读
  952. $r = $this->config['slave_no'];
  953. } else {
  954. // 读操作连接从服务器 每次随机连接的数据库
  955. $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1));
  956. }
  957. } else {
  958. // 读写操作不区分服务器 每次随机连接的数据库
  959. $r = floor(mt_rand(0, count($_config['hostname']) - 1));
  960. }
  961. $dbMaster = false;
  962. if ($m != $r) {
  963. $dbMaster = [];
  964. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  965. $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0];
  966. }
  967. }
  968. $dbConfig = [];
  969. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  970. $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0];
  971. }
  972. return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster);
  973. }
  974. /**
  975. * 析构方法
  976. * @access public
  977. */
  978. public function __destruct()
  979. {
  980. // 释放查询
  981. if ($this->PDOStatement) {
  982. $this->free();
  983. }
  984. // 关闭连接
  985. $this->close();
  986. }
  987. }