Connection.php 27 KB

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