Connection.php 59 KB

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