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
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! Integration tests for MSSQL/T-SQL dialect support.

use sql_splitter::parser::{detect_dialect, DialectConfidence, Parser, SqlDialect, StatementType};
use sql_splitter::splitter::Splitter;
use sql_splitter::validate::{ValidateOptions, Validator};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use tempfile::{NamedTempFile, TempDir};
use test_data_gen::{Generator, RenderConfig, Renderer, Scale};

fn mssql_simple_fixture() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/static/mssql/simple.sql")
}

fn mssql_edge_cases_fixture() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/static/mssql/edge_cases.sql")
}

#[test]
fn test_mssql_dialect_detection() {
    let content = br#"SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[users] (
    [id] INT IDENTITY(1,1) NOT NULL
)
GO
"#;

    let result = detect_dialect(content);
    assert_eq!(result.dialect, SqlDialect::Mssql);
    assert_eq!(result.confidence, DialectConfidence::High);
}

#[test]
fn test_mssql_dialect_detection_brackets() {
    let content = br#"CREATE TABLE [users] (
    [id] INT IDENTITY(1,1) NOT NULL,
    [name] NVARCHAR(100)
) ON [PRIMARY]
"#;

    let result = detect_dialect(content);
    assert_eq!(result.dialect, SqlDialect::Mssql);
}

#[test]
fn test_mssql_go_batch_separator() {
    let content = br#"CREATE TABLE [users] ([id] INT)
GO
INSERT INTO [users] VALUES (1)
GO
INSERT INTO [users] VALUES (2)
GO
"#;

    let mut parser = Parser::with_dialect(content.as_slice(), 64 * 1024, SqlDialect::Mssql);

    let stmt1 = parser.read_statement().unwrap().unwrap();
    assert!(String::from_utf8_lossy(&stmt1).contains("CREATE TABLE"));

    let stmt2 = parser.read_statement().unwrap().unwrap();
    assert!(String::from_utf8_lossy(&stmt2).contains("INSERT INTO"));
    assert!(String::from_utf8_lossy(&stmt2).contains("(1)"));

    let stmt3 = parser.read_statement().unwrap().unwrap();
    assert!(String::from_utf8_lossy(&stmt3).contains("INSERT INTO"));
    assert!(String::from_utf8_lossy(&stmt3).contains("(2)"));
}

#[test]
fn test_mssql_parse_create_table() {
    let stmt = b"CREATE TABLE [dbo].[users] ([id] INT IDENTITY(1,1) NOT NULL)";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::CreateTable);
    assert_eq!(table_name, "users");
}

#[test]
fn test_mssql_parse_insert() {
    let stmt = b"INSERT INTO [dbo].[users] ([id], [name]) VALUES (1, N'Alice')";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::Insert);
    assert_eq!(table_name, "users");
}

#[test]
fn test_mssql_parse_create_nonclustered_index() {
    let stmt = b"CREATE NONCLUSTERED INDEX [IX_users_email] ON [dbo].[users] ([email])";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::CreateIndex);
    assert_eq!(table_name, "users");
}

#[test]
fn test_mssql_parse_create_clustered_index() {
    let stmt = b"CREATE CLUSTERED INDEX [IX_users_id] ON [users] ([id])";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::CreateIndex);
    assert_eq!(table_name, "users");
}

#[test]
fn test_mssql_split_simple() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().to_path_buf();

    let stats = Splitter::new(mssql_simple_fixture(), output_dir.clone())
        .with_dialect(SqlDialect::Mssql)
        .split()
        .unwrap();

    assert_eq!(stats.tables_found, 2);
    assert!(stats.table_names.contains(&"users".to_string()));
    assert!(stats.table_names.contains(&"orders".to_string()));

    // Verify output files exist
    assert!(output_dir.join("users.sql").exists());
    assert!(output_dir.join("orders.sql").exists());

    // Verify content has semicolons (added for MSSQL)
    let users_content = fs::read_to_string(output_dir.join("users.sql")).unwrap();
    assert!(users_content.contains("CREATE TABLE"));
    assert!(users_content.contains("INSERT INTO"));
}

#[test]
fn test_mssql_split_edge_cases() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().to_path_buf();

    let stats = Splitter::new(mssql_edge_cases_fixture(), output_dir.clone())
        .with_dialect(SqlDialect::Mssql)
        .split()
        .unwrap();

    assert!(stats.tables_found >= 2);
    assert!(stats.table_names.contains(&"products".to_string()));

    // Verify products.sql has Unicode strings
    let products_content = fs::read_to_string(output_dir.join("products.sql")).unwrap();
    assert!(products_content.contains("日本語"));
}

#[test]
fn test_mssql_unicode_string_handling() {
    let content = "INSERT INTO [dbo].[users] ([name]) VALUES (N'日本語')
GO
INSERT INTO [dbo].[users] ([name]) VALUES (N'Ελληνικά')
GO
";

    let mut parser = Parser::with_dialect(content.as_bytes(), 64 * 1024, SqlDialect::Mssql);

    let stmt1 = parser.read_statement().unwrap().unwrap();
    let stmt1_str = String::from_utf8_lossy(&stmt1);
    assert!(stmt1_str.contains("日本語"));

    let stmt2 = parser.read_statement().unwrap().unwrap();
    let stmt2_str = String::from_utf8_lossy(&stmt2);
    assert!(stmt2_str.contains("Ελληνικά"));
}

#[test]
fn test_mssql_bracket_escape() {
    let stmt = b"CREATE TABLE [table with ]] bracket] ([col]] name] INT)";

    let (stmt_type, _) = Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);
    assert_eq!(stmt_type, StatementType::CreateTable);
}

#[test]
fn test_mssql_identity_parsing() {
    let stmt = b"CREATE TABLE [t] ([id] BIGINT IDENTITY(100,10) NOT NULL PRIMARY KEY)";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::CreateTable);
    assert_eq!(table_name, "t");
}

#[test]
fn test_mssql_bulk_insert_classification() {
    let stmt = b"BULK INSERT [dbo].[data] FROM 'C:\\data\\file.csv'";

    let (stmt_type, table_name) =
        Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);

    assert_eq!(stmt_type, StatementType::Insert);
    assert_eq!(table_name, "data");
}

#[test]
fn test_mssql_go_with_count() {
    let content = br#"PRINT 'Hello'
GO 5
INSERT INTO [t] VALUES (1)
GO
"#;

    let mut parser = Parser::with_dialect(content.as_slice(), 64 * 1024, SqlDialect::Mssql);

    // First statement: PRINT 'Hello'
    let stmt1 = parser.read_statement().unwrap().unwrap();
    assert!(String::from_utf8_lossy(&stmt1).contains("PRINT"));

    // Second statement: INSERT
    let stmt2 = parser.read_statement().unwrap().unwrap();
    assert!(String::from_utf8_lossy(&stmt2).contains("INSERT"));
}

#[test]
fn test_mssql_go_case_insensitive() {
    let content = br#"SELECT 1
go
SELECT 2
Go
SELECT 3
GO
"#;

    let mut parser = Parser::with_dialect(content.as_slice(), 64 * 1024, SqlDialect::Mssql);

    let _ = parser.read_statement().unwrap().unwrap();
    let _ = parser.read_statement().unwrap().unwrap();
    let _ = parser.read_statement().unwrap().unwrap();

    // All three should be parsed successfully
}

#[test]
fn test_mssql_schema_qualified_names() {
    let stmts = [
        (b"CREATE TABLE [users] ([id] INT)".as_slice(), "users"),
        (b"CREATE TABLE [dbo].[users] ([id] INT)".as_slice(), "users"),
        (
            b"CREATE TABLE [mydb].[dbo].[users] ([id] INT)".as_slice(),
            "users",
        ),
    ];

    for (stmt, expected_table) in stmts {
        let (stmt_type, table_name) =
            Parser::<&[u8]>::parse_statement_with_dialect(stmt, SqlDialect::Mssql);
        assert_eq!(stmt_type, StatementType::CreateTable);
        assert_eq!(
            table_name,
            expected_table,
            "Failed for: {}",
            String::from_utf8_lossy(stmt)
        );
    }
}

// Phase 4 Tests: Schema Commands

#[test]
fn test_mssql_schema_pk_parsing_clustered() {
    use sql_splitter::schema::SchemaBuilder;

    let stmt = r#"CREATE TABLE [dbo].[users] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [name] NVARCHAR(100),
        CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
    )"#;

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(stmt);
    let schema = builder.build();

    let table = schema.get_table("users").expect("Table should exist");
    assert_eq!(table.primary_key.len(), 1, "Should have 1 PK column");

    let pk_col = table
        .column(table.primary_key[0])
        .expect("PK column should exist");
    assert_eq!(pk_col.name, "id");
    assert!(pk_col.is_primary_key);
}

#[test]
fn test_mssql_schema_composite_pk() {
    use sql_splitter::schema::SchemaBuilder;

    let stmt = r#"CREATE TABLE [dbo].[order_items] (
        [order_id] INT NOT NULL,
        [product_id] BIGINT NOT NULL,
        [quantity] INT NOT NULL,
        CONSTRAINT [PK_order_items] PRIMARY KEY CLUSTERED ([order_id], [product_id])
    )"#;

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(stmt);
    let schema = builder.build();

    let table = schema.get_table("order_items").expect("Table should exist");
    assert_eq!(table.primary_key.len(), 2, "Should have 2 PK columns");

    let pk_col1 = table
        .column(table.primary_key[0])
        .expect("First PK column should exist");
    let pk_col2 = table
        .column(table.primary_key[1])
        .expect("Second PK column should exist");
    assert_eq!(pk_col1.name, "order_id");
    assert_eq!(pk_col2.name, "product_id");
}

#[test]
fn test_mssql_schema_fk_parsing() {
    use sql_splitter::schema::SchemaBuilder;

    let users_stmt = r#"CREATE TABLE [dbo].[users] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [name] NVARCHAR(100),
        CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ([id])
    )"#;

    let orders_stmt = r#"CREATE TABLE [dbo].[orders] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [user_id] INT NOT NULL,
        CONSTRAINT [PK_orders] PRIMARY KEY CLUSTERED ([id]),
        CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users]([id])
    )"#;

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(users_stmt);
    builder.parse_create_table(orders_stmt);
    let schema = builder.build();

    let orders = schema
        .get_table("orders")
        .expect("Orders table should exist");
    assert_eq!(orders.foreign_keys.len(), 1, "Should have 1 FK");

    let fk = &orders.foreign_keys[0];
    assert_eq!(fk.name.as_deref(), Some("FK_orders_users"));
    assert_eq!(fk.referenced_table, "users");
    assert_eq!(fk.column_names, vec!["user_id"]);
    assert_eq!(fk.referenced_columns, vec!["id"]);
}

#[test]
fn test_mssql_schema_index_parsing() {
    use sql_splitter::schema::SchemaBuilder;

    let table_stmt = r#"CREATE TABLE [dbo].[products] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [sku] NVARCHAR(50) NOT NULL,
        [name] NVARCHAR(255) NOT NULL,
        CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
    )"#;

    let index_stmt = r#"CREATE NONCLUSTERED INDEX [IX_products_sku] ON [dbo].[products] ([sku])"#;
    let unique_index_stmt =
        r#"CREATE UNIQUE NONCLUSTERED INDEX [UX_products_name] ON [dbo].[products] ([name])"#;

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(table_stmt);
    builder.parse_create_index(index_stmt);
    builder.parse_create_index(unique_index_stmt);
    let schema = builder.build();

    let products = schema
        .get_table("products")
        .expect("Products table should exist");
    // Note: PK constraint may be parsed as an index too, so check for at least 2 user-created indexes
    assert!(
        products.indexes.len() >= 2,
        "Should have at least 2 indexes"
    );

    let idx1 = products
        .indexes
        .iter()
        .find(|i| i.name == "IX_products_sku")
        .expect("Index should exist");
    assert!(!idx1.is_unique);
    assert_eq!(idx1.columns, vec!["sku"]);

    let idx2 = products
        .indexes
        .iter()
        .find(|i| i.name == "UX_products_name")
        .expect("Unique index should exist");
    assert!(idx2.is_unique);
    assert_eq!(idx2.columns, vec!["name"]);
}

// Phase 5 Tests: Data Commands

#[test]
fn test_mssql_insert_row_parsing() {
    use sql_splitter::parser::mysql_insert::parse_mysql_insert_rows;
    use sql_splitter::schema::SchemaBuilder;

    let create_stmt = r#"CREATE TABLE [dbo].[orders] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [user_id] INT NOT NULL,
        [total] DECIMAL(10,2),
        [status] NVARCHAR(50),
        CONSTRAINT [PK_orders] PRIMARY KEY CLUSTERED ([id])
    )"#;

    let insert_stmt = b"INSERT INTO [dbo].[orders] ([user_id], [total], [status]) VALUES (1, 99.99, N'completed')";

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(create_stmt);
    let schema = builder.build();
    let table = schema.get_table("orders").expect("Table should exist");

    let rows = parse_mysql_insert_rows(insert_stmt, table).expect("Should parse rows");
    assert_eq!(rows.len(), 1, "Should parse 1 row");

    // Verify values were parsed
    let row = &rows[0];
    assert_eq!(row.all_values.len(), 3, "Should have 3 values");
}

#[test]
fn test_mssql_insert_unicode_strings() {
    use sql_splitter::parser::mysql_insert::parse_mysql_insert_rows;
    use sql_splitter::schema::SchemaBuilder;

    let create_stmt = r#"CREATE TABLE [dbo].[products] (
        [id] INT NOT NULL,
        [name] NVARCHAR(255) NOT NULL,
        CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED ([id])
    )"#;

    let insert_stmt = b"INSERT INTO [dbo].[products] ([id], [name]) VALUES (1, N'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e')";

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(create_stmt);
    let schema = builder.build();
    let table = schema.get_table("products").expect("Table should exist");

    let rows = parse_mysql_insert_rows(insert_stmt, table).expect("Should parse rows");
    assert_eq!(rows.len(), 1, "Should parse 1 row");

    // Verify unicode was parsed correctly
    let row = &rows[0];
    assert_eq!(row.all_values.len(), 2, "Should have 2 values");
}

#[test]
fn test_mssql_insert_column_mapping() {
    use sql_splitter::parser::mysql_insert::{parse_mysql_insert_rows, PkValue};
    use sql_splitter::schema::SchemaBuilder;

    // Schema has columns in order: id, user_id, total, status
    let create_stmt = r#"CREATE TABLE [dbo].[orders] (
        [id] INT IDENTITY(1,1) NOT NULL,
        [user_id] INT NOT NULL,
        [total] DECIMAL(10,2),
        [status] NVARCHAR(50),
        CONSTRAINT [PK_orders] PRIMARY KEY CLUSTERED ([id])
    )"#;

    // INSERT specifies columns in different order: user_id, total, status (no id)
    let insert_stmt = b"INSERT INTO [dbo].[orders] ([user_id], [total], [status]) VALUES (1, 99.99, N'completed')";

    let mut builder = SchemaBuilder::new();
    builder.parse_create_table(create_stmt);
    let schema = builder.build();
    let table = schema.get_table("orders").expect("Table should exist");

    let rows = parse_mysql_insert_rows(insert_stmt, table).expect("Should parse rows");
    assert_eq!(rows.len(), 1, "Should parse 1 row");

    let row = &rows[0];

    // The all_values should be in VALUE order (3 values for the 3 columns specified)
    assert_eq!(row.all_values.len(), 3, "Should have 3 values");

    // First value should be the user_id = 1
    assert_eq!(
        row.all_values[0],
        PkValue::Int(1),
        "First value should be user_id=1"
    );
}

// Phase 5 Data Command Tests

fn mssql_multi_tenant_fixture() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/static/mssql/multi_tenant.sql")
}

#[test]
fn test_mssql_sample_command() {
    use sql_splitter::sample::{GlobalTableMode, SampleConfig, SampleMode};

    let temp_dir = TempDir::new().unwrap();
    let output_file = temp_dir.path().join("sampled.sql");

    let config = SampleConfig {
        input: mssql_simple_fixture(),
        output: Some(output_file.clone()),
        dialect: SqlDialect::Mssql,
        mode: SampleMode::Percent(100),
        seed: 42,
        preserve_relations: false,
        progress: false,
        tables_filter: None,
        exclude: vec![],
        root_tables: vec![],
        include_global: GlobalTableMode::Lookups,
        dry_run: false,
        config_file: None,
        max_total_rows: None,
        strict_fk: false,
        include_schema: true,
    };

    let stats = sql_splitter::sample::run(config).unwrap();

    assert!(stats.total_rows_selected > 0, "Should sample some rows");
    assert!(output_file.exists(), "Output file should exist");

    let content = fs::read_to_string(&output_file).unwrap();
    assert!(content.contains("CREATE TABLE"), "Should include schema");
    assert!(content.contains("INSERT INTO"), "Should include data");
}

#[test]
fn test_mssql_shard_command() {
    use sql_splitter::shard::{GlobalTableMode, ShardConfig};

    let config = ShardConfig {
        input: mssql_multi_tenant_fixture(),
        output: None,
        dialect: SqlDialect::Mssql,
        tenant_column: Some("tenant_id".to_string()),
        tenant_value: "1".to_string(),
        root_tables: vec![],
        include_global: GlobalTableMode::Lookups,
        dry_run: true,
        progress: false,
        config_file: None,
        max_selected_rows: None,
        strict_fk: false,
        include_schema: true,
    };

    let stats = sql_splitter::shard::run(config).unwrap();

    // Should have processed tables
    assert!(stats.tables_processed > 0, "Should process some tables");

    // Tenant 1 should have users and orders
    let users_stats = stats.table_stats.iter().find(|t| t.name == "users");
    assert!(users_stats.is_some(), "Should have users table stats");
    let users = users_stats.unwrap();
    assert_eq!(users.rows_selected, 2, "Should select 2 users for tenant 1");

    let orders_stats = stats.table_stats.iter().find(|t| t.name == "orders");
    assert!(orders_stats.is_some(), "Should have orders table stats");
    let orders = orders_stats.unwrap();
    assert_eq!(
        orders.rows_selected, 2,
        "Should select 2 orders for tenant 1"
    );
}

#[test]
fn test_mssql_diff_command() {
    use sql_splitter::differ::{DiffConfig, DiffOutputFormat, Differ};

    let config = DiffConfig {
        old_path: mssql_simple_fixture(),
        new_path: mssql_edge_cases_fixture(),
        dialect: Some(SqlDialect::Mssql),
        tables: vec![],
        exclude: vec![],
        ignore_columns: vec![],
        schema_only: false,
        data_only: false,
        progress: false,
        format: DiffOutputFormat::Text,
        verbose: false,
        max_pk_entries: 1_000_000,
        allow_no_pk: false,
        ignore_column_order: false,
        pk_overrides: std::collections::HashMap::new(),
    };

    let differ = Differ::new(config);
    let result = differ.diff().unwrap();

    // Should detect schema differences
    let schema_diff = result.schema.expect("Should have schema diff");
    assert!(
        !schema_diff.tables_added.is_empty() || !schema_diff.tables_removed.is_empty(),
        "Should detect table changes"
    );
}

#[test]
fn test_mssql_shard_tenant_column_detection() {
    use sql_splitter::shard::{GlobalTableMode, ShardConfig};

    // Don't specify tenant_column - let it auto-detect
    let config = ShardConfig {
        input: mssql_multi_tenant_fixture(),
        output: None,
        dialect: SqlDialect::Mssql,
        tenant_column: None, // Auto-detect
        tenant_value: "1".to_string(),
        root_tables: vec![],
        include_global: GlobalTableMode::Lookups,
        dry_run: true,
        progress: false,
        config_file: None,
        max_selected_rows: None,
        strict_fk: false,
        include_schema: true,
    };

    let stats = sql_splitter::shard::run(config).unwrap();

    // Should have auto-detected tenant_id
    assert_eq!(
        stats.detected_tenant_column,
        Some("tenant_id".to_string()),
        "Should auto-detect tenant_id column"
    );
}

// Phase 6: Query Command Tests

#[test]
fn test_mssql_query_command() {
    use sql_splitter::duckdb::{QueryConfig, QueryEngine};

    let config = QueryConfig {
        dialect: Some(SqlDialect::Mssql),
        disk_mode: false,
        cache_enabled: false,
        tables: None,
        memory_limit: None,
        progress: false,
    };

    let mut engine = QueryEngine::new(&config).expect("Should create engine");
    engine
        .import_dump(&mssql_simple_fixture())
        .expect("Should import dump");
    let result = engine
        .query("SELECT COUNT(*) as cnt FROM users")
        .expect("Should execute query");

    // Should have imported data (at least the table exists)
    assert!(!result.rows.is_empty(), "Query should return result");
}

#[test]
fn test_mssql_query_with_nvarchar() {
    use sql_splitter::duckdb::{QueryConfig, QueryEngine};

    let config = QueryConfig {
        dialect: Some(SqlDialect::Mssql),
        disk_mode: false,
        cache_enabled: false,
        tables: None,
        memory_limit: None,
        progress: false,
    };

    let mut engine = QueryEngine::new(&config).expect("Should create engine");
    engine
        .import_dump(&mssql_simple_fixture())
        .expect("Should import dump");
    let result = engine
        .query("SELECT email FROM users")
        .expect("Should execute query");

    // Should properly parse N'string' values
    assert!(!result.rows.is_empty(), "Query should return result");
}

// ============================================
// Phase 7: Test Data Generator Integration Tests
// ============================================

fn create_temp_sql(content: &str) -> NamedTempFile {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(content.as_bytes()).unwrap();
    file.flush().unwrap();
    file
}

/// Generate an MSSQL dump with test_data_gen
fn generate_mssql_dump(seed: u64, scale: Scale) -> NamedTempFile {
    let mut gen = Generator::new(seed, scale);
    let data = gen.generate();
    let renderer = Renderer::new(RenderConfig::mssql());
    let output = renderer.render_to_string(&data).unwrap();
    create_temp_sql(&output)
}

#[test]
fn test_mssql_generator_small_scale() {
    let file = generate_mssql_dump(42, Scale::Small);
    let content = fs::read_to_string(file.path()).unwrap();

    // Verify MSSQL-specific syntax
    assert!(
        content.contains("SET ANSI_NULLS ON;"),
        "Should have MSSQL header"
    );
    assert!(
        content.contains("SET QUOTED_IDENTIFIER ON;"),
        "Should have MSSQL header"
    );
    assert!(
        content.contains("CREATE TABLE [tenants]"),
        "Should use bracket quoting"
    );
    assert!(
        content.contains("INSERT INTO [tenants]"),
        "Should use bracket quoting for inserts"
    );
    assert!(
        content.contains("INT IDENTITY(1,1) NOT NULL PRIMARY KEY"),
        "Should use IDENTITY"
    );
    assert!(content.contains("NVARCHAR"), "Should use NVARCHAR types");
    assert!(content.contains("N'"), "Should use Unicode string literals");
    assert!(
        content.contains("DATETIME2"),
        "Should use DATETIME2 for timestamps"
    );
    assert!(content.contains("BIT"), "Should use BIT for booleans");
}

#[test]
fn test_mssql_generator_analyze() {
    use sql_splitter::analyzer::Analyzer;

    let file = generate_mssql_dump(42, Scale::Small);

    let stats = Analyzer::new(file.path().to_path_buf())
        .with_dialect(SqlDialect::Mssql)
        .analyze()
        .unwrap();

    // Small scale should have: tenants, users, roles, permissions, categories, products,
    // customers, orders, order_items, projects, tasks, folders, comments, etc.
    assert!(
        stats.len() >= 10,
        "Should find at least 10 tables, found {}",
        stats.len()
    );

    let table_names: Vec<String> = stats.iter().map(|s| s.table_name.clone()).collect();
    assert!(table_names.contains(&"tenants".to_string()));
    assert!(table_names.contains(&"users".to_string()));
    assert!(table_names.contains(&"orders".to_string()));
}

#[test]
fn test_mssql_generator_split() {
    let file = generate_mssql_dump(42, Scale::Small);
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().to_path_buf();

    let stats = Splitter::new(file.path().to_path_buf(), output_dir.clone())
        .with_dialect(SqlDialect::Mssql)
        .split()
        .unwrap();

    assert!(stats.tables_found >= 10, "Should find at least 10 tables");
    assert!(output_dir.join("tenants.sql").exists());
    assert!(output_dir.join("users.sql").exists());
    assert!(output_dir.join("orders.sql").exists());
}

#[test]
fn test_mssql_generator_validate() {
    let file = generate_mssql_dump(42, Scale::Small);

    let options = ValidateOptions {
        path: file.path().to_path_buf(),
        dialect: Some(SqlDialect::Mssql),
        progress: false,
        strict: false,
        json: false,
        max_rows_per_table: 1_000_000,
        fk_checks_enabled: true,
        max_pk_fk_keys: None,
    };

    let summary = Validator::new(options).validate().unwrap();

    assert_eq!(summary.summary.errors, 0, "Should have no errors");
    assert!(
        summary.summary.tables_scanned >= 10,
        "Should scan at least 10 tables"
    );
}

#[test]
fn test_mssql_generator_split_merge_roundtrip() {
    use sql_splitter::merger::Merger;

    let file = generate_mssql_dump(42, Scale::Small);
    let split_dir = TempDir::new().unwrap();
    let merged_file = NamedTempFile::new().unwrap();

    // Split
    let split_stats = Splitter::new(file.path().to_path_buf(), split_dir.path().to_path_buf())
        .with_dialect(SqlDialect::Mssql)
        .split()
        .unwrap();

    // Merge
    let merge_stats = Merger::new(
        split_dir.path().to_path_buf(),
        Some(merged_file.path().to_path_buf()),
    )
    .with_dialect(SqlDialect::Mssql)
    .merge()
    .unwrap();

    assert_eq!(
        split_stats.tables_found, merge_stats.tables_merged,
        "All tables should be merged back"
    );

    // Validate merged result
    let options = ValidateOptions {
        path: merged_file.path().to_path_buf(),
        dialect: Some(SqlDialect::Mssql),
        progress: false,
        strict: false,
        json: false,
        max_rows_per_table: 1_000_000,
        fk_checks_enabled: false, // FK checks may fail due to ordering
        max_pk_fk_keys: None,
    };

    let summary = Validator::new(options).validate().unwrap();
    assert_eq!(
        summary.summary.errors, 0,
        "Merged file should have no errors"
    );
}

#[test]
fn test_mssql_generator_sample_command() {
    use sql_splitter::sample::{GlobalTableMode, SampleConfig, SampleMode};

    let file = generate_mssql_dump(42, Scale::Small);
    let temp_dir = TempDir::new().unwrap();
    let output_file = temp_dir.path().join("sampled.sql");

    let config = SampleConfig {
        input: file.path().to_path_buf(),
        output: Some(output_file.clone()),
        dialect: SqlDialect::Mssql,
        mode: SampleMode::Percent(50),
        seed: 42,
        preserve_relations: true,
        progress: false,
        tables_filter: None,
        exclude: vec![],
        root_tables: vec![],
        include_global: GlobalTableMode::Lookups,
        dry_run: false,
        config_file: None,
        max_total_rows: None,
        strict_fk: false,
        include_schema: true,
    };

    let stats = sql_splitter::sample::run(config).unwrap();

    assert!(stats.total_rows_selected > 0, "Should sample some rows");
    assert!(output_file.exists(), "Output file should exist");

    let content = fs::read_to_string(&output_file).unwrap();
    assert!(content.contains("CREATE TABLE"), "Should include schema");
    assert!(content.contains("INSERT INTO"), "Should include data");
}

#[test]
fn test_mssql_generator_medium_scale() {
    let file = generate_mssql_dump(42, Scale::Medium);
    let content = fs::read_to_string(file.path()).unwrap();

    // Medium scale should generate more data
    let insert_count = content.matches("INSERT INTO").count();
    assert!(
        insert_count >= 10,
        "Medium scale should have multiple INSERT statements, found {}",
        insert_count
    );
}

#[test]
fn test_mssql_generator_deterministic() {
    // Two generators with same seed should produce identical output
    let file1 = generate_mssql_dump(12345, Scale::Small);
    let file2 = generate_mssql_dump(12345, Scale::Small);

    let content1 = fs::read_to_string(file1.path()).unwrap();
    let content2 = fs::read_to_string(file2.path()).unwrap();

    assert_eq!(
        content1, content2,
        "Same seed should produce identical output"
    );

    // Different seed should produce different output
    let file3 = generate_mssql_dump(99999, Scale::Small);
    let content3 = fs::read_to_string(file3.path()).unwrap();

    assert_ne!(
        content1, content3,
        "Different seed should produce different output"
    );
}

#[test]
fn test_mssql_generator_production_style() {
    // Test the production-style MSSQL output with GO separators, [dbo]. prefix, and named constraints
    let mut gen = Generator::new(42, Scale::Small);
    let data = gen.generate();

    let renderer = Renderer::new(RenderConfig::mssql_production());
    let sql = renderer.render_to_string(&data).unwrap();

    // Verify GO batch separators
    assert!(sql.contains("GO\n"), "Should have GO batch separators");
    assert!(
        sql.contains("SET ANSI_NULLS ON\nGO"),
        "Header should use GO separators"
    );

    // Verify [dbo]. schema prefix
    assert!(
        sql.contains("[dbo].[tenants]"),
        "Should have [dbo]. schema prefix on CREATE TABLE"
    );
    assert!(
        sql.contains("INSERT INTO [dbo].[tenants]"),
        "Should have [dbo]. schema prefix on INSERT"
    );

    // Verify named CONSTRAINT syntax
    assert!(
        sql.contains("CONSTRAINT [PK_tenants] PRIMARY KEY CLUSTERED"),
        "Should have named PK constraint"
    );

    // Verify ON [PRIMARY] filegroup
    assert!(
        sql.contains(") ON [PRIMARY];"),
        "Should have ON [PRIMARY] filegroup"
    );
}

// ============================================================================
// Redact command tests for MSSQL
// ============================================================================

use sql_splitter::redactor::{RedactConfig, Redactor};

#[test]
fn test_mssql_redact_null_strategy() {
    // Generate a small MSSQL fixture
    let input_file = generate_mssql_dump(42, Scale::Small);
    let output_dir = TempDir::new().unwrap();
    let output_file = output_dir.path().join("redacted.sql");

    // Configure redaction: set email columns to NULL
    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .output(Some(output_file.clone()))
        .dialect(SqlDialect::Mssql)
        .null_patterns(vec!["*.email".to_string()])
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    // Verify redaction occurred
    assert!(stats.tables_processed > 0, "Should have processed tables");
    assert!(stats.columns_redacted > 0, "Should have redacted columns");

    // Verify output file exists and has content
    let output_content = fs::read_to_string(&output_file).unwrap();
    assert!(!output_content.is_empty(), "Output should not be empty");

    // Verify NULL values appear in place of emails
    assert!(
        output_content.contains("NULL"),
        "Should contain NULL values"
    );
}

#[test]
fn test_mssql_redact_hash_strategy() {
    let input_file = generate_mssql_dump(42, Scale::Small);
    let output_dir = TempDir::new().unwrap();
    let output_file = output_dir.path().join("redacted.sql");

    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .output(Some(output_file.clone()))
        .dialect(SqlDialect::Mssql)
        .hash_patterns(vec!["*.email".to_string()])
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    assert!(stats.columns_redacted > 0, "Should have redacted columns");

    let output_content = fs::read_to_string(&output_file).unwrap();
    // Verify the output is valid SQL and has been modified
    assert!(!output_content.is_empty(), "Output should not be empty");
    // Hash strategy produces hex strings, verify they appear
    assert!(
        output_content.contains("INSERT INTO"),
        "Should contain INSERT statements"
    );
}

#[test]
fn test_mssql_redact_preserves_bracket_quoting() {
    // Create a simple MSSQL INSERT to test bracket preservation
    let input_content = r#"CREATE TABLE [users] (
    [id] INT IDENTITY(1,1) NOT NULL,
    [email] NVARCHAR(255),
    [name] NVARCHAR(100)
);
INSERT INTO [users] ([id], [email], [name]) VALUES (1, N'alice@example.com', N'Alice');
INSERT INTO [users] ([id], [email], [name]) VALUES (2, N'bob@example.com', N'Bob');
"#;

    let mut input_file = NamedTempFile::new().unwrap();
    input_file.write_all(input_content.as_bytes()).unwrap();
    input_file.flush().unwrap();

    let output_dir = TempDir::new().unwrap();
    let output_file = output_dir.path().join("redacted.sql");

    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .output(Some(output_file.clone()))
        .dialect(SqlDialect::Mssql)
        .null_patterns(vec!["*.email".to_string()])
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    assert_eq!(stats.rows_redacted, 2, "Should have redacted 2 rows");

    let output_content = fs::read_to_string(&output_file).unwrap();

    // Verify bracket quoting is preserved in output
    assert!(
        output_content.contains("[users]"),
        "Should preserve [users] bracket quoting"
    );
    assert!(
        output_content.contains("[id]"),
        "Should preserve [id] bracket quoting"
    );
    assert!(
        output_content.contains("[name]"),
        "Should preserve [name] bracket quoting"
    );
}

#[test]
fn test_mssql_redact_unicode_strings() {
    // Test that Unicode N'...' strings are handled correctly
    let input_content = r#"CREATE TABLE [users] (
    [id] INT NOT NULL,
    [name] NVARCHAR(100),
    [bio] NVARCHAR(500)
);
INSERT INTO [users] ([id], [name], [bio]) VALUES (1, N'日本語', N'Unicode text with émojis 🎉');
INSERT INTO [users] ([id], [name], [bio]) VALUES (2, N'中文', N'More unicode: café');
"#;

    let mut input_file = NamedTempFile::new().unwrap();
    input_file.write_all(input_content.as_bytes()).unwrap();
    input_file.flush().unwrap();

    let output_dir = TempDir::new().unwrap();
    let output_file = output_dir.path().join("redacted.sql");

    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .output(Some(output_file.clone()))
        .dialect(SqlDialect::Mssql)
        .null_patterns(vec!["*.bio".to_string()])
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    assert_eq!(stats.rows_redacted, 2, "Should have redacted 2 rows");
    assert_eq!(
        stats.columns_redacted, 2,
        "Should have redacted 2 bio columns"
    );

    let output_content = fs::read_to_string(&output_file).unwrap();

    // The bio column should be NULL, but names should be preserved
    assert!(output_content.contains("NULL"), "Bio should be NULL");
    // Unicode names may be preserved depending on how they're parsed
}

#[test]
fn test_mssql_redact_fake_strategy() {
    let input_file = generate_mssql_dump(42, Scale::Small);
    let output_dir = TempDir::new().unwrap();
    let output_file = output_dir.path().join("redacted.sql");

    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .output(Some(output_file.clone()))
        .dialect(SqlDialect::Mssql)
        .fake_patterns(vec!["*.name".to_string()])
        .seed(Some(42)) // For reproducibility
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    assert!(
        stats.columns_redacted > 0,
        "Should have redacted name columns"
    );

    let output_content = fs::read_to_string(&output_file).unwrap();
    assert!(!output_content.is_empty(), "Output should not be empty");
}

#[test]
fn test_mssql_redact_dry_run() {
    let input_file = generate_mssql_dump(42, Scale::Small);

    let config = RedactConfig::builder()
        .input(input_file.path().to_path_buf())
        .dialect(SqlDialect::Mssql)
        .null_patterns(vec!["*.email".to_string(), "*.password".to_string()])
        .dry_run(true)
        .build()
        .unwrap();

    let mut redactor = Redactor::new(config).unwrap();
    let stats = redactor.run().unwrap();

    // Dry run should still report statistics
    assert!(stats.tables_processed > 0, "Dry run should report tables");
    // Note: dry run counts statements, not actual rows, so stats may differ
}

#[test]
fn test_mssql_redact_reproducible_with_seed() {
    let input_file = generate_mssql_dump(42, Scale::Small);
    let output_dir = TempDir::new().unwrap();
    let output_file1 = output_dir.path().join("redacted1.sql");
    let output_file2 = output_dir.path().join("redacted2.sql");

    // Run redaction twice with same seed
    for output_file in [&output_file1, &output_file2] {
        let config = RedactConfig::builder()
            .input(input_file.path().to_path_buf())
            .output(Some(output_file.clone()))
            .dialect(SqlDialect::Mssql)
            .hash_patterns(vec!["*.email".to_string()])
            .seed(Some(12345))
            .build()
            .unwrap();

        let mut redactor = Redactor::new(config).unwrap();
        redactor.run().unwrap();
    }

    let content1 = fs::read_to_string(&output_file1).unwrap();
    let content2 = fs::read_to_string(&output_file2).unwrap();

    assert_eq!(
        content1, content2,
        "Same seed should produce identical output"
    );
}