Connection.php 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155
  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. $config['dsn'] = "dm:host=".$config['hostname'].";dbname=".$config['database'];
  458. }
  459. if ($config['debug']) {
  460. $startTime = microtime(true);
  461. }
  462. $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
  463. if ($config['debug']) {
  464. // 记录数据库连接信息
  465. $this->log('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']);
  466. }
  467. return $this->links[$linkNum];
  468. } catch (\PDOException $e) {
  469. if ($autoConnection) {
  470. $this->log($e->getMessage(), 'error');
  471. return $this->connect($autoConnection, $linkNum);
  472. } else {
  473. throw $e;
  474. }
  475. }
  476. }
  477. /**
  478. * 释放查询结果
  479. * @access public
  480. */
  481. public function free()
  482. {
  483. $this->PDOStatement = null;
  484. }
  485. /**
  486. * 获取PDO对象
  487. * @access public
  488. * @return \PDO|false
  489. */
  490. public function getPdo()
  491. {
  492. if (!$this->linkID) {
  493. return false;
  494. }
  495. return $this->linkID;
  496. }
  497. /**
  498. * 执行查询 使用生成器返回数据
  499. * @access public
  500. * @param string $sql sql指令
  501. * @param array $bind 参数绑定
  502. * @param bool $master 是否在主服务器读操作
  503. * @param Model $model 模型对象实例
  504. * @param array $condition 查询条件
  505. * @param mixed $relation 关联查询
  506. * @return \Generator
  507. */
  508. public function getCursor($sql, $bind = [], $master = false, $model = null, $condition = null, $relation = null)
  509. {
  510. $this->initConnect($master);
  511. // 记录SQL语句
  512. $this->queryStr = $sql;
  513. $this->bind = $bind;
  514. Db::$queryTimes++;
  515. // 调试开始
  516. $this->debug(true);
  517. // 预处理
  518. $this->PDOStatement = $this->linkID->prepare($sql);
  519. // 是否为存储过程调用
  520. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  521. // 参数绑定
  522. if ($procedure) {
  523. $this->bindParam($bind);
  524. } else {
  525. $this->bindValue($bind);
  526. }
  527. // 执行查询
  528. $this->PDOStatement->execute();
  529. // 调试结束
  530. $this->debug(false, '', $master);
  531. // 返回结果集
  532. while ($result = $this->PDOStatement->fetch($this->fetchType)) {
  533. if ($model) {
  534. $instance = $model->newInstance($result, $condition);
  535. if ($relation) {
  536. $instance->relationQuery($relation);
  537. }
  538. yield $instance;
  539. } else {
  540. yield $result;
  541. }
  542. }
  543. }
  544. /**
  545. * 执行查询 返回数据集
  546. * @access public
  547. * @param string $sql sql指令
  548. * @param array $bind 参数绑定
  549. * @param bool $master 是否在主服务器读操作
  550. * @param bool $pdo 是否返回PDO对象
  551. * @return array
  552. * @throws BindParamException
  553. * @throws \PDOException
  554. * @throws \Exception
  555. * @throws \Throwable
  556. */
  557. public function query($sql, $bind = [], $master = false, $pdo = false)
  558. {
  559. $this->initConnect($master);
  560. if (!$this->linkID) {
  561. return false;
  562. }
  563. // 记录SQL语句
  564. $this->queryStr = $sql;
  565. $this->bind = $bind;
  566. Db::$queryTimes++;
  567. try {
  568. // 调试开始
  569. $this->debug(true);
  570. // 预处理
  571. $this->PDOStatement = $this->linkID->prepare($sql);
  572. // 是否为存储过程调用
  573. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  574. // 参数绑定
  575. if ($procedure) {
  576. $this->bindParam($bind);
  577. } else {
  578. $this->bindValue($bind);
  579. }
  580. // 执行查询
  581. $this->PDOStatement->execute();
  582. // 调试结束
  583. $this->debug(false, '', $master);
  584. // 返回结果集
  585. return $this->getResult($pdo, $procedure);
  586. } catch (\PDOException $e) {
  587. if ($this->isBreak($e)) {
  588. return $this->close()->query($sql, $bind, $master, $pdo);
  589. }
  590. throw new PDOException($e, $this->config, $this->getLastsql());
  591. } catch (\Throwable $e) {
  592. if ($this->isBreak($e)) {
  593. return $this->close()->query($sql, $bind, $master, $pdo);
  594. }
  595. throw $e;
  596. } catch (\Exception $e) {
  597. if ($this->isBreak($e)) {
  598. return $this->close()->query($sql, $bind, $master, $pdo);
  599. }
  600. throw $e;
  601. }
  602. }
  603. /**
  604. * 执行语句
  605. * @access public
  606. * @param string $sql sql指令
  607. * @param array $bind 参数绑定
  608. * @param Query $query 查询对象
  609. * @return int
  610. * @throws BindParamException
  611. * @throws \PDOException
  612. * @throws \Exception
  613. * @throws \Throwable
  614. */
  615. public function execute($sql, $bind = [], Query $query = null)
  616. {
  617. $this->initConnect(true);
  618. if (!$this->linkID) {
  619. return false;
  620. }
  621. // 记录SQL语句
  622. $this->queryStr = $sql;
  623. $this->bind = $bind;
  624. Db::$executeTimes++;
  625. try {
  626. // 调试开始
  627. $this->debug(true);
  628. // 预处理
  629. $this->PDOStatement = $this->linkID->prepare($sql);
  630. // 是否为存储过程调用
  631. $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
  632. // 参数绑定
  633. if ($procedure) {
  634. $this->bindParam($bind);
  635. } else {
  636. $this->bindValue($bind);
  637. }
  638. // 执行语句
  639. $this->PDOStatement->execute();
  640. // 调试结束
  641. $this->debug(false, '', true);
  642. if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) {
  643. $query->readMaster();
  644. }
  645. $this->numRows = $this->PDOStatement->rowCount();
  646. return $this->numRows;
  647. } catch (\PDOException $e) {
  648. if ($this->isBreak($e)) {
  649. return $this->close()->execute($sql, $bind, $query);
  650. }
  651. throw new PDOException($e, $this->config, $this->getLastsql());
  652. } catch (\Throwable $e) {
  653. if ($this->isBreak($e)) {
  654. return $this->close()->execute($sql, $bind, $query);
  655. }
  656. throw $e;
  657. } catch (\Exception $e) {
  658. if ($this->isBreak($e)) {
  659. return $this->close()->execute($sql, $bind, $query);
  660. }
  661. throw $e;
  662. }
  663. }
  664. /**
  665. * 查找单条记录
  666. * @access public
  667. * @param Query $query 查询对象
  668. * @return array|null|\PDOStatement|string
  669. * @throws DbException
  670. * @throws ModelNotFoundException
  671. * @throws DataNotFoundException
  672. */
  673. public function find(Query $query)
  674. {
  675. // 分析查询表达式
  676. $options = $query->getOptions();
  677. $pk = $query->getPk($options);
  678. $data = $options['data'];
  679. $query->setOption('limit', 1);
  680. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  681. // 判断查询缓存
  682. $cache = $options['cache'];
  683. if (is_string($cache['key'])) {
  684. $key = $cache['key'];
  685. } else {
  686. $key = $this->getCacheKey($query, $data);
  687. }
  688. $result = Container::get('cache')->get($key);
  689. if (false !== $result) {
  690. return $result;
  691. }
  692. }
  693. if (is_string($pk) && !is_array($data)) {
  694. if (isset($key) && strpos($key, '|')) {
  695. list($a, $val) = explode('|', $key);
  696. $item[$pk] = $val;
  697. } else {
  698. $item[$pk] = $data;
  699. }
  700. $data = $item;
  701. }
  702. $query->setOption('data', $data);
  703. // 生成查询SQL
  704. $sql = $this->builder->select($query);
  705. $query->removeOption('limit');
  706. $bind = $query->getBind();
  707. if (!empty($options['fetch_sql'])) {
  708. // 获取实际执行的SQL语句
  709. return $this->getRealSql($sql, $bind);
  710. }
  711. // 事件回调
  712. $result = $query->trigger('before_find');
  713. if (!$result) {
  714. // 执行查询
  715. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  716. if ($resultSet instanceof \PDOStatement) {
  717. // 返回PDOStatement对象
  718. return $resultSet;
  719. }
  720. $result = isset($resultSet[0]) ? $resultSet[0] : null;
  721. }
  722. if (isset($cache) && $result) {
  723. // 缓存数据
  724. $this->cacheData($key, $result, $cache);
  725. }
  726. return $result;
  727. }
  728. /**
  729. * 使用游标查询记录
  730. * @access public
  731. * @param Query $query 查询对象
  732. * @return \Generator
  733. */
  734. public function cursor(Query $query)
  735. {
  736. // 分析查询表达式
  737. $options = $query->getOptions();
  738. // 生成查询SQL
  739. $sql = $this->builder->select($query);
  740. $bind = $query->getBind();
  741. $condition = isset($options['where']['AND']) ? $options['where']['AND'] : null;
  742. $relation = isset($options['relaltion']) ? $options['relation'] : null;
  743. // 执行查询操作
  744. return $this->getCursor($sql, $bind, $options['master'], $query->getModel(), $condition, $relation);
  745. }
  746. /**
  747. * 查找记录
  748. * @access public
  749. * @param Query $query 查询对象
  750. * @return array|\PDOStatement|string
  751. * @throws DbException
  752. * @throws ModelNotFoundException
  753. * @throws DataNotFoundException
  754. */
  755. public function select(Query $query)
  756. {
  757. // 分析查询表达式
  758. $options = $query->getOptions();
  759. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  760. $resultSet = $this->getCacheData($query, $options['cache'], null, $key);
  761. if (false !== $resultSet) {
  762. return $resultSet;
  763. }
  764. }
  765. // 生成查询SQL
  766. $sql = $this->builder->select($query);
  767. $query->removeOption('limit');
  768. $bind = $query->getBind();
  769. if (!empty($options['fetch_sql'])) {
  770. // 获取实际执行的SQL语句
  771. return $this->getRealSql($sql, $bind);
  772. }
  773. $resultSet = $query->trigger('before_select');
  774. if (!$resultSet) {
  775. // 执行查询操作
  776. $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']);
  777. if ($resultSet instanceof \PDOStatement) {
  778. // 返回PDOStatement对象
  779. return $resultSet;
  780. }
  781. }
  782. if (!empty($options['cache']) && false !== $resultSet) {
  783. // 缓存数据集
  784. $this->cacheData($key, $resultSet, $options['cache']);
  785. }
  786. return $resultSet;
  787. }
  788. /**
  789. * 插入记录
  790. * @access public
  791. * @param Query $query 查询对象
  792. * @param boolean $replace 是否replace
  793. * @param boolean $getLastInsID 返回自增主键
  794. * @param string $sequence 自增序列名
  795. * @return integer|string
  796. */
  797. public function insert(Query $query, $replace = false, $getLastInsID = false, $sequence = null)
  798. {
  799. // 分析查询表达式
  800. $options = $query->getOptions();
  801. // 生成SQL语句
  802. $sql = $this->builder->insert($query, $replace);
  803. $bind = $query->getBind();
  804. if (!empty($options['fetch_sql'])) {
  805. // 获取实际执行的SQL语句
  806. return $this->getRealSql($sql, $bind);
  807. }
  808. // 执行操作
  809. $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query);
  810. if ($result) {
  811. $sequence = $sequence ?: (isset($options['sequence']) ? $options['sequence'] : null);
  812. $lastInsId = $this->getLastInsID($sequence);
  813. $data = $options['data'];
  814. if ($lastInsId) {
  815. $pk = $query->getPk($options);
  816. if (is_string($pk)) {
  817. $data[$pk] = $lastInsId;
  818. }
  819. }
  820. $query->setOption('data', $data);
  821. $query->trigger('after_insert');
  822. if ($getLastInsID) {
  823. return $lastInsId;
  824. }
  825. }
  826. return $result;
  827. }
  828. /**
  829. * 批量插入记录
  830. * @access public
  831. * @param Query $query 查询对象
  832. * @param mixed $dataSet 数据集
  833. * @param bool $replace 是否replace
  834. * @param integer $limit 每次写入数据限制
  835. * @return integer|string
  836. * @throws \Exception
  837. * @throws \Throwable
  838. */
  839. public function insertAll(Query $query, $dataSet = [], $replace = false, $limit = null)
  840. {
  841. if (!is_array(reset($dataSet))) {
  842. return false;
  843. }
  844. $options = $query->getOptions();
  845. if ($limit) {
  846. // 分批写入 自动启动事务支持
  847. $this->startTrans();
  848. try {
  849. $array = array_chunk($dataSet, $limit, true);
  850. $count = 0;
  851. foreach ($array as $item) {
  852. $sql = $this->builder->insertAll($query, $item, $replace);
  853. $bind = $query->getBind();
  854. if (!empty($options['fetch_sql'])) {
  855. $fetchSql[] = $this->getRealSql($sql, $bind);
  856. } else {
  857. $count += $this->execute($sql, $bind, $query);
  858. }
  859. }
  860. // 提交事务
  861. $this->commit();
  862. } catch (\Exception $e) {
  863. $this->rollback();
  864. throw $e;
  865. } catch (\Throwable $e) {
  866. $this->rollback();
  867. throw $e;
  868. }
  869. return isset($fetchSql) ? implode(';', $fetchSql) : $count;
  870. }
  871. $sql = $this->builder->insertAll($query, $dataSet, $replace);
  872. $bind = $query->getBind();
  873. if (!empty($options['fetch_sql'])) {
  874. return $this->getRealSql($sql, $bind);
  875. }
  876. return $this->execute($sql, $bind, $query);
  877. }
  878. /**
  879. * 通过Select方式插入记录
  880. * @access public
  881. * @param Query $query 查询对象
  882. * @param string $fields 要插入的数据表字段名
  883. * @param string $table 要插入的数据表名
  884. * @return integer|string
  885. * @throws PDOException
  886. */
  887. public function selectInsert(Query $query, $fields, $table)
  888. {
  889. // 分析查询表达式
  890. $options = $query->getOptions();
  891. $table = $this->parseSqlTable($table);
  892. $sql = $this->builder->selectInsert($query, $fields, $table);
  893. $bind = $query->getBind();
  894. if (!empty($options['fetch_sql'])) {
  895. return $this->getRealSql($sql, $bind);
  896. }
  897. return $this->execute($sql, $bind, $query);
  898. }
  899. /**
  900. * 更新记录
  901. * @access public
  902. * @param Query $query 查询对象
  903. * @return integer|string
  904. * @throws Exception
  905. * @throws PDOException
  906. */
  907. public function update(Query $query)
  908. {
  909. $options = $query->getOptions();
  910. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  911. $key = $options['cache']['key'];
  912. }
  913. $pk = $query->getPk($options);
  914. $data = $options['data'];
  915. if (empty($options['where'])) {
  916. // 如果存在主键数据 则自动作为更新条件
  917. if (is_string($pk) && isset($data[$pk])) {
  918. $where[$pk] = [$pk, '=', $data[$pk]];
  919. if (!isset($key)) {
  920. $key = $this->getCacheKey($query, $data[$pk]);
  921. }
  922. unset($data[$pk]);
  923. } elseif (is_array($pk)) {
  924. // 增加复合主键支持
  925. foreach ($pk as $field) {
  926. if (isset($data[$field])) {
  927. $where[$field] = [$field, '=', $data[$field]];
  928. } else {
  929. // 如果缺少复合主键数据则不执行
  930. throw new Exception('miss complex primary data');
  931. }
  932. unset($data[$field]);
  933. }
  934. }
  935. if (!isset($where)) {
  936. // 如果没有任何更新条件则不执行
  937. throw new Exception('miss update condition');
  938. } else {
  939. $options['where']['AND'] = $where;
  940. $query->setOption('where', ['AND' => $where]);
  941. }
  942. } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'])) {
  943. foreach ($options['where']['AND'] as $val) {
  944. if (is_array($val) && $val[0] == $pk) {
  945. $key = $this->getCacheKey($query, $val);
  946. }
  947. }
  948. }
  949. // 更新数据
  950. $query->setOption('data', $data);
  951. // 生成UPDATE SQL语句
  952. $sql = $this->builder->update($query);
  953. $bind = $query->getBind();
  954. if (!empty($options['fetch_sql'])) {
  955. // 获取实际执行的SQL语句
  956. return $this->getRealSql($sql, $bind);
  957. }
  958. // 检测缓存
  959. $cache = Container::get('cache');
  960. if (isset($key) && $cache->get($key)) {
  961. // 删除缓存
  962. $cache->rm($key);
  963. } elseif (!empty($options['cache']['tag'])) {
  964. $cache->clear($options['cache']['tag']);
  965. }
  966. // 执行操作
  967. $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query);
  968. if ($result) {
  969. if (is_string($pk) && isset($where[$pk])) {
  970. $data[$pk] = $where[$pk];
  971. } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
  972. list($a, $val) = explode('|', $key);
  973. $data[$pk] = $val;
  974. }
  975. $query->setOption('data', $data);
  976. $query->trigger('after_update');
  977. }
  978. return $result;
  979. }
  980. /**
  981. * 删除记录
  982. * @access public
  983. * @param Query $query 查询对象
  984. * @return int
  985. * @throws Exception
  986. * @throws PDOException
  987. */
  988. public function delete(Query $query)
  989. {
  990. // 分析查询表达式
  991. $options = $query->getOptions();
  992. $pk = $query->getPk($options);
  993. $data = $options['data'];
  994. if (isset($options['cache']) && is_string($options['cache']['key'])) {
  995. $key = $options['cache']['key'];
  996. } elseif (!is_null($data) && true !== $data && !is_array($data)) {
  997. $key = $this->getCacheKey($query, $data);
  998. } elseif (is_string($pk) && isset($options['where']['AND'])) {
  999. foreach ($options['where']['AND'] as $val) {
  1000. if (is_array($val) && $val[0] == $pk) {
  1001. $key = $this->getCacheKey($query, $val);
  1002. }
  1003. }
  1004. }
  1005. if (true !== $data && empty($options['where'])) {
  1006. // 如果条件为空 不进行删除操作 除非设置 1=1
  1007. throw new Exception('delete without condition');
  1008. }
  1009. // 生成删除SQL语句
  1010. $sql = $this->builder->delete($query);
  1011. $bind = $query->getBind();
  1012. if (!empty($options['fetch_sql'])) {
  1013. // 获取实际执行的SQL语句
  1014. return $this->getRealSql($sql, $bind);
  1015. }
  1016. // 检测缓存
  1017. $cache = Container::get('cache');
  1018. if (isset($key) && $cache->get($key)) {
  1019. // 删除缓存
  1020. $cache->rm($key);
  1021. } elseif (!empty($options['cache']['tag'])) {
  1022. $cache->clear($options['cache']['tag']);
  1023. }
  1024. // 执行操作
  1025. $result = $this->execute($sql, $bind, $query);
  1026. if ($result) {
  1027. if (!is_array($data) && is_string($pk) && isset($key) && strpos($key, '|')) {
  1028. list($a, $val) = explode('|', $key);
  1029. $item[$pk] = $val;
  1030. $data = $item;
  1031. }
  1032. $options['data'] = $data;
  1033. $query->trigger('after_delete');
  1034. }
  1035. return $result;
  1036. }
  1037. /**
  1038. * 得到某个字段的值
  1039. * @access public
  1040. * @param Query $query 查询对象
  1041. * @param string $field 字段名
  1042. * @param mixed $default 默认值
  1043. * @param bool $one 是否返回一个值
  1044. * @return mixed
  1045. */
  1046. public function value(Query $query, $field, $default = null, $one = true)
  1047. {
  1048. $options = $query->getOptions();
  1049. if (isset($options['field'])) {
  1050. $query->removeOption('field');
  1051. }
  1052. if (is_string($field)) {
  1053. $field = array_map('trim', explode(',', $field));
  1054. }
  1055. $query->setOption('field', $field);
  1056. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  1057. $cache = $options['cache'];
  1058. $result = $this->getCacheData($query, $cache, null, $key);
  1059. if (false !== $result) {
  1060. return $result;
  1061. }
  1062. }
  1063. if ($one) {
  1064. $query->setOption('limit', 1);
  1065. }
  1066. // 生成查询SQL
  1067. $sql = $this->builder->select($query);
  1068. if (isset($options['field'])) {
  1069. $query->setOption('field', $options['field']);
  1070. } else {
  1071. $query->removeOption('field');
  1072. }
  1073. $query->removeOption('limit');
  1074. $bind = $query->getBind();
  1075. if (!empty($options['fetch_sql'])) {
  1076. // 获取实际执行的SQL语句
  1077. return $this->getRealSql($sql, $bind);
  1078. }
  1079. // 执行查询操作
  1080. $pdo = $this->query($sql, $bind, $options['master'], true);
  1081. $result = $pdo->fetchColumn();
  1082. if (isset($cache) && false !== $result) {
  1083. // 缓存数据
  1084. $this->cacheData($key, $result, $cache);
  1085. }
  1086. return false !== $result ? $result : $default;
  1087. }
  1088. /**
  1089. * 得到某个字段的值
  1090. * @access public
  1091. * @param Query $query 查询对象
  1092. * @param string $aggregate 聚合方法
  1093. * @param mixed $field 字段名
  1094. * @return mixed
  1095. */
  1096. public function aggregate(Query $query, $aggregate, $field)
  1097. {
  1098. if (is_string($field) && 0 === stripos($field, 'DISTINCT ')) {
  1099. list($distinct, $field) = explode(' ', $field);
  1100. }
  1101. $field = $aggregate . '(' . (!empty($distinct) ? 'DISTINCT ' : '') . $this->builder->parseKey($query, $field, true) . ') AS tp_' . strtolower($aggregate);
  1102. return $this->value($query, $field, 0, false);
  1103. }
  1104. /**
  1105. * 得到某个列的数组
  1106. * @access public
  1107. * @param Query $query 查询对象
  1108. * @param string $field 字段名 多个字段用逗号分隔
  1109. * @param string $key 索引
  1110. * @return array
  1111. */
  1112. public function column(Query $query, $field, $key = '')
  1113. {
  1114. $options = $query->getOptions();
  1115. if (isset($options['field'])) {
  1116. $query->removeOption('field');
  1117. }
  1118. if (is_null($field)) {
  1119. $field = ['*'];
  1120. } elseif (is_string($field)) {
  1121. $field = array_map('trim', explode(',', $field));
  1122. }
  1123. if ($key && ['*'] != $field) {
  1124. array_unshift($field, $key);
  1125. $field = array_unique($field);
  1126. }
  1127. $query->setOption('field', $field);
  1128. if (empty($options['fetch_sql']) && !empty($options['cache'])) {
  1129. // 判断查询缓存
  1130. $cache = $options['cache'];
  1131. $result = $this->getCacheData($query, $cache, null, $guid);
  1132. if (false !== $result) {
  1133. return $result;
  1134. }
  1135. }
  1136. // 生成查询SQL
  1137. $sql = $this->builder->select($query);
  1138. // 还原field参数
  1139. if (isset($options['field'])) {
  1140. $query->setOption('field', $options['field']);
  1141. } else {
  1142. $query->removeOption('field');
  1143. }
  1144. $bind = $query->getBind();
  1145. if (!empty($options['fetch_sql'])) {
  1146. // 获取实际执行的SQL语句
  1147. return $this->getRealSql($sql, $bind);
  1148. }
  1149. // 执行查询操作
  1150. $pdo = $this->query($sql, $bind, $options['master'], true);
  1151. if (1 == $pdo->columnCount()) {
  1152. $result = $pdo->fetchAll(PDO::FETCH_COLUMN);
  1153. } else {
  1154. $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC);
  1155. if (['*'] == $field && $key) {
  1156. $result = array_column($resultSet, null, $key);
  1157. } elseif ($resultSet) {
  1158. $fields = array_keys($resultSet[0]);
  1159. $count = count($fields);
  1160. $key1 = array_shift($fields);
  1161. $key2 = $fields ? array_shift($fields) : '';
  1162. $key = $key ?: $key1;
  1163. if (strpos($key, '.')) {
  1164. list($alias, $key) = explode('.', $key);
  1165. }
  1166. if (2 == $count) {
  1167. $column = $key2;
  1168. } elseif (1 == $count) {
  1169. $column = $key1;
  1170. } else {
  1171. $column = null;
  1172. }
  1173. $result = array_column($resultSet, $column, $key);
  1174. } else {
  1175. $result = [];
  1176. }
  1177. }
  1178. if (isset($cache) && isset($guid)) {
  1179. // 缓存数据
  1180. $this->cacheData($guid, $result, $cache);
  1181. }
  1182. return $result;
  1183. }
  1184. /**
  1185. * 执行查询但只返回PDOStatement对象
  1186. * @access public
  1187. * @return \PDOStatement|string
  1188. */
  1189. public function pdo(Query $query)
  1190. {
  1191. // 分析查询表达式
  1192. $options = $query->getOptions();
  1193. // 生成查询SQL
  1194. $sql = $this->builder->select($query);
  1195. $bind = $query->getBind();
  1196. if (!empty($options['fetch_sql'])) {
  1197. // 获取实际执行的SQL语句
  1198. return $this->getRealSql($sql, $bind);
  1199. }
  1200. // 执行查询操作
  1201. return $this->query($sql, $bind, $options['master'], true);
  1202. }
  1203. /**
  1204. * 根据参数绑定组装最终的SQL语句 便于调试
  1205. * @access public
  1206. * @param string $sql 带参数绑定的sql语句
  1207. * @param array $bind 参数绑定列表
  1208. * @return string
  1209. */
  1210. public function getRealSql($sql, array $bind = [])
  1211. {
  1212. if (is_array($sql)) {
  1213. $sql = implode(';', $sql);
  1214. }
  1215. foreach ($bind as $key => $val) {
  1216. $value = is_array($val) ? $val[0] : $val;
  1217. $type = is_array($val) ? $val[1] : PDO::PARAM_STR;
  1218. if (self::PARAM_FLOAT == $type) {
  1219. $value = (float) $value;
  1220. } elseif (PDO::PARAM_STR == $type) {
  1221. $value = '\'' . addslashes($value) . '\'';
  1222. } elseif (PDO::PARAM_INT == $type && '' === $value) {
  1223. $value = 0;
  1224. }
  1225. // 判断占位符
  1226. $sql = is_numeric($key) ?
  1227. substr_replace($sql, $value, strpos($sql, '?'), 1) :
  1228. substr_replace($sql, $value, strpos($sql, ':' . $key), strlen(':' . $key));
  1229. }
  1230. return rtrim($sql);
  1231. }
  1232. /**
  1233. * 参数绑定
  1234. * 支持 ['name'=>'value','id'=>123] 对应命名占位符
  1235. * 或者 ['value',123] 对应问号占位符
  1236. * @access public
  1237. * @param array $bind 要绑定的参数列表
  1238. * @return void
  1239. * @throws BindParamException
  1240. */
  1241. protected function bindValue(array $bind = [])
  1242. {
  1243. foreach ($bind as $key => $val) {
  1244. // 占位符
  1245. $param = is_int($key) ? $key + 1 : ':' . $key;
  1246. if (is_array($val)) {
  1247. if (PDO::PARAM_INT == $val[1] && '' === $val[0]) {
  1248. $val[0] = 0;
  1249. } elseif (self::PARAM_FLOAT == $val[1]) {
  1250. $val[0] = (float) $val[0];
  1251. $val[1] = PDO::PARAM_STR;
  1252. }
  1253. $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]);
  1254. } else {
  1255. $result = $this->PDOStatement->bindValue($param, $val);
  1256. }
  1257. if (!$result) {
  1258. throw new BindParamException(
  1259. "Error occurred when binding parameters '{$param}'",
  1260. $this->config,
  1261. $this->getLastsql(),
  1262. $bind
  1263. );
  1264. }
  1265. }
  1266. }
  1267. /**
  1268. * 存储过程的输入输出参数绑定
  1269. * @access public
  1270. * @param array $bind 要绑定的参数列表
  1271. * @return void
  1272. * @throws BindParamException
  1273. */
  1274. protected function bindParam($bind)
  1275. {
  1276. foreach ($bind as $key => $val) {
  1277. $param = is_int($key) ? $key + 1 : ':' . $key;
  1278. if (is_array($val)) {
  1279. array_unshift($val, $param);
  1280. $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val);
  1281. } else {
  1282. $result = $this->PDOStatement->bindValue($param, $val);
  1283. }
  1284. if (!$result) {
  1285. $param = array_shift($val);
  1286. throw new BindParamException(
  1287. "Error occurred when binding parameters '{$param}'",
  1288. $this->config,
  1289. $this->getLastsql(),
  1290. $bind
  1291. );
  1292. }
  1293. }
  1294. }
  1295. /**
  1296. * 获得数据集数组
  1297. * @access protected
  1298. * @param bool $pdo 是否返回PDOStatement
  1299. * @param bool $procedure 是否存储过程
  1300. * @return array
  1301. */
  1302. protected function getResult($pdo = false, $procedure = false)
  1303. {
  1304. if ($pdo) {
  1305. // 返回PDOStatement对象处理
  1306. return $this->PDOStatement;
  1307. }
  1308. if ($procedure) {
  1309. // 存储过程返回结果
  1310. return $this->procedure();
  1311. }
  1312. $result = $this->PDOStatement->fetchAll($this->fetchType);
  1313. $this->numRows = count($result);
  1314. return $result;
  1315. }
  1316. /**
  1317. * 获得存储过程数据集
  1318. * @access protected
  1319. * @return array
  1320. */
  1321. protected function procedure()
  1322. {
  1323. $item = [];
  1324. do {
  1325. $result = $this->getResult();
  1326. if ($result) {
  1327. $item[] = $result;
  1328. }
  1329. } while ($this->PDOStatement->nextRowset());
  1330. $this->numRows = count($item);
  1331. return $item;
  1332. }
  1333. /**
  1334. * 执行数据库事务
  1335. * @access public
  1336. * @param callable $callback 数据操作方法回调
  1337. * @return mixed
  1338. * @throws PDOException
  1339. * @throws \Exception
  1340. * @throws \Throwable
  1341. */
  1342. public function transaction($callback)
  1343. {
  1344. $this->startTrans();
  1345. try {
  1346. $result = null;
  1347. if (is_callable($callback)) {
  1348. $result = call_user_func_array($callback, [$this]);
  1349. }
  1350. $this->commit();
  1351. return $result;
  1352. } catch (\Exception $e) {
  1353. $this->rollback();
  1354. throw $e;
  1355. } catch (\Throwable $e) {
  1356. $this->rollback();
  1357. throw $e;
  1358. }
  1359. }
  1360. /**
  1361. * 启动XA事务
  1362. * @access public
  1363. * @param string $xid XA事务id
  1364. * @return void
  1365. */
  1366. public function startTransXa($xid)
  1367. {}
  1368. /**
  1369. * 预编译XA事务
  1370. * @access public
  1371. * @param string $xid XA事务id
  1372. * @return void
  1373. */
  1374. public function prepareXa($xid)
  1375. {}
  1376. /**
  1377. * 提交XA事务
  1378. * @access public
  1379. * @param string $xid XA事务id
  1380. * @return void
  1381. */
  1382. public function commitXa($xid)
  1383. {}
  1384. /**
  1385. * 回滚XA事务
  1386. * @access public
  1387. * @param string $xid XA事务id
  1388. * @return void
  1389. */
  1390. public function rollbackXa($xid)
  1391. {}
  1392. /**
  1393. * 启动事务
  1394. * @access public
  1395. * @return void
  1396. * @throws \PDOException
  1397. * @throws \Exception
  1398. */
  1399. public function startTrans()
  1400. {
  1401. $this->initConnect(true);
  1402. if (!$this->linkID) {
  1403. return false;
  1404. }
  1405. ++$this->transTimes;
  1406. try {
  1407. if (1 == $this->transTimes) {
  1408. $this->linkID->beginTransaction();
  1409. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  1410. $this->linkID->exec(
  1411. $this->parseSavepoint('trans' . $this->transTimes)
  1412. );
  1413. }
  1414. } catch (\Exception $e) {
  1415. if ($this->isBreak($e)) {
  1416. --$this->transTimes;
  1417. return $this->close()->startTrans();
  1418. }
  1419. throw $e;
  1420. }
  1421. }
  1422. /**
  1423. * 用于非自动提交状态下面的查询提交
  1424. * @access public
  1425. * @return void
  1426. * @throws PDOException
  1427. */
  1428. public function commit()
  1429. {
  1430. $this->initConnect(true);
  1431. if (1 == $this->transTimes) {
  1432. $this->linkID->commit();
  1433. }
  1434. --$this->transTimes;
  1435. }
  1436. /**
  1437. * 事务回滚
  1438. * @access public
  1439. * @return void
  1440. * @throws PDOException
  1441. */
  1442. public function rollback()
  1443. {
  1444. $this->initConnect(true);
  1445. if (1 == $this->transTimes) {
  1446. $this->linkID->rollBack();
  1447. } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
  1448. $this->linkID->exec(
  1449. $this->parseSavepointRollBack('trans' . $this->transTimes)
  1450. );
  1451. }
  1452. $this->transTimes = max(0, $this->transTimes - 1);
  1453. }
  1454. /**
  1455. * 是否支持事务嵌套
  1456. * @return bool
  1457. */
  1458. protected function supportSavepoint()
  1459. {
  1460. return false;
  1461. }
  1462. /**
  1463. * 生成定义保存点的SQL
  1464. * @access protected
  1465. * @param $name
  1466. * @return string
  1467. */
  1468. protected function parseSavepoint($name)
  1469. {
  1470. return 'SAVEPOINT ' . $name;
  1471. }
  1472. /**
  1473. * 生成回滚到保存点的SQL
  1474. * @access protected
  1475. * @param $name
  1476. * @return string
  1477. */
  1478. protected function parseSavepointRollBack($name)
  1479. {
  1480. return 'ROLLBACK TO SAVEPOINT ' . $name;
  1481. }
  1482. /**
  1483. * 批处理执行SQL语句
  1484. * 批处理的指令都认为是execute操作
  1485. * @access public
  1486. * @param array $sqlArray SQL批处理指令
  1487. * @param array $bind 参数绑定
  1488. * @return boolean
  1489. */
  1490. public function batchQuery($sqlArray = [], $bind = [])
  1491. {
  1492. if (!is_array($sqlArray)) {
  1493. return false;
  1494. }
  1495. // 自动启动事务支持
  1496. $this->startTrans();
  1497. try {
  1498. foreach ($sqlArray as $sql) {
  1499. $this->execute($sql, $bind);
  1500. }
  1501. // 提交事务
  1502. $this->commit();
  1503. } catch (\Exception $e) {
  1504. $this->rollback();
  1505. throw $e;
  1506. }
  1507. return true;
  1508. }
  1509. /**
  1510. * 获得查询次数
  1511. * @access public
  1512. * @param boolean $execute 是否包含所有查询
  1513. * @return integer
  1514. */
  1515. public function getQueryTimes($execute = false)
  1516. {
  1517. return $execute ? Db::$queryTimes + Db::$executeTimes : Db::$queryTimes;
  1518. }
  1519. /**
  1520. * 获得执行次数
  1521. * @access public
  1522. * @return integer
  1523. */
  1524. public function getExecuteTimes()
  1525. {
  1526. return Db::$executeTimes;
  1527. }
  1528. /**
  1529. * 关闭数据库(或者重新连接)
  1530. * @access public
  1531. * @return $this
  1532. */
  1533. public function close()
  1534. {
  1535. $this->linkID = null;
  1536. $this->linkWrite = null;
  1537. $this->linkRead = null;
  1538. $this->links = [];
  1539. // 释放查询
  1540. $this->free();
  1541. return $this;
  1542. }
  1543. /**
  1544. * 是否断线
  1545. * @access protected
  1546. * @param \PDOException|\Exception $e 异常对象
  1547. * @return bool
  1548. */
  1549. protected function isBreak($e)
  1550. {
  1551. if (!$this->config['break_reconnect']) {
  1552. return false;
  1553. }
  1554. $error = $e->getMessage();
  1555. foreach ($this->breakMatchStr as $msg) {
  1556. if (false !== stripos($error, $msg)) {
  1557. return true;
  1558. }
  1559. }
  1560. return false;
  1561. }
  1562. /**
  1563. * 获取最近一次查询的sql语句
  1564. * @access public
  1565. * @return string
  1566. */
  1567. public function getLastSql()
  1568. {
  1569. return $this->getRealSql($this->queryStr, $this->bind);
  1570. }
  1571. /**
  1572. * 获取最近插入的ID
  1573. * @access public
  1574. * @param string $sequence 自增序列名
  1575. * @return string
  1576. */
  1577. public function getLastInsID($sequence = null)
  1578. {
  1579. return $this->linkID->lastInsertId($sequence);
  1580. }
  1581. /**
  1582. * 获取返回或者影响的记录数
  1583. * @access public
  1584. * @return integer
  1585. */
  1586. public function getNumRows()
  1587. {
  1588. return $this->numRows;
  1589. }
  1590. /**
  1591. * 获取最近的错误信息
  1592. * @access public
  1593. * @return string
  1594. */
  1595. public function getError()
  1596. {
  1597. if ($this->PDOStatement) {
  1598. $error = $this->PDOStatement->errorInfo();
  1599. $error = $error[1] . ':' . $error[2];
  1600. } else {
  1601. $error = '';
  1602. }
  1603. if ('' != $this->queryStr) {
  1604. $error .= "\n [ SQL语句 ] : " . $this->getLastsql();
  1605. }
  1606. return $error;
  1607. }
  1608. /**
  1609. * 数据库调试 记录当前SQL及分析性能
  1610. * @access protected
  1611. * @param boolean $start 调试开始标记 true 开始 false 结束
  1612. * @param string $sql 执行的SQL语句 留空自动获取
  1613. * @param bool $master 主从标记
  1614. * @return void
  1615. */
  1616. protected function debug($start, $sql = '', $master = false)
  1617. {
  1618. if (!empty($this->config['debug'])) {
  1619. // 开启数据库调试模式
  1620. $debug = Container::get('debug');
  1621. if ($start) {
  1622. $debug->remark('queryStartTime', 'time');
  1623. } else {
  1624. // 记录操作结束时间
  1625. $debug->remark('queryEndTime', 'time');
  1626. $runtime = $debug->getRangeTime('queryStartTime', 'queryEndTime');
  1627. $sql = $sql ?: $this->getLastsql();
  1628. $result = [];
  1629. // SQL性能分析
  1630. if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
  1631. $result = $this->getExplain($sql);
  1632. }
  1633. // SQL监听
  1634. $this->triggerSql($sql, $runtime, $result, $master);
  1635. }
  1636. }
  1637. }
  1638. /**
  1639. * 监听SQL执行
  1640. * @access public
  1641. * @param callable $callback 回调方法
  1642. * @return void
  1643. */
  1644. public function listen($callback)
  1645. {
  1646. self::$event[] = $callback;
  1647. }
  1648. /**
  1649. * 触发SQL事件
  1650. * @access protected
  1651. * @param string $sql SQL语句
  1652. * @param float $runtime SQL运行时间
  1653. * @param mixed $explain SQL分析
  1654. * @param bool $master 主从标记
  1655. * @return void
  1656. */
  1657. protected function triggerSql($sql, $runtime, $explain = [], $master = false)
  1658. {
  1659. if (!empty(self::$event)) {
  1660. foreach (self::$event as $callback) {
  1661. if (is_callable($callback)) {
  1662. call_user_func_array($callback, [$sql, $runtime, $explain, $master]);
  1663. }
  1664. }
  1665. } else {
  1666. if ($this->config['deploy']) {
  1667. // 分布式记录当前操作的主从
  1668. $master = $master ? 'master|' : 'slave|';
  1669. } else {
  1670. $master = '';
  1671. }
  1672. // 未注册监听则记录到日志中
  1673. $this->log('[ SQL ] ' . $sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]');
  1674. if (!empty($explain)) {
  1675. $this->log('[ EXPLAIN : ' . var_export($explain, true) . ' ]');
  1676. }
  1677. }
  1678. }
  1679. public function log($log, $type = 'sql')
  1680. {
  1681. $this->config['debug'] && Container::get('log')->record($log, $type);
  1682. }
  1683. /**
  1684. * 初始化数据库连接
  1685. * @access protected
  1686. * @param boolean $master 是否主服务器
  1687. * @return void
  1688. */
  1689. protected function initConnect($master = true)
  1690. {
  1691. if (!empty($this->config['deploy'])) {
  1692. // 采用分布式数据库
  1693. if ($master || $this->transTimes) {
  1694. if (!$this->linkWrite) {
  1695. $this->linkWrite = $this->multiConnect(true);
  1696. }
  1697. $this->linkID = $this->linkWrite;
  1698. } else {
  1699. if (!$this->linkRead) {
  1700. $this->linkRead = $this->multiConnect(false);
  1701. }
  1702. $this->linkID = $this->linkRead;
  1703. }
  1704. } elseif (!$this->linkID) {
  1705. // 默认单数据库
  1706. $this->linkID = $this->connect();
  1707. }
  1708. }
  1709. /**
  1710. * 连接分布式服务器
  1711. * @access protected
  1712. * @param boolean $master 主服务器
  1713. * @return PDO
  1714. */
  1715. protected function multiConnect($master = false)
  1716. {
  1717. $_config = [];
  1718. // 分布式数据库配置解析
  1719. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1720. $_config[$name] = is_string($this->config[$name]) ? explode(',', $this->config[$name]) : $this->config[$name];
  1721. }
  1722. // 主服务器序号
  1723. $m = floor(mt_rand(0, $this->config['master_num'] - 1));
  1724. if ($this->config['rw_separate']) {
  1725. // 主从式采用读写分离
  1726. if ($master) // 主服务器写入
  1727. {
  1728. $r = $m;
  1729. } elseif (is_numeric($this->config['slave_no'])) {
  1730. // 指定服务器读
  1731. $r = $this->config['slave_no'];
  1732. } else {
  1733. // 读操作连接从服务器 每次随机连接的数据库
  1734. $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1));
  1735. }
  1736. } else {
  1737. // 读写操作不区分服务器 每次随机连接的数据库
  1738. $r = floor(mt_rand(0, count($_config['hostname']) - 1));
  1739. }
  1740. $dbMaster = false;
  1741. if ($m != $r) {
  1742. $dbMaster = [];
  1743. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1744. $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0];
  1745. }
  1746. }
  1747. $dbConfig = [];
  1748. foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
  1749. $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0];
  1750. }
  1751. return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster);
  1752. }
  1753. /**
  1754. * 析构方法
  1755. * @access public
  1756. */
  1757. public function __destruct()
  1758. {
  1759. // 关闭连接
  1760. $this->close();
  1761. }
  1762. /**
  1763. * 缓存数据
  1764. * @access protected
  1765. * @param string $key 缓存标识
  1766. * @param mixed $data 缓存数据
  1767. * @param array $config 缓存参数
  1768. */
  1769. protected function cacheData($key, $data, $config = [])
  1770. {
  1771. $cache = Container::get('cache');
  1772. if (isset($config['tag'])) {
  1773. $cache->tag($config['tag'])->set($key, $data, $config['expire']);
  1774. } else {
  1775. $cache->set($key, $data, $config['expire']);
  1776. }
  1777. }
  1778. /**
  1779. * 获取缓存数据
  1780. * @access protected
  1781. * @param Query $query 查询对象
  1782. * @param mixed $cache 缓存设置
  1783. * @param array $options 缓存
  1784. * @return mixed
  1785. */
  1786. protected function getCacheData(Query $query, $cache, $data, &$key = null)
  1787. {
  1788. // 判断查询缓存
  1789. $key = is_string($cache['key']) ? $cache['key'] : $this->getCacheKey($query, $data);
  1790. return Container::get('cache')->get($key);
  1791. }
  1792. /**
  1793. * 生成缓存标识
  1794. * @access protected
  1795. * @param Query $query 查询对象
  1796. * @param mixed $value 缓存数据
  1797. * @return string
  1798. */
  1799. protected function getCacheKey(Query $query, $value)
  1800. {
  1801. if (is_scalar($value)) {
  1802. $data = $value;
  1803. } elseif (is_array($value) && isset($value[1], $value[2]) && in_array($value[1], ['=', 'eq'], true) && is_scalar($value[2])) {
  1804. $data = $value[2];
  1805. }
  1806. $prefix = 'think:' . $this->getConfig('database') . '.';
  1807. if (isset($data)) {
  1808. return $prefix . $query->getTable() . '|' . $data;
  1809. }
  1810. try {
  1811. return md5($prefix . serialize($query->getOptions()) . serialize($query->getBind(false)));
  1812. } catch (\Exception $e) {
  1813. throw new Exception('closure not support cache(true)');
  1814. }
  1815. }
  1816. }