chengkun
2025-06-05 4080b5997b38ca84b3b203c7101dcadb97b76925
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
<?php
 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
 
namespace think\db;
 
use BackedEnum;
use Closure;
use Stringable;
use think\db\BaseQuery as Query;
use think\db\exception\DbException as Exception;
use UnitEnum;
 
/**
 * Db Builder.
 */
class Builder extends BaseBuilder
{
 
    /**
     * 数据分析.
     *
     * @param Query $query  查询对象
     * @param array $data   数据
     * @param array $fields 字段信息
     * @param array $bind   参数绑定
     *
     * @return array
     */
    protected function parseData(Query $query, array $data = [], array $fields = [], array $bind = []): array
    {
        if (empty($data)) {
            return [];
        }
 
        $options = $query->getOptions();
 
        // 获取绑定信息
        if (empty($bind)) {
            $bind = $query->getFieldsBindType();
        }
 
        if (empty($fields)) {
            if (empty($options['field']) || '*' == $options['field']) {
                $fields = array_keys($bind);
            } else {
                $fields = $options['field'];
            }
        }
 
        $result = [];
 
        foreach ($data as $key => $val) {
            $item = $this->parseKey($query, $key, true);
            if ($val instanceof BackedEnum) {
                $val = $val->value;
            } elseif ($val instanceof UnitEnum) {
                $val = $val->name;
            } elseif ($val instanceof Raw) {
                $result[$item] = $this->parseRaw($query, $val);
                continue;
            } elseif (is_null($val) && in_array($key, $fields, true)) {
                $result[$item] = 'NULL';
                continue;
            } elseif (!is_scalar($val) && (in_array($key, (array) $query->getOptions('json')) || 'json' == $query->getFieldType($key))) {
                $val = json_encode($val);
            }
 
            if (str_contains($key, '->')) {
                [$key, $name] = explode('->', $key, 2);
                $item         = $this->parseKey($query, $key);
 
                $result[$item . '->' . $name] = 'json_set(' . $item . ', \'$.' . $name . '\', ' . $this->parseDataBind($query, $key . '->' . $name, $val, $bind) . ')';
            } elseif (!str_contains($key, '.') && !in_array($key, $fields, true)) {
                if ($options['strict']) {
                    throw new Exception('fields not exists:[' . $key . ']');
                }
            } elseif (is_array($val) && !empty($val) && is_string($val[0])) {
                if (in_array(strtoupper($val[0]), ['INC', 'DEC'])) {
                    $result[$item] = match (strtoupper($val[0])) {
                        'INC' => $item . ' + ' . floatval($val[1]),
                        'DEC' => $item . ' - ' . floatval($val[1]),
                    };
                }
            } elseif (is_scalar($val)) {
                // 过滤非标量数据
                if (!$query->isAutoBind() && Connection::PARAM_STR == $bind[$key]) {
                    $val = '\'' . $val . '\'';
                }
                $result[$item] = !$query->isAutoBind() ? $val : $this->parseDataBind($query, $key, $val, $bind);
            }
        }
 
        return $result;
    }
 
    /**
     * 数据绑定处理.
     *
     * @param Query  $query 查询对象
     * @param string $key   字段名
     * @param mixed  $data  数据
     * @param array  $bind  绑定数据
     *
     * @return string
     */
    protected function parseDataBind(Query $query, string $key, $data, array $bind = []): string
    {
        if ($data instanceof Raw) {
            return $this->parseRaw($query, $data);
        }
 
        $name = $query->bindValue($data, $bind[$key] ?? Connection::PARAM_STR);
 
        return ':' . $name;
    }
 
    /**
     * 字段名分析.
     *
     * @param Query $query  查询对象
     * @param mixed $key    字段名
     * @param bool  $strict 严格检测
     *
     * @return string
     */
    public function parseKey(Query $query, string | int | Raw $key, bool $strict = false): string
    {
        return $key;
    }
 
    /**
     * 查询额外参数分析.
     *
     * @param Query  $query 查询对象
     * @param string $extra 额外参数
     *
     * @return string
     */
    protected function parseExtra(Query $query, string $extra): string
    {
        return preg_match('/^[\w]+$/i', $extra) ? ' ' . strtoupper($extra) : '';
    }
 
    /**
     * field分析.
     *
     * @param Query $query  查询对象
     * @param array $fields 字段名
     *
     * @return string
     */
    protected function parseField(Query $query, array $fields): string
    {
        if (empty($fields)) {
            return '*';
        }
 
        // 支持 'field1' => 'field2' 这样的字段别名定义
        $array = array_map(function ($field, $key) use ($query) {
            if ($field instanceof Raw) {
                return $this->parseRaw($query, $field);
            } elseif (!is_numeric($key)) {
                // 字段别名定义
                return $this->parseKey($query, $key) . ' AS ' . $this->parseKey($query, $field, true);
            } else {
                return $this->parseKey($query, $field);
            }
        }, $fields, array_keys($fields));
 
        return implode(',', $array);
    }
 
    /**
     * table分析.
     *
     * @param Query $query  查询对象
     * @param array|string $tables 表名
     *
     * @return string
     */
    protected function parseTable(Query $query, array | string $tables): string
    {
        $item    = [];
        $options = $query->getOptions();
 
        foreach ((array) $tables as $key => $table) {
            if ($table instanceof Raw) {
                $item[] = $this->parseRaw($query, $table);
            } elseif (!is_numeric($key)) {
                $item[] = $this->parseKey($query, $key) . ' ' . $this->parseKey($query, $table);
            } elseif (isset($options['alias'][$table])) {
                $item[] = $this->parseKey($query, $table) . ' ' . $this->parseKey($query, $options['alias'][$table]);
            } else {
                $item[] = $this->parseKey($query, $table);
            }
        }
 
        return implode(',', $item);
    }
 
    /**
     * where分析.
     *
     * @param Query $query 查询对象
     * @param array $where 查询条件
     *
     * @return string
     */
    protected function parseWhere(Query $query, array $where): string
    {
        $options  = $query->getOptions();
        $whereStr = $this->buildWhere($query, $where);
 
        if (!empty($options['soft_delete'])) {
            // 附加软删除条件
            [$field, $condition] = $options['soft_delete'];
 
            $binds    = $query->getFieldsBindType();
            $whereStr = $whereStr ? '( ' . $whereStr . ' ) AND ' : '';
            $whereStr = $whereStr . $this->parseWhereItem($query, $field, $condition, $binds);
        }
 
        return empty($whereStr) ? '' : ' WHERE ' . $whereStr;
    }
 
    /**
     * where子单元分析.
     *
     * @param Query $query 查询对象
     * @param mixed $field 查询字段
     * @param array $val   查询条件
     * @param array $binds 参数绑定
     *
     * @return string
     */
    protected function parseWhereItem(Query $query, $field, array $val, array $binds = []): string
    {
        // 字段分析
        $key = $field ? $this->parseKey($query, $field, true) : '';
 
        [$exp, $value] = $val;
 
        // 检测操作符
        if (!is_string($exp)) {
            throw new Exception('where express error:' . var_export($exp, true));
        }
 
        $exp = strtoupper($exp);
        if (isset($this->exp[$exp])) {
            $exp = $this->exp[$exp];
        }
 
        if (is_string($field) && 'LIKE' != $exp) {
            $bindType = $binds[$field] ?? Connection::PARAM_STR;
        } else {
            $bindType = Connection::PARAM_STR;
        }
 
        if ($value instanceof Raw) {
        } elseif ($value instanceof Stringable) {
            // 对象数据写入
            $value = $value->__toString();
        } elseif ($value instanceof BackedEnum) {
            $value = $value->value;
        } elseif ($value instanceof UnitEnum) {
            $value = $value->name;
        }
 
        if (is_scalar($value) && !in_array($exp, ['EXP', 'NOT NULL', 'NULL', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN']) && !str_contains($exp, 'TIME')) {
            if (is_string($value) && str_starts_with($value, ':') && $query->isBind(substr($value, 1))) {
            } else {
                $name  = $query->bindValue($value, $bindType);
                $value = ':' . $name;
            }
        }
 
        // 解析查询表达式
        foreach ($this->parser as $fun => $parse) {
            if (in_array($exp, $parse)) {
                return $this->$fun($query, $key, $exp, $value, $field, $bindType, $val[2] ?? 'AND');
            }
        }
 
        throw new Exception('where express error:' . $exp);
    }
 
    /**
     * 模糊查询.
     *
     * @param Query  $query    查询对象
     * @param string $key
     * @param string $exp
     * @param array  $value
     * @param string $field
     * @param int    $bindType
     * @param string $logic
     *
     * @return string
     */
    protected function parseLike(Query $query, string $key, string $exp, $value, $field, int $bindType, string $logic): string
    {
        // 模糊匹配
        if (is_array($value)) {
            $array = [];
            foreach ($value as $item) {
                $name    = $query->bindValue($item, Connection::PARAM_STR);
                $array[] = $key . ' ' . $exp . ' :' . $name;
            }
 
            $whereStr = '(' . implode(' ' . strtoupper($logic) . ' ', $array) . ')';
        } else {
            $whereStr = $key . ' ' . $exp . ' ' . $value;
        }
 
        return $whereStr;
    }
 
    /**
     * 表达式查询.
     *
     * @param Query  $query    查询对象
     * @param string $key
     * @param string $exp
     * @param Raw    $value
     * @param string $field
     * @param int    $bindType
     *
     * @return string
     */
    protected function parseExp(Query $query, string $key, string $exp, Raw $value, string $field, int $bindType): string
    {
        // 表达式查询
        return '( ' . $key . ' ' . $this->parseRaw($query, $value) . ' )';
    }
 
    /**
     * Null查询.
     *
     * @param Query  $query    查询对象
     * @param string $key
     * @param string $exp
     * @param mixed  $value
     * @param string $field
     * @param int    $bindType
     *
     * @return string
     */
    protected function parseNull(Query $query, string $key, string $exp, $value, $field, int $bindType): string
    {
        // NULL 查询
        return $key . ' IS ' . $exp;
    }
 
    /**
     * 范围查询.
     *
     * @param Query  $query    查询对象
     * @param string $key
     * @param string $exp
     * @param mixed  $value
     * @param string $field
     * @param int    $bindType
     *
     * @return string
     */
    protected function parseBetween(Query $query, string $key, string $exp, array | string $value, $field, int $bindType): string
    {
        // BETWEEN 查询
        $data = is_array($value) ? $value : explode(',', $value);
 
        $min = $query->bindValue($data[0], $bindType);
        $max = $query->bindValue($data[1], $bindType);
 
        return $key . ' ' . $exp . ' :' . $min . ' AND :' . $max . ' ';
    }
 
    /**
     * IN查询.
     *
     * @param Query  $query    查询对象
     * @param string $key
     * @param string $exp
     * @param mixed  $value
     * @param string $field
     * @param int    $bindType
     *
     * @return string
     */
    protected function parseIn(Query $query, string $key, string $exp, $value, $field, int $bindType): string
    {
        // IN 查询
        if ($value instanceof Closure) {
            $value = $this->parseClosure($query, $value, false);
        } elseif ($value instanceof Raw) {
            $value = $this->parseRaw($query, $value);
        } else {
            $value = array_unique(is_array($value) ? $value : explode(',', (string) $value));
            if (count($value) === 0) {
                return 'IN' == $exp ? '0 = 1' : '1 = 1';
            }
 
            if ($query->isAutoBind()) {
                $array = [];
                foreach ($value as $v) {
                    $name    = $query->bindValue($v, $bindType);
                    $array[] = ':' . $name;
                }
                $value = implode(',', $array);
            } elseif (Connection::PARAM_STR == $bindType) {
                $value = '\'' . implode('\',\'', $value) . '\'';
            } else {
                $value = implode(',', $value);
            }
 
            if (!str_contains($value, ',')) {
                return $key . ('IN' == $exp ? ' = ' : ' <> ') . $value;
            }
        }
 
        return $key . ' ' . $exp . ' (' . $value . ')';
    }
 
    /**
     * 日期时间条件解析.
     *
     * @param Query  $query    查询对象
     * @param mixed  $value
     * @param string $key
     * @param int    $bindType
     *
     * @return string
     */
    protected function parseDateTime(Query $query, $value, string $key, int $bindType): string
    {
        $options = $query->getOptions();
 
        // 获取时间字段类型
        if (str_contains($key, '.')) {
            [$table, $key] = explode('.', $key);
 
            if (isset($options['alias']) && $pos = array_search($table, $options['alias'])) {
                $table = $pos;
            }
        } else {
            $table = $options['table'];
        }
 
        $type = $query->getFieldType($key);
 
        if ($type) {
            if (is_string($value)) {
                $value = strtotime($value) ?: $value;
            }
 
            if (is_int($value)) {
                if (preg_match('/(datetime|timestamp)/is', $type)) {
                    // 日期及时间戳类型
                    $value = date('Y-m-d H:i:s', $value);
                } elseif (preg_match('/(date)/is', $type)) {
                    // 日期及时间戳类型
                    $value = date('Y-m-d', $value);
                }
            }
        }
 
        $name = $query->bindValue($value, $bindType);
 
        return ':' . $name;
    }
 
    /**
     * limit分析.
     *
     * @param Query $query 查询对象
     * @param mixed $limit
     *
     * @return string
     */
    protected function parseLimit(Query $query, string $limit): string
    {
        return (!empty($limit) && !str_contains($limit, '(')) ? ' LIMIT ' . $limit . ' ' : '';
    }
 
    /**
     * join分析.
     *
     * @param Query $query 查询对象
     * @param array $join
     *
     * @return string
     */
    protected function parseJoin(Query $query, array $join): string
    {
        $joinStr = '';
 
        foreach ($join as $item) {
            [$table, $type, $on] = $item;
 
            if (str_contains($on, '=')) {
                [$val1, $val2] = explode('=', $on, 2);
 
                $condition = $this->parseKey($query, $val1) . '=' . $this->parseKey($query, $val2);
            } else {
                $condition = $on;
            }
 
            $table = $this->parseTable($query, $table);
 
            $joinStr .= ' ' . $type . ' JOIN ' . $table . ' ON ' . $condition;
        }
 
        return $joinStr;
    }
 
    /**
     * order分析.
     *
     * @param Query $query 查询对象
     * @param array $order
     *
     * @return string
     */
    protected function parseOrder(Query $query, array $order): string
    {
        $array = [];
        foreach ($order as $key => $val) {
            if ($val instanceof Raw) {
                $array[] = $this->parseRaw($query, $val);
            } elseif (is_array($val) && preg_match('/^[\w\.]+$/', $key)) {
                $array[] = $this->parseOrderField($query, $key, $val);
            } elseif ('[rand]' == $val) {
                $array[] = $this->parseRand($query);
            } elseif (is_string($val)) {
                if (is_numeric($key)) {
                    [$key, $sort] = explode(' ', str_contains($val, ' ') ? $val : $val . ' ');
                } else {
                    $sort = $val;
                }
 
                if (preg_match('/^[\w\.]+$/', $key)) {
                    $sort    = strtoupper($sort);
                    $sort    = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
                    $array[] = $this->parseKey($query, $key, true) . $sort;
                } else {
                    throw new Exception('order express error:' . $key);
                }
            }
        }
 
        return empty($array) ? '' : ' ORDER BY ' . implode(',', $array);
    }
 
    /**
     * 分析Raw对象
     *
     * @param Query $query 查询对象
     * @param Raw   $raw   Raw对象
     *
     * @return string
     */
    protected function parseRaw(Query $query, Raw $raw): string
    {
        $sql  = $raw->getValue();
        $bind = $raw->getBind();
 
        if ($bind) {
            $query->bindParams($sql, $bind);
        }
 
        return $sql;
    }
 
    /**
     * 随机排序.
     *
     * @param Query $query 查询对象
     *
     * @return string
     */
    protected function parseRand(Query $query): string
    {
        return '';
    }
 
    /**
     * orderField分析.
     *
     * @param Query  $query 查询对象
     * @param string $key
     * @param array  $val
     *
     * @return string
     */
    protected function parseOrderField(Query $query, string $key, array $val): string
    {
        if (isset($val['sort'])) {
            $sort = $val['sort'];
            unset($val['sort']);
        } else {
            $sort = '';
        }
 
        $sort = strtoupper($sort);
        $sort = in_array($sort, ['ASC', 'DESC'], true) ? ' ' . $sort : '';
        $bind = $query->getFieldsBindType();
 
        foreach ($val as $k => $item) {
            $val[$k] = $this->parseDataBind($query, $key, $item, $bind);
        }
 
        return 'field(' . $this->parseKey($query, $key, true) . ',' . implode(',', $val) . ')' . $sort;
    }
 
    /**
     * group分析.
     *
     * @param Query $query 查询对象
     * @param mixed $group
     *
     * @return string
     */
    protected function parseGroup(Query $query, string | array $group): string
    {
        if (empty($group)) {
            return '';
        }
 
        if (is_string($group)) {
            $group = explode(',', $group);
        }
 
        $val = [];
        foreach ($group as $key) {
            $val[] = $this->parseKey($query, $key);
        }
 
        return ' GROUP BY ' . implode(',', $val);
    }
 
    /**
     * having分析.
     *
     * @param Query  $query  查询对象
     * @param string $having
     *
     * @return string
     */
    protected function parseHaving(Query $query, string $having): string
    {
        return !empty($having) ? ' HAVING ' . $having : '';
    }
 
    /**
     * comment分析.
     *
     * @param Query  $query   查询对象
     * @param string $comment
     *
     * @return string
     */
    protected function parseComment(Query $query, string $comment): string
    {
        if (str_contains($comment, '*/')) {
            $comment = strstr($comment, '*/', true);
        }
 
        return !empty($comment) ? ' /* ' . $comment . ' */' : '';
    }
 
    /**
     * distinct分析.
     *
     * @param Query $query    查询对象
     * @param mixed $distinct
     *
     * @return string
     */
    protected function parseDistinct(Query $query, bool $distinct): string
    {
        return !empty($distinct) ? ' DISTINCT ' : '';
    }
 
    /**
     * index分析,可在操作链中指定需要强制使用的索引.
     *
     * @param Query $query 查询对象
     * @param mixed $index
     *
     * @return string
     */
    protected function parseForce(Query $query, string | array $index): string
    {
        if (empty($index)) {
            return '';
        }
 
        if (is_array($index)) {
            $index = implode(',', $index);
        }
 
        return sprintf(' FORCE INDEX ( %s ) ', $index);
    }
 
    /**
     * 设置锁机制.
     *
     * @param Query       $query 查询对象
     * @param bool|string $lock
     *
     * @return string
     */
    protected function parseLock(Query $query, bool | string $lock = false): string
    {
        if (is_bool($lock)) {
            return $lock ? ' FOR UPDATE ' : '';
        }
 
        if (is_string($lock) && !empty($lock)) {
            return ' ' . trim($lock) . ' ';
        }
        return '';
    }
 
    /**
     * 生成insertall SQL.
     *
     * @param Query $query   查询对象
     * @param  array $keys  字段名
     * @param  array $datas 数据
     *
     * @return string
     */
    public function insertAllByKeys(Query $query, array $keys, array $datas): string
    {
        $options = $query->getOptions();
 
        // 获取绑定信息
        $bind   = $query->getFieldsBindType();
        $fields = [];
        $values = [];
 
        foreach ($keys as $field) {
            $fields[] = $this->parseKey($query, $field);
        }
 
        foreach ($datas as $k => $data) {
            foreach ($data as $key => &$val) {
                if (!$query->isAutoBind()) {
                    $val = Connection::PARAM_STR == $bind[$keys[$key]] ? '\'' . $val . '\'' : $val;
                } else {
                    $val = $this->parseDataBind($query, $keys[$key], $val, $bind);
                }
            }
 
            $values[] = 'SELECT ' . implode(',', $data);
        }
 
        return str_replace(
            ['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'],
            [
                !empty($options['replace']) ? 'REPLACE' : 'INSERT',
                $this->parseTable($query, $options['table']),
                $this->parseExtra($query, $options['extra']),
                implode(' , ', $fields),
                implode(' UNION ALL ', $values),
                $this->parseComment($query, $options['comment']),
            ],
            $this->insertAllSql
        );
    }
}