Connection.php 30 KB

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