-
Notifications
You must be signed in to change notification settings - Fork 4
/
Driver.php
1499 lines (1404 loc) · 48.5 KB
/
Driver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\db;
use PDO;
use think\exception\PDOException;
abstract class Driver
{
/**
* PDO操作实例
* @var \PDOStatement
*/
protected $PDOStatement = null;
/**
* 当前连接ID
* @var \PDO
*/
protected $_linkID = null;
// 当前操作所属的模型名
protected $model = '_think_';
// 当前SQL指令
protected $queryStr = '';
// 模型SQL
protected $modelSql = [];
// 最后插入ID
protected $lastInsID = null;
// 返回或者影响记录数
protected $numRows = 0;
// 事物操作PDO实例
protected $transPDO = null;
// 事务指令数
protected $transTimes = 0;
// 错误信息
protected $error = '';
// 数据库连接ID 支持多个连接
protected $linkID = [];
// 数据库连接参数配置
protected $config = [
'type' => '', // 数据库类型
'hostname' => '127.0.0.1', // 服务器地址
'database' => '', // 数据库名
'username' => '', // 用户名
'password' => '', // 密码
'hostport' => '', // 端口
'dsn' => '', //
'params' => [], // 数据库连接参数
'charset' => 'utf8', // 数据库编码默认采用utf8
'prefix' => '', // 数据库表前缀
'debug' => false, // 数据库调试模式
'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
'rw_separate' => false, // 数据库读写是否分离 主从式有效
'master_num' => 1, // 读写分离后 主服务器数量
'slave_no' => '', // 指定从服务器序号
'db_like_fields' => '',
];
// 数据库表达式
protected $exp = [
'eq' => '=',
'neq' => '<>',
'gt' => '>',
'egt' => '>=',
'lt' => '<',
'elt' => '<=',
'notlike' => 'NOT LIKE',
'like' => 'LIKE',
'in' => 'IN',
'notin' => 'NOT IN',
'not in' => 'NOT IN',
'between' => 'BETWEEN',
'not between' => 'NOT BETWEEN',
'notbetween' => 'NOT BETWEEN'
];
// 查询表达式
protected $selectSql = '%HINT% SELECT%DISTINCT% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT% %UNION%%LOCK%%COMMENT%';
// 查询次数
protected $queryTimes = 0;
// 执行次数
protected $executeTimes = 0;
// PDO连接参数
protected $options = [
PDO::ATTR_CASE => PDO::CASE_LOWER,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
];
/**
* 服务器断线标识字符
* @var array
*/
protected $breakMatchStr = [
'server has gone away',
'no connection to the server',
'Lost connection',
'is dead or not enabled',
'Error while sending',
'decryption failed or bad record mac',
'server closed the connection unexpectedly',
'SSL connection has been closed unexpectedly',
'Error writing data to the connection',
'Resource deadlock avoided',
'failed with errno',
'child connection forced to terminate due to client_idle_limit',
'query_wait_timeout',
'reset by peer',
'Physical connection is not usable',
'TCP Provider: Error code 0x68',
'ORA-03114',
'Packets out of order. Expected',
'Adaptive Server connection failed',
'Communication link failure',
'connection is no longer usable',
'Login timeout expired',
'SQLSTATE[HY000] [2002] Connection refused',
'running with the --read-only option so it cannot execute this statement',
'The connection is broken and recovery is not possible. The connection is marked by the client driver as unrecoverable. No attempt was made to restore the connection.',
'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Try again',
'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known',
'SQLSTATE[HY000]: General error: 7 SSL SYSCALL error: EOF detected',
'SQLSTATE[HY000] [2002] Connection timed out',
'SSL: Connection timed out',
'SQLSTATE[HY000]: General error: 1105 The last transaction was aborted due to Seamless Scaling. Please retry.',
];
// 参数绑定
protected $bind = [];
/**
* Driver constructor.
* 架构函数 读取数据库配置信息
* @access public
* @param array $config 数据库配置数组
*/
public function __construct($config = [])
{
if (!empty($config)) {
$this->config = array_merge($this->config, $config);
if (is_array($this->config['params'])) {
$this->options = $this->config['params'] + $this->options;
}
}
}
/**
* 连接数据库方法
* @param array $config
* @param int $linkNum
* @param bool $autoConnection
* @return mixed
* @throws \Exception
*/
public function connect($config = [], $linkNum = 0, $autoConnection = false)
{
if (!isset($this->linkID[$linkNum])) {
if (empty($config)) {
$config = $this->config;
}
try {
if (empty($config['dsn'])) {
$config['dsn'] = $this->parseDsn($config);
}
if (version_compare(PHP_VERSION, '5.3.6', '<=')) {
// 禁用模拟预处理语句
$this->options[PDO::ATTR_EMULATE_PREPARES] = false;
}
$this->linkID[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $this->options);
} catch (\PDOException $e) {
if ($autoConnection) {
trace($e->getMessage(), 'ERR');
return $this->connect($autoConnection, $linkNum);
} elseif ($config['debug']) {
StrackE($e->getMessage());
}
}
}
return $this->linkID[$linkNum];
}
/**
* 解析pdo连接的dsn信息
* @param $config
* @return string
*/
protected function parseDsn($config): string
{
}
/**
* 释放查询结果
* @access public
*/
public function free()
{
$this->PDOStatement = null;
}
/**
* 执行查询 返回数据集
* @access public
* @param string $str sql指令
* @param boolean $fetchSql 不执行只是获取SQL
* @param boolean $master 是否在主服务器读操作
* @return array|bool|string
* @throws PDOException
* @throws \Throwable
*/
public function query($str, $fetchSql = false, $master = false)
{
$this->initConnect($master);
if (!$this->_linkID) {
return false;
}
$this->queryStr = $str;
if (!empty($this->bind)) {
$that = $this;
$this->queryStr = strtr($this->queryStr, array_map(function ($val) use ($that) {
return '\'' . $that->escapeString($val) . '\'';
}, $this->bind));
}
if ($fetchSql) {
return $this->queryStr;
}
//释放前次的查询结果
if (!empty($this->PDOStatement)) {
$this->free();
}
$this->queryTimes++;
try {
// 调试开始
$this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str);
if (false === $this->PDOStatement) {
$this->error();
return false;
}
foreach ($this->bind as $key => $val) {
if (is_array($val)) {
$this->PDOStatement->bindValue($key, $val[0], $val[1]);
} else {
$this->PDOStatement->bindValue($key, $val);
}
}
$this->bind = [];
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if (false === $result) {
$this->error();
return false;
} else {
return $this->getResult();
}
} catch (\PDOException | \Exception | \Throwable $e) {
if ($this->transTimes > 0) {
// 当前是开启了事务 避免多层事务失效 直接重置事务计数
if ($this->isBreak($e)) {
$this->transTimes = 0;
}
} else {
if ($this->isBreak($e)) {
return $this->close()->query($str, $fetchSql, $master);
}
}
// 针对pdoException 进行错误信息定制
if ($e instanceof \PDOException) {
throw new PDOException($e, $this->config, $this->getLastsql());
} else {
throw $e;
}
}
}
/**
* 执行语句
* @access public
* @param string $str sql指令
* @param boolean $fetchSql 不执行只是获取SQL
* @return bool|int|string
* @throws PDOException
* @throws \Throwable
*/
public function execute($str, $fetchSql = false)
{
$this->initConnect(true);
if (!$this->_linkID) {
return false;
}
$this->queryStr = $str;
if (!empty($this->bind)) {
$that = $this;
$this->queryStr = strtr($this->queryStr, array_map(function ($val) use ($that) {
return '\'' . $that->escapeString($val) . '\'';
}, $this->bind));
}
if ($fetchSql) {
return $this->queryStr;
}
//释放前次的查询结果
if (!empty($this->PDOStatement)) {
$this->free();
}
$this->executeTimes++;
try {
// 记录开始执行时间
$this->debug(true);
$this->PDOStatement = $this->_linkID->prepare($str);
if (false === $this->PDOStatement) {
$this->error();
return false;
}
foreach ($this->bind as $key => $val) {
if (is_array($val)) {
$this->PDOStatement->bindValue($key, $val[0], $val[1]);
} else {
$this->PDOStatement->bindValue($key, $val);
}
}
$this->bind = [];
$result = $this->PDOStatement->execute();
// 调试结束
$this->debug(false);
if (false === $result) {
$this->error();
return false;
} else {
$this->numRows = $this->PDOStatement->rowCount();
if (preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) {
$this->lastInsID = $this->_linkID->lastInsertId();
}
return $this->numRows;
}
} catch (\PDOException | \Exception | \Throwable $e) {
if ($this->transTimes > 0) {
// 当前是开启了事务 避免多层事务失效 直接重置事务计数
if ($this->isBreak($e)) {
$this->transTimes = 0;
}
} else {
if ($this->isBreak($e)) {
return $this->close()->execute($str, $fetchSql);
}
}
// 针对pdoException 进行错误信息定制
if ($e instanceof \PDOException) {
throw new PDOException($e, $this->config, $this->getLastsql());
} else {
throw $e;
}
}
}
/**
* 启动事务
* @return bool|void
* @throws \Exception
*/
public function startTrans()
{
$this->transTimes++;
$this->initConnect(true);
if (!$this->_linkID) return false;
try {
//数据rollback 支持
if ($this->transTimes == 1) {
$this->_linkID->beginTransaction();
}
} catch (\Exception $e) {
if ($this->isBreak($e)) {
--$this->transTimes;
return $this->close()->startTrans();
}
throw $e;
}
return;
}
/**
* 用于非自动提交状态下面的查询提交
* @return bool
* @throws \Exception
*/
public function commit()
{
if ($this->transTimes == 1) {
$result = $this->_linkID->commit();
$this->transTimes = 0;
if (!$result) {
$this->error();
return false;
}
} else {
--$this->transTimes;
}
return true;
}
/**
* 事务回滚
* @return bool
* @throws \Exception
*/
public function rollback()
{
if ($this->transTimes == 1) {
$result = $this->_linkID->rollback();
$this->transTimes = 0;
if (!$result) {
$this->error();
return false;
}
} else {
--$this->transTimes;
}
return true;
}
/**
* 获得所有的查询数据
* @access private
* @return array
*/
private function getResult()
{
//返回数据集
$result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
$this->numRows = count($result);
return $result;
}
/**
* 获得查询次数
* @access public
* @param boolean $execute 是否包含所有查询
* @return integer
*/
public function getQueryTimes($execute = false)
{
return $execute ? $this->queryTimes + $this->executeTimes : $this->queryTimes;
}
/**
* 获得执行次数
* @access public
* @return integer
*/
public function getExecuteTimes()
{
return $this->executeTimes;
}
/**
* 关闭数据库
* @access public
*/
public function close()
{
$this->linkID = null;
// 释放查询
$this->free();
/**
* 释放事务计数
* 事务是不能跨连接执行的 避免下一次事务被污染
*/
$this->transTimes = 0;
return $this;
}
/**
* 是否断线
* @access protected
* @param \PDOException|\Exception $e 异常对象
* @return bool
*/
protected function isBreak($e)
{
$error = $e->getMessage();
foreach ($this->breakMatchStr as $msg) {
if (false !== stripos($error, $msg)) {
return true;
}
}
return false;
}
/**
* 数据库错误信息,并显示当前的SQL语句
* @return string
* @throws \Exception
*/
public function error()
{
if ($this->PDOStatement) {
$error = $this->PDOStatement->errorInfo();
$this->error = $error[1] . ':' . $error[2];
} else {
$this->error = '';
}
if ('' != $this->queryStr) {
$this->error .= "\n [ SQL语句 ] : " . $this->queryStr;
}
// 记录错误日志
trace($this->error, 'ERR');
if ($this->config['debug']) {
// 开启数据库调试模式
StrackE($this->error);
} else {
return $this->error;
}
}
/**
* 设置锁机制
* @param bool $lock
* @return string
*/
protected function parseLock($lock = false)
{
return $lock ? ' FOR UPDATE ' : '';
}
/**
* set分析
* @access protected
* @param array $data
* @return string
*/
protected function parseSet($data)
{
$set = [];
foreach ($data as $key => $val) {
if (isset($val[0]) && 'exp' == $val[0]) {
$set[] = $this->parseKey($key) . '=' . $val[1];
} elseif (is_null($val)) {
$set[] = $this->parseKey($key) . '=NULL';
} elseif (is_scalar($val)) {
// 过滤非标量数据
if (0 === strpos($val, ':') && in_array($val, array_keys($this->bind))) {
$set[] = $this->parseKey($key) . '=' . $val;
} else {
$name = count($this->bind);
$set[] = $this->parseKey($key) . '=:' . $key . '_' . $name;
$this->bindParam($key . '_' . $name, $val);
}
}
}
return ' SET ' . implode(',', $set);
}
/**
* 参数绑定
* @access protected
* @param string $name 绑定参数名
* @param mixed $value 绑定值
* @return void
*/
protected function bindParam($name, $value)
{
$this->bind[':' . $name] = $value;
}
/**
* 字段名分析
* @param $key
* @param bool $strict
* @return mixed
*/
protected function parseKey($key, $strict = false)
{
return $key;
}
/**
* value分析
* @access protected
* @param mixed $value
* @return string
*/
protected function parseValue($value)
{
if (is_string($value)) {
$value = strpos($value, ':') === 0 && in_array($value, array_keys($this->bind)) ? $this->escapeString($value) : '\'' . $this->escapeString($value) . '\'';
} elseif (isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp') {
$value = $this->escapeString($value[1]);
} elseif (is_array($value)) {
$value = array_map([$this, 'parseValue'], $value);
} elseif (is_bool($value)) {
$value = $value ? '1' : '0';
} elseif (is_null($value)) {
$value = 'null';
}
return $value;
}
/**
* field分析
* @access protected
* @param mixed $fields
* @return string
*/
protected function parseField($fields)
{
if (is_string($fields) && '' !== $fields) {
$fields = explode(',', $fields);
}
if (is_array($fields)) {
// 完善数组方式传字段名的支持
// 支持 'field1'=>'field2' 这样的字段别名定义
$array = [];
foreach ($fields as $key => $field) {
if (!is_numeric($key)) {
$array[] = $this->parseKey($key) . ' AS ' . $this->parseKey($field);
} else {
$array[] = $this->parseKey($field);
}
}
$fieldsStr = implode(',', $array);
} else {
$fieldsStr = '*';
}
return $fieldsStr;
}
/**
* table分析
* @access protected
* @param mixed $tables
* @return string
*/
protected function parseTable($tables)
{
if (is_array($tables)) {
// 支持别名定义
$array = [];
foreach ($tables as $table => $alias) {
if (!is_numeric($table)) {
$array[] = $this->parseKey($table) . ' ' . $this->parseKey($alias);
} else {
$array[] = $this->parseKey($alias);
}
}
$tables = $array;
} elseif (is_string($tables)) {
$tables = array_map([$this, 'parseKey'], explode(',', $tables));
}
return implode(',', $tables);
}
/**
* where分析
* @access protected
* @param mixed $where
* @return string
* @throws \Exception
*/
protected function parseWhere($where)
{
$whereStr = '';
if (is_string($where)) {
// 直接使用字符串条件
$whereStr = $where;
} else {
// 使用数组表达式
$operate = isset($where['_logic']) ? strtoupper($where['_logic']) : '';
if (in_array($operate, ['AND', 'OR', 'XOR'])) {
// 定义逻辑运算规则 例如 OR XOR AND NOT
$operate = ' ' . $operate . ' ';
unset($where['_logic']);
} else {
// 默认进行 AND 运算
$operate = ' AND ';
}
foreach ($where as $key => $val) {
if (is_numeric($key)) {
$key = '_complex';
}
if (0 === strpos($key, '_')) {
// 解析特殊条件表达式
$whereStr .= $this->parseThinkWhere($key, $val);
} else {
// 查询字段的安全过滤
// if(!preg_match('/^[A-Z_\|\&\-.a-z0-9\(\)\,]+$/',trim($key))){
// StrackE(L('_EXPRESS_ERROR_').':'.$key);
// }
// 多条件支持
$multi = is_array($val) && isset($val['_multi']);
$key = trim($key);
$str = [];
if (strpos($key, '|')) {
// 支持 name|title|nickname 方式定义查询字段
$array = explode('|', $key);
foreach ($array as $m => $k) {
$v = $multi ? $val[$m] : $val;
$str[] = $this->parseWhereItem($this->parseKey($k), $v);
}
$whereStr .= '( ' . implode(' OR ', $str) . ' )';
} elseif (strpos($key, '&')) {
$array = explode('&', $key);
foreach ($array as $m => $k) {
$v = $multi ? $val[$m] : $val;
$str[] = '(' . $this->parseWhereItem($this->parseKey($k), $v) . ')';
}
$whereStr .= '( ' . implode(' AND ', $str) . ' )';
} else {
$whereStr .= $this->parseWhereItem($this->parseKey($key), $val);
}
}
$whereStr .= $operate;
}
$whereStr = substr($whereStr, 0, -strlen($operate));
}
return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
}
/**
* where子单元分析
* @param $key
* @param $val
* @return string
* @throws \Exception
*/
protected function parseWhereItem($key, $val)
{
$whereStr = '';
if (is_array($val)) {
if (is_string($val[0])) {
$exp = strtolower($val[0]);
if (preg_match('/^(eq|neq|gt|egt|lt|elt)$/', $exp)) {
// 比较运算
$whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
} elseif (preg_match('/^(notlike|like)$/', $exp)) {
// 模糊查找
if (is_array($val[1])) {
$likeLogic = isset($val[2]) ? strtoupper($val[2]) : 'OR';
if (in_array($likeLogic, ['AND', 'OR', 'XOR'])) {
$like = [];
foreach ($val[1] as $item) {
$like[] = $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($item);
}
$whereStr .= '(' . implode(' ' . $likeLogic . ' ', $like) . ')';
}
} else {
$whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($val[1]);
}
} elseif ('bind' == $exp) {
// 使用表达式
$whereStr .= $key . ' = :' . $val[1];
} elseif ('find_in_set' == $exp) {
$whereStr .= 'FIND_IN_SET(\'' . $val[1] . '\',' . $key . ')';
} elseif ('exp' == $exp) {
// 使用表达式
$whereStr .= $key . ' ' . $val[1];
} elseif (preg_match('/^(notin|not in|in)$/', $exp)) {
// IN 运算
if (isset($val[2]) && 'exp' == $val[2]) {
$whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $val[1];
} else {
if (is_string($val[1])) {
$val[1] = explode(',', $val[1]);
}
$zone = implode(',', $this->parseValue($val[1]));
$whereStr .= $key . ' ' . $this->exp[$exp] . ' (' . $zone . ')';
}
} elseif (preg_match('/^(notbetween|not between|between)$/', $exp)) {
// BETWEEN运算
$data = is_string($val[1]) ? explode(',', $val[1]) : $val[1];
$whereStr .= $key . ' ' . $this->exp[$exp] . ' ' . $this->parseValue($data[0]) . ' AND ' . $this->parseValue($data[1]);
} else {
StrackE(L('_EXPRESS_ERROR_') . ':' . $val[0]);
}
} else {
$count = count($val);
$rule = isset($val[$count - 1]) ? (is_array($val[$count - 1]) ? strtoupper($val[$count - 1][0]) : strtoupper($val[$count - 1])) : '';
if (in_array($rule, ['AND', 'OR', 'XOR'])) {
$count = $count - 1;
} else {
$rule = 'AND';
}
for ($i = 0; $i < $count; $i++) {
$data = is_array($val[$i]) ? $val[$i][1] : $val[$i];
if ('exp' == strtolower($val[$i][0])) {
$whereStr .= $key . ' ' . $data . ' ' . $rule . ' ';
} else {
$whereStr .= $this->parseWhereItem($key, $val[$i]) . ' ' . $rule . ' ';
}
}
$whereStr = '( ' . substr($whereStr, 0, -4) . ' )';
}
} else {
//对字符串类型字段采用模糊匹配
$likeFields = $this->config['db_like_fields'];
if ($likeFields && preg_match('/^(' . $likeFields . ')$/i', $key)) {
$whereStr .= $key . ' LIKE ' . $this->parseValue('%' . $val . '%');
} else {
$whereStr .= $key . ' = ' . $this->parseValue($val);
}
}
return $whereStr;
}
/**
* 特殊条件分析
* @access protected
* @param $key
* @param $val
* @return string
* @throws \Exception
*/
protected function parseThinkWhere($key, $val)
{
$whereStr = '';
switch ($key) {
case '_string':
// 字符串模式查询条件
$whereStr = $val;
break;
case '_complex':
// 复合查询条件
$whereStr = substr($this->parseWhere($val), 6);
break;
case '_query':
// 字符串模式查询条件
parse_str($val, $where);
if (isset($where['_logic'])) {
$op = ' ' . strtoupper($where['_logic']) . ' ';
unset($where['_logic']);
} else {
$op = ' AND ';
}
$array = [];
foreach ($where as $field => $data) {
$array[] = $this->parseKey($field) . ' = ' . $this->parseValue($data);
}
$whereStr = implode($op, $array);
break;
}
return '( ' . $whereStr . ' )';
}
/**
* limit分析
* @param $limit
* @return string
*/
protected function parseLimit($limit)
{
return (!empty($limit) && false === strpos($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
}
/**
* join分析
* @access protected
* @param mixed $join
* @return string
*/
protected function parseJoin($join)
{
$joinStr = '';
if (!empty($join)) {
$joinStr = ' ' . implode(' ', $join) . ' ';
}
return $joinStr;
}
/**
* order分析
* @access protected
* @param mixed $order
* @return string
*/
protected function parseOrder($order)
{
if (empty($order)) {
return '';
}
$array = [];
if (is_array($order)) {
foreach ($order as $key => $val) {
if (is_numeric($key)) {
if (false === strpos($val, '(')) {
$array[] = $this->parseKey($val);
} else {
// 复杂order条件 包含 () JSON_EXTRACT
$array[] = $val;
}
} else {
$sort = in_array(strtolower($val), ['asc', 'desc']) ? ' ' . $val : '';
$array[] = $this->parseKey($key, true) . $sort;
}
}
} elseif ('[RAND]' == $order) {
// 随机排序
$array[] = $this->parseRand();
} else {
foreach (explode(',', $order) as $val) {
if (preg_match('/\s+(ASC|DESC)$/i', rtrim($val), $match, PREG_OFFSET_CAPTURE)) {
$array[] = $this->parseKey(ltrim(substr($val, 0, $match[0][1]))) . ' ' . $match[1][0];
} elseif (false === strpos($val, '(')) {
$array[] = $this->parseKey($val);
}
}
}
$order = implode(',', $array);
return !empty($order) ? ' ORDER BY ' . $order : '';
}
/**
* group分析
* @access protected
* @param mixed $group
* @return string
*/
protected function parseGroup($group)
{
return !empty($group) ? ' GROUP BY ' . $group : '';
}
/**
* having分析
* @access protected
* @param string $having
* @return string
*/
protected function parseHaving($having)
{
return !empty($having) ? ' HAVING ' . $having : '';
}
/**
* comment分析
* @access protected
* @param string $comment
* @return string
*/
protected function parseComment($comment)
{
return !empty($comment) ? ' /* ' . $comment . ' */' : '';
}
/**
* 增加 Hint
* @param $hint
* @return string
*/
protected function parseHint($hint)
{
return !empty($hint) ? '/*' . $hint . '*/' : '';
}
/**
* distinct分析
* @access protected
* @param mixed $distinct
* @return string
*/
protected function parseDistinct($distinct)
{
return !empty($distinct) ? ' DISTINCT ' : '';
}
/**
* union分析