Total Complexity | 346 |
Total Lines | 2126 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
25 | abstract class Connection |
||
1 ignored issue
–
show
|
|||
26 | { |
||
27 | const PARAM_FLOAT = 21; |
||
28 | protected static $instance = []; |
||
29 | /** @var PDOStatement PDO操作实例 */ |
||
30 | protected $PDOStatement; |
||
31 | |||
32 | /** @var string 当前SQL指令 */ |
||
33 | protected $queryStr = ''; |
||
34 | // 返回或者影响记录数 |
||
35 | protected $numRows = 0; |
||
36 | // 事务指令数 |
||
37 | protected $transTimes = 0; |
||
38 | // 错误信息 |
||
39 | protected $error = ''; |
||
40 | |||
41 | /** @var PDO[] 数据库连接ID 支持多个连接 */ |
||
42 | protected $links = []; |
||
43 | |||
44 | /** @var PDO 当前连接ID */ |
||
45 | protected $linkID; |
||
46 | protected $linkRead; |
||
47 | protected $linkWrite; |
||
48 | |||
49 | // 查询结果类型 |
||
50 | protected $fetchType = PDO::FETCH_ASSOC; |
||
51 | // 字段属性大小写 |
||
52 | protected $attrCase = PDO::CASE_LOWER; |
||
53 | // 监听回调 |
||
54 | protected static $event = []; |
||
55 | |||
56 | // 数据表信息 |
||
57 | protected static $info = []; |
||
58 | |||
59 | // 使用Builder类 |
||
60 | protected $builderClassName; |
||
61 | // Builder对象 |
||
62 | protected $builder; |
||
63 | // 数据库连接参数配置 |
||
64 | protected $config = [ |
||
65 | // 数据库类型 |
||
66 | 'type' => '', |
||
67 | // 服务器地址 |
||
68 | 'hostname' => '', |
||
69 | // 数据库名 |
||
70 | 'database' => '', |
||
71 | // 用户名 |
||
72 | 'username' => '', |
||
73 | // 密码 |
||
74 | 'password' => '', |
||
75 | // 端口 |
||
76 | 'hostport' => '', |
||
77 | // 连接dsn |
||
78 | 'dsn' => '', |
||
79 | // 数据库连接参数 |
||
80 | 'params' => [], |
||
81 | // 数据库编码默认采用utf8 |
||
82 | 'charset' => 'utf8', |
||
83 | // 数据库表前缀 |
||
84 | 'prefix' => '', |
||
85 | // 数据库调试模式 |
||
86 | 'debug' => false, |
||
87 | // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) |
||
88 | 'deploy' => 0, |
||
89 | // 数据库读写是否分离 主从式有效 |
||
90 | 'rw_separate' => false, |
||
91 | // 读写分离后 主服务器数量 |
||
92 | 'master_num' => 1, |
||
93 | // 指定从服务器序号 |
||
94 | 'slave_no' => '', |
||
95 | // 模型写入后自动读取主服务器 |
||
96 | 'read_master' => false, |
||
97 | // 是否严格检查字段是否存在 |
||
98 | 'fields_strict' => true, |
||
99 | // 数据集返回类型 |
||
100 | 'resultset_type' => '', |
||
101 | // 自动写入时间戳字段 |
||
102 | 'auto_timestamp' => false, |
||
103 | // 时间字段取出后的默认时间格式 |
||
104 | 'datetime_format' => 'Y-m-d H:i:s', |
||
105 | // 是否需要进行SQL性能分析 |
||
106 | 'sql_explain' => false, |
||
107 | // Builder类 |
||
108 | 'builder' => '', |
||
109 | // Query类 |
||
110 | 'query' => '\\think\\db\\Query', |
||
111 | // 是否需要断线重连 |
||
112 | 'break_reconnect' => false, |
||
113 | // 断线标识字符串 |
||
114 | 'break_match_str' => [], |
||
115 | ]; |
||
116 | |||
117 | // PDO连接参数 |
||
118 | protected $params = [ |
||
119 | PDO::ATTR_CASE => PDO::CASE_NATURAL, |
||
120 | PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, |
||
121 | PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, |
||
122 | PDO::ATTR_STRINGIFY_FETCHES => false, |
||
123 | PDO::ATTR_EMULATE_PREPARES => false, |
||
124 | ]; |
||
125 | |||
126 | // 服务器断线标识字符 |
||
127 | protected $breakMatchStr = [ |
||
128 | 'server has gone away', |
||
129 | 'no connection to the server', |
||
130 | 'Lost connection', |
||
131 | 'is dead or not enabled', |
||
132 | 'Error while sending', |
||
133 | 'decryption failed or bad record mac', |
||
134 | 'server closed the connection unexpectedly', |
||
135 | 'SSL connection has been closed unexpectedly', |
||
136 | 'Error writing data to the connection', |
||
137 | 'Resource deadlock avoided', |
||
138 | 'failed with errno', |
||
139 | ]; |
||
140 | |||
141 | // 绑定参数 |
||
142 | protected $bind = []; |
||
143 | |||
144 | /** |
||
145 | * 架构函数 读取数据库配置信息 |
||
146 | * @access public |
||
147 | * @param array $config 数据库配置数组 |
||
148 | */ |
||
149 | public function __construct(array $config = []) |
||
150 | { |
||
151 | if (!empty($config)) { |
||
152 | $this->config = array_merge($this->config, $config); |
||
153 | } |
||
154 | |||
155 | // 创建Builder对象 |
||
156 | $class = $this->getBuilderClass(); |
||
157 | |||
158 | $this->builder = new $class($this); |
||
159 | |||
160 | // 执行初始化操作 |
||
161 | $this->initialize(); |
||
162 | } |
||
163 | |||
164 | /** |
||
165 | * 初始化 |
||
166 | * @access protected |
||
167 | * @return void |
||
168 | */ |
||
169 | protected function initialize() |
||
170 | {} |
||
171 | |||
172 | /** |
||
173 | * 取得数据库连接类实例 |
||
174 | * @access public |
||
175 | * @param mixed $config 连接配置 |
||
176 | * @param bool|string $name 连接标识 true 强制重新连接 |
||
177 | * @return Connection |
||
178 | * @throws Exception |
||
179 | */ |
||
180 | public static function instance($config = [], $name = false) |
||
181 | { |
||
182 | if (false === $name) { |
||
183 | $name = md5(serialize($config)); |
||
184 | } |
||
185 | |||
186 | if (true === $name || !isset(self::$instance[$name])) { |
||
187 | if (empty($config['type'])) { |
||
188 | throw new InvalidArgumentException('Undefined db type'); |
||
189 | } |
||
190 | |||
191 | // 记录初始化信息 |
||
192 | Container::get('app')->log('[ DB ] INIT ' . $config['type']); |
||
193 | |||
194 | if (true === $name) { |
||
195 | $name = md5(serialize($config)); |
||
196 | } |
||
197 | |||
198 | self::$instance[$name] = Loader::factory($config['type'], '\\think\\db\\connector\\', $config); |
||
199 | } |
||
200 | |||
201 | return self::$instance[$name]; |
||
202 | } |
||
203 | |||
204 | /** |
||
205 | * 获取当前连接器类对应的Builder类 |
||
206 | * @access public |
||
207 | * @return string |
||
208 | */ |
||
209 | public function getBuilderClass() |
||
210 | { |
||
211 | if (!empty($this->builderClassName)) { |
||
212 | return $this->builderClassName; |
||
213 | } |
||
214 | |||
215 | return $this->getConfig('builder') ?: '\\think\\db\\builder\\' . ucfirst($this->getConfig('type')); |
||
216 | } |
||
217 | |||
218 | /** |
||
219 | * 设置当前的数据库Builder对象 |
||
220 | * @access protected |
||
221 | * @param Builder $builder |
||
222 | * @return void |
||
223 | */ |
||
224 | protected function setBuilder(Builder $builder) |
||
225 | { |
||
226 | $this->builder = $builder; |
||
227 | |||
228 | return $this; |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * 获取当前的builder实例对象 |
||
233 | * @access public |
||
234 | * @return Builder |
||
235 | */ |
||
236 | public function getBuilder() |
||
237 | { |
||
238 | return $this->builder; |
||
239 | } |
||
240 | |||
241 | /** |
||
242 | * 解析pdo连接的dsn信息 |
||
243 | * @access protected |
||
244 | * @param array $config 连接信息 |
||
245 | * @return string |
||
246 | */ |
||
247 | abstract protected function parseDsn($config); |
||
248 | |||
249 | /** |
||
250 | * 取得数据表的字段信息 |
||
251 | * @access public |
||
252 | * @param string $tableName |
||
253 | * @return array |
||
254 | */ |
||
255 | abstract public function getFields($tableName); |
||
256 | |||
257 | /** |
||
258 | * 取得数据库的表信息 |
||
259 | * @access public |
||
260 | * @param string $dbName |
||
1 ignored issue
–
show
|
|||
261 | * @return array |
||
262 | */ |
||
263 | abstract public function getTables($dbName); |
||
264 | |||
265 | /** |
||
266 | * SQL性能分析 |
||
267 | * @access protected |
||
268 | * @param string $sql |
||
269 | * @return array |
||
270 | */ |
||
271 | abstract protected function getExplain($sql); |
||
272 | |||
273 | /** |
||
274 | * 对返数据表字段信息进行大小写转换出来 |
||
275 | * @access public |
||
276 | * @param array $info 字段信息 |
||
277 | * @return array |
||
278 | */ |
||
279 | public function fieldCase($info) |
||
280 | { |
||
281 | // 字段大小写转换 |
||
282 | switch ($this->attrCase) { |
||
283 | case PDO::CASE_LOWER: |
||
1 ignored issue
–
show
|
|||
284 | $info = array_change_key_case($info); |
||
285 | break; |
||
286 | case PDO::CASE_UPPER: |
||
1 ignored issue
–
show
|
|||
287 | $info = array_change_key_case($info, CASE_UPPER); |
||
288 | break; |
||
289 | case PDO::CASE_NATURAL: |
||
1 ignored issue
–
show
|
|||
290 | default: |
||
1 ignored issue
–
show
|
|||
291 | // 不做转换 |
||
292 | } |
||
293 | |||
294 | return $info; |
||
295 | } |
||
296 | |||
297 | /** |
||
298 | * 获取字段绑定类型 |
||
299 | * @access public |
||
300 | * @param string $type 字段类型 |
||
301 | * @return integer |
||
302 | */ |
||
303 | public function getFieldBindType($type) |
||
304 | { |
||
305 | if (0 === strpos($type, 'set') || 0 === strpos($type, 'enum')) { |
||
306 | $bind = PDO::PARAM_STR; |
||
307 | } elseif (preg_match('/(double|float|decimal|real|numeric)/is', $type)) { |
||
308 | $bind = self::PARAM_FLOAT; |
||
309 | } elseif (preg_match('/(int|serial|bit)/is', $type)) { |
||
310 | $bind = PDO::PARAM_INT; |
||
311 | } elseif (preg_match('/bool/is', $type)) { |
||
312 | $bind = PDO::PARAM_BOOL; |
||
313 | } else { |
||
314 | $bind = PDO::PARAM_STR; |
||
315 | } |
||
316 | |||
317 | return $bind; |
||
318 | } |
||
319 | |||
320 | /** |
||
321 | * 将SQL语句中的__TABLE_NAME__字符串替换成带前缀的表名(小写) |
||
322 | * @access public |
||
323 | * @param string $sql sql语句 |
||
324 | * @return string |
||
325 | */ |
||
326 | public function parseSqlTable($sql) |
||
327 | { |
||
328 | if (false !== strpos($sql, '__')) { |
||
329 | $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) { |
||
330 | return $this->getConfig('prefix') . strtolower($match[1]); |
||
331 | }, $sql); |
||
332 | } |
||
333 | |||
334 | return $sql; |
||
335 | } |
||
336 | |||
337 | /** |
||
338 | * 获取数据表信息 |
||
339 | * @access public |
||
340 | * @param mixed $tableName 数据表名 留空自动获取 |
||
341 | * @param string $fetch 获取信息类型 包括 fields type bind pk |
||
342 | * @return mixed |
||
343 | */ |
||
344 | public function getTableInfo($tableName, $fetch = '') |
||
345 | { |
||
346 | if (is_array($tableName)) { |
||
347 | $tableName = key($tableName) ?: current($tableName); |
||
348 | } |
||
349 | |||
350 | if (strpos($tableName, ',')) { |
||
351 | // 多表不获取字段信息 |
||
352 | return false; |
||
353 | } else { |
||
354 | $tableName = $this->parseSqlTable($tableName); |
||
355 | } |
||
356 | |||
357 | // 修正子查询作为表名的问题 |
||
358 | if (strpos($tableName, ')')) { |
||
359 | return []; |
||
360 | } |
||
361 | |||
362 | list($tableName) = explode(' ', $tableName); |
||
363 | |||
364 | if (false === strpos($tableName, '.')) { |
||
365 | $schema = $this->getConfig('database') . '.' . $tableName; |
||
366 | } else { |
||
367 | $schema = $tableName; |
||
368 | } |
||
369 | |||
370 | if (!isset(self::$info[$schema])) { |
||
371 | // 读取缓存 |
||
372 | $cacheFile = Container::get('app')->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR . $schema . '.php'; |
||
373 | |||
374 | if (!$this->config['debug'] && is_file($cacheFile)) { |
||
375 | $info = include $cacheFile; |
||
376 | } else { |
||
377 | $info = $this->getFields($tableName); |
||
378 | } |
||
379 | |||
380 | $fields = array_keys($info); |
||
381 | $bind = $type = []; |
||
382 | |||
383 | foreach ($info as $key => $val) { |
||
384 | // 记录字段类型 |
||
385 | $type[$key] = $val['type']; |
||
386 | $bind[$key] = $this->getFieldBindType($val['type']); |
||
387 | |||
388 | if (!empty($val['primary'])) { |
||
389 | $pk[] = $key; |
||
390 | } |
||
391 | } |
||
392 | |||
393 | if (isset($pk)) { |
||
394 | // 设置主键 |
||
395 | $pk = count($pk) > 1 ? $pk : $pk[0]; |
||
396 | } else { |
||
397 | $pk = null; |
||
398 | } |
||
399 | |||
400 | self::$info[$schema] = ['fields' => $fields, 'type' => $type, 'bind' => $bind, 'pk' => $pk]; |
||
401 | } |
||
402 | |||
403 | return $fetch ? self::$info[$schema][$fetch] : self::$info[$schema]; |
||
404 | } |
||
405 | |||
406 | /** |
||
407 | * 获取数据表的主键 |
||
408 | * @access public |
||
409 | * @param string $tableName 数据表名 |
||
410 | * @return string|array |
||
411 | */ |
||
412 | public function getPk($tableName) |
||
413 | { |
||
414 | return $this->getTableInfo($tableName, 'pk'); |
||
415 | } |
||
416 | |||
417 | /** |
||
418 | * 获取数据表字段信息 |
||
419 | * @access public |
||
420 | * @param string $tableName 数据表名 |
||
421 | * @return array |
||
422 | */ |
||
423 | public function getTableFields($tableName) |
||
424 | { |
||
425 | return $this->getTableInfo($tableName, 'fields'); |
||
426 | } |
||
427 | |||
428 | /** |
||
429 | * 获取数据表字段类型 |
||
430 | * @access public |
||
431 | * @param string $tableName 数据表名 |
||
432 | * @param string $field 字段名 |
||
433 | * @return array|string |
||
434 | */ |
||
435 | public function getFieldsType($tableName, $field = null) |
||
436 | { |
||
437 | $result = $this->getTableInfo($tableName, 'type'); |
||
438 | |||
439 | if ($field && isset($result[$field])) { |
||
440 | return $result[$field]; |
||
441 | } |
||
442 | |||
443 | return $result; |
||
444 | } |
||
445 | |||
446 | /** |
||
447 | * 获取数据表绑定信息 |
||
448 | * @access public |
||
449 | * @param string $tableName 数据表名 |
||
450 | * @return array |
||
451 | */ |
||
452 | public function getFieldsBind($tableName) |
||
453 | { |
||
454 | return $this->getTableInfo($tableName, 'bind'); |
||
455 | } |
||
456 | |||
457 | /** |
||
458 | * 获取数据库的配置参数 |
||
459 | * @access public |
||
460 | * @param string $config 配置名称 |
||
461 | * @return mixed |
||
462 | */ |
||
463 | public function getConfig($config = '') |
||
464 | { |
||
465 | return $config ? $this->config[$config] : $this->config; |
||
466 | } |
||
467 | |||
468 | /** |
||
469 | * 设置数据库的配置参数 |
||
470 | * @access public |
||
471 | * @param string|array $config 配置名称 |
||
472 | * @param mixed $value 配置值 |
||
473 | * @return void |
||
474 | */ |
||
475 | public function setConfig($config, $value = '') |
||
476 | { |
||
477 | if (is_array($config)) { |
||
478 | $this->config = array_merge($this->config, $config); |
||
479 | } else { |
||
480 | $this->config[$config] = $value; |
||
481 | } |
||
482 | } |
||
483 | |||
484 | /** |
||
485 | * 连接数据库方法 |
||
486 | * @access public |
||
487 | * @param array $config 连接参数 |
||
488 | * @param integer $linkNum 连接序号 |
||
489 | * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) |
||
490 | * @return PDO |
||
491 | * @throws Exception |
||
492 | */ |
||
493 | public function connect(array $config = [], $linkNum = 0, $autoConnection = false) |
||
494 | { |
||
495 | if (isset($this->links[$linkNum])) { |
||
496 | return $this->links[$linkNum]; |
||
497 | } |
||
498 | |||
499 | if (!$config) { |
||
500 | $config = $this->config; |
||
501 | } else { |
||
502 | $config = array_merge($this->config, $config); |
||
503 | } |
||
504 | |||
505 | // 连接参数 |
||
506 | if (isset($config['params']) && is_array($config['params'])) { |
||
507 | $params = $config['params'] + $this->params; |
||
508 | } else { |
||
509 | $params = $this->params; |
||
510 | } |
||
511 | |||
512 | // 记录当前字段属性大小写设置 |
||
513 | $this->attrCase = $params[PDO::ATTR_CASE]; |
||
514 | |||
515 | if (!empty($config['break_match_str'])) { |
||
516 | $this->breakMatchStr = array_merge($this->breakMatchStr, (array) $config['break_match_str']); |
||
517 | } |
||
518 | |||
519 | try { |
||
520 | if (empty($config['dsn'])) { |
||
521 | $config['dsn'] = $this->parseDsn($config); |
||
522 | } |
||
523 | |||
524 | if ($config['debug']) { |
||
525 | $startTime = microtime(true); |
||
526 | } |
||
527 | |||
528 | $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); |
||
529 | |||
530 | if ($config['debug']) { |
||
531 | // 记录数据库连接信息 |
||
532 | $this->log('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']); |
||
533 | } |
||
534 | |||
535 | return $this->links[$linkNum]; |
||
536 | } catch (\PDOException $e) { |
||
537 | if ($autoConnection) { |
||
538 | $this->log($e->getMessage(), 'error'); |
||
539 | return $this->connect($autoConnection, $linkNum); |
||
540 | } else { |
||
541 | throw $e; |
||
542 | } |
||
543 | } |
||
544 | } |
||
545 | |||
546 | /** |
||
547 | * 释放查询结果 |
||
548 | * @access public |
||
549 | */ |
||
550 | public function free() |
||
551 | { |
||
552 | $this->PDOStatement = null; |
||
553 | } |
||
554 | |||
555 | /** |
||
556 | * 获取PDO对象 |
||
557 | * @access public |
||
558 | * @return \PDO|false |
||
559 | */ |
||
560 | public function getPdo() |
||
561 | { |
||
562 | if (!$this->linkID) { |
||
563 | return false; |
||
564 | } |
||
565 | |||
566 | return $this->linkID; |
||
567 | } |
||
568 | |||
569 | /** |
||
570 | * 执行查询 使用生成器返回数据 |
||
571 | * @access public |
||
572 | * @param string $sql sql指令 |
||
573 | * @param array $bind 参数绑定 |
||
574 | * @param bool $master 是否在主服务器读操作 |
||
575 | * @param Model $model 模型对象实例 |
||
576 | * @param array $condition 查询条件 |
||
577 | * @param mixed $relation 关联查询 |
||
578 | * @return \Generator |
||
579 | */ |
||
580 | public function getCursor($sql, $bind = [], $master = false, $model = null, $condition = null, $relation = null) |
||
581 | { |
||
582 | $this->initConnect($master); |
||
583 | |||
584 | // 记录SQL语句 |
||
585 | $this->queryStr = $sql; |
||
586 | |||
587 | $this->bind = $bind; |
||
588 | |||
589 | Db::$queryTimes++; |
||
590 | |||
591 | // 调试开始 |
||
592 | $this->debug(true); |
||
593 | |||
594 | // 预处理 |
||
595 | $this->PDOStatement = $this->linkID->prepare($sql); |
||
596 | |||
597 | // 是否为存储过程调用 |
||
598 | $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); |
||
599 | |||
600 | // 参数绑定 |
||
601 | if ($procedure) { |
||
602 | $this->bindParam($bind); |
||
603 | } else { |
||
604 | $this->bindValue($bind); |
||
605 | } |
||
606 | |||
607 | // 执行查询 |
||
608 | $this->PDOStatement->execute(); |
||
609 | |||
610 | // 调试结束 |
||
611 | $this->debug(false, '', $master); |
||
612 | |||
613 | // 返回结果集 |
||
614 | while ($result = $this->PDOStatement->fetch($this->fetchType)) { |
||
615 | if ($model) { |
||
616 | $instance = $model->newInstance($result, $condition); |
||
617 | |||
618 | if ($relation) { |
||
619 | $instance->relationQuery($relation); |
||
620 | } |
||
621 | |||
622 | yield $instance; |
||
623 | } else { |
||
624 | yield $result; |
||
625 | } |
||
626 | } |
||
627 | } |
||
628 | |||
629 | /** |
||
630 | * 执行查询 返回数据集 |
||
631 | * @access public |
||
632 | * @param string $sql sql指令 |
||
633 | * @param array $bind 参数绑定 |
||
634 | * @param bool $master 是否在主服务器读操作 |
||
635 | * @param bool $pdo 是否返回PDO对象 |
||
636 | * @return array |
||
637 | * @throws BindParamException |
||
638 | * @throws \PDOException |
||
639 | * @throws \Exception |
||
640 | * @throws \Throwable |
||
641 | */ |
||
642 | public function query($sql, $bind = [], $master = false, $pdo = false) |
||
643 | { |
||
644 | $this->initConnect($master); |
||
645 | |||
646 | if (!$this->linkID) { |
||
647 | return false; |
||
648 | } |
||
649 | |||
650 | // 记录SQL语句 |
||
651 | $this->queryStr = $sql; |
||
652 | |||
653 | $this->bind = $bind; |
||
654 | |||
655 | Db::$queryTimes++; |
||
656 | |||
657 | try { |
||
658 | // 调试开始 |
||
659 | $this->debug(true); |
||
660 | |||
661 | // 预处理 |
||
662 | $this->PDOStatement = $this->linkID->prepare($sql); |
||
663 | |||
664 | // 是否为存储过程调用 |
||
665 | $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); |
||
666 | |||
667 | // 参数绑定 |
||
668 | if ($procedure) { |
||
669 | $this->bindParam($bind); |
||
670 | } else { |
||
671 | $this->bindValue($bind); |
||
672 | } |
||
673 | |||
674 | // 执行查询 |
||
675 | $this->PDOStatement->execute(); |
||
676 | |||
677 | // 调试结束 |
||
678 | $this->debug(false, '', $master); |
||
679 | |||
680 | // 返回结果集 |
||
681 | return $this->getResult($pdo, $procedure); |
||
682 | } catch (\PDOException $e) { |
||
683 | if ($this->isBreak($e)) { |
||
684 | return $this->close()->query($sql, $bind, $master, $pdo); |
||
685 | } |
||
686 | |||
687 | throw new PDOException($e, $this->config, $this->getLastsql()); |
||
688 | } catch (\Throwable $e) { |
||
689 | if ($this->isBreak($e)) { |
||
690 | return $this->close()->query($sql, $bind, $master, $pdo); |
||
691 | } |
||
692 | |||
693 | throw $e; |
||
694 | } catch (\Exception $e) { |
||
695 | if ($this->isBreak($e)) { |
||
696 | return $this->close()->query($sql, $bind, $master, $pdo); |
||
697 | } |
||
698 | |||
699 | throw $e; |
||
700 | } |
||
701 | } |
||
702 | |||
703 | /** |
||
704 | * 执行语句 |
||
705 | * @access public |
||
706 | * @param string $sql sql指令 |
||
707 | * @param array $bind 参数绑定 |
||
708 | * @param Query $query 查询对象 |
||
709 | * @return int |
||
710 | * @throws BindParamException |
||
711 | * @throws \PDOException |
||
712 | * @throws \Exception |
||
713 | * @throws \Throwable |
||
714 | */ |
||
715 | public function execute($sql, $bind = [], Query $query = null) |
||
716 | { |
||
717 | $this->initConnect(true); |
||
718 | |||
719 | if (!$this->linkID) { |
||
720 | return false; |
||
721 | } |
||
722 | |||
723 | // 记录SQL语句 |
||
724 | $this->queryStr = $sql; |
||
725 | |||
726 | $this->bind = $bind; |
||
727 | |||
728 | Db::$executeTimes++; |
||
729 | try { |
||
730 | // 调试开始 |
||
731 | $this->debug(true); |
||
732 | |||
733 | // 预处理 |
||
734 | $this->PDOStatement = $this->linkID->prepare($sql); |
||
735 | |||
736 | // 是否为存储过程调用 |
||
737 | $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']); |
||
738 | |||
739 | // 参数绑定 |
||
740 | if ($procedure) { |
||
741 | $this->bindParam($bind); |
||
742 | } else { |
||
743 | $this->bindValue($bind); |
||
744 | } |
||
745 | |||
746 | // 执行语句 |
||
747 | $this->PDOStatement->execute(); |
||
748 | |||
749 | // 调试结束 |
||
750 | $this->debug(false, '', true); |
||
751 | |||
752 | if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) { |
||
753 | $query->readMaster(); |
||
754 | } |
||
755 | |||
756 | $this->numRows = $this->PDOStatement->rowCount(); |
||
757 | |||
758 | return $this->numRows; |
||
759 | } catch (\PDOException $e) { |
||
760 | if ($this->isBreak($e)) { |
||
761 | return $this->close()->execute($sql, $bind, $query); |
||
762 | } |
||
763 | |||
764 | throw new PDOException($e, $this->config, $this->getLastsql()); |
||
765 | } catch (\Throwable $e) { |
||
766 | if ($this->isBreak($e)) { |
||
767 | return $this->close()->execute($sql, $bind, $query); |
||
768 | } |
||
769 | |||
770 | throw $e; |
||
771 | } catch (\Exception $e) { |
||
772 | if ($this->isBreak($e)) { |
||
773 | return $this->close()->execute($sql, $bind, $query); |
||
774 | } |
||
775 | |||
776 | throw $e; |
||
777 | } |
||
778 | } |
||
779 | |||
780 | /** |
||
781 | * 查找单条记录 |
||
782 | * @access public |
||
783 | * @param Query $query 查询对象 |
||
784 | * @return array|null|\PDOStatement|string |
||
785 | * @throws DbException |
||
786 | * @throws ModelNotFoundException |
||
787 | * @throws DataNotFoundException |
||
788 | */ |
||
789 | public function find(Query $query) |
||
790 | { |
||
791 | // 分析查询表达式 |
||
792 | $options = $query->getOptions(); |
||
793 | $pk = $query->getPk($options); |
||
794 | |||
795 | $data = $options['data']; |
||
796 | $query->setOption('limit', 1); |
||
797 | |||
798 | if (empty($options['fetch_sql']) && !empty($options['cache'])) { |
||
799 | // 判断查询缓存 |
||
800 | $cache = $options['cache']; |
||
801 | |||
802 | if (is_string($cache['key'])) { |
||
803 | $key = $cache['key']; |
||
804 | } else { |
||
805 | $key = $this->getCacheKey($query, $data); |
||
806 | } |
||
807 | |||
808 | $result = Container::get('cache')->get($key); |
||
809 | |||
810 | if (false !== $result) { |
||
811 | return $result; |
||
812 | } |
||
813 | } |
||
814 | |||
815 | if (is_string($pk) && !is_array($data)) { |
||
816 | if (isset($key) && strpos($key, '|')) { |
||
817 | list($a, $val) = explode('|', $key); |
||
818 | $item[$pk] = $val; |
||
819 | } else { |
||
820 | $item[$pk] = $data; |
||
821 | } |
||
822 | $data = $item; |
||
823 | } |
||
824 | |||
825 | $query->setOption('data', $data); |
||
826 | |||
827 | // 生成查询SQL |
||
828 | $sql = $this->builder->select($query); |
||
829 | |||
830 | $query->removeOption('limit'); |
||
831 | |||
832 | $bind = $query->getBind(); |
||
833 | |||
834 | if (!empty($options['fetch_sql'])) { |
||
835 | // 获取实际执行的SQL语句 |
||
836 | return $this->getRealSql($sql, $bind); |
||
837 | } |
||
838 | |||
839 | // 事件回调 |
||
840 | $result = $query->trigger('before_find'); |
||
841 | |||
842 | if (!$result) { |
||
843 | // 执行查询 |
||
844 | $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']); |
||
845 | |||
846 | if ($resultSet instanceof \PDOStatement) { |
||
847 | // 返回PDOStatement对象 |
||
848 | return $resultSet; |
||
849 | } |
||
850 | |||
851 | $result = isset($resultSet[0]) ? $resultSet[0] : null; |
||
852 | } |
||
853 | |||
854 | if (isset($cache) && $result) { |
||
855 | // 缓存数据 |
||
856 | $this->cacheData($key, $result, $cache); |
||
857 | } |
||
858 | |||
859 | return $result; |
||
860 | } |
||
861 | |||
862 | /** |
||
863 | * 使用游标查询记录 |
||
864 | * @access public |
||
865 | * @param Query $query 查询对象 |
||
866 | * @return \Generator |
||
867 | */ |
||
868 | public function cursor(Query $query) |
||
869 | { |
||
870 | // 分析查询表达式 |
||
871 | $options = $query->getOptions(); |
||
872 | |||
873 | // 生成查询SQL |
||
874 | $sql = $this->builder->select($query); |
||
875 | |||
876 | $bind = $query->getBind(); |
||
877 | |||
878 | $condition = isset($options['where']['AND']) ? $options['where']['AND'] : null; |
||
879 | $relation = isset($options['relaltion']) ? $options['relation'] : null; |
||
880 | |||
881 | // 执行查询操作 |
||
882 | return $this->getCursor($sql, $bind, $options['master'], $query->getModel(), $condition, $relation); |
||
883 | } |
||
884 | |||
885 | /** |
||
886 | * 查找记录 |
||
887 | * @access public |
||
888 | * @param Query $query 查询对象 |
||
889 | * @return array|\PDOStatement|string |
||
890 | * @throws DbException |
||
891 | * @throws ModelNotFoundException |
||
892 | * @throws DataNotFoundException |
||
893 | */ |
||
894 | public function select(Query $query) |
||
895 | { |
||
896 | // 分析查询表达式 |
||
897 | $options = $query->getOptions(); |
||
898 | |||
899 | if (empty($options['fetch_sql']) && !empty($options['cache'])) { |
||
900 | $resultSet = $this->getCacheData($query, $options['cache'], null, $key); |
||
901 | |||
902 | if (false !== $resultSet) { |
||
903 | return $resultSet; |
||
904 | } |
||
905 | } |
||
906 | |||
907 | // 生成查询SQL |
||
908 | $sql = $this->builder->select($query); |
||
909 | |||
910 | $query->removeOption('limit'); |
||
911 | |||
912 | $bind = $query->getBind(); |
||
913 | |||
914 | if (!empty($options['fetch_sql'])) { |
||
915 | // 获取实际执行的SQL语句 |
||
916 | return $this->getRealSql($sql, $bind); |
||
917 | } |
||
918 | |||
919 | $resultSet = $query->trigger('before_select'); |
||
920 | |||
921 | if (!$resultSet) { |
||
922 | // 执行查询操作 |
||
923 | $resultSet = $this->query($sql, $bind, $options['master'], $options['fetch_pdo']); |
||
924 | |||
925 | if ($resultSet instanceof \PDOStatement) { |
||
926 | // 返回PDOStatement对象 |
||
927 | return $resultSet; |
||
928 | } |
||
929 | } |
||
930 | |||
931 | if (!empty($options['cache']) && false !== $resultSet) { |
||
932 | // 缓存数据集 |
||
933 | $this->cacheData($key, $resultSet, $options['cache']); |
||
934 | } |
||
935 | |||
936 | return $resultSet; |
||
937 | } |
||
938 | |||
939 | /** |
||
940 | * 插入记录 |
||
941 | * @access public |
||
942 | * @param Query $query 查询对象 |
||
943 | * @param boolean $replace 是否replace |
||
944 | * @param boolean $getLastInsID 返回自增主键 |
||
945 | * @param string $sequence 自增序列名 |
||
946 | * @return integer|string |
||
947 | */ |
||
948 | public function insert(Query $query, $replace = false, $getLastInsID = false, $sequence = null) |
||
989 | } |
||
990 | |||
991 | /** |
||
992 | * 批量插入记录 |
||
993 | * @access public |
||
994 | * @param Query $query 查询对象 |
||
995 | * @param mixed $dataSet 数据集 |
||
996 | * @param bool $replace 是否replace |
||
997 | * @param integer $limit 每次写入数据限制 |
||
998 | * @return integer|string |
||
999 | * @throws \Exception |
||
1000 | * @throws \Throwable |
||
1001 | */ |
||
1002 | public function insertAll(Query $query, $dataSet = [], $replace = false, $limit = null) |
||
1003 | { |
||
1004 | if (!is_array(reset($dataSet))) { |
||
1005 | return false; |
||
1006 | } |
||
1007 | |||
1008 | $options = $query->getOptions(); |
||
1009 | |||
1010 | if ($limit) { |
||
1011 | // 分批写入 自动启动事务支持 |
||
1012 | $this->startTrans(); |
||
1013 | |||
1014 | try { |
||
1015 | $array = array_chunk($dataSet, $limit, true); |
||
1016 | $count = 0; |
||
1017 | |||
1018 | foreach ($array as $item) { |
||
1019 | $sql = $this->builder->insertAll($query, $item, $replace); |
||
1020 | $bind = $query->getBind(); |
||
1021 | |||
1022 | if (!empty($options['fetch_sql'])) { |
||
1023 | $fetchSql[] = $this->getRealSql($sql, $bind); |
||
1024 | } else { |
||
1025 | $count += $this->execute($sql, $bind, $query); |
||
1026 | } |
||
1027 | } |
||
1028 | |||
1029 | // 提交事务 |
||
1030 | $this->commit(); |
||
1031 | } catch (\Exception $e) { |
||
1032 | $this->rollback(); |
||
1033 | throw $e; |
||
1034 | } catch (\Throwable $e) { |
||
1035 | $this->rollback(); |
||
1036 | throw $e; |
||
1037 | } |
||
1038 | |||
1039 | return isset($fetchSql) ? implode(';', $fetchSql) : $count; |
||
1040 | } |
||
1041 | |||
1042 | $sql = $this->builder->insertAll($query, $dataSet, $replace); |
||
1043 | $bind = $query->getBind(); |
||
1044 | |||
1045 | if (!empty($options['fetch_sql'])) { |
||
1046 | return $this->getRealSql($sql, $bind); |
||
1047 | } |
||
1048 | |||
1049 | return $this->execute($sql, $bind, $query); |
||
1050 | } |
||
1051 | |||
1052 | /** |
||
1053 | * 通过Select方式插入记录 |
||
1054 | * @access public |
||
1055 | * @param Query $query 查询对象 |
||
1056 | * @param string $fields 要插入的数据表字段名 |
||
1057 | * @param string $table 要插入的数据表名 |
||
1058 | * @return integer|string |
||
1059 | * @throws PDOException |
||
1060 | */ |
||
1061 | public function selectInsert(Query $query, $fields, $table) |
||
1062 | { |
||
1063 | // 分析查询表达式 |
||
1064 | $options = $query->getOptions(); |
||
1065 | |||
1066 | $table = $this->parseSqlTable($table); |
||
1067 | |||
1068 | $sql = $this->builder->selectInsert($query, $fields, $table); |
||
1069 | |||
1070 | $bind = $query->getBind(); |
||
1071 | |||
1072 | if (!empty($options['fetch_sql'])) { |
||
1073 | return $this->getRealSql($sql, $bind); |
||
1074 | } |
||
1075 | |||
1076 | return $this->execute($sql, $bind, $query); |
||
1077 | } |
||
1078 | |||
1079 | /** |
||
1080 | * 更新记录 |
||
1081 | * @access public |
||
1082 | * @param Query $query 查询对象 |
||
1083 | * @return integer|string |
||
1084 | * @throws Exception |
||
1085 | * @throws PDOException |
||
1086 | */ |
||
1087 | public function update(Query $query) |
||
1172 | } |
||
1173 | |||
1174 | /** |
||
1175 | * 删除记录 |
||
1176 | * @access public |
||
1177 | * @param Query $query 查询对象 |
||
1178 | * @return int |
||
1179 | * @throws Exception |
||
1180 | * @throws PDOException |
||
1181 | */ |
||
1182 | public function delete(Query $query) |
||
1242 | } |
||
1243 | |||
1244 | /** |
||
1245 | * 得到某个字段的值 |
||
1246 | * @access public |
||
1247 | * @param Query $query 查询对象 |
||
1248 | * @param string $field 字段名 |
||
1249 | * @param mixed $default 默认值 |
||
1250 | * @param bool $one 是否返回一个值 |
||
1251 | * @return mixed |
||
1252 | */ |
||
1253 | public function value(Query $query, $field, $default = null, $one = true) |
||
1254 | { |
||
1255 | $options = $query->getOptions(); |
||
1256 | |||
1257 | if (isset($options['field'])) { |
||
1258 | $query->removeOption('field'); |
||
1259 | } |
||
1260 | |||
1261 | if (is_string($field)) { |
||
1262 | $field = array_map('trim', explode(',', $field)); |
||
1263 | } |
||
1264 | |||
1265 | $query->setOption('field', $field); |
||
1266 | |||
1267 | if (empty($options['fetch_sql']) && !empty($options['cache'])) { |
||
1268 | $cache = $options['cache']; |
||
1269 | $result = $this->getCacheData($query, $cache, null, $key); |
||
1270 | |||
1271 | if (false !== $result) { |
||
1272 | return $result; |
||
1273 | } |
||
1274 | } |
||
1275 | |||
1276 | if ($one) { |
||
1277 | $query->setOption('limit', 1); |
||
1278 | } |
||
1279 | |||
1280 | // 生成查询SQL |
||
1281 | $sql = $this->builder->select($query); |
||
1282 | |||
1283 | if (isset($options['field'])) { |
||
1284 | $query->setOption('field', $options['field']); |
||
1285 | } else { |
||
1286 | $query->removeOption('field'); |
||
1287 | } |
||
1288 | |||
1289 | $query->removeOption('limit'); |
||
1290 | |||
1291 | $bind = $query->getBind(); |
||
1292 | |||
1293 | if (!empty($options['fetch_sql'])) { |
||
1294 | // 获取实际执行的SQL语句 |
||
1295 | return $this->getRealSql($sql, $bind); |
||
1296 | } |
||
1297 | |||
1298 | // 执行查询操作 |
||
1299 | $pdo = $this->query($sql, $bind, $options['master'], true); |
||
1300 | |||
1301 | $result = $pdo->fetchColumn(); |
||
1302 | |||
1303 | if (isset($cache) && false !== $result) { |
||
1304 | // 缓存数据 |
||
1305 | $this->cacheData($key, $result, $cache); |
||
1306 | } |
||
1307 | |||
1308 | return false !== $result ? $result : $default; |
||
1309 | } |
||
1310 | |||
1311 | /** |
||
1312 | * 得到某个字段的值 |
||
1313 | * @access public |
||
1314 | * @param Query $query 查询对象 |
||
1315 | * @param string $aggregate 聚合方法 |
||
1316 | * @param mixed $field 字段名 |
||
1317 | * @return mixed |
||
1318 | */ |
||
1319 | public function aggregate(Query $query, $aggregate, $field) |
||
1320 | { |
||
1321 | if (is_string($field) && 0 === stripos($field, 'DISTINCT ')) { |
||
1322 | list($distinct, $field) = explode(' ', $field); |
||
1323 | } |
||
1324 | |||
1325 | $field = $aggregate . '(' . (!empty($distinct) ? 'DISTINCT ' : '') . $this->builder->parseKey($query, $field, true) . ') AS tp_' . strtolower($aggregate); |
||
1326 | |||
1327 | return $this->value($query, $field, 0, false); |
||
1328 | } |
||
1329 | |||
1330 | /** |
||
1331 | * 得到某个列的数组 |
||
1332 | * @access public |
||
1333 | * @param Query $query 查询对象 |
||
1334 | * @param string $field 字段名 多个字段用逗号分隔 |
||
1335 | * @param string $key 索引 |
||
1336 | * @return array |
||
1337 | */ |
||
1338 | public function column(Query $query, $field, $key = '') |
||
1339 | { |
||
1340 | $options = $query->getOptions(); |
||
1341 | |||
1342 | if (isset($options['field'])) { |
||
1343 | $query->removeOption('field'); |
||
1344 | } |
||
1345 | |||
1346 | if (is_null($field)) { |
||
1347 | $field = ['*']; |
||
1348 | } elseif (is_string($field)) { |
||
1349 | $field = array_map('trim', explode(',', $field)); |
||
1350 | } |
||
1351 | |||
1352 | if ($key && ['*'] != $field) { |
||
1353 | array_unshift($field, $key); |
||
1354 | $field = array_unique($field); |
||
1355 | } |
||
1356 | |||
1357 | $query->setOption('field', $field); |
||
1358 | |||
1359 | if (empty($options['fetch_sql']) && !empty($options['cache'])) { |
||
1360 | // 判断查询缓存 |
||
1361 | $cache = $options['cache']; |
||
1362 | $result = $this->getCacheData($query, $cache, null, $guid); |
||
1363 | |||
1364 | if (false !== $result) { |
||
1365 | return $result; |
||
1366 | } |
||
1367 | } |
||
1368 | |||
1369 | // 生成查询SQL |
||
1370 | $sql = $this->builder->select($query); |
||
1371 | |||
1372 | // 还原field参数 |
||
1373 | if (isset($options['field'])) { |
||
1374 | $query->setOption('field', $options['field']); |
||
1375 | } else { |
||
1376 | $query->removeOption('field'); |
||
1377 | } |
||
1378 | |||
1379 | $bind = $query->getBind(); |
||
1380 | |||
1381 | if (!empty($options['fetch_sql'])) { |
||
1382 | // 获取实际执行的SQL语句 |
||
1383 | return $this->getRealSql($sql, $bind); |
||
1384 | } |
||
1385 | |||
1386 | // 执行查询操作 |
||
1387 | $pdo = $this->query($sql, $bind, $options['master'], true); |
||
1388 | |||
1389 | if (1 == $pdo->columnCount()) { |
||
1390 | $result = $pdo->fetchAll(PDO::FETCH_COLUMN); |
||
1391 | } else { |
||
1392 | $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC); |
||
1393 | |||
1394 | if (['*'] == $field && $key) { |
||
1395 | $result = array_column($resultSet, null, $key); |
||
1396 | } elseif ($resultSet) { |
||
1397 | $fields = array_keys($resultSet[0]); |
||
1398 | $count = count($fields); |
||
1399 | $key1 = array_shift($fields); |
||
1400 | $key2 = $fields ? array_shift($fields) : ''; |
||
1401 | $key = $key ?: $key1; |
||
1402 | |||
1403 | if (strpos($key, '.')) { |
||
1404 | list($alias, $key) = explode('.', $key); |
||
1405 | } |
||
1406 | |||
1407 | if (2 == $count) { |
||
1408 | $column = $key2; |
||
1409 | } elseif (1 == $count) { |
||
1410 | $column = $key1; |
||
1411 | } else { |
||
1412 | $column = null; |
||
1413 | } |
||
1414 | |||
1415 | $result = array_column($resultSet, $column, $key); |
||
1416 | } else { |
||
1417 | $result = []; |
||
1418 | } |
||
1419 | } |
||
1420 | |||
1421 | if (isset($cache) && isset($guid)) { |
||
1422 | // 缓存数据 |
||
1423 | $this->cacheData($guid, $result, $cache); |
||
1424 | } |
||
1425 | |||
1426 | return $result; |
||
1427 | } |
||
1428 | |||
1429 | /** |
||
1430 | * 执行查询但只返回PDOStatement对象 |
||
1431 | * @access public |
||
1432 | * @return \PDOStatement|string |
||
1433 | */ |
||
1434 | public function pdo(Query $query) |
||
1435 | { |
||
1436 | // 分析查询表达式 |
||
1437 | $options = $query->getOptions(); |
||
1438 | |||
1439 | // 生成查询SQL |
||
1440 | $sql = $this->builder->select($query); |
||
1441 | |||
1442 | $bind = $query->getBind(); |
||
1443 | |||
1444 | if (!empty($options['fetch_sql'])) { |
||
1445 | // 获取实际执行的SQL语句 |
||
1446 | return $this->getRealSql($sql, $bind); |
||
1447 | } |
||
1448 | |||
1449 | // 执行查询操作 |
||
1450 | return $this->query($sql, $bind, $options['master'], true); |
||
1451 | } |
||
1452 | |||
1453 | /** |
||
1454 | * 根据参数绑定组装最终的SQL语句 便于调试 |
||
1455 | * @access public |
||
1456 | * @param string $sql 带参数绑定的sql语句 |
||
1457 | * @param array $bind 参数绑定列表 |
||
1458 | * @return string |
||
1459 | */ |
||
1460 | public function getRealSql($sql, array $bind = []) |
||
1461 | { |
||
1462 | if (is_array($sql)) { |
||
1463 | $sql = implode(';', $sql); |
||
1464 | } |
||
1465 | |||
1466 | foreach ($bind as $key => $val) { |
||
1467 | $value = is_array($val) ? $val[0] : $val; |
||
1468 | $type = is_array($val) ? $val[1] : PDO::PARAM_STR; |
||
1469 | |||
1470 | if (self::PARAM_FLOAT == $type) { |
||
1471 | $value = (float) $value; |
||
1472 | } elseif (PDO::PARAM_STR == $type) { |
||
1473 | $value = '\'' . addslashes($value) . '\''; |
||
1474 | } elseif (PDO::PARAM_INT == $type && '' === $value) { |
||
1475 | $value = 0; |
||
1476 | } |
||
1477 | |||
1478 | // 判断占位符 |
||
1479 | $sql = is_numeric($key) ? |
||
1480 | substr_replace($sql, $value, strpos($sql, '?'), 1) : |
||
1481 | substr_replace($sql, $value, strpos($sql, ':' . $key), strlen(':' . $key)); |
||
1482 | } |
||
1483 | |||
1484 | return rtrim($sql); |
||
1485 | } |
||
1486 | |||
1487 | /** |
||
1488 | * 参数绑定 |
||
1489 | * 支持 ['name'=>'value','id'=>123] 对应命名占位符 |
||
1490 | * 或者 ['value',123] 对应问号占位符 |
||
1491 | * @access public |
||
1492 | * @param array $bind 要绑定的参数列表 |
||
1493 | * @return void |
||
1494 | * @throws BindParamException |
||
1495 | */ |
||
1496 | protected function bindValue(array $bind = []) |
||
1497 | { |
||
1498 | foreach ($bind as $key => $val) { |
||
1499 | // 占位符 |
||
1500 | $param = is_int($key) ? $key + 1 : ':' . $key; |
||
1501 | |||
1502 | if (is_array($val)) { |
||
1503 | if (PDO::PARAM_INT == $val[1] && '' === $val[0]) { |
||
1504 | $val[0] = 0; |
||
1505 | } elseif (self::PARAM_FLOAT == $val[1]) { |
||
1506 | $val[0] = (float) $val[0]; |
||
1507 | $val[1] = PDO::PARAM_STR; |
||
1508 | } |
||
1509 | |||
1510 | $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]); |
||
1511 | } else { |
||
1512 | $result = $this->PDOStatement->bindValue($param, $val); |
||
1513 | } |
||
1514 | |||
1515 | if (!$result) { |
||
1516 | throw new BindParamException( |
||
1517 | "Error occurred when binding parameters '{$param}'", |
||
1518 | $this->config, |
||
1519 | $this->getLastsql(), |
||
1520 | $bind |
||
1521 | ); |
||
1522 | } |
||
1523 | } |
||
1524 | } |
||
1525 | |||
1526 | /** |
||
1527 | * 存储过程的输入输出参数绑定 |
||
1528 | * @access public |
||
1529 | * @param array $bind 要绑定的参数列表 |
||
1530 | * @return void |
||
1531 | * @throws BindParamException |
||
1532 | */ |
||
1533 | protected function bindParam($bind) |
||
1534 | { |
||
1535 | foreach ($bind as $key => $val) { |
||
1536 | $param = is_int($key) ? $key + 1 : ':' . $key; |
||
1537 | |||
1538 | if (is_array($val)) { |
||
1539 | array_unshift($val, $param); |
||
1540 | $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val); |
||
1541 | } else { |
||
1542 | $result = $this->PDOStatement->bindValue($param, $val); |
||
1543 | } |
||
1544 | |||
1545 | if (!$result) { |
||
1546 | $param = array_shift($val); |
||
1547 | |||
1548 | throw new BindParamException( |
||
1549 | "Error occurred when binding parameters '{$param}'", |
||
1550 | $this->config, |
||
1551 | $this->getLastsql(), |
||
1552 | $bind |
||
1553 | ); |
||
1554 | } |
||
1555 | } |
||
1556 | } |
||
1557 | |||
1558 | /** |
||
1559 | * 获得数据集数组 |
||
1560 | * @access protected |
||
1561 | * @param bool $pdo 是否返回PDOStatement |
||
1562 | * @param bool $procedure 是否存储过程 |
||
1563 | * @return array |
||
1564 | */ |
||
1565 | protected function getResult($pdo = false, $procedure = false) |
||
1566 | { |
||
1567 | if ($pdo) { |
||
1568 | // 返回PDOStatement对象处理 |
||
1569 | return $this->PDOStatement; |
||
1570 | } |
||
1571 | |||
1572 | if ($procedure) { |
||
1573 | // 存储过程返回结果 |
||
1574 | return $this->procedure(); |
||
1575 | } |
||
1576 | |||
1577 | $result = $this->PDOStatement->fetchAll($this->fetchType); |
||
1578 | |||
1579 | $this->numRows = count($result); |
||
1580 | |||
1581 | return $result; |
||
1582 | } |
||
1583 | |||
1584 | /** |
||
1585 | * 获得存储过程数据集 |
||
1586 | * @access protected |
||
1587 | * @return array |
||
1588 | */ |
||
1589 | protected function procedure() |
||
1590 | { |
||
1591 | $item = []; |
||
1592 | |||
1593 | do { |
||
1594 | $result = $this->getResult(); |
||
1595 | if ($result) { |
||
1596 | $item[] = $result; |
||
1597 | } |
||
1598 | } while ($this->PDOStatement->nextRowset()); |
||
1599 | |||
1600 | $this->numRows = count($item); |
||
1601 | |||
1602 | return $item; |
||
1603 | } |
||
1604 | |||
1605 | /** |
||
1606 | * 执行数据库事务 |
||
1607 | * @access public |
||
1608 | * @param callable $callback 数据操作方法回调 |
||
1609 | * @return mixed |
||
1610 | * @throws PDOException |
||
1611 | * @throws \Exception |
||
1612 | * @throws \Throwable |
||
1613 | */ |
||
1614 | public function transaction($callback) |
||
1615 | { |
||
1616 | $this->startTrans(); |
||
1617 | |||
1618 | try { |
||
1619 | $result = null; |
||
1620 | if (is_callable($callback)) { |
||
1621 | $result = call_user_func_array($callback, [$this]); |
||
1622 | } |
||
1623 | |||
1624 | $this->commit(); |
||
1625 | return $result; |
||
1626 | } catch (\Exception $e) { |
||
1627 | $this->rollback(); |
||
1628 | throw $e; |
||
1629 | } catch (\Throwable $e) { |
||
1630 | $this->rollback(); |
||
1631 | throw $e; |
||
1632 | } |
||
1633 | } |
||
1634 | |||
1635 | /** |
||
1636 | * 启动XA事务 |
||
1637 | * @access public |
||
1638 | * @param string $xid XA事务id |
||
1639 | * @return void |
||
1640 | */ |
||
1641 | public function startTransXa($xid) |
||
1642 | {} |
||
1643 | |||
1644 | /** |
||
1645 | * 预编译XA事务 |
||
1646 | * @access public |
||
1647 | * @param string $xid XA事务id |
||
1648 | * @return void |
||
1649 | */ |
||
1650 | public function prepareXa($xid) |
||
1651 | {} |
||
1652 | |||
1653 | /** |
||
1654 | * 提交XA事务 |
||
1655 | * @access public |
||
1656 | * @param string $xid XA事务id |
||
1657 | * @return void |
||
1658 | */ |
||
1659 | public function commitXa($xid) |
||
1660 | {} |
||
1661 | |||
1662 | /** |
||
1663 | * 回滚XA事务 |
||
1664 | * @access public |
||
1665 | * @param string $xid XA事务id |
||
1666 | * @return void |
||
1667 | */ |
||
1668 | public function rollbackXa($xid) |
||
1669 | {} |
||
1670 | |||
1671 | /** |
||
1672 | * 启动事务 |
||
1673 | * @access public |
||
1674 | * @return void |
||
1675 | * @throws \PDOException |
||
1676 | * @throws \Exception |
||
1677 | */ |
||
1678 | public function startTrans() |
||
1679 | { |
||
1680 | $this->initConnect(true); |
||
1681 | if (!$this->linkID) { |
||
1682 | return false; |
||
1683 | } |
||
1684 | |||
1685 | ++$this->transTimes; |
||
1686 | |||
1687 | try { |
||
1688 | if (1 == $this->transTimes) { |
||
1689 | $this->linkID->beginTransaction(); |
||
1690 | } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { |
||
1691 | $this->linkID->exec( |
||
1692 | $this->parseSavepoint('trans' . $this->transTimes) |
||
1693 | ); |
||
1694 | } |
||
1695 | } catch (\Exception $e) { |
||
1696 | if ($this->isBreak($e)) { |
||
1697 | --$this->transTimes; |
||
1698 | return $this->close()->startTrans(); |
||
1699 | } |
||
1700 | throw $e; |
||
1701 | } |
||
1702 | } |
||
1703 | |||
1704 | /** |
||
1705 | * 用于非自动提交状态下面的查询提交 |
||
1706 | * @access public |
||
1707 | * @return void |
||
1708 | * @throws PDOException |
||
1709 | */ |
||
1710 | public function commit() |
||
1711 | { |
||
1712 | $this->initConnect(true); |
||
1713 | |||
1714 | if (1 == $this->transTimes) { |
||
1715 | $this->linkID->commit(); |
||
1716 | } |
||
1717 | |||
1718 | --$this->transTimes; |
||
1719 | } |
||
1720 | |||
1721 | /** |
||
1722 | * 事务回滚 |
||
1723 | * @access public |
||
1724 | * @return void |
||
1725 | * @throws PDOException |
||
1726 | */ |
||
1727 | public function rollback() |
||
1728 | { |
||
1729 | $this->initConnect(true); |
||
1730 | |||
1731 | if (1 == $this->transTimes) { |
||
1732 | $this->linkID->rollBack(); |
||
1733 | } elseif ($this->transTimes > 1 && $this->supportSavepoint()) { |
||
1734 | $this->linkID->exec( |
||
1735 | $this->parseSavepointRollBack('trans' . $this->transTimes) |
||
1736 | ); |
||
1737 | } |
||
1738 | |||
1739 | $this->transTimes = max(0, $this->transTimes - 1); |
||
1740 | } |
||
1741 | |||
1742 | /** |
||
1743 | * 是否支持事务嵌套 |
||
1744 | * @return bool |
||
1745 | */ |
||
1746 | protected function supportSavepoint() |
||
1747 | { |
||
1748 | return false; |
||
1749 | } |
||
1750 | |||
1751 | /** |
||
1752 | * 生成定义保存点的SQL |
||
1753 | * @access protected |
||
1754 | * @param $name |
||
1755 | * @return string |
||
1756 | */ |
||
1757 | protected function parseSavepoint($name) |
||
1758 | { |
||
1759 | return 'SAVEPOINT ' . $name; |
||
1760 | } |
||
1761 | |||
1762 | /** |
||
1763 | * 生成回滚到保存点的SQL |
||
1764 | * @access protected |
||
1765 | * @param $name |
||
1766 | * @return string |
||
1767 | */ |
||
1768 | protected function parseSavepointRollBack($name) |
||
1769 | { |
||
1770 | return 'ROLLBACK TO SAVEPOINT ' . $name; |
||
1771 | } |
||
1772 | |||
1773 | /** |
||
1774 | * 批处理执行SQL语句 |
||
1775 | * 批处理的指令都认为是execute操作 |
||
1776 | * @access public |
||
1777 | * @param array $sqlArray SQL批处理指令 |
||
1778 | * @param array $bind 参数绑定 |
||
1779 | * @return boolean |
||
1780 | */ |
||
1781 | public function batchQuery($sqlArray = [], $bind = []) |
||
1782 | { |
||
1783 | if (!is_array($sqlArray)) { |
||
1784 | return false; |
||
1785 | } |
||
1786 | |||
1787 | // 自动启动事务支持 |
||
1788 | $this->startTrans(); |
||
1789 | |||
1790 | try { |
||
1791 | foreach ($sqlArray as $sql) { |
||
1792 | $this->execute($sql, $bind); |
||
1793 | } |
||
1794 | // 提交事务 |
||
1795 | $this->commit(); |
||
1796 | } catch (\Exception $e) { |
||
1797 | $this->rollback(); |
||
1798 | throw $e; |
||
1799 | } |
||
1800 | |||
1801 | return true; |
||
1802 | } |
||
1803 | |||
1804 | /** |
||
1805 | * 获得查询次数 |
||
1806 | * @access public |
||
1807 | * @param boolean $execute 是否包含所有查询 |
||
1808 | * @return integer |
||
1809 | */ |
||
1810 | public function getQueryTimes($execute = false) |
||
1811 | { |
||
1812 | return $execute ? Db::$queryTimes + Db::$executeTimes : Db::$queryTimes; |
||
1813 | } |
||
1814 | |||
1815 | /** |
||
1816 | * 获得执行次数 |
||
1817 | * @access public |
||
1818 | * @return integer |
||
1819 | */ |
||
1820 | public function getExecuteTimes() |
||
1821 | { |
||
1822 | return Db::$executeTimes; |
||
1823 | } |
||
1824 | |||
1825 | /** |
||
1826 | * 关闭数据库(或者重新连接) |
||
1827 | * @access public |
||
1828 | * @return $this |
||
1829 | */ |
||
1830 | public function close() |
||
1831 | { |
||
1832 | $this->linkID = null; |
||
1833 | $this->linkWrite = null; |
||
1834 | $this->linkRead = null; |
||
1835 | $this->links = []; |
||
1836 | |||
1837 | // 释放查询 |
||
1838 | $this->free(); |
||
1839 | |||
1840 | return $this; |
||
1841 | } |
||
1842 | |||
1843 | /** |
||
1844 | * 是否断线 |
||
1845 | * @access protected |
||
1846 | * @param \PDOException|\Exception $e 异常对象 |
||
1847 | * @return bool |
||
1848 | */ |
||
1849 | protected function isBreak($e) |
||
1850 | { |
||
1851 | if (!$this->config['break_reconnect']) { |
||
1852 | return false; |
||
1853 | } |
||
1854 | |||
1855 | $error = $e->getMessage(); |
||
1856 | |||
1857 | foreach ($this->breakMatchStr as $msg) { |
||
1858 | if (false !== stripos($error, $msg)) { |
||
1859 | return true; |
||
1860 | } |
||
1861 | } |
||
1862 | return false; |
||
1863 | } |
||
1864 | |||
1865 | /** |
||
1866 | * 获取最近一次查询的sql语句 |
||
1867 | * @access public |
||
1868 | * @return string |
||
1869 | */ |
||
1870 | public function getLastSql() |
||
1871 | { |
||
1872 | return $this->getRealSql($this->queryStr, $this->bind); |
||
1873 | } |
||
1874 | |||
1875 | /** |
||
1876 | * 获取最近插入的ID |
||
1877 | * @access public |
||
1878 | * @param string $sequence 自增序列名 |
||
1879 | * @return string |
||
1880 | */ |
||
1881 | public function getLastInsID($sequence = null) |
||
1882 | { |
||
1883 | return $this->linkID->lastInsertId($sequence); |
||
1884 | } |
||
1885 | |||
1886 | /** |
||
1887 | * 获取返回或者影响的记录数 |
||
1888 | * @access public |
||
1889 | * @return integer |
||
1890 | */ |
||
1891 | public function getNumRows() |
||
1892 | { |
||
1893 | return $this->numRows; |
||
1894 | } |
||
1895 | |||
1896 | /** |
||
1897 | * 获取最近的错误信息 |
||
1898 | * @access public |
||
1899 | * @return string |
||
1900 | */ |
||
1901 | public function getError() |
||
1915 | } |
||
1916 | |||
1917 | /** |
||
1918 | * 数据库调试 记录当前SQL及分析性能 |
||
1919 | * @access protected |
||
1920 | * @param boolean $start 调试开始标记 true 开始 false 结束 |
||
1921 | * @param string $sql 执行的SQL语句 留空自动获取 |
||
1922 | * @param bool $master 主从标记 |
||
1923 | * @return void |
||
1924 | */ |
||
1925 | protected function debug($start, $sql = '', $master = false) |
||
1926 | { |
||
1927 | if (!empty($this->config['debug'])) { |
||
1928 | // 开启数据库调试模式 |
||
1929 | $debug = Container::get('debug'); |
||
1930 | |||
1931 | if ($start) { |
||
1932 | $debug->remark('queryStartTime', 'time'); |
||
1933 | } else { |
||
1934 | // 记录操作结束时间 |
||
1935 | $debug->remark('queryEndTime', 'time'); |
||
1936 | $runtime = $debug->getRangeTime('queryStartTime', 'queryEndTime'); |
||
1937 | $sql = $sql ?: $this->getLastsql(); |
||
1938 | $result = []; |
||
1939 | |||
1940 | // SQL性能分析 |
||
1941 | if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) { |
||
1942 | $result = $this->getExplain($sql); |
||
1943 | } |
||
1944 | |||
1945 | // SQL监听 |
||
1946 | $this->triggerSql($sql, $runtime, $result, $master); |
||
1947 | } |
||
1948 | } |
||
1949 | } |
||
1950 | |||
1951 | /** |
||
1952 | * 监听SQL执行 |
||
1953 | * @access public |
||
1954 | * @param callable $callback 回调方法 |
||
1955 | * @return void |
||
1956 | */ |
||
1957 | public function listen($callback) |
||
1958 | { |
||
1959 | self::$event[] = $callback; |
||
1960 | } |
||
1961 | |||
1962 | /** |
||
1963 | * 触发SQL事件 |
||
1964 | * @access protected |
||
1965 | * @param string $sql SQL语句 |
||
1966 | * @param float $runtime SQL运行时间 |
||
1967 | * @param mixed $explain SQL分析 |
||
1968 | * @param bool $master 主从标记 |
||
1969 | * @return void |
||
1970 | */ |
||
1971 | protected function triggerSql($sql, $runtime, $explain = [], $master = false) |
||
1972 | { |
||
1973 | if (!empty(self::$event)) { |
||
1974 | foreach (self::$event as $callback) { |
||
1975 | if (is_callable($callback)) { |
||
1976 | call_user_func_array($callback, [$sql, $runtime, $explain, $master]); |
||
1977 | } |
||
1978 | } |
||
1979 | } else { |
||
1980 | if ($this->config['deploy']) { |
||
1981 | // 分布式记录当前操作的主从 |
||
1982 | $master = $master ? 'master|' : 'slave|'; |
||
1983 | } else { |
||
1984 | $master = ''; |
||
1985 | } |
||
1986 | |||
1987 | // 未注册监听则记录到日志中 |
||
1988 | $this->log('[ SQL ] ' . $sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]'); |
||
1989 | |||
1990 | if (!empty($explain)) { |
||
1991 | $this->log('[ EXPLAIN : ' . var_export($explain, true) . ' ]'); |
||
1992 | } |
||
1993 | } |
||
1994 | } |
||
1995 | |||
1996 | public function log($log, $type = 'sql') |
||
1997 | { |
||
1998 | $this->config['debug'] && Container::get('log')->record($log, $type); |
||
1999 | } |
||
2000 | |||
2001 | /** |
||
2002 | * 初始化数据库连接 |
||
2003 | * @access protected |
||
2004 | * @param boolean $master 是否主服务器 |
||
2005 | * @return void |
||
2006 | */ |
||
2007 | protected function initConnect($master = true) |
||
2027 | } |
||
2028 | } |
||
2029 | |||
2030 | /** |
||
2031 | * 连接分布式服务器 |
||
2032 | * @access protected |
||
2033 | * @param boolean $master 主服务器 |
||
2034 | * @return PDO |
||
2035 | */ |
||
2036 | protected function multiConnect($master = false) |
||
2037 | { |
||
2038 | $_config = []; |
||
2039 | |||
2040 | // 分布式数据库配置解析 |
||
2041 | foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { |
||
2042 | $_config[$name] = is_string($this->config[$name]) ? explode(',', $this->config[$name]) : $this->config[$name]; |
||
2043 | } |
||
2044 | |||
2045 | // 主服务器序号 |
||
2046 | $m = floor(mt_rand(0, $this->config['master_num'] - 1)); |
||
2047 | |||
2048 | if ($this->config['rw_separate']) { |
||
2049 | // 主从式采用读写分离 |
||
2050 | if ($master) // 主服务器写入 |
||
2051 | { |
||
2052 | $r = $m; |
||
2053 | } elseif (is_numeric($this->config['slave_no'])) { |
||
2054 | // 指定服务器读 |
||
2055 | $r = $this->config['slave_no']; |
||
2056 | } else { |
||
2057 | // 读操作连接从服务器 每次随机连接的数据库 |
||
2058 | $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1)); |
||
2059 | } |
||
2060 | } else { |
||
2061 | // 读写操作不区分服务器 每次随机连接的数据库 |
||
2062 | $r = floor(mt_rand(0, count($_config['hostname']) - 1)); |
||
2063 | } |
||
2064 | $dbMaster = false; |
||
2065 | |||
2066 | if ($m != $r) { |
||
2067 | $dbMaster = []; |
||
2068 | foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { |
||
2069 | $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0]; |
||
2070 | } |
||
2071 | } |
||
2072 | |||
2073 | $dbConfig = []; |
||
2074 | |||
2075 | foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) { |
||
2076 | $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0]; |
||
2077 | } |
||
2078 | |||
2079 | return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster); |
||
2080 | } |
||
2081 | |||
2082 | /** |
||
2083 | * 析构方法 |
||
2084 | * @access public |
||
2085 | */ |
||
2086 | public function __destruct() |
||
2087 | { |
||
2088 | // 关闭连接 |
||
2089 | $this->close(); |
||
2090 | } |
||
2091 | |||
2092 | /** |
||
2093 | * 缓存数据 |
||
2094 | * @access protected |
||
2095 | * @param string $key 缓存标识 |
||
2096 | * @param mixed $data 缓存数据 |
||
2097 | * @param array $config 缓存参数 |
||
2098 | */ |
||
2099 | protected function cacheData($key, $data, $config = []) |
||
2100 | { |
||
2101 | $cache = Container::get('cache'); |
||
2102 | |||
2103 | if (isset($config['tag'])) { |
||
2104 | $cache->tag($config['tag'])->set($key, $data, $config['expire']); |
||
2105 | } else { |
||
2106 | $cache->set($key, $data, $config['expire']); |
||
2107 | } |
||
2108 | } |
||
2109 | |||
2110 | /** |
||
2111 | * 获取缓存数据 |
||
2112 | * @access protected |
||
2113 | * @param Query $query 查询对象 |
||
2114 | * @param mixed $cache 缓存设置 |
||
2115 | * @param array $options 缓存 |
||
2116 | * @return mixed |
||
2117 | */ |
||
2118 | protected function getCacheData(Query $query, $cache, $data, &$key = null) |
||
2119 | { |
||
2120 | // 判断查询缓存 |
||
2121 | $key = is_string($cache['key']) ? $cache['key'] : $this->getCacheKey($query, $data); |
||
2122 | |||
2123 | return Container::get('cache')->get($key); |
||
2124 | } |
||
2125 | |||
2126 | /** |
||
2127 | * 生成缓存标识 |
||
2128 | * @access protected |
||
2129 | * @param Query $query 查询对象 |
||
2130 | * @param mixed $value 缓存数据 |
||
2131 | * @return string |
||
2132 | */ |
||
2133 | protected function getCacheKey(Query $query, $value) |
||
2151 | } |
||
2152 | } |
||
2153 | |||
2154 | } |
||
2155 |