Connection.php 30 KB

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