sql-splitter 1.13.1

High-performance CLI tool for splitting large SQL dump files into individual table files
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
//! Integration tests that verify JSON output matches JSON schemas.
//!
//! Each command that supports --json output is tested against its corresponding
//! schema in the schemas/ directory.

use jsonschema::Validator;
use serde_json::Value;
use std::fs;
use std::io::Write;
use std::process::Command;
use tempfile::{NamedTempFile, TempDir};

fn sql_splitter_bin() -> Command {
    Command::new(env!("CARGO_BIN_EXE_sql-splitter"))
}

fn create_temp_sql(content: &str) -> NamedTempFile {
    let mut file = NamedTempFile::new().expect("Failed to create temp file");
    file.write_all(content.as_bytes())
        .expect("Failed to write temp file");
    file.flush().expect("Failed to flush temp file");
    file
}

fn load_schema(name: &str) -> Validator {
    let schema_path = format!("schemas/{}.schema.json", name);
    let schema_str = fs::read_to_string(&schema_path)
        .unwrap_or_else(|_| panic!("Failed to read schema: {}", schema_path));
    let schema: Value = serde_json::from_str(&schema_str).expect("Invalid schema JSON");
    Validator::new(&schema).expect("Failed to compile schema")
}

fn validate_json_output(output: &std::process::Output, schema_name: &str) {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        output.status.success(),
        "Command failed with stderr: {}",
        stderr
    );

    let json: Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("Invalid JSON output: {}\nOutput: {}", e, stdout));

    let schema = load_schema(schema_name);
    let result = schema.validate(&json);

    if let Err(error) = result {
        panic!(
            "JSON output doesn't match {} schema:\n  - {}: {}\n\nOutput was:\n{}",
            schema_name,
            error.instance_path(),
            error,
            serde_json::to_string_pretty(&json).unwrap()
        );
    }
}

// =============================================================================
// Analyze Command
// =============================================================================

#[test]
fn test_analyze_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');

CREATE TABLE orders (id INT PRIMARY KEY, user_id INT);
INSERT INTO orders VALUES (1, 1);
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("analyze")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "analyze");
}

#[test]
fn test_analyze_empty_file_matches_schema() {
    let file = create_temp_sql("");

    let output = sql_splitter_bin()
        .arg("analyze")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "analyze");
}

// =============================================================================
// Validate Command
// =============================================================================

#[test]
fn test_validate_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("validate")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "validate");
}

#[test]
fn test_validate_with_issues_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY);
INSERT INTO orphans VALUES (1, 'test');
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("validate")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: Value = serde_json::from_str(&stdout).expect("Invalid JSON");
    let schema = load_schema("validate");

    if let Err(error) = schema.validate(&json) {
        panic!(
            "JSON output doesn't match validate schema:\n  - {}: {}\n\nOutput was:\n{}",
            error.instance_path(),
            error,
            serde_json::to_string_pretty(&json).unwrap()
        );
    }
}

// =============================================================================
// Split Command
// =============================================================================

#[test]
fn test_split_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');

CREATE TABLE orders (id INT PRIMARY KEY, user_id INT);
INSERT INTO orders VALUES (1, 1);
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");

    let output = sql_splitter_bin()
        .arg("split")
        .arg(file.path())
        .arg("--output")
        .arg(output_dir.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "split");
}

#[test]
fn test_split_dry_run_json_matches_schema() {
    let sql = "CREATE TABLE test (id INT); INSERT INTO test VALUES (1);";
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");

    let output = sql_splitter_bin()
        .arg("split")
        .arg(file.path())
        .arg("--output")
        .arg(output_dir.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--dry-run")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "split");
}

// =============================================================================
// Merge Command
// =============================================================================

#[test]
fn test_merge_json_matches_schema() {
    let split_dir = TempDir::new().expect("Failed to create temp dir");
    fs::write(
        split_dir.path().join("users.sql"),
        "CREATE TABLE users (id INT);\nINSERT INTO users VALUES (1);\n",
    )
    .expect("Failed to write file");
    fs::write(
        split_dir.path().join("orders.sql"),
        "CREATE TABLE orders (id INT);\nINSERT INTO orders VALUES (1);\n",
    )
    .expect("Failed to write file");

    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let merged_path = output_dir.path().join("merged.sql");

    let output = sql_splitter_bin()
        .arg("merge")
        .arg(split_dir.path())
        .arg("--output")
        .arg(&merged_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "merge");
}

#[test]
fn test_merge_dry_run_json_matches_schema() {
    let split_dir = TempDir::new().expect("Failed to create temp dir");
    fs::write(split_dir.path().join("test.sql"), "SELECT 1;\n").expect("Failed to write file");

    let output = sql_splitter_bin()
        .arg("merge")
        .arg(split_dir.path())
        .arg("--dry-run")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "merge");
}

// =============================================================================
// Sample Command
// =============================================================================

#[test]
fn test_sample_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');
INSERT INTO users VALUES (3, 'Charlie');
INSERT INTO users VALUES (4, 'Dave');
INSERT INTO users VALUES (5, 'Eve');
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let sample_path = output_dir.path().join("sample.sql");

    let output = sql_splitter_bin()
        .arg("sample")
        .arg(file.path())
        .arg("--output")
        .arg(&sample_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--percent")
        .arg("50")
        .arg("--seed")
        .arg("12345")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "sample");
}

#[test]
fn test_sample_rows_mode_json_matches_schema() {
    let sql = r#"
CREATE TABLE items (id INT PRIMARY KEY);
INSERT INTO items VALUES (1);
INSERT INTO items VALUES (2);
INSERT INTO items VALUES (3);
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let sample_path = output_dir.path().join("sample.sql");

    let output = sql_splitter_bin()
        .arg("sample")
        .arg(file.path())
        .arg("--output")
        .arg(&sample_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--rows")
        .arg("2")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "sample");
}

// =============================================================================
// Convert Command
// =============================================================================

#[test]
fn test_convert_json_matches_schema() {
    let sql = r#"
CREATE TABLE `users` (`id` INT AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(255));
INSERT INTO `users` VALUES (1, 'Alice');
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let converted_path = output_dir.path().join("converted.sql");

    let output = sql_splitter_bin()
        .arg("convert")
        .arg(file.path())
        .arg("--output")
        .arg(&converted_path)
        .arg("--from")
        .arg("mysql")
        .arg("--to")
        .arg("postgres")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "convert");
}

#[test]
fn test_convert_dry_run_json_matches_schema() {
    let sql = "CREATE TABLE test (id INT);";
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("convert")
        .arg(file.path())
        .arg("--to")
        .arg("postgres")
        .arg("--dry-run")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "convert");
}

// =============================================================================
// Redact Command
// =============================================================================

#[test]
fn test_redact_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255), name VARCHAR(255));
INSERT INTO users VALUES (1, 'alice@example.com', 'Alice');
INSERT INTO users VALUES (2, 'bob@example.com', 'Bob');
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let redacted_path = output_dir.path().join("redacted.sql");

    let output = sql_splitter_bin()
        .arg("redact")
        .arg(file.path())
        .arg("--output")
        .arg(&redacted_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--null")
        .arg("email")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "redact");
}

#[test]
fn test_redact_no_matches_json_matches_schema() {
    let sql = r#"
CREATE TABLE items (id INT PRIMARY KEY, count INT);
INSERT INTO items VALUES (1, 100);
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let redacted_path = output_dir.path().join("redacted.sql");

    let output = sql_splitter_bin()
        .arg("redact")
        .arg(file.path())
        .arg("--output")
        .arg(&redacted_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--null")
        .arg("nonexistent")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "redact");
}

// =============================================================================
// Graph Command
// =============================================================================

#[test]
fn test_graph_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(255)
);

CREATE TABLE orders (
    id INT PRIMARY KEY,
    user_id INT,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("graph")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "graph");
}

#[test]
fn test_graph_no_relationships_json_matches_schema() {
    let sql = r#"
CREATE TABLE standalone (
    id INT PRIMARY KEY,
    data VARCHAR(255)
);
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("graph")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "graph");
}

// =============================================================================
// Shard Command
// =============================================================================

#[test]
fn test_shard_json_matches_schema() {
    let sql = r#"
CREATE TABLE tenants (id INT PRIMARY KEY, name VARCHAR(255));
INSERT INTO tenants VALUES (1, 'Acme');
INSERT INTO tenants VALUES (2, 'Globex');

CREATE TABLE users (id INT PRIMARY KEY, tenant_id INT, name VARCHAR(255));
INSERT INTO users VALUES (1, 1, 'Alice');
INSERT INTO users VALUES (2, 1, 'Bob');
INSERT INTO users VALUES (3, 2, 'Charlie');
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");
    let shard_path = output_dir.path().join("shard.sql");

    let output = sql_splitter_bin()
        .arg("shard")
        .arg(file.path())
        .arg("--output")
        .arg(&shard_path)
        .arg("--dialect")
        .arg("mysql")
        .arg("--tenant-column")
        .arg("tenant_id")
        .arg("--tenant-value")
        .arg("1")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "shard");
}

#[test]
fn test_shard_dry_run_json_matches_schema() {
    let sql = r#"
CREATE TABLE data (id INT PRIMARY KEY, org_id INT);
INSERT INTO data VALUES (1, 100);
INSERT INTO data VALUES (2, 200);
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("shard")
        .arg(file.path())
        .arg("--dialect")
        .arg("mysql")
        .arg("--tenant-column")
        .arg("org_id")
        .arg("--tenant-value")
        .arg("100")
        .arg("--dry-run")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "shard");
}

// =============================================================================
// PostgreSQL Dialect Tests
// =============================================================================

#[test]
fn test_analyze_postgres_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(255));
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("analyze")
        .arg(file.path())
        .arg("--dialect")
        .arg("postgres")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "analyze");
}

#[test]
fn test_graph_postgres_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255)
);

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    user_id INT REFERENCES users(id)
);
"#;
    let file = create_temp_sql(sql);

    let output = sql_splitter_bin()
        .arg("graph")
        .arg(file.path())
        .arg("--dialect")
        .arg("postgres")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "graph");
}

// =============================================================================
// SQLite Dialect Tests
// =============================================================================

#[test]
fn test_split_sqlite_json_matches_schema() {
    let sql = r#"
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users VALUES (1, 'Alice');
INSERT INTO users VALUES (2, 'Bob');
"#;
    let file = create_temp_sql(sql);
    let output_dir = TempDir::new().expect("Failed to create temp dir");

    let output = sql_splitter_bin()
        .arg("split")
        .arg(file.path())
        .arg("--output")
        .arg(output_dir.path())
        .arg("--dialect")
        .arg("sqlite")
        .arg("--json")
        .output()
        .expect("Failed to execute command");

    validate_json_output(&output, "split");
}

// =============================================================================
// Schema File Validation
// =============================================================================

/// Test that all schema files are valid JSON
#[test]
fn test_all_schema_files_are_valid_json() {
    let schema_files = [
        "analyze", "validate", "split", "merge", "sample", "convert", "redact", "graph", "shard",
    ];

    for name in schema_files {
        let schema_path = format!("schemas/{}.schema.json", name);
        let schema_str = fs::read_to_string(&schema_path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {}", schema_path, e));

        let _: Value = serde_json::from_str(&schema_str)
            .unwrap_or_else(|e| panic!("{} contains invalid JSON: {}", schema_path, e));
    }
}

/// Test that all schema files are valid JSON Schema (can be compiled)
#[test]
fn test_all_schema_files_are_valid_json_schema() {
    let schema_files = [
        "analyze", "validate", "split", "merge", "sample", "convert", "redact", "graph", "shard",
    ];

    for name in schema_files {
        let schema_path = format!("schemas/{}.schema.json", name);
        let schema_str = fs::read_to_string(&schema_path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {}", schema_path, e));

        let schema: Value = serde_json::from_str(&schema_str)
            .unwrap_or_else(|e| panic!("{} contains invalid JSON: {}", schema_path, e));

        Validator::new(&schema)
            .unwrap_or_else(|e| panic!("{} is not a valid JSON Schema: {}", schema_path, e));
    }
}

/// Test that all schema files have required metadata
#[test]
fn test_all_schema_files_have_metadata() {
    let schema_files = [
        "analyze", "validate", "split", "merge", "sample", "convert", "redact", "graph", "shard",
    ];

    for name in schema_files {
        let schema_path = format!("schemas/{}.schema.json", name);
        let schema_str = fs::read_to_string(&schema_path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {}", schema_path, e));

        let schema: Value = serde_json::from_str(&schema_str).unwrap();

        assert!(
            schema.get("$schema").is_some(),
            "{} missing $schema field",
            schema_path
        );
        assert!(
            schema.get("title").is_some(),
            "{} missing title field",
            schema_path
        );
        assert!(
            schema.get("description").is_some(),
            "{} missing description field",
            schema_path
        );
    }
}