sqltool 0.6.1

功能强大的数据库迁移、同步、运维工具,支持异构数据库自动转换、自动分库分表、慢查询检测、数据对比、备份恢复,提供多语言SDK
Documentation
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
#!/usr/bin/env node
/**
 * SQLTool Node.js 完整调用示例
 *
 * 功能覆盖:
 *   - 数据迁移 (transfer)
 *   - 数据备份 (backup)
 *   - 数据对比 (compare-data)
 *   - 分库分表 (create-shard)
 *   - 慢查询检测 (detect-slow-query)
 *   - 跨分片查询 (spanning-query)
 *   - 日志管理 (insert-log/query-logs)
 *   - SQL注入检测 (detect-sql-injection)
 *   - 安全SQL构建 (build-safe-sql)
 *
 * 安装依赖:
 *   npm install axios
 *
 * 使用方法:
 *   node sqltool_demo.js                    # HTTP API 模式
 *   node sqltool_demo.js --cli             # CLI 模式
 */

const { execSync } = require('child_process');
const axios = require('axios');

// =============================================================================
// HTTP API 客户端
// =============================================================================

class SqlToolClient {
    constructor(baseUrl = 'http://localhost:8080', apiKey = null) {
        this.baseUrl = baseUrl.replace(/\/$/, '');
        this.client = axios.create({
            baseURL: this.baseUrl,
            timeout: 60000,
            headers: { 'Content-Type': 'application/json' }
        });
        if (apiKey) {
            this.client.defaults.headers.common['Authorization'] = `Bearer ${apiKey}`;
        }
    }

    async _post(path, data) {
        const response = await this.client.post(path, data);
        return response.data;
    }

    async _get(path) {
        const response = await this.client.get(path);
        return response.data;
    }

    // -------------------------------------------------------------------------
    // 健康检查
    // -------------------------------------------------------------------------

    async healthCheck() {
        return this._get('/api/health');
    }

    // -------------------------------------------------------------------------
    // 数据迁移
    // -------------------------------------------------------------------------

    /**
     * 数据迁移
     *
     * @param {Object} params
     * @param {string} params.source - 源数据库连接字符串
     * @param {string} params.target - 目标数据库连接字符串
     * @param {string} params.sourceType - 源数据库类型 (mysql/postgresql/sqlite/oracle)
     * @param {string} params.targetType - 目标数据库类型
     * @param {string} params.tables - 表名列表,逗号分隔,空表示所有表
     * @param {number} params.batchSize - 批量大小
     * @param {boolean} params.verifyData - 是否验证数据
     * @param {boolean} params.skipErrors - 是否跳过错误
     */
    async transfer({
        source,
        target,
        sourceType = 'mysql',
        targetType = 'postgresql',
        tables = '',
        batchSize = 1000,
        verifyData = true,
        skipErrors = true
    }) {
        return this._post('/api/transfer', {
            source,
            target,
            source_type: sourceType,
            target_type: targetType,
            tables,
            batch_size: batchSize,
            verify_data: verifyData,
            skip_errors: skipErrors
        });
    }

    // -------------------------------------------------------------------------
    // 数据库备份
    // -------------------------------------------------------------------------

    /**
     * 数据库备份
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接字符串
     * @param {string} params.dbType - 数据库类型
     * @param {string} params.output - 备份文件路径
     * @param {string} params.backupType - 备份类型 (full/incremental/differential)
     * @param {boolean} params.compress - 是否压缩
     * @param {boolean} params.includeProcedures - 包含存储过程
     * @param {boolean} params.includeFunctions - 包含函数
     * @param {boolean} params.includeTriggers - 包含触发器
     * @param {number} params.parallelTables - 并行备份表数
     */
    async backup({
        source,
        dbType = 'mysql',
        output = '/tmp/backup.sql',
        backupType = 'full',
        compress = true,
        includeProcedures = true,
        includeFunctions = true,
        includeTriggers = true,
        parallelTables = 4
    }) {
        return this._post('/api/backup', {
            source,
            db_type: dbType,
            output,
            backup_type: backupType,
            compress,
            include_procedures: includeProcedures,
            include_functions: includeFunctions,
            include_triggers: includeTriggers,
            parallel_tables: parallelTables
        });
    }

    // -------------------------------------------------------------------------
    // 数据对比
    // -------------------------------------------------------------------------

    /**
     * 数据对比
     *
     * @param {Object} params
     * @param {string} params.source - 源数据库
     * @param {string} params.target - 目标数据库
     * @param {string} params.table - 表名
     * @param {string} params.sourceType - 源类型
     * @param {string} params.targetType - 目标类型
     * @param {string} params.primaryKey - 主键字段
     * @param {string} params.ignoreFields - 忽略字段
     * @param {string} params.compareMode - 对比模式 (full/sample)
     */
    async compareData({
        source,
        target,
        table,
        sourceType = 'mysql',
        targetType = 'mysql',
        primaryKey = 'id',
        ignoreFields = '',
        compareMode = 'full'
    }) {
        return this._post('/api/compare', {
            source,
            target,
            source_type: sourceType,
            target_type: targetType,
            table,
            primary_key: primaryKey,
            ignore_fields: ignoreFields,
            compare_mode: compareMode
        });
    }

    // -------------------------------------------------------------------------
    // 分库分表
    // -------------------------------------------------------------------------

    /**
     * 创建分片
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接
     * @param {string} params.table - 表名
     * @param {string} params.strategy - 分片策略 (row_count/time/size/hash)
     * @param {string} params.threshold - 阈值
     * @param {string} params.prefix - 分片前缀
     */
    async createShard({
        source,
        table,
        strategy = 'row_count',
        threshold = '1000000',
        prefix = 'shard'
    }) {
        return this._post('/api/shard/create', {
            source,
            table,
            strategy,
            threshold,
            prefix
        });
    }

    // -------------------------------------------------------------------------
    // 慢查询检测
    // -------------------------------------------------------------------------

    /**
     * 慢查询检测
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接
     * @param {string} params.dbType - 数据库类型
     * @param {number} params.thresholdMs - 阈值(毫秒)
     * @param {number} params.limit - 返回数量
     */
    async detectSlowQuery({
        source,
        dbType = 'mysql',
        thresholdMs = 1000,
        limit = 10
    }) {
        return this._post('/api/detect-slow', {
            source,
            db_type: dbType,
            threshold_ms: thresholdMs,
            limit
        });
    }

    // -------------------------------------------------------------------------
    // 跨分片查询
    // -------------------------------------------------------------------------

    /**
     * 跨分片查询
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接
     * @param {string} params.table - 表名
     * @param {string} params.condition - WHERE条件
     * @param {string} params.orderBy - 排序字段
     * @param {string} params.orderDir - 排序方向 (ASC/DESC)
     * @param {number} params.limit - 返回数量
     * @param {number} params.offset - 偏移量
     */
    async spanningQuery({
        source,
        table,
        condition = '1=1',
        orderBy = '',
        orderDir = 'ASC',
        limit = 100,
        offset = 0
    }) {
        return this._post('/api/spanning-query', {
            source,
            table,
            condition,
            order_by: orderBy,
            order_dir: orderDir,
            limit,
            offset
        });
    }

    // -------------------------------------------------------------------------
    // 日志管理 - 插入
    // -------------------------------------------------------------------------

    /**
     * 插入日志
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接
     * @param {string} params.table - 日志表名
     * @param {string} params.level - 日志级别 (DEBUG/INFO/WARN/ERROR)
     * @param {string} params.message - 日志消息
     * @param {string} params.sourceName - 来源名称
     */
    async insertLog({
        source,
        table = 'app_logs',
        level = 'INFO',
        message = '',
        sourceName = ''
    }) {
        return this._post('/api/log/insert', {
            source,
            table,
            level,
            message,
            source_name: sourceName
        });
    }

    // -------------------------------------------------------------------------
    // 日志管理 - 查询
    // -------------------------------------------------------------------------

    /**
     * 查询日志
     *
     * @param {Object} params
     * @param {string} params.source - 数据库连接
     * @param {string} params.table - 日志表名
     * @param {string} params.levels - 级别过滤(逗号分隔)
     * @param {string} params.keyword - 关键字过滤
     * @param {number} params.startTime - 开始时间
     * @param {number} params.endTime - 结束时间
     * @param {number} params.limit - 返回数量
     */
    async queryLogs({
        source,
        table = 'app_logs',
        levels = '',
        keyword = '',
        startTime = 0,
        endTime = 0,
        limit = 100
    }) {
        const result = await this._post('/api/log/query', {
            source,
            table,
            levels,
            keyword,
            start_time: startTime,
            end_time: endTime,
            limit
        });
        return result.rows || [];
    }

    // -------------------------------------------------------------------------
    // SQL注入检测
    // -------------------------------------------------------------------------

    /**
     * SQL注入检测
     *
     * @param {string} inputText - 要检测的输入
     */
    async detectInjection(inputText) {
        return this._post('/api/security/detect-injection', {
            input: inputText
        });
    }

    // -------------------------------------------------------------------------
    // 安全SQL构建
    // -------------------------------------------------------------------------

    /**
     * 安全SQL构建
     *
     * @param {Object} params
     * @param {string} params.table - 表名
     * @param {string} params.field - 字段名
     * @param {string} params.operator - 操作符 (=, !=, <, >, LIKE, IN)
     * @param {string} params.value - 值
     */
    async buildSafeSql({
        table,
        field,
        operator = '=',
        value = ''
    }) {
        return this._post('/api/security/build-safe-sql', {
            table,
            field,
            operator,
            value
        });
    }
}


// =============================================================================
// CLI 客户端
// =============================================================================

class SqlToolCLI {
    constructor(binaryPath = 'sqltool') {
        this.binaryPath = binaryPath;
    }

    run(...args) {
        try {
            const result = execSync(`${this.binaryPath} ${args.join(' ')}`, {
                encoding: 'utf-8',
                timeout: 60000
            });
            return result;
        } catch (error) {
            return `: ${error.message}`;
        }
    }

    // -------------------------------------------------------------------------
    // 数据迁移
    // -------------------------------------------------------------------------

    /**
     * 数据迁移
     *
     * 示例:
     *   cli.transfer(
     *     'mysql://root:pass@localhost:3306/source',
     *     'postgresql://postgres:pass@localhost:5432/target',
     *     'mysql', 'postgresql', 'users,orders', 5000
     *   );
     */
    transfer(source, target, sourceType, targetType, tables = '', batchSize = 1000) {
        const args = [
            'transfer',
            '-s', source,
            '-t', target,
            '-S', sourceType,
            '-T', targetType,
            '-B', batchSize
        ];
        if (tables) args.push('--tables', tables);
        return this.run(...args);
    }

    // -------------------------------------------------------------------------
    // 数据库备份
    // -------------------------------------------------------------------------

    /**
     * 数据库备份
     *
     * 示例:
     *   cli.backup(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     '/tmp/backup.sql', 'mysql', 'full', true
     *   );
     */
    backup(source, output, dbType = 'mysql', backupType = 'full', compress = true) {
        const args = ['backup', '-s', source, '-T', dbType, '-o', output, '-t', backupType];
        if (compress) args.push('-c');
        return this.run(...args);
    }

    // -------------------------------------------------------------------------
    // 数据对比
    // -------------------------------------------------------------------------

    /**
     * 数据对比
     *
     * 示例:
     *   cli.compareData(
     *     'mysql://root@localhost/db1',
     *     'mysql://root@localhost/db2',
     *     'users', 'id', 'mysql', 'mysql'
     *   );
     */
    compareData(source, target, table, primaryKey = 'id', sourceType = 'mysql', targetType = 'mysql') {
        return this.run(
            'compare-data',
            '-s', source,
            '-t', target,
            '-S', sourceType,
            '-T', targetType,
            '--table', table,
            '--primary-key', primaryKey
        );
    }

    // -------------------------------------------------------------------------
    // 创建分片
    // -------------------------------------------------------------------------

    /**
     * 创建分片
     *
     * 示例:
     *   cli.createShard(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     'orders', 'row_count', '1000000', 'orders_shard'
     *   );
     */
    createShard(source, table, strategy = 'row_count', threshold = '1000000', prefix = 'shard') {
        return this.run(
            'create-shard',
            '-s', source,
            '--table', table,
            '--strategy', strategy,
            '--threshold', threshold,
            '--prefix', prefix
        );
    }

    // -------------------------------------------------------------------------
    // 慢查询检测
    // -------------------------------------------------------------------------

    /**
     * 慢查询检测
     *
     * 示例:
     *   cli.detectSlowQuery(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     'mysql', 1000
     *   );
     */
    detectSlowQuery(source, dbType = 'mysql', thresholdMs = 1000) {
        return this.run(
            'detect-slow-query',
            '-s', source,
            '-T', dbType,
            '--threshold-ms', thresholdMs
        );
    }

    // -------------------------------------------------------------------------
    // 跨分片查询
    // -------------------------------------------------------------------------

    /**
     * 跨分片查询
     *
     * 示例:
     *   cli.spanningQuery(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     'orders', "status='pending'", 'created_at', 100, 0
     *   );
     */
    spanningQuery(source, table, condition = '1=1', orderBy = '', limit = 100, offset = 0) {
        const args = [
            'spanning-query',
            '-s', source,
            '--table', table,
            '--condition', condition,
            '-L', limit,
            '--offset', offset
        ];
        if (orderBy) args.push('--order-by', orderBy);
        return this.run(...args);
    }

    // -------------------------------------------------------------------------
    // 插入日志
    // -------------------------------------------------------------------------

    /**
     * 插入日志
     *
     * 示例:
     *   cli.insertLog(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     '用户登录成功', 'app_logs', 'INFO', 'auth-service'
     *   );
     */
    insertLog(source, message, table = 'app_logs', level = 'INFO', sourceName = '') {
        const args = [
            'insert-log',
            '-s', source,
            '--table', table,
            '--level', level,
            '--message', message
        ];
        if (sourceName) args.push('--source-name', sourceName);
        return this.run(...args);
    }

    // -------------------------------------------------------------------------
    // 查询日志
    // -------------------------------------------------------------------------

    /**
     * 查询日志
     *
     * 示例:
     *   cli.queryLogs(
     *     'mysql://root:pass@localhost:3306/mydb',
     *     'app_logs', 'ERROR,WARN', 'login', 50
     *   );
     */
    queryLogs(source, table = 'app_logs', levels = '', keyword = '', limit = 100) {
        const args = ['query-logs', '-s', source, '--table', table, '-L', limit];
        if (levels) args.push('--levels', levels);
        if (keyword) args.push('--keyword', keyword);
        return this.run(...args);
    }

    // -------------------------------------------------------------------------
    // SQL注入检测
    // -------------------------------------------------------------------------

    /**
     * SQL注入检测
     *
     * 示例:
     *   cli.detectInjection("' OR '1'='1");
     */
    detectInjection(inputText) {
        return this.run('detect-sql-injection', '-i', inputText);
    }

    // -------------------------------------------------------------------------
    // 安全SQL构建
    // -------------------------------------------------------------------------

    /**
     * 安全SQL构建
     *
     * 示例:
     *   cli.buildSafeSql('users', 'name', '=', "John O'Brien");
     */
    buildSafeSql(table, field, operator = '=', value = '') {
        return this.run(
            'build-safe-sql',
            '--table', table,
            '--field', field,
            '--operator', operator,
            '--value', value
        );
    }
}


// =============================================================================
// 主函数
// =============================================================================

async function main() {
    const args = process.argv.slice(2);
    const useCLI = args.includes('--cli');
    const binaryPath = args.find(arg => arg.startsWith('--binary='))?.split('=')[1]
        || '/Users/Zhuanz/Desktop/website/composer/sqlmap/target/release/sqltool';

    console.log(`

         SQLTool Node.js  v0.4.1           

    `);

    if (useCLI) {
        console.log('模式: CLI');
        console.log(`: ${binaryPath}\n`);

        const cli = new SqlToolCLI(binaryPath);

        // 1. SQL注入检测
        console.log('1. SQL注入检测...');
        console.log('='.repeat(60));
        console.log(cli.detectInjection("' OR '1'='1"));

        // 2. 安全SQL构建
        console.log('\n2. 安全SQL构建...');
        console.log('='.repeat(60));
        console.log(cli.buildSafeSql('users', 'name', '=', "test'; DROP TABLE"));

        // 3. 数据迁移
        console.log('\n3. 数据迁移...');
        console.log('='.repeat(60));
        console.log(cli.transfer(
            'mysql://root:pass@localhost:3306/source',
            'postgresql://postgres:pass@localhost:5432/target',
            'mysql', 'postgresql', 'users,orders', 5000
        ));

        // 4. 数据库备份
        console.log('\n4. 数据库备份...');
        console.log('='.repeat(60));
        console.log(cli.backup(
            'mysql://root:pass@localhost:3306/mydb',
            '/tmp/backup.sql', 'mysql', 'full', true
        ));

        // 5. 数据对比
        console.log('\n5. 数据对比...');
        console.log('='.repeat(60));
        console.log(cli.compareData(
            'mysql://root@localhost/db1',
            'mysql://root@localhost/db2',
            'users', 'id'
        ));

    } else {
        console.log('模式: HTTP API');
        console.log('URL: http://localhost:8080\n');

        const client = new SqlToolClient('http://localhost:8080');

        try {
            // 健康检查
            console.log('0. 健康检查...');
            console.log('='.repeat(60));
            console.log(JSON.stringify(await client.healthCheck(), null, 2));

            // 1. SQL注入检测
            console.log('\n1. SQL注入检测...');
            console.log('='.repeat(60));
            const injResult = await client.detectInjection("' OR '1'='1");
            console.log(JSON.stringify(injResult, null, 2));
            if (injResult.risk_level === 'High' || injResult.risk_level === 'Critical') {
                console.log('⚠️ 警告: 检测到高风险SQL注入攻击!');
            }

            // 2. 安全SQL构建
            console.log('\n2. 安全SQL构建...');
            console.log('='.repeat(60));
            const sqlResult = await client.buildSafeSql({
                table: 'users',
                field: 'email',
                operator: 'LIKE',
                value: '%@example.com'
            });
            console.log(JSON.stringify(sqlResult, null, 2));

            // 3. 数据迁移示例
            console.log('\n3. 数据迁移 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const transferResult = await client.transfer({
                source: 'mysql://root:password@localhost:3306/source_db',
                target: 'postgresql://postgres:password@localhost:5432/target_db',
                sourceType: 'mysql',
                targetType: 'postgresql',
                tables: 'users,orders,products',
                batchSize: 5000,
                verifyData: true
            });
            console.log(JSON.stringify(transferResult, null, 2));

            // 4. 数据库备份示例
            console.log('\n4. 数据库备份 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const backupResult = await client.backup({
                source: 'mysql://root:password@localhost:3306/mydb',
                dbType: 'mysql',
                output: '/tmp/backup_20240101.sql',
                backupType: 'full',
                compress: true
            });
            console.log(JSON.stringify(backupResult, null, 2));

            // 5. 数据对比示例
            console.log('\n5. 数据对比 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const compareResult = await client.compareData({
                source: 'mysql://root:password@localhost:3306/db1',
                target: 'mysql://root:password@localhost:3306/db2',
                table: 'users',
                primaryKey: 'id',
                ignoreFields: 'updated_at'
            });
            console.log(JSON.stringify(compareResult, null, 2));

            // 6. 分库分表示例
            console.log('\n6. 分库分表 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const shardResult = await client.createShard({
                source: 'mysql://root:password@localhost:3306/mydb',
                table: 'orders',
                strategy: 'row_count',
                threshold: '1000000',
                prefix: 'orders_shard'
            });
            console.log(JSON.stringify(shardResult, null, 2));

            // 7. 慢查询检测示例
            console.log('\n7. 慢查询检测 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const slowResult = await client.detectSlowQuery({
                source: 'mysql://root:password@localhost:3306/mydb',
                thresholdMs: 1000,
                limit: 10
            });
            console.log(JSON.stringify(slowResult, null, 2));

            // 8. 跨分片查询示例
            console.log('\n8. 跨分片查询 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const spanResult = await client.spanningQuery({
                source: 'mysql://root:password@localhost:3306/mydb',
                table: 'orders',
                condition: "status='pending'",
                orderBy: 'created_at',
                orderDir: 'DESC',
                limit: 100
            });
            console.log(JSON.stringify(spanResult, null, 2));

            // 9. 插入日志示例
            console.log('\n9. 插入日志 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const logInsertResult = await client.insertLog({
                source: 'mysql://root:password@localhost:3306/mydb',
                table: 'app_logs',
                level: 'INFO',
                message: '用户登录成功',
                sourceName: 'auth-service'
            });
            console.log(JSON.stringify(logInsertResult, null, 2));

            // 10. 查询日志示例
            console.log('\n10. 查询日志 (需要真实数据库连接)...');
            console.log('='.repeat(60));
            const logQueryResult = await client.queryLogs({
                source: 'mysql://root:password@localhost:3306/mydb',
                table: 'app_logs',
                levels: 'ERROR,WARN',
                keyword: 'login',
                limit: 50
            });
            console.log(JSON.stringify(logQueryResult, null, 2));

        } catch (error) {
            console.error(`\n: ${error.message}`);
            if (error.code === 'ECONNREFUSED') {
                console.log('\n请先启动 sqltool server:');
                console.log('  sqltool server -p 8080 -s mysql://localhost/mydb');
            }
            process.exit(1);
        }
    }

    console.log('\n' + '='.repeat(60));
    console.log('示例执行完成!');
    console.log('='.repeat(60));
}

main();