chengkun
2025-09-09 1ff9e27b020822168a95edd83be567e7153837f3
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
<?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 Psr\SimpleCache\CacheInterface;
use think\DbManager;
 
/**
 * 数据库连接基础类.
 */
abstract class Connection implements ConnectionInterface
{
    const PARAM_INT   = 1;
    const PARAM_STR   = 2;
    const PARAM_BOOL  = 5;
    const PARAM_FLOAT = 21;
 
    /**
     * 当前SQL指令.
     *
     * @var string
     */
    protected $queryStr = '';
 
    /**
     * 返回或者影响记录数.
     *
     * @var int
     */
    protected $numRows = 0;
 
    /**
     * 事务指令数.
     *
     * @var int
     */
    protected $transTimes = 0;
 
    /**
     * 错误信息.
     *
     * @var string
     */
    protected $error = '';
 
    /**
     * 数据库连接ID 支持多个连接.
     *
     * @var array
     */
    protected $links = [];
 
    /**
     * 当前连接ID.
     *
     * @var object
     */
    protected $linkID;
 
    /**
     * 当前读连接ID.
     *
     * @var object
     */
    protected $linkRead;
 
    /**
     * 当前写连接ID.
     *
     * @var object
     */
    protected $linkWrite;
 
    /**
     * 数据表信息.
     *
     * @var array
     */
    protected $info = [];
 
    /**
     * 查询开始时间.
     *
     * @var float
     */
    protected $queryStartTime;
 
    /**
     * Builder对象
     *
     * @var Builder
     */
    protected $builder;
 
    /**
     * Db对象
     *
     * @var DbManager
     */
    protected $db;
 
    /**
     * 是否读取主库.
     *
     * @var bool
     */
    protected $readMaster = false;
 
    /**
     * 数据库连接参数配置.
     *
     * @var array
     */
    protected $config = [];
 
    /**
     * 缓存对象
     *
     * @var CacheInterface
     */
    protected $cache;
 
    /**
     * 架构函数 读取数据库配置信息.
     *
     * @param array $config 数据库配置数组
     */
    public function __construct(array $config = [])
    {
        if (!empty($config)) {
            $this->config = array_merge($this->config, $config);
        }
 
        // 创建Builder对象
        $class = $this->getBuilderClass();
 
        $this->builder = new $class($this);
    }
 
    /**
     * 获取当前的builder实例对象
     *
     * @return Builder
     */
    public function getBuilder()
    {
        return $this->builder;
    }
 
    /**
     * 创建查询对象
     */
    public function newQuery()
    {
        $class = $this->getQueryClass();
 
        /** @var BaseQuery $query */
        $query = new $class($this);
 
        $timeRule = $this->db->getConfig('time_query_rule');
        if (!empty($timeRule)) {
            $query->timeRule($timeRule);
        }
 
        return $query;
    }
 
    /**
     * 指定表名开始查询.
     *
     * @param $table
     *
     * @return BaseQuery
     */
    public function table($table)
    {
        return $this->newQuery()->table($table);
    }
 
    /**
     * 指定表名开始查询(不带前缀).
     *
     * @param $name
     *
     * @return BaseQuery
     */
    public function name($name)
    {
        return $this->newQuery()->name($name);
    }
 
    /**
     * 设置当前的数据库Db对象
     *
     * @param DbManager $db
     *
     * @return void
     */
    public function setDb(DbManager $db)
    {
        $this->db = $db;
    }
 
    /**
     * 设置当前的缓存对象
     *
     * @param CacheInterface $cache
     *
     * @return void
     */
    public function setCache(CacheInterface $cache)
    {
        $this->cache = $cache;
    }
 
    /**
     * 获取当前的缓存对象
     *
     * @return CacheInterface|null
     */
    public function getCache()
    {
        return $this->cache;
    }
 
    /**
     * 获取数据库的配置参数.
     *
     * @param string $config 配置名称
     *
     * @return mixed
     */
    public function getConfig(string $config = '')
    {
        if ('' === $config) {
            return $this->config;
        }
 
        return $this->config[$config] ?? null;
    }
 
    /**
     * 数据库SQL监控.
     *
     * @param string $sql    执行的SQL语句 留空自动获取
     * @param bool   $master 主从标记
     *
     * @return void
     */
    protected function trigger(string $sql = '', bool $master = false): void
    {
        $listen = $this->db->getListen();
        if (empty($listen)) {
            $listen[] = function ($sql, $time, $master) {
                if (str_starts_with($sql, 'CONNECT:')) {
                    $this->db->log($sql);
 
                    return;
                }
 
                // 记录SQL
                if (is_bool($master)) {
                    // 分布式记录当前操作的主从
                    $master = $master ? 'master|' : 'slave|';
                } else {
                    $master = '';
                }
 
                $this->db->log($sql . ' [ ' . $master . 'RunTime:' . $time . 's ]');
            };
        }
 
        $runtime = number_format((microtime(true) - $this->queryStartTime), 6);
        $sql     = $sql ?: $this->getLastsql();
 
        if (empty($this->config['deploy'])) {
            $master = null;
        }
 
        foreach ($listen as $callback) {
            if (is_callable($callback)) {
                $callback($sql, $runtime, $master);
            }
        }
    }
 
    /**
     * 缓存数据.
     *
     * @param CacheItem $cacheItem 缓存Item
     */
    protected function cacheData(CacheItem $cacheItem)
    {
        if ($cacheItem->getTag() && method_exists($this->cache, 'tag')) {
            $this->cache->tag($cacheItem->getTag())->set($cacheItem->getKey(), $cacheItem->get(), $cacheItem->getExpire());
        } else {
            $this->cache->set($cacheItem->getKey(), $cacheItem->get(), $cacheItem->getExpire());
        }
    }
 
    /**
     * 分析缓存Key.
     *
     * @param BaseQuery $query  查询对象
     * @param string    $method 查询方法
     *
     * @return string
     */
    protected function getCacheKey(BaseQuery $query, string $method = ''): string
    {
        if (!empty($query->getOptions('key')) && empty($method)) {
            $key = 'think_' . $this->getConfig('database') . '.' . var_export($query->getTable(), true) . '|' . $query->getOptions('key');
        } else {
            $key = $query->getQueryGuid();
        }
 
        return $key;
    }
 
    /**
     * 分析缓存.
     *
     * @param BaseQuery $query  查询对象
     * @param array     $cache  缓存信息
     * @param string    $method 查询方法
     *
     * @return CacheItem
     */
    protected function parseCache(BaseQuery $query, array $cache, string $method = ''): CacheItem
    {
        [$key, $expire, $tag] = $cache;
 
        if ($key instanceof CacheItem) {
            $cacheItem = $key;
        } else {
            if (true === $key) {
                $key = $this->getCacheKey($query, $method);
            }
 
            $cacheItem = new CacheItem($key);
            $cacheItem->expire($expire);
            $cacheItem->tag($tag);
        }
 
        return $cacheItem;
    }
 
    /**
     * 获取返回或者影响的记录数.
     *
     * @return int
     */
    public function getNumRows(): int
    {
        return $this->numRows;
    }
 
    /**
     * 获取最终的SQL语句.
     *
     * @param string $sql  带参数绑定的sql语句
     * @param array  $bind 参数绑定列表
     *
     * @return string
     */
    public function getRealSql(string $sql, array $bind = []): string
    {
        foreach ($bind as $key => $val) {
            $value = strval(is_array($val) ? $val[0] : $val);
            $type  = is_array($val) ? $val[1] : self::PARAM_STR;
 
            if (self::PARAM_FLOAT == $type || self::PARAM_STR == $type) {
                $value = '\'' . addslashes($value) . '\'';
            } elseif (self::PARAM_INT == $type && '' === $value) {
                $value = '0';
            }
 
            // 判断占位符
            $sql = is_numeric($key) ?
            substr_replace($sql, $value, strpos($sql, '?'), 1) :
            str_replace(
                [':' . $key . ' ', ':' . $key . ',', ':' . $key . ')'],
                [$value . ' ', $value . ',', $value . ')'],
                $sql);
        }
 
        return rtrim($sql);
    }
 
    /**
     * 析构方法.
     */
    public function __destruct()
    {
        // 关闭连接
        $this->close();
    }
}