Connection.php 30 KB

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