chengkun
2025-09-12 b21e53f16f228d3192eb54178f081395878b2406
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
<?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 think\db\BaseQuery as Query;
use think\db\exception\DbException as Exception;
use think\helper\Str;
 
/**
 * SQL获取类.
 */
class Fetch
{
    /**
     * Connection对象
     *
     * @var Connection
     */
    protected $connection;
 
    /**
     * Builder对象
     *
     * @var Builder
     */
    protected $builder;
 
    /**
     * 创建一个查询SQL获取对象
     *
     * @param Query $query 查询对象
     */
    public function __construct(protected Query $query)
    {
        $this->connection = $query->getConnection();
        $this->builder    = $this->connection->getBuilder();
    }
 
    /**
     * 聚合查询.
     *
     * @param string $aggregate 聚合方法
     * @param string $field     字段名
     *
     * @return string
     */
    protected function aggregate(string $aggregate, string $field): string
    {
        $this->query->parseOptions();
 
        $field = $aggregate . '(' . $this->builder->parseKey($this->query, $field) . ') AS think_' . strtolower($aggregate);
 
        return $this->value($field, 0, false);
    }
 
    /**
     * 得到某个字段的值
     *
     * @param string $field   字段名
     * @param mixed  $default 默认值
     * @param bool   $one
     *
     * @return string
     */
    public function value(string $field, $default = null, bool $one = true): string
    {
        $options = $this->query->parseOptions();
 
        if (isset($options['field'])) {
            $this->query->removeOption('field');
        }
 
        $this->query->setOption('field', (array) $field);
 
        // 生成查询SQL
        $sql = $this->builder->select($this->query, $one);
 
        if (isset($options['field'])) {
            $this->query->setOption('field', $options['field']);
        } else {
            $this->query->removeOption('field');
        }
 
        return $this->fetch($sql);
    }
 
    /**
     * 得到某个列的数组.
     *
     * @param string $field 字段名 多个字段用逗号分隔
     * @param string $key   索引
     *
     * @return string
     */
    public function column(string $field, string $key = ''): string
    {
        $options = $this->query->parseOptions();
 
        if (isset($options['field'])) {
            $this->query->removeOption('field');
        }
 
        if ($key && '*' != $field) {
            $field = $key . ',' . $field;
        }
 
        $field = array_map('trim', explode(',', $field));
 
        $this->query->setOption('field', $field);
 
        // 生成查询SQL
        $sql = $this->builder->select($this->query);
 
        if (isset($options['field'])) {
            $this->query->setOption('field', $options['field']);
        } else {
            $this->query->removeOption('field');
        }
 
        return $this->fetch($sql);
    }
 
    /**
     * 插入记录.
     *
     * @param array $data 数据
     *
     * @return string
     */
    public function insert(array $data = []): string
    {
        $options = $this->query->parseOptions();
 
        if (!empty($data)) {
            $this->query->setOption('data', $data);
        }
 
        $sql = $this->builder->insert($this->query);
 
        return $this->fetch($sql);
    }
 
    /**
     * 插入记录并获取自增ID.
     *
     * @param array $data 数据
     *
     * @return string
     */
    public function insertGetId(array $data = []): string
    {
        return $this->insert($data);
    }
 
    /**
     * 保存数据 自动判断insert或者update.
     *
     * @param array $data        数据
     * @param bool  $forceInsert 是否强制insert
     *
     * @return string
     */
    public function save(array $data = [], bool $forceInsert = false): string
    {
        if ($forceInsert) {
            return $this->insert($data);
        }
 
        $data = array_merge($this->query->getOptions('data') ?: [], $data);
 
        $this->query->setOption('data', $data);
 
        if ($this->query->getOptions('where')) {
            $isUpdate = true;
        } else {
            $isUpdate = $this->query->parseUpdateData($data);
        }
 
        return $isUpdate ? $this->update() : $this->insert();
    }
 
    /**
     * 批量插入记录.
     *
     * @param array $dataSet 数据集
     * @param int   $limit   每次写入数据限制
     *
     * @return string
     */
    public function insertAll(array $dataSet = [], ?int $limit = null): string
    {
        $options = $this->query->parseOptions();
 
        if (empty($dataSet)) {
            $dataSet = $options['data'];
        }
 
        if (empty($limit) && !empty($options['limit'])) {
            $limit = $options['limit'];
        }
 
        if ($limit) {
            $array    = array_chunk($dataSet, $limit, true);
            $fetchSql = [];
            foreach ($array as $item) {
                $sql  = $this->builder->insertAll($this->query, $item);
                $bind = $this->query->getBind();
 
                $fetchSql[] = $this->connection->getRealSql($sql, $bind);
            }
 
            return implode(';', $fetchSql);
        }
 
        $sql = $this->builder->insertAll($this->query, $dataSet);
 
        return $this->fetch($sql);
    }
 
    /**
     * 通过Select方式插入记录.
     *
     * @param array  $fields 要插入的数据表字段名
     * @param string $table  要插入的数据表名
     *
     * @return string
     */
    public function selectInsert(array $fields, string $table): string
    {
        $this->query->parseOptions();
 
        $sql = $this->builder->selectInsert($this->query, $fields, $table);
 
        return $this->fetch($sql);
    }
 
    /**
     * 字段值增长
     *
     * @param string    $field 字段名
     * @param float     $step  步进值
     * @param int       $lazyTime 延迟时间(秒)
     *
     * @return string
     */
    public function setInc(string $field, float $step = 1, int $lazyTime = 0)
    {
        return $this->inc($field, $step)->update();
    }
 
    /**
     * 字段值减少
     *
     * @param string    $field 字段名
     * @param float     $step  步进值
     * @param int       $lazyTime 延迟时间(秒)
     *
     * @return string
     */
    public function setDec(string $field, float $step = 1, int $lazyTime = 0)
    {
        return $this->dec($field, $step)->update();
    }
 
    /**
     * 更新记录.
     *
     * @param mixed $data 数据
     *
     * @return string
     */
    public function update(array $data = []): string
    {
        $options = $this->query->parseOptions();
 
        $data = !empty($data) ? $data : $options['data'];
 
        $pk = $this->query->getPk();
 
        if (empty($options['where'])) {
            // 如果存在主键数据 则自动作为更新条件
            if (is_string($pk) && isset($data[$pk])) {
                $this->query->where($pk, '=', $data[$pk]);
                unset($data[$pk]);
            } elseif (is_array($pk)) {
                // 增加复合主键支持
                foreach ($pk as $field) {
                    if (isset($data[$field])) {
                        $this->query->where($field, '=', $data[$field]);
                    } else {
                        // 如果缺少复合主键数据则不执行
                        throw new Exception('miss complex primary data');
                    }
                    unset($data[$field]);
                }
            }
 
            if (empty($this->query->getOptions('where'))) {
                // 如果没有任何更新条件则不执行
                throw new Exception('miss update condition');
            }
        }
 
        // 更新数据
        $this->query->setOption('data', $data);
 
        // 生成UPDATE SQL语句
        $sql = $this->builder->update($this->query);
 
        return $this->fetch($sql);
    }
 
    /**
     * 删除记录.
     *
     * @param mixed $data 表达式 true 表示强制删除
     *
     * @return string
     */
    public function delete($data = null): string
    {
        $options = $this->query->parseOptions();
 
        if (!is_null($data) && true !== $data) {
            // AR模式分析主键条件
            $this->query->parsePkWhere($data);
        }
 
        if (!empty($options['soft_delete'])) {
            // 软删除
            [$field, $condition] = $options['soft_delete'];
            if ($condition) {
                $this->query->setOption('soft_delete', null);
                $this->query->setOption('data', [$field => $condition]);
                // 生成删除SQL语句
                $sql = $this->builder->update($this->query);
 
                return $this->fetch($sql);
            }
        }
 
        // 生成删除SQL语句
        $sql = $this->builder->delete($this->query);
 
        return $this->fetch($sql);
    }
 
    /**
     * 查找记录 返回SQL.
     *
     * @param array $data
     *
     * @return string
     */
    public function select(array $data = []): string
    {
        $this->query->parseOptions();
 
        if (!empty($data)) {
            // 主键条件分析
            $this->query->parsePkWhere($data);
        }
 
        // 生成查询SQL
        $sql = $this->builder->select($this->query);
 
        return $this->fetch($sql);
    }
 
    /**
     * 查找单条记录 返回SQL语句.
     *
     * @param mixed $data
     *
     * @return string
     */
    public function find($data = null): string
    {
        $this->query->parseOptions();
 
        if (!is_null($data)) {
            // AR模式分析主键条件
            $this->query->parsePkWhere($data);
        }
 
        // 生成查询SQL
        $sql = $this->builder->select($this->query, true);
 
        // 获取实际执行的SQL语句
        return $this->fetch($sql);
    }
 
    /**
     * 查找多条记录 如果不存在则抛出异常.
     *
     * @param mixed $data
     *
     * @return string
     */
    public function selectOrFail($data = null): string
    {
        return $this->select($data);
    }
 
    /**
     * 查找单条记录 如果不存在则抛出异常.
     *
     * @param mixed $data
     *
     * @return string
     */
    public function findOrFail($data = null): string
    {
        return $this->find($data);
    }
 
    /**
     * 查找单条记录 不存在返回空数据(或者空模型).
     *
     * @param mixed $data 数据
     *
     * @return string
     */
    public function findOrEmpty($data = null)
    {
        return $this->find($data);
    }
 
    /**
     * 获取实际的SQL语句.
     *
     * @param string $sql
     *
     * @return string
     */
    public function fetch(string $sql): string
    {
        $bind = $this->query->getBind();
 
        return $this->connection->getRealSql($sql, $bind);
    }
 
    /**
     * COUNT查询.
     *
     * @param string $field 字段名
     *
     * @return string
     */
    public function count(string $field = '*'): string
    {
        $options = $this->query->parseOptions();
 
        if (!empty($options['group'])) {
            // 支持GROUP
            $subSql = $this->query->field('count(' . $field . ') AS think_count')->buildSql();
            $query  = $this->query->newQuery()->table([$subSql => '_group_count_']);
 
            return $query->fetchsql()->aggregate('COUNT', '*');
        }
 
        return $this->aggregate('COUNT', $field);
    }
 
    /**
     * SUM查询.
     *
     * @param string $field 字段名
     *
     * @return string
     */
    public function sum(string $field): string
    {
        return $this->aggregate('SUM', $field);
    }
 
    /**
     * MIN查询.
     *
     * @param string $field 字段名
     *
     * @return string
     */
    public function min(string $field): string
    {
        return $this->aggregate('MIN', $field);
    }
 
    /**
     * MAX查询.
     *
     * @param string $field 字段名
     *
     * @return string
     */
    public function max(string $field): string
    {
        return $this->aggregate('MAX', $field);
    }
 
    /**
     * AVG查询.
     *
     * @param string $field 字段名
     *
     * @return string
     */
    public function avg(string $field): string
    {
        return $this->aggregate('AVG', $field);
    }
 
    public function __call($method, $args)
    {
        if (strtolower(substr($method, 0, 5)) == 'getby') {
            // 根据某个字段获取记录
            $field = Str::snake(substr($method, 5));
 
            return $this->where($field, '=', $args[0])->find();
        }
 
        if (strtolower(substr($method, 0, 10)) == 'getfieldby') {
            // 根据某个字段获取记录的某个值
            $name = Str::snake(substr($method, 10));
 
            return $this->where($name, '=', $args[0])->value($args[1]);
        }
 
        $result = call_user_func_array([$this->query, $method], $args);
 
        return $result === $this->query ? $this : $result;
    }
}