Connection.php 30 KB

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