Connection.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132
  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 InvalidArgumentException;
  13. use PDO;
  14. use PDOStatement;
  15. use think\Container;
  16. use think\Db;
  17. use think\db\exception\BindParamException;
  18. use think\Debug;
  19. use think\Exception;
  20. use think\exception\PDOException;
  21. abstract class Connection
  22. {
  23. protected static $instance = [];
  24. /** @var PDOStatement PDO操作实例 */
  25. protected $PDOStatement;
  26. /** @var string 当前SQL指令 */
  27. protected $queryStr = '';
  28. // 返回或者影响记录数
  29. protected $numRows = 0;
  30. // 事务指令数
  31. protected $transTimes = 0;
  32. // 错误信息
  33. protected $error = '';
  34. /** @var PDO[] 数据库连接ID 支持多个连接 */
  35. protected $links = [];
  36. /** @var PDO 当前连接ID */
  37. protected $linkID;
  38. protected $linkRead;
  39. protected $linkWrite;
  40. // 查询结果类型
  41. protected $fetchType = PDO::FETCH_ASSOC;
  42. // 字段属性大小写
  43. protected $attrCase = PDO::CASE_LOWER;
  44. // 监听回调
  45. protected static $event = [];
  46. // 数据表信息
  47. protected static $info = [];
  48. // 使用Builder类
  49. protected $builderClassName;
  50. // Builder对象
  51. protected $builder;
  52. // 数据库连接参数配置
  53. protected $config = [
  54. // 数据库类型
  55. 'type' => '',
  56. // 服务器地址
  57. 'hostname' => '',
  58. // 数据库名
  59. 'database' => '',
  60. // 用户名
  61. 'username' => '',
  62. // 密码
  63. 'password' => '',
  64. // 端口
  65. 'hostport' => '',
  66. // 连接dsn
  67. 'dsn' => '',
  68. // 数据库连接参数
  69. 'params' => [],
  70. // 数据库编码默认采用utf8
  71. 'charset' => 'utf8',
  72. // 数据库表前缀
  73. 'prefix' => '',
  74. // 数据库调试模式
  75. 'debug' => false,
  76. // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
  77. 'deploy' => 0,
  78. // 数据库读写是否分离 主从式有效
  79. 'rw_separate' => false,
  80. // 读写分离后 主服务器数量
  81. 'master_num' => 1,
  82. // 指定从服务器序号
  83. 'slave_no' => '',
  84. // 是否严格检查字段是否存在
  85. 'fields_strict' => true,
  86. // 数据集返回类型
  87. 'resultset_type' => '',
  88. // 自动写入时间戳字段
  89. 'auto_timestamp' => false,
  90. // 时间字段取出后的默认时间格式
  91. 'datetime_format' => 'Y-m-d H:i:s',
  92. // 是否需要进行SQL性能分析
  93. 'sql_explain' => false,
  94. // Builder类
  95. 'builder' => '',
  96. // Query类
  97. 'query' => '\\think\\db\\Query',
  98. // 是否需要断线重连
  99. 'break_reconnect' => false,
  100. ];
  101. // PDO连接参数
  102. protected $params = [
  103. PDO::ATTR_CASE => PDO::CASE_NATURAL,
  104. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  105. PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
  106. PDO::ATTR_STRINGIFY_FETCHES => false,
  107. PDO::ATTR_EMULATE_PREPARES => false,
  108. ];
  109. // 绑定参数
  110. protected $bind = [];
  111. /**
  112. * 架构函数 读取数据库配置信息
  113. * @access public
  114. * @param array $config 数据库配置数组
  115. */
  116. public function __construct(array $config = [])
  117. {
  118. if (!empty($config)) {
  119. $this->config = array_merge($this->config, $config);
  120. }
  121. // 创建Builder对象
  122. $class = $this->getBuilderClass();
  123. $this->builder = new $class($this);
  124. // 执行初始化操作
  125. $this->initialize();
  126. }
  127. /**
  128. * 初始化
  129. * @access protected
  130. * @return void
  131. */
  132. protected function initialize()
  133. {}
  134. /**
  135. * 取得数据库连接类实例
  136. * @access public
  137. * @param mixed $config 连接配置
  138. * @param bool|string $name 连接标识 true 强制重新连接
  139. * @return Connection
  140. * @throws Exception
  141. */
  142. public static function instance($config = [], $name = false)
  143. {
  144. if (false === $name) {
  145. $name = md5(serialize($config));
  146. }
  147. if (true === $name || !isset(self::$instance[$name])) {
  148. // 解析连接参数 支持数组和字符串
  149. $options = self::parseConfig($config);
  150. if (empty($options['type'])) {
  151. throw new InvalidArgumentException('Undefined db type');
  152. }
  153. $class = false !== strpos($options['type'], '\\') ? $options['type'] : '\\think\\db\\connector\\' . ucwords($options['type']);
  154. // 记录初始化信息
  155. Container::get('app')->log('[ DB ] INIT ' . $options['type']);
  156. if (true === $name) {
  157. $name = md5(serialize($config));
  158. }
  159. self::$instance[$name] = new $class($options);
  160. }
  161. return self::$instance[$name];
  162. }
  163. /**
  164. * 获取当前连接器类对应的Builder类
  165. * @access public
  166. * @return string
  167. */
  168. public function getBuilderClass()
  169. {
  170. if (!empty($this->builderClassName)) {
  171. return $this->builderClassName;
  172. } else {
  173. return $this->getConfig('builder') ?: '\\think\\db\\builder\\' . ucfirst($this->getConfig('type'));
  174. }
  175. }
  176. /**
  177. * 设置当前的数据库Builder对象
  178. * @access protected
  179. * @param Builder $builder
  180. * @return void
  181. */
  182. protected function setBuilder(Builder $builder)
  183. {
  184. $this->builder = $builder;
  185. return $this;
  186. }
  187. /**
  188. * 获取当前的builder实例对象
  189. * @access public
  190. * @return Builder
  191. */
  192. public function getBuilder()
  193. {
  194. return $this->builder;
  195. }
  196. /**
  197. * 解析pdo连接的dsn信息
  198. * @access protected
  199. * @param array $config 连接信息
  200. * @return string
  201. */
  202. abstract protected function parseDsn($config);
  203. /**
  204. * 取得数据表的字段信息
  205. * @access public
  206. * @param string $tableName
  207. * @return array
  208. */
  209. abstract public function getFields($tableName);
  210. /**
  211. * 取得数据库的表信息
  212. * @access public
  213. * @param string $dbName
  214. * @return array
  215. */
  216. abstract public function getTables($dbName);
  217. /**
  218. * SQL性能分析
  219. * @access protected
  220. * @param string $sql
  221. * @return array
  222. */
  223. abstract protected function getExplain($sql);
  224. /**
  225. * 对返数据表字段信息进行大小写转换出来
  226. * @access public
  227. * @param array $info 字段信息
  228. * @return array
  229. */
  230. public function fieldCase($info)
  231. {
  232. // 字段大小写转换
  233. switch ($this->attrCase) {
  234. case PDO::CASE_LOWER:
  235. $info = array_change_key_case($info);
  236. break;
  237. case PDO::CASE_UPPER:
  238. $info = array_change_key_case($info, CASE_UPPER);
  239. break;
  240. case PDO::CASE_NATURAL:
  241. default:
  242. // 不做转换
  243. }
  244. return $info;
  245. }
  246. /**
  247. * 获取字段绑定类型
  248. * @access public
  249. * @param string $type 字段类型
  250. * @return integer
  251. */
  252. public function getFieldBindType($type)
  253. {
  254. if (0 === strpos($type, 'set') || 0 === strpos($type, 'enum')) {
  255. $bind = PDO::PARAM_STR;
  256. } elseif (preg_match('/(int|double|float|decimal|real|numeric|serial|bit)/is', $type)) {
  257. $bind = PDO::PARAM_INT;
  258. } elseif (preg_match('/bool/is', $type)) {
  259. $bind = PDO::PARAM_BOOL;
  260. } else {
  261. $bind = PDO::PARAM_STR;
  262. }
  263. return $bind;
  264. }
  265. /**
  266. * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写)
  267. * @access public
  268. * @param string $sql sql语句
  269. * @return string
  270. */
  271. public function parseSqlTable($sql)
  272. {
  273. if (false !== strpos($sql, '__')) {
  274. $prefix = $this->getConfig('prefix');
  275. $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {
  276. return $prefix . strtolower($match[1]);
  277. }, $sql);
  278. }
  279. return $sql;
  280. }
  281. /**
  282. * 获取数据表信息
  283. * @access public
  284. * @param mixed $tableName 数据表名 留空自动获取
  285. * @param string $fetch 获取信息类型 包括 fields type bind pk
  286. * @return mixed
  287. */
  288. public function getTableInfo($tableName, $fetch = '')
  289. {
  290. if (is_array($tableName)) {
  291. $tableName = key($tableName) ?: current($tableName);
  292. }
  293. if (strpos($tableName, ',')) {
  294. // 多表不获取字段信息
  295. return false;
  296. } else {
  297. $tableName = $this->parseSqlTable($tableName);
  298. }
  299. // 修正子查询作为表名的问题
  300. if (strpos($tableName, ')')) {
  301. return [];
  302. }
  303. list($tableName) = explode(' ', $tableName);
  304. if (!strpos($tableName, '.')) {
  305. $schema = $this->getConfig('database') . '.' . $tableName;
  306. } else {
  307. $schema = $tableName;
  308. }
  309. if (!isset(self::$info[$schema])) {
  310. // 读取缓存
  311. $cacheFile = Container::get('app')->getRuntimePath() . 'schema/' . $schema . '.php';
  312. if (!$this->config['debug'] && is_file($cacheFile)) {
  313. $info = include $cacheFile;
  314. } else {
  315. $info = $this->getFields($tableName);
  316. }
  317. $fields = array_keys($info);
  318. $bind = $type = [];
  319. foreach ($info as $key => $val) {
  320. // 记录字段类型
  321. $type[$key] = $val['type'];
  322. $bind[$key] = $this->getFieldBindType($val['type']);
  323. if (!empty($val['primary'])) {
  324. $pk[] = $key;
  325. }
  326. }
  327. if (isset($pk)) {
  328. // 设置主键
  329. $pk = count($pk) > 1 ? $pk : $pk[0];
  330. } else {
  331. $pk = null;
  332. }
  333. self::$info[$schema] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk];
  334. }
  335. return $fetch ? self::$info[$schema][$fetch] : self::$info[$schema];
  336. }
  337. /**
  338. * 获取数据表的主键
  339. * @access public
  340. * @param string $tableName 数据表名
  341. * @return string|array
  342. */
  343. public function getPk($tableName)
  344. {
  345. return $this->getTableInfo($tableName, 'pk');
  346. }
  347. /**
  348. * 获取数据表字段信息
  349. * @access public
  350. * @param string $tableName 数据表名
  351. * @return array
  352. */
  353. public function getTableFields($tableName)
  354. {
  355. return $this->getTableInfo($tableName, 'fields');
  356. }
  357. /**
  358. * 获取数据表字段类型
  359. * @access public
  360. * @param string $tableName 数据表名
  361. * @param string $field 字段名
  362. * @return array|string
  363. */
  364. public function getFieldsType($tableName, $field = null)
  365. {
  366. $result = $this->getTableInfo($tableName, 'type');
  367. if ($field && isset($result[$field])) {
  368. return $result[$field];
  369. }
  370. return $result;
  371. }
  372. /**
  373. * 获取数据表绑定信息
  374. * @access public
  375. * @param string $tableName 数据表名
  376. * @return array
  377. */
  378. public function getFieldsBind($tableName)
  379. {
  380. return $this->getTableInfo($tableName, 'bind');
  381. }
  382. /**
  383. * 获取数据库的配置参数
  384. * @access public
  385. * @param string $config 配置名称
  386. * @return mixed
  387. */
  388. public function getConfig($config = '')
  389. {
  390. return $config ? $this->config[$config] : $this->config;
  391. }
  392. /**
  393. * 设置数据库的配置参数
  394. * @access public
  395. * @param string|array $config 配置名称
  396. * @param mixed $value 配置值
  397. * @return void
  398. */
  399. public function setConfig($config, $value = '')
  400. {
  401. if (is_array($config)) {
  402. $this->config = array_merge($this->config, $config);
  403. } else {
  404. $this->config[$config] = $value;
  405. }
  406. }
  407. /**
  408. * 连接数据库方法
  409. * @access public
  410. * @param array $config 连接参数
  411. * @param integer $linkNum 连接序号
  412. * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式)
  413. * @return PDO
  414. * @throws Exception
  415. */
  416. public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
  417. {
  418. if (!isset($this->links[$linkNum])) {
  419. if (!$config) {
  420. $config = $this->config;
  421. } else {
  422. $config = array_merge($this->config, $config);
  423. }
  424. // 连接参数
  425. if (isset($config['params']) && is_array($config['params'])) {
  426. $params = $config['params'] + $this->params;
  427. } else {
  428. $params = $this->params;
  429. }
  430. // 记录当前字段属性大小写设置
  431. $this->attrCase = $params[PDO::ATTR_CASE];
  432. try {
  433. if (empty($config['dsn'])) {
  434. $config['dsn'] = $this->parseDsn($config);
  435. }
  436. if ($config['debug']) {
  437. $startTime = microtime(true);
  438. }
  439. $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
  440. if ($config['debug']) {
  441. // 记录数据库连接信息
  442. $this->log('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']);
  443. }
  444. } catch (\PDOException $e) {
  445. if ($autoConnection) {
  446. $this->log($e->getMessage(), 'error');
  447. return $this->connect($autoConnection, $linkNum);
  448. } else {
  449. throw $e;
  450. }
  451. }
  452. }
  453. return $this->links[$linkNum];
  454. }
  455. /**
  456. * 释放查询结果
  457. * @access public
  458. */
  459. public function free()
  460. {
  461. $this->PDOStatement = null;
  462. }
  463. /**
  464. * 获取PDO对象
  465. * @access public
  466. * @return \PDO|false
  467. */
  468. public function getPdo()
  469. {
  470. if (!$this->linkID) {
  471. return false;
  472. } else {
  473. return $this->linkID;
  474. }
  475. }
  476. /**
  477. * 执行查询 使用生成器返回数据
  478. * @access public
  479. * @param string $sql sql指令
  480. * @param array $bind 参数绑定
  481. * @param bool $master 是否在主服务器读操作
  482. * @param Model $model 模型对象实例
  483. * @param array $condition 查询条件
  484. * @param mixed $relation 关联查询
  485. * @return \Generator
  486. */
  487. public function getCursor($sql, $bind = [], $master = false, $model = null, $condition = null, $relation = null)
  488. {
  489. $this->initConnect($master);
  490. // 记录SQL语句
  491. $this->queryStr = $sql;
  492. $this->bind = $bind;
  493. // 释放前次的查询结果
  494. if (!empty($this->PDOStatement)) {
  495. $this->free();
  496. }
  497. Db::$queryTimes++;
  498. // 调试开始
  499. $this->debug(true);
  500. // 预处理
  501. if (empty($this->PDOStatement)) {
  502. $this->PDOStatement = $this->linkID->prepare($sql);
  503. }
  504. // 是否为存储过程调用
  505. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  506. // 参数绑定
  507. if ($procedure) {
  508. $this->bindParam($bind);
  509. } else {
  510. $this->bindValue($bind);
  511. }
  512. // 执行查询
  513. $this->PDOStatement->execute();
  514. // 调试结束
  515. $this->debug(false);
  516. // 返回结果集
  517. while ($result = $this->PDOStatement->fetch($this->fetchType)) {
  518. if ($model) {
  519. $instance = $model->newInstance($result, $condition);
  520. if ($relation) {
  521. $instance->relationQuery($relation);
  522. }
  523. yield $instance;
  524. } else {
  525. yield $result;
  526. }
  527. }
  528. }
  529. /**
  530. * 执行查询 返回数据集
  531. * @access public
  532. * @param string $sql sql指令
  533. * @param array $bind 参数绑定
  534. * @param bool $master 是否在主服务器读操作
  535. * @param bool $pdo 是否返回PDO对象
  536. * @return array
  537. * @throws BindParamException
  538. * @throws \PDOException
  539. * @throws \Exception
  540. * @throws \Throwable
  541. */
  542. public function query($sql, $bind = [], $master = false, $pdo = false)
  543. {
  544. $this->initConnect($master);
  545. if (!$this->linkID) {
  546. return false;
  547. }
  548. // 记录SQL语句
  549. $this->queryStr = $sql;
  550. $this->bind = $bind;
  551. Db::$queryTimes++;
  552. try {
  553. // 调试开始
  554. $this->debug(true);
  555. // 释放前次的查询结果
  556. if (!empty($this->PDOStatement)) {
  557. $this->free();
  558. }
  559. // 预处理
  560. if (empty($this->PDOStatement)) {
  561. $this->PDOStatement = $this->linkID->prepare($sql);
  562. }
  563. // 是否为存储过程调用
  564. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  565. // 参数绑定
  566. if ($procedure) {
  567. $this->bindParam($bind);
  568. } else {
  569. $this->bindValue($bind);
  570. }
  571. // 执行查询
  572. $this->PDOStatement->execute();
  573. // 调试结束
  574. $this->debug(false);
  575. // 返回结果集
  576. return $this->getResult($pdo, $procedure);
  577. } catch (\PDOException $e) {
  578. if ($this->isBreak($e)) {
  579. return $this->close()->query($sql, $bind, $master, $pdo);
  580. }
  581. throw new PDOException($e, $this->config, $this->getLastsql());
  582. } catch (\Throwable $e) {
  583. if ($this->isBreak($e)) {
  584. return $this->close()->query($sql, $bind, $master, $pdo);
  585. }
  586. throw $e;
  587. } catch (\Exception $e) {
  588. if ($this->isBreak($e)) {
  589. return $this->close()->query($sql, $bind, $master, $pdo);
  590. }
  591. throw $e;
  592. }
  593. }
  594. /**
  595. * 执行语句
  596. * @access public
  597. * @param string $sql sql指令
  598. * @param array $bind 参数绑定
  599. * @return int
  600. * @throws BindParamException
  601. * @throws \PDOException
  602. * @throws \Exception
  603. * @throws \Throwable
  604. */
  605. public function execute($sql, $bind = [])
  606. {
  607. $this->initConnect(true);
  608. if (!$this->linkID) {
  609. return false;
  610. }
  611. // 记录SQL语句
  612. $this->queryStr = $sql;
  613. $this->bind = $bind;
  614. Db::$executeTimes++;
  615. try {
  616. // 调试开始
  617. $this->debug(true);
  618. //释放前次的查询结果
  619. if (!empty($this->PDOStatement) && $this->PDOStatement->queryString != $sql) {
  620. $this->free();
  621. }
  622. // 预处理
  623. if (empty($this->PDOStatement)) {
  624. $this->PDOStatement = $this->linkID->prepare($sql);
  625. }
  626. // 是否为存储过程调用
  627. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  628. // 参数绑定
  629. if ($procedure) {
  630. $this->bindParam($bind);
  631. } else {
  632. $this->bindValue($bind);
  633. }
  634. // 执行语句
  635. $this->PDOStatement->execute();
  636. // 调试结束
  637. $this->debug(false);
  638. $this->numRows = $this->PDOStatement->rowCount();
  639. return $this->numRows;
  640. } catch (\PDOException $e) {
  641. if ($this->isBreak($e)) {
  642. return $this->close()->execute($sql, $bind);
  643. }
  644. throw new PDOException($e, $this->config, $this->getLastsql());
  645. } catch (\Throwable $e) {
  646. if ($this->isBreak($e)) {
  647. return $this->close()->execute($sql, $bind);
  648. }
  649. throw $e;
  650. } catch (\Exception $e) {
  651. if ($this->isBreak($e)) {
  652. return $this->close()->execute($sql, $bind);
  653. }
  654. throw $e;
  655. }
  656. }
  657. /**
  658. * 查找单条记录
  659. * @access public
  660. * @param Query $query 查询对象
  661. * @return array|null|\PDOStatement|string
  662. * @throws DbException
  663. * @throws ModelNotFoundException
  664. * @throws DataNotFoundException
  665. */
  666. public function find(Query $query)
  667. {
  668. // 分析查询表达式
  669. $options = $query->getOptions();
  670. $pk = $query->getPk($options);
  671. if (!empty($options['cache']) && true === $options['cache']['key'] && is_string($pk) && isset($options['where']['AND'][$pk])) {
  672. $key = $this->getCacheKey($options['where']['AND'][$pk], $options);
  673. }
  674. $data = $options['data'];
  675. $result = false;
  676. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  677. // 判断查询缓存
  678. $cache = $options['cache'];
  679. if (is_string($cache['key'])) {
  680. $key = $cache['key'];
  681. } elseif (!isset($key)) {
  682. $key = $this->getCacheKey($data, $options, $query->getBind(false));
  683. }
  684. $result = Container::get('cache')->get($key);
  685. }
  686. if (false === $result) {
  687. if (is_string($pk)) {
  688. if (!is_array($data)) {
  689. if (isset($key) && strpos($key, '|')) {
  690. list($a, $val) = explode('|', $key);
  691. $item[$pk] = $val;
  692. } else {
  693. $item[$pk] = $data;
  694. }
  695. $data = $item;
  696. }
  697. }
  698. $query->setOption('data', $data);
  699. $query->setOption('limit', 1);
  700. // 生成查询SQL
  701. $sql = $this->builder->select($query);
  702. $bind = $query->getBind();
  703. if (!empty($options['fetch_sql'])) {
  704. // 获取实际执行的SQL语句
  705. return $this->getRealSql($sql, $bind);
  706. }
  707. // 事件回调
  708. if ($result = $query->trigger('before_find')) {
  709. } else {
  710. // 执行查询
  711. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  712. if ($resultSet instanceof \PDOStatement) {
  713. // 返回PDOStatement对象
  714. return $resultSet;
  715. }
  716. $result = isset($resultSet[0]) ? $resultSet[0] : null;
  717. }
  718. if (isset($cache) && $result) {
  719. // 缓存数据
  720. $this->cacheData($key, $result, $cache);
  721. }
  722. }
  723. return $result;
  724. }
  725. /**
  726. * 使用游标查询记录
  727. * @access public
  728. * @param Query $query 查询对象
  729. * @return \Generator
  730. */
  731. public function cursor(Query $query)
  732. {
  733. // 分析查询表达式
  734. $options = $query->getOptions();
  735. // 生成查询SQL
  736. $sql = $this->builder->select($query);
  737. $bind = $query->getBind();
  738. $condition = isset($options['where']['AND']) ? $options['where']['AND'] : null;
  739. $relation = isset($options['relaltion']) ? $options['relation'] : null;
  740. // 执行查询操作
  741. return $this->getCursor($sql, $bind, $options['master'], $query->getModel(), $condition, $relation);
  742. }
  743. /**
  744. * 查找记录
  745. * @access public
  746. * @param Query $query 查询对象
  747. * @return array|\PDOStatement|string
  748. * @throws DbException
  749. * @throws ModelNotFoundException
  750. * @throws DataNotFoundException
  751. */
  752. public function select(Query $query)
  753. {
  754. // 分析查询表达式
  755. $options = $query->getOptions();
  756. $resultSet = false;
  757. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  758. // 判断查询缓存
  759. $cache = $options['cache'];
  760. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options) . serialize($query->getBind(false)));
  761. $resultSet = Container::get('cache')->get($key);
  762. }
  763. if (false === $resultSet) {
  764. // 生成查询SQL
  765. $sql = $this->builder->select($query);
  766. $bind = $query->getBind();
  767. if (!empty($options['fetch_sql'])) {
  768. // 获取实际执行的SQL语句
  769. return $this->getRealSql($sql, $bind);
  770. }
  771. if ($resultSet = $query->trigger('before_select')) {
  772. } else {
  773. // 执行查询操作
  774. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  775. if ($resultSet instanceof \PDOStatement) {
  776. // 返回PDOStatement对象
  777. return $resultSet;
  778. }
  779. }
  780. if (isset($cache) && false !== $resultSet) {
  781. // 缓存数据集
  782. $this->cacheData($key, $resultSet, $cache);
  783. }
  784. }
  785. return $resultSet;
  786. }
  787. /**
  788. * 插入记录
  789. * @access public
  790. * @param Query $query 查询对象
  791. * @param boolean $replace 是否replace
  792. * @param boolean $getLastInsID 返回自增主键
  793. * @param string $sequence 自增序列名
  794. * @return integer|string
  795. */
  796. public function insert(Query $query, $replace = false, $getLastInsID = false, $sequence = null)
  797. {
  798. // 分析查询表达式
  799. $options = $query->getOptions();
  800. // 生成SQL语句
  801. $sql = $this->builder->insert($query, $replace);
  802. $bind = $query->getBind();
  803. if (!empty($options['fetch_sql'])) {
  804. // 获取实际执行的SQL语句
  805. return $this->getRealSql($sql, $bind);
  806. }
  807. // 执行操作
  808. $result = $this->execute($sql, $bind);
  809. if ($result) {
  810. $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null);
  811. $lastInsId = $this->getLastInsID($sequence);
  812. $data = $options['data'];
  813. if ($lastInsId) {
  814. $pk = $query->getPk($options);
  815. if (is_string($pk)) {
  816. $data[$pk] = $lastInsId;
  817. }
  818. }
  819. $query->setOption('data', $data);
  820. $query->trigger('after_insert');
  821. if ($getLastInsID) {
  822. return $lastInsId;
  823. }
  824. }
  825. return $result;
  826. }
  827. /**
  828. * 批量插入记录
  829. * @access public
  830. * @param Query $query 查询对象
  831. * @param mixed $dataSet 数据集
  832. * @param bool $replace 是否replace
  833. * @param integer $limit 每次写入数据限制
  834. * @return integer|string
  835. * @throws \Exception
  836. * @throws \Throwable
  837. */
  838. public function insertAll(Query $query, $dataSet = [], $replace = false, $limit = null)
  839. {
  840. if (!is_array(reset($dataSet))) {
  841. return false;
  842. }
  843. $options = $query->getOptions();
  844. if ($limit) {
  845. // 分批写入 自动启动事务支持
  846. $this->startTrans();
  847. try {
  848. $array = array_chunk($dataSet, $limit, true);
  849. $count = 0;
  850. foreach ($array as $item) {
  851. $sql = $this->builder->insertAll($query, $item, $replace);
  852. $bind = $query->getBind();
  853. if (!empty($options['fetch_sql'])) {
  854. $fetchSql[] = $this->getRealSql($sql, $bind);
  855. } else {
  856. $count += $this->execute($sql, $bind);
  857. }
  858. }
  859. // 提交事务
  860. $this->commit();
  861. } catch (\Exception $e) {
  862. $this->rollback();
  863. throw $e;
  864. } catch (\Throwable $e) {
  865. $this->rollback();
  866. throw $e;
  867. }
  868. return isset($fetchSql) ? implode(';', $fetchSql) : $count;
  869. }
  870. $sql = $this->builder->insertAll($query, $dataSet, $replace);
  871. $bind = $query->getBind();
  872. if (!empty($options['fetch_sql'])) {
  873. // 获取实际执行的SQL语句
  874. return $this->getRealSql($sql, $bind);
  875. } else {
  876. // 执行操作
  877. return $this->execute($sql, $bind);
  878. }
  879. }
  880. /**
  881. * 通过Select方式插入记录
  882. * @access public
  883. * @param Query $query 查询对象
  884. * @param string $fields 要插入的数据表字段名
  885. * @param string $table 要插入的数据表名
  886. * @return integer|string
  887. * @throws PDOException
  888. */
  889. public function selectInsert(Query $query, $fields, $table)
  890. {
  891. // 分析查询表达式
  892. $options = $query->getOptions();
  893. // 生成SQL语句
  894. $table = $this->parseSqlTable($table);
  895. $sql = $this->builder->selectInsert($query, $fields, $table);
  896. $bind = $query->getBind();
  897. if (!empty($options['fetch_sql'])) {
  898. // 获取实际执行的SQL语句
  899. return $this->getRealSql($sql, $bind);
  900. } else {
  901. // 执行操作
  902. return $this->execute($sql, $bind);
  903. }
  904. }
  905. /**
  906. * 更新记录
  907. * @access public
  908. * @param Query $query 查询对象
  909. * @return integer|string
  910. * @throws Exception
  911. * @throws PDOException
  912. */
  913. public function update(Query $query)
  914. {
  915. $options = $query->getOptions();
  916. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  917. $key = $options['cache']['key'];
  918. }
  919. $pk = $query->getPk($options);
  920. $data = $options['data'];
  921. if (empty($options['where'])) {
  922. // 如果存在主键数据 则自动作为更新条件
  923. if (is_string($pk) && isset($data[$pk])) {
  924. $where[$pk] = [$pk, '=', $data[$pk]];
  925. if (!isset($key)) {
  926. $key = $this->getCacheKey($data[$pk], $options);
  927. }
  928. unset($data[$pk]);
  929. } elseif (is_array($pk)) {
  930. // 增加复合主键支持
  931. foreach ($pk as $field) {
  932. if (isset($data[$field])) {
  933. $where[$field] = [$field, '=', $data[$field]];
  934. } else {
  935. // 如果缺少复合主键数据则不执行
  936. throw new Exception('miss complex primary data');
  937. }
  938. unset($data[$field]);
  939. }
  940. }
  941. if (!isset($where)) {
  942. // 如果没有任何更新条件则不执行
  943. throw new Exception('miss update condition');
  944. } else {
  945. $options['where']['AND'] = $where;
  946. $query->setOption('where', ['AND' => $where]);
  947. }
  948. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
  949. $key = $this->getCacheKey($options['where']['AND'][$pk], $options);
  950. }
  951. // 更新数据
  952. $query->setOption('data', $data);
  953. // 生成UPDATE SQL语句
  954. $sql = $this->builder->update($query);
  955. $bind = $query->getBind();
  956. if (!empty($options['fetch_sql'])) {
  957. // 获取实际执行的SQL语句
  958. return $this->getRealSql($sql, $bind);
  959. } else {
  960. // 检测缓存
  961. $cache = Container::get('cache');
  962. if (isset($key) && $cache->get($key)) {
  963. // 删除缓存
  964. $cache->rm($key);
  965. } elseif (!empty($options['cache']['tag'])) {
  966. $cache->clear($options['cache']['tag']);
  967. }
  968. // 执行操作
  969. $result = '' == $sql ? 0 : $this->execute($sql, $bind);
  970. if ($result) {
  971. if (is_string($pk) && isset($where[$pk])) {
  972. $data[$pk] = $where[$pk];
  973. } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
  974. list($a, $val) = explode('|', $key);
  975. $data[$pk] = $val;
  976. }
  977. $query->setOption('data', $data);
  978. $query->trigger('after_update');
  979. }
  980. return $result;
  981. }
  982. }
  983. /**
  984. * 删除记录
  985. * @access public
  986. * @param Query $query 查询对象
  987. * @return int
  988. * @throws Exception
  989. * @throws PDOException
  990. */
  991. public function delete(Query $query)
  992. {
  993. // 分析查询表达式
  994. $options = $query->getOptions();
  995. $pk = $query->getPk($options);
  996. $data = $options['data'];
  997. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  998. $key = $options['cache']['key'];
  999. } elseif (!is_null($data) && true !== $data && !is_array($data)) {
  1000. $key = $this->getCacheKey($data, $options);
  1001. } elseif (is_string($pk) && isset($options['where']['AND'][$pk])) {
  1002. $key = $this->getCacheKey($options['where']['AND'][$pk], $options);
  1003. }
  1004. if (true !== $data && empty($options['where'])) {
  1005. // 如果条件为空 不进行删除操作 除非设置 1=1
  1006. throw new Exception('delete without condition');
  1007. }
  1008. // 生成删除SQL语句
  1009. $sql = $this->builder->delete($query);
  1010. $bind = $query->getBind();
  1011. if (!empty($options['fetch_sql'])) {
  1012. // 获取实际执行的SQL语句
  1013. return $this->getRealSql($sql, $bind);
  1014. }
  1015. // 检测缓存
  1016. $cache = Container::get('cache');
  1017. if (isset($key) && $cache->get($key)) {
  1018. // 删除缓存
  1019. $cache->rm($key);
  1020. } elseif (!empty($options['cache']['tag'])) {
  1021. $cache->clear($options['cache']['tag']);
  1022. }
  1023. // 执行操作
  1024. $result = $this->execute($sql, $bind);
  1025. if ($result) {
  1026. if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) {
  1027. list($a, $val) = explode('|', $key);
  1028. $item[$pk] = $val;
  1029. $data = $item;
  1030. }
  1031. $options['data'] = $data;
  1032. $query->trigger('after_delete');
  1033. }
  1034. return $result;
  1035. }
  1036. /**
  1037. * 得到某个字段的值
  1038. * @access public
  1039. * @param Query $query 查询对象
  1040. * @param string $field 字段名
  1041. * @param bool $default 默认值
  1042. * @return mixed
  1043. */
  1044. public function value(Query $query, $field, $default = null)
  1045. {
  1046. $options = $query->getOptions();
  1047. $result = false;
  1048. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  1049. // 判断查询缓存
  1050. $cache = $options['cache'];
  1051. $key = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($options) . serialize($query->getBind(false)));
  1052. $result = Container::get('cache')->get($key);
  1053. }
  1054. if (false === $result) {
  1055. if (isset($options['field'])) {
  1056. $query->removeOption('field');
  1057. }
  1058. if (is_string($field)) {
  1059. $field = array_map('trim', explode(',', $field));
  1060. }
  1061. $query->setOption('field', $field);
  1062. $query->setOption('limit', 1);
  1063. // 生成查询SQL
  1064. $sql = $this->builder->select($query);
  1065. $bind = $query->getBind();
  1066. if (!empty($options['fetch_sql'])) {
  1067. // 获取实际执行的SQL语句
  1068. return $this->getRealSql($sql, $bind);
  1069. }
  1070. // 执行查询操作
  1071. $pdo = $this->query($sql, $bind, $options['master'], true);
  1072. if (is_string($pdo)) {
  1073. // 返回SQL语句
  1074. return $pdo;
  1075. }
  1076. $result = $pdo->fetchColumn();
  1077. if (isset($cache) && false !== $result) {
  1078. // 缓存数据
  1079. $this->cacheData($key, $result, $cache);
  1080. }
  1081. }
  1082. return false !== $result ? $result : $default;
  1083. }
  1084. /**
  1085. * 得到某个字段的值
  1086. * @access public
  1087. * @param Query $query 查询对象
  1088. * @param string $aggregate 聚合方法
  1089. * @param string $field 字段名
  1090. * @return mixed
  1091. */
  1092. public function aggregate(Query $query, $aggregate, $field)
  1093. {
  1094. $field = $aggregate . '(' . $this->builder->parseKey($query, $field) . ') AS tp_' . strtolower($aggregate);
  1095. return $this->value($query, $field, 0);
  1096. }
  1097. /**
  1098. * 得到某个列的数组
  1099. * @access public
  1100. * @param Query $query 查询对象
  1101. * @param string $field 字段名 多个字段用逗号分隔
  1102. * @param string $key 索引
  1103. * @return array
  1104. */
  1105. public function column(Query $query, $field, $key = '')
  1106. {
  1107. $options = $query->getOptions();
  1108. $result = false;
  1109. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  1110. // 判断查询缓存
  1111. $cache = $options['cache'];
  1112. $guid = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($options) . serialize($query->getBind(false)));
  1113. $result = Container::get('cache')->get($guid);
  1114. }
  1115. if (false === $result) {
  1116. if (isset($options['field'])) {
  1117. $query->removeOption('field');
  1118. }
  1119. if (is_null($field)) {
  1120. $field = '*';
  1121. } elseif ($key && '*' != $field) {
  1122. $field = $key . ',' . $field;
  1123. }
  1124. if (is_string($field)) {
  1125. $field = array_map('trim', explode(',', $field));
  1126. }
  1127. $query->setOption('field', $field);
  1128. // 生成查询SQL
  1129. $sql = $this->builder->select($query);
  1130. $bind = $query->getBind();
  1131. if (!empty($options['fetch_sql'])) {
  1132. // 获取实际执行的SQL语句
  1133. return $this->getRealSql($sql, $bind);
  1134. }
  1135. // 执行查询操作
  1136. $pdo = $this->query($sql, $bind, $options['master'], true);
  1137. if (1 == $pdo->columnCount()) {
  1138. $result = $pdo->fetchAll(PDO::FETCH_COLUMN);
  1139. } else {
  1140. $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC);
  1141. if ('*' == $field && $key) {
  1142. $result = array_column($resultSet, null, $key);
  1143. } elseif ($resultSet) {
  1144. $fields = array_keys($resultSet[0]);
  1145. $count = count($fields);
  1146. $key1 = array_shift($fields);
  1147. $key2 = $fields ? array_shift($fields) : '';
  1148. $key = $key ?: $key1;
  1149. if (strpos($key, '.')) {
  1150. list($alias, $key) = explode('.', $key);
  1151. }
  1152. if (2 == $count) {
  1153. $column = $key2;
  1154. } elseif (1 == $count) {
  1155. $column = $key1;
  1156. } else {
  1157. $column = null;
  1158. }
  1159. $result = array_column($resultSet, $column, $key);
  1160. } else {
  1161. $result = [];
  1162. }
  1163. }
  1164. if (isset($cache) && isset($guid)) {
  1165. // 缓存数据
  1166. $this->cacheData($guid, $result, $cache);
  1167. }
  1168. }
  1169. return $result;
  1170. }
  1171. /**
  1172. * 执行查询但只返回PDOStatement对象
  1173. * @access public
  1174. * @return \PDOStatement|string
  1175. */
  1176. public function pdo(Query $query)
  1177. {
  1178. // 分析查询表达式
  1179. $options = $query->getOptions();
  1180. // 生成查询SQL
  1181. $sql = $this->builder->select($query);
  1182. $bind = $query->getBind();
  1183. if (!empty($options['fetch_sql'])) {
  1184. // 获取实际执行的SQL语句
  1185. return $this->getRealSql($sql, $bind);
  1186. }
  1187. // 执行查询操作
  1188. return $this->query($sql, $bind, $options['master'], true);
  1189. }
  1190. /**
  1191. * 根据参数绑定组装最终的SQL语句 便于调试
  1192. * @access public
  1193. * @param string $sql 带参数绑定的sql语句
  1194. * @param array $bind 参数绑定列表
  1195. * @return string
  1196. */
  1197. public function getRealSql($sql, array $bind = [])
  1198. {
  1199. if (is_array($sql)) {
  1200. $sql = implode(';', $sql);
  1201. }
  1202. foreach ($bind as $key => $val) {
  1203. $value = is_array($val) ? $val[0] : $val;
  1204. $type = is_array($val) ? $val[1] : PDO::PARAM_STR;
  1205. if (PDO::PARAM_STR == $type) {
  1206. $value = '\'' . addslashes($value) . '\'';
  1207. } elseif (PDO::PARAM_INT == $type) {
  1208. $value = (float) $value;
  1209. }
  1210. // 判断占位符
  1211. $sql = is_numeric($key) ?
  1212. substr_replace($sql, $value, strpos($sql, '?'), 1) :
  1213. str_replace(
  1214. [':' . $key . ')', ':' . $key . ',', ':' . $key . ' ', ':' . $key . PHP_EOL],
  1215. [$value . ')', $value . ',', $value . ' ', $value . PHP_EOL],
  1216. $sql . ' ');
  1217. }
  1218. return rtrim($sql);
  1219. }
  1220. /**
  1221. * 参数绑定
  1222. * 支持 ['name'=>'value','id'=>123] 对应命名占位符
  1223. * 或者 ['value',123] 对应问号占位符
  1224. * @access public
  1225. * @param array $bind 要绑定的参数列表
  1226. * @return void
  1227. * @throws BindParamException
  1228. */
  1229. protected function bindValue(array $bind = [])
  1230. {
  1231. foreach ($bind as $key => $val) {
  1232. // 占位符
  1233. $param = is_numeric($key) ? $key + 1 : ':' . $key;
  1234. if (is_array($val)) {
  1235. if (PDO::PARAM_INT == $val[1] && '' === $val[0]) {
  1236. $val[0] = 0;
  1237. }
  1238. $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]);
  1239. } else {
  1240. $result = $this->PDOStatement->bindValue($param, $val);
  1241. }
  1242. if (!$result) {
  1243. throw new BindParamException(
  1244. "Error occurred when binding parameters '{$param}'",
  1245. $this->config,
  1246. $this->getLastsql(),
  1247. $bind
  1248. );
  1249. }
  1250. }
  1251. }
  1252. /**
  1253. * 存储过程的输入输出参数绑定
  1254. * @access public
  1255. * @param array $bind 要绑定的参数列表
  1256. * @return void
  1257. * @throws BindParamException
  1258. */
  1259. protected function bindParam($bind)
  1260. {
  1261. foreach ($bind as $key => $val) {
  1262. $param = is_numeric($key) ? $key + 1 : ':' . $key;
  1263. if (is_array($val)) {
  1264. array_unshift($val, $param);
  1265. $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val);
  1266. } else {
  1267. $result = $this->PDOStatement->bindValue($param, $val);
  1268. }
  1269. if (!$result) {
  1270. $param = array_shift($val);
  1271. throw new BindParamException(
  1272. "Error occurred when binding parameters '{$param}'",
  1273. $this->config,
  1274. $this->getLastsql(),
  1275. $bind
  1276. );
  1277. }
  1278. }
  1279. }
  1280. /**
  1281. * 获得数据集数组
  1282. * @access protected
  1283. * @param bool $pdo 是否返回PDOStatement
  1284. * @param bool $procedure 是否存储过程
  1285. * @return array
  1286. */
  1287. protected function getResult($pdo = false, $procedure = false)
  1288. {
  1289. if ($pdo) {
  1290. // 返回PDOStatement对象处理
  1291. return $this->PDOStatement;
  1292. }
  1293. if ($procedure) {
  1294. // 存储过程返回结果
  1295. return $this->procedure();
  1296. }
  1297. $result = $this->PDOStatement->fetchAll($this->fetchType);
  1298. $this->numRows = count($result);
  1299. return $result;
  1300. }
  1301. /**
  1302. * 获得存储过程数据集
  1303. * @access protected
  1304. * @return array
  1305. */
  1306. protected function procedure()
  1307. {
  1308. $item = [];
  1309. do {
  1310. $result = $this->getResult();
  1311. if ($result) {
  1312. $item[] = $result;
  1313. }
  1314. } while ($this->PDOStatement->nextRowset());
  1315. $this->numRows = count($item);
  1316. return $item;
  1317. }
  1318. /**
  1319. * 执行数据库事务
  1320. * @access public
  1321. * @param callable $callback 数据操作方法回调
  1322. * @return mixed
  1323. * @throws PDOException
  1324. * @throws \Exception
  1325. * @throws \Throwable
  1326. */
  1327. public function transaction($callback)
  1328. {
  1329. $this->startTrans();
  1330. try {
  1331. $result = null;
  1332. if (is_callable($callback)) {
  1333. $result = call_user_func_array($callback, [$this]);
  1334. }
  1335. $this->commit();
  1336. return $result;
  1337. } catch (\Exception $e) {
  1338. $this->rollback();
  1339. throw $e;
  1340. } catch (\Throwable $e) {
  1341. $this->rollback();
  1342. throw $e;
  1343. }
  1344. }
  1345. /**
  1346. * 启动事务
  1347. * @access public
  1348. * @return void
  1349. * @throws \PDOException
  1350. * @throws \Exception
  1351. */
  1352. public function startTrans()
  1353. {
  1354. $this->initConnect(true);
  1355. if (!$this->linkID) {
  1356. return false;
  1357. }
  1358. ++$this->transTimes;
  1359. try {
  1360. if (1 == $this->transTimes) {
  1361. $this->linkID->beginTransaction();
  1362. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  1363. $this->linkID->exec(
  1364. $this->parseSavepoint('trans' . $this->transTimes)
  1365. );
  1366. }
  1367. } catch (\PDOException $e) {
  1368. if ($this->isBreak($e)) {
  1369. return $this->close()->startTrans();
  1370. }
  1371. throw $e;
  1372. } catch (\Exception $e) {
  1373. if ($this->isBreak($e)) {
  1374. return $this->close()->startTrans();
  1375. }
  1376. throw $e;
  1377. }
  1378. }
  1379. /**
  1380. * 用于非自动提交状态下面的查询提交
  1381. * @access public
  1382. * @return void
  1383. * @throws PDOException
  1384. */
  1385. public function commit()
  1386. {
  1387. $this->initConnect(true);
  1388. if (1 == $this->transTimes) {
  1389. $this->linkID->commit();
  1390. }
  1391. --$this->transTimes;
  1392. }
  1393. /**
  1394. * 事务回滚
  1395. * @access public
  1396. * @return void
  1397. * @throws PDOException
  1398. */
  1399. public function rollback()
  1400. {
  1401. $this->initConnect(true);
  1402. if (1 == $this->transTimes) {
  1403. $this->linkID->rollBack();
  1404. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  1405. $this->linkID->exec(
  1406. $this->parseSavepointRollBack('trans' . $this->transTimes)
  1407. );
  1408. }
  1409. $this->transTimes = max(0, $this->transTimes - 1);
  1410. }
  1411. /**
  1412. * 是否支持事务嵌套
  1413. * @return bool
  1414. */
  1415. protected function supportSavepoint()
  1416. {
  1417. return false;
  1418. }
  1419. /**
  1420. * 生成定义保存点的SQL
  1421. * @access protected
  1422. * @param $name
  1423. * @return string
  1424. */
  1425. protected function parseSavepoint($name)
  1426. {
  1427. return 'SAVEPOINT ' . $name;
  1428. }
  1429. /**
  1430. * 生成回滚到保存点的SQL
  1431. * @access protected
  1432. * @param $name
  1433. * @return string
  1434. */
  1435. protected function parseSavepointRollBack($name)
  1436. {
  1437. return 'ROLLBACK TO SAVEPOINT ' . $name;
  1438. }
  1439. /**
  1440. * 批处理执行SQL语句
  1441. * 批处理的指令都认为是execute操作
  1442. * @access public
  1443. * @param array $sqlArray SQL批处理指令
  1444. * @param array $bind 参数绑定
  1445. * @return boolean
  1446. */
  1447. public function batchQuery($sqlArray = [], $bind = [])
  1448. {
  1449. if (!is_array($sqlArray)) {
  1450. return false;
  1451. }
  1452. // 自动启动事务支持
  1453. $this->startTrans();
  1454. try {
  1455. foreach ($sqlArray as $sql) {
  1456. $this->execute($sql, $bind);
  1457. }
  1458. // 提交事务
  1459. $this->commit();
  1460. } catch (\Exception $e) {
  1461. $this->rollback();
  1462. throw $e;
  1463. }
  1464. return true;
  1465. }
  1466. /**
  1467. * 获得查询次数
  1468. * @access public
  1469. * @param boolean $execute 是否包含所有查询
  1470. * @return integer
  1471. */
  1472. public function getQueryTimes($execute = false)
  1473. {
  1474. return $execute ? Db::$queryTimes + Db::$executeTimes : Db::$queryTimes;
  1475. }
  1476. /**
  1477. * 获得执行次数
  1478. * @access public
  1479. * @return integer
  1480. */
  1481. public function getExecuteTimes()
  1482. {
  1483. return Db::$executeTimes;
  1484. }
  1485. /**
  1486. * 关闭数据库(或者重新连接)
  1487. * @access public
  1488. * @return $this
  1489. */
  1490. public function close()
  1491. {
  1492. $this->linkID = null;
  1493. $this->linkWrite = null;
  1494. $this->linkRead = null;
  1495. $this->links = [];
  1496. return $this;
  1497. }
  1498. /**
  1499. * 是否断线
  1500. * @access protected
  1501. * @param \PDOException|\Exception $e 异常对象
  1502. * @return bool
  1503. */
  1504. protected function isBreak($e)
  1505. {
  1506. if (!$this->config['break_reconnect']) {
  1507. return false;
  1508. }
  1509. $info = [
  1510. 'server has gone away',
  1511. 'no connection to the server',
  1512. 'Lost connection',
  1513. 'is dead or not enabled',
  1514. 'Error while sending',
  1515. 'decryption failed or bad record mac',
  1516. 'server closed the connection unexpectedly',
  1517. 'SSL connection has been closed unexpectedly',
  1518. 'Error writing data to the connection',
  1519. 'Resource deadlock avoided',
  1520. ];
  1521. $error = $e->getMessage();
  1522. foreach ($info as $msg) {
  1523. if (false !== stripos($error, $msg)) {
  1524. return true;
  1525. }
  1526. }
  1527. return false;
  1528. }
  1529. /**
  1530. * 获取最近一次查询的sql语句
  1531. * @access public
  1532. * @return string
  1533. */
  1534. public function getLastSql()
  1535. {
  1536. return $this->getRealSql($this->queryStr, $this->bind);
  1537. }
  1538. /**
  1539. * 获取最近插入的ID
  1540. * @access public
  1541. * @param string $sequence 自增序列名
  1542. * @return string
  1543. */
  1544. public function getLastInsID($sequence = null)
  1545. {
  1546. return $this->linkID->lastInsertId($sequence);
  1547. }
  1548. /**
  1549. * 获取返回或者影响的记录数
  1550. * @access public
  1551. * @return integer
  1552. */
  1553. public function getNumRows()
  1554. {
  1555. return $this->numRows;
  1556. }
  1557. /**
  1558. * 获取最近的错误信息
  1559. * @access public
  1560. * @return string
  1561. */
  1562. public function getError()
  1563. {
  1564. if ($this->PDOStatement) {
  1565. $error = $this->PDOStatement->errorInfo();
  1566. $error = $error[1] . ':' . $error[2];
  1567. } else {
  1568. $error = '';
  1569. }
  1570. if ('' != $this->queryStr) {
  1571. $error .= "\n [ SQL语句 ] : " . $this->getLastsql();
  1572. }
  1573. return $error;
  1574. }
  1575. /**
  1576. * 数据库调试 记录当前SQL及分析性能
  1577. * @access protected
  1578. * @param boolean $start 调试开始标记 true 开始 false 结束
  1579. * @param string $sql 执行的SQL语句 留空自动获取
  1580. * @return void
  1581. */
  1582. protected function debug($start, $sql = '')
  1583. {
  1584. if (!empty($this->config['debug'])) {
  1585. // 开启数据库调试模式
  1586. $debug = Container::get('debug');
  1587. if ($start) {
  1588. $debug->remark('queryStartTime', 'time');
  1589. } else {
  1590. // 记录操作结束时间
  1591. $debug->remark('queryEndTime', 'time');
  1592. $runtime = $debug->getRangeTime('queryStartTime', 'queryEndTime');
  1593. $sql = $sql ?: $this->getLastsql();
  1594. $result = [];
  1595. // SQL性能分析
  1596. if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
  1597. $result = $this->getExplain($sql);
  1598. }
  1599. // SQL监听
  1600. $this->triggerSql($sql, $runtime, $result);
  1601. }
  1602. }
  1603. }
  1604. /**
  1605. * 监听SQL执行
  1606. * @access public
  1607. * @param callable $callback 回调方法
  1608. * @return void
  1609. */
  1610. public function listen($callback)
  1611. {
  1612. self::$event[] = $callback;
  1613. }
  1614. /**
  1615. * 触发SQL事件
  1616. * @access protected
  1617. * @param string $sql SQL语句
  1618. * @param float $runtime SQL运行时间
  1619. * @param mixed $explain SQL分析
  1620. * @return bool
  1621. */
  1622. protected function triggerSql($sql, $runtime, $explain = [])
  1623. {
  1624. if (!empty(self::$event)) {
  1625. foreach (self::$event as $callback) {
  1626. if (is_callable($callback)) {
  1627. call_user_func_array($callback, [$sql, $runtime, $explain]);
  1628. }
  1629. }
  1630. } else {
  1631. // 未注册监听则记录到日志中
  1632. $this->log('[ SQL ] ' . $sql . ' [ RunTime:' . $runtime . 's ]');
  1633. if (!empty($explain)) {
  1634. $this->log('[ EXPLAIN : ' . var_export($explain, true) . ' ]');
  1635. }
  1636. }
  1637. }
  1638. public function log($log, $type = 'sql')
  1639. {
  1640. $this->config['debug'] && Container::get('log')->record($log, $type);
  1641. }
  1642. /**
  1643. * 初始化数据库连接
  1644. * @access protected
  1645. * @param boolean $master 是否主服务器
  1646. * @return void
  1647. */
  1648. protected function initConnect($master = true)
  1649. {
  1650. if (!empty($this->config['deploy'])) {
  1651. // 采用分布式数据库
  1652. if ($master || $this->transTimes) {
  1653. if (!$this->linkWrite) {
  1654. $this->linkWrite = $this->multiConnect(true);
  1655. }
  1656. $this->linkID = $this->linkWrite;
  1657. } else {
  1658. if (!$this->linkRead) {
  1659. $this->linkRead = $this->multiConnect(false);
  1660. }
  1661. $this->linkID = $this->linkRead;
  1662. }
  1663. } elseif (!$this->linkID) {
  1664. // 默认单数据库
  1665. $this->linkID = $this->connect();
  1666. }
  1667. }
  1668. /**
  1669. * 连接分布式服务器
  1670. * @access protected
  1671. * @param boolean $master 主服务器
  1672. * @return PDO
  1673. */
  1674. protected function multiConnect($master = false)
  1675. {
  1676. $_config = [];
  1677. // 分布式数据库配置解析
  1678. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1679. $_config[$name] = explode(',', $this->config[$name]);
  1680. }
  1681. // 主服务器序号
  1682. $m = floor(mt_rand(0, $this->config['master_num'] - 1));
  1683. if ($this->config['rw_separate']) {
  1684. // 主从式采用读写分离
  1685. if ($master) // 主服务器写入
  1686. {
  1687. $r = $m;
  1688. } elseif (is_numeric($this->config['slave_no'])) {
  1689. // 指定服务器读
  1690. $r = $this->config['slave_no'];
  1691. } else {
  1692. // 读操作连接从服务器 每次随机连接的数据库
  1693. $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1));
  1694. }
  1695. } else {
  1696. // 读写操作不区分服务器 每次随机连接的数据库
  1697. $r = floor(mt_rand(0, count($_config['hostname']) - 1));
  1698. }
  1699. $dbMaster = false;
  1700. if ($m != $r) {
  1701. $dbMaster = [];
  1702. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1703. $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0];
  1704. }
  1705. }
  1706. $dbConfig = [];
  1707. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1708. $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0];
  1709. }
  1710. return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster);
  1711. }
  1712. /**
  1713. * 析构方法
  1714. * @access public
  1715. */
  1716. public function __destruct()
  1717. {
  1718. // 释放查询
  1719. $this->free();
  1720. // 关闭连接
  1721. $this->close();
  1722. }
  1723. /**
  1724. * 缓存数据
  1725. * @access protected
  1726. * @param string $key 缓存标识
  1727. * @param mixed $data 缓存数据
  1728. * @param array $config 缓存参数
  1729. */
  1730. protected function cacheData($key, $data, $config = [])
  1731. {
  1732. $cache = Container::get('cache');
  1733. if (isset($config['tag'])) {
  1734. $cache->tag($config['tag'])->set($key, $data, $config['expire']);
  1735. } else {
  1736. $cache->set($key, $data, $config['expire']);
  1737. }
  1738. }
  1739. /**
  1740. * 生成缓存标识
  1741. * @access protected
  1742. * @param mixed $value 缓存数据
  1743. * @param array $options 缓存参数
  1744. * @param array $bind 绑定参数
  1745. * @return string
  1746. */
  1747. protected function getCacheKey($value, $options, $bind = [])
  1748. {
  1749. if (is_scalar($value)) {
  1750. $data = $value;
  1751. } elseif (is_array($value) && isset($value[1], $value[2]) && in_array($value[1], ['=', 'eq'])) {
  1752. $data = $value[2];
  1753. }
  1754. if (isset($data)) {
  1755. return 'think:' . (is_array($options['table']) ? key($options['table']) : $options['table']) . '|' . $data;
  1756. } else {
  1757. try {
  1758. return md5(serialize($options) . serialize($bind));
  1759. } catch (\Exception $e) {
  1760. return;
  1761. }
  1762. }
  1763. }
  1764. /**
  1765. * 数据库连接参数解析
  1766. * @access private
  1767. * @param mixed $config
  1768. * @return array
  1769. */
  1770. private static function parseConfig($config)
  1771. {
  1772. if (empty($config)) {
  1773. $config = Container::get('config')->pull('database');
  1774. } elseif (is_string($config) && false === strpos($config, '/')) {
  1775. // 支持读取配置参数
  1776. $config = Container::get('config')->get('database.' . $config);
  1777. }
  1778. if (is_string($config)) {
  1779. return self::parseDsnConfig($config);
  1780. } else {
  1781. return $config;
  1782. }
  1783. }
  1784. /**
  1785. * DSN解析
  1786. * 格式: mysql://username:passwd@localhost:3306/DbName?param1=val1&param2=val2#utf8
  1787. * @access private
  1788. * @param string $dsnStr
  1789. * @return array
  1790. */
  1791. private static function parseDsnConfig($dsnStr)
  1792. {
  1793. $info = parse_url($dsnStr);
  1794. if (!$info) {
  1795. return [];
  1796. }
  1797. $dsn = [
  1798. 'type' => $info['scheme'],
  1799. 'username' => isset($info['user']) ? $info['user'] : '',
  1800. 'password' => isset($info['pass']) ? $info['pass'] : '',
  1801. 'hostname' => isset($info['host']) ? $info['host'] : '',
  1802. 'hostport' => isset($info['port']) ? $info['port'] : '',
  1803. 'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
  1804. 'charset' => isset($info['fragment']) ? $info['fragment'] : 'utf8',
  1805. ];
  1806. if (isset($info['query'])) {
  1807. parse_str($info['query'], $dsn['params']);
  1808. } else {
  1809. $dsn['params'] = [];
  1810. }
  1811. return $dsn;
  1812. }
  1813. }