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
/// Comprehensive edge case and mutation tests for the SQL parser.
///
/// These tests cover:
/// - Malformed SQL
/// - Unusual encodings and binary data
/// - Edge cases in string handling
/// - Multi-line statements
/// - Comments (-- and /* */)
/// - Nested quotes and escaped characters
/// - Very long statements
/// - Empty files and truncated input
/// - NULL bytes and BOM
use sql_splitter::parser::{Parser, SqlDialect, StatementType};

// =========================================================================
// A. Statement Splitting (read_statement) Edge Cases
// =========================================================================

mod read_statement_tests {
    use super::*;

    // A.1 Basic termination variants

    #[test]
    fn test_statement_without_trailing_semicolon() {
        let sql = b"CREATE TABLE t1 (id INT)";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        assert_eq!(stmt.unwrap(), b"CREATE TABLE t1 (id INT)");

        let next = parser.read_statement().unwrap();
        assert!(next.is_none());
    }

    #[test]
    fn test_empty_input() {
        let sql = b"";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_none());
    }

    #[test]
    fn test_whitespace_only_input() {
        let sql = b"   \n\t  ";
        let mut parser = Parser::new(&sql[..], 1024);

        // Whitespace without semicolon returns the whitespace as a statement at EOF
        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some()); // Contains whitespace
    }

    // A.2 Strings, escapes, and nested quotes

    #[test]
    fn test_double_quoted_string_with_semicolon() {
        let sql = b"INSERT INTO t1 VALUES (\"hello; world\");";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt, b"INSERT INTO t1 VALUES (\"hello; world\");");

        let next = parser.read_statement().unwrap();
        assert!(next.is_none());
    }

    #[test]
    fn test_mixed_quotes_with_semicolons() {
        let sql = b"INSERT INTO t1 VALUES ('foo \"bar; baz\"', \"x'y;z\");";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(
            stmt,
            b"INSERT INTO t1 VALUES ('foo \"bar; baz\"', \"x'y;z\");"
        );
    }

    #[test]
    fn test_sql_style_doubled_quotes() {
        // SQL uses '' to escape single quotes, not \'
        let sql = b"INSERT INTO t1 VALUES ('it''s a test; still one');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt, b"INSERT INTO t1 VALUES ('it''s a test; still one');");
    }

    #[test]
    fn test_escape_near_buffer_boundary() {
        // Use tiny buffer to force multiple fill_buf calls
        let sql = b"INSERT INTO t1 VALUES ('foo\\'bar');";
        let mut parser = Parser::new(&sql[..], 8);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt, b"INSERT INTO t1 VALUES ('foo\\'bar');");
    }

    #[test]
    fn test_multiple_backslashes() {
        let sql = b"INSERT INTO t1 VALUES ('\\\\');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt, b"INSERT INTO t1 VALUES ('\\\\');");
    }

    #[test]
    fn test_escaped_semicolon_in_string() {
        let sql = b"INSERT INTO t1 VALUES ('escaped\\;semicolon');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        // Note: \; is not a standard escape, but backslash escapes the next char
        assert!(stmt.len() > 0);
    }

    #[test]
    fn test_backtick_with_semicolon_inside() {
        // Note: Current parser does NOT treat backticks as string delimiters
        // This documents that limitation
        let sql = b"CREATE TABLE `t;weird` (id INT);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        // Parser may split early at the semicolon inside backticks
        // This test documents current behavior
        assert!(stmt.len() > 0);
    }

    // A.3 Multi-line and formatting

    #[test]
    fn test_multiline_statement() {
        let sql = b"CREATE TABLE t1 (\n  id INT,\n  name VARCHAR(255)\n);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(
            stmt,
            b"CREATE TABLE t1 (\n  id INT,\n  name VARCHAR(255)\n);"
        );
    }

    #[test]
    fn test_newlines_inside_string() {
        let sql = b"INSERT INTO t1 VALUES ('first line\nsecond line; still in string');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(
            stmt,
            b"INSERT INTO t1 VALUES ('first line\nsecond line; still in string');"
        );
    }

    // A.4 Comments and semicolons
    // Note: Current parser does NOT handle SQL comments

    #[test]
    fn test_single_line_comment_with_semicolon() {
        // Documents current behavior: semicolon in comment WILL split
        let sql = b"-- comment with ; semicolon\nCREATE TABLE t1 (id INT);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt1 = parser.read_statement().unwrap().unwrap();
        // Current behavior: splits at the semicolon in the comment
        assert!(stmt1.ends_with(b";"));
    }

    #[test]
    fn test_block_comment_with_semicolon() {
        // Documents current limitation: block comments with semicolons break parsing
        let sql = b"CREATE TABLE t1 (id INT) /* comment; with semicolon */ ;";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt1 = parser.read_statement().unwrap().unwrap();
        // Current behavior: splits at semicolon inside comment
        assert!(stmt1.len() > 0);
    }

    // A.5 Truncation, malformed strings, EOF

    #[test]
    fn test_unclosed_single_quote_at_eof() {
        let sql = b"INSERT INTO t1 VALUES ('unterminated";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        // Returns the fragment, no panic
    }

    #[test]
    fn test_unclosed_double_quote_at_eof() {
        let sql = b"INSERT INTO t1 VALUES (\"unterminated";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
    }

    #[test]
    fn test_truncated_escape_at_eof() {
        let sql = b"INSERT INTO t1 VALUES ('foo\\";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
    }

    // A.6 Weird bytes / encodings

    #[test]
    fn test_null_byte_inside_string() {
        let sql = b"INSERT INTO t1 VALUES ('a\0b;still_in_string');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        // Should not split at the semicolon inside the string
        assert!(stmt.contains(&b';'));
    }

    #[test]
    fn test_binary_hex_data() {
        let sql = b"INSERT INTO t1 VALUES (X'00FFABCD');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt, b"INSERT INTO t1 VALUES (X'00FFABCD');");
    }

    #[test]
    fn test_utf8_bom_prefix() {
        let sql = b"\xEF\xBB\xBFCREATE TABLE t1 (id INT);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        assert!(stmt.len() > 0);
    }

    #[test]
    fn test_very_long_statement() {
        // Create a statement larger than typical buffer size
        let mut sql = b"INSERT INTO t1 VALUES (".to_vec();
        for i in 0..10000 {
            if i > 0 {
                sql.extend_from_slice(b", ");
            }
            sql.extend_from_slice(format!("'{}'", i).as_bytes());
        }
        sql.extend_from_slice(b");");

        let mut parser = Parser::new(&sql[..], 1024);
        let stmt = parser.read_statement().unwrap().unwrap();
        assert_eq!(stmt.len(), sql.len());
    }

    #[test]
    fn test_multiple_statements() {
        let sql = b"CREATE TABLE t1 (id INT); INSERT INTO t1 VALUES (1); DROP TABLE t1;";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt1 = parser.read_statement().unwrap().unwrap();
        let stmt2 = parser.read_statement().unwrap().unwrap();
        let stmt3 = parser.read_statement().unwrap().unwrap();
        let stmt4 = parser.read_statement().unwrap();

        assert!(stmt1.starts_with(b"CREATE"));
        assert!(stmt2.ends_with(b";"));
        assert!(stmt3.ends_with(b";"));
        assert!(stmt4.is_none());
    }
}

// =========================================================================
// B. Statement Parsing (parse_statement) Edge Cases
// =========================================================================

mod parse_statement_tests {
    use super::*;

    // B.1 CREATE TABLE variations

    #[test]
    fn test_create_table_leading_whitespace() {
        let stmt = b"   \t\nCREATE TABLE users (id INT);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_create_table_if_not_exists() {
        // Documents current behavior: captures "IF" as table name
        let stmt = b"CREATE TABLE IF NOT EXISTS users (id INT);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        // Current limitation: extracts "IF" instead of "users"
        // This test documents the behavior
        assert!(!name.is_empty());
    }

    #[test]
    fn test_create_table_schema_qualified() {
        // Schema-qualified names extract just the table name (not the schema)
        let stmt = b"CREATE TABLE db.users (id INT);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_create_table_schema_qualified_backticks() {
        let stmt = b"CREATE TABLE `db`.`users` (id INT);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        // Current behavior: captures only "db"
        assert!(!name.is_empty());
    }

    #[test]
    fn test_create_table_double_quoted_identifier() {
        let stmt = b"CREATE TABLE \"User\" (id INT);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "User");
    }

    #[test]
    fn test_create_table_lowercase() {
        let stmt = b"create table users (id int);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_create_table_mixed_case() {
        let stmt = b"Create Table Users (Id Int);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "Users");
    }

    // B.2 INSERT INTO variations

    #[test]
    fn test_insert_leading_whitespace() {
        let stmt = b"  INSERT INTO posts VALUES (1);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "posts");
    }

    #[test]
    fn test_insert_schema_qualified() {
        // Schema-qualified names extract just the table name (not the schema)
        let stmt = b"INSERT INTO db.posts VALUES (1);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "posts");
    }

    #[test]
    fn test_insert_with_column_list() {
        let stmt = b"INSERT INTO posts(id, name) VALUES (1, 'x');";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "posts");
    }

    #[test]
    fn test_insert_lowercase() {
        let stmt = b"insert into posts values (1);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "posts");
    }

    // B.3 CREATE INDEX variations

    #[test]
    fn test_create_index_basic() {
        let stmt = b"CREATE INDEX idx_posts_on_user_id ON posts(user_id);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateIndex);
        assert_eq!(name, "posts");
    }

    #[test]
    fn test_create_index_backtick_table() {
        let stmt = b"CREATE INDEX idx ON `posts` (id);";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::CreateIndex);
        assert_eq!(name, "posts");
    }

    #[test]
    fn test_create_unique_index() {
        // Documents current limitation: UNIQUE keyword breaks detection
        let stmt = b"CREATE UNIQUE INDEX idx ON posts(user_id);";
        let (typ, _name) = Parser::<&[u8]>::parse_statement(stmt);
        // Current behavior: may not recognize as CreateIndex
        // This documents the limitation
        assert!(typ == StatementType::CreateIndex || typ == StatementType::Unknown);
    }

    // B.4 ALTER TABLE variations

    #[test]
    fn test_alter_table_if_exists() {
        // Documents current behavior with IF EXISTS
        let stmt = b"ALTER TABLE IF EXISTS orders ADD COLUMN status INT;";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::AlterTable);
        // Current limitation: may extract "IF" as table name
        assert!(!name.is_empty());
    }

    #[test]
    fn test_alter_table_schema_qualified() {
        // Schema-qualified names extract just the table name (not the schema)
        let stmt = b"ALTER TABLE db.orders ADD COLUMN status INT;";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::AlterTable);
        assert_eq!(name, "orders");
    }

    // B.5 DROP TABLE variations

    #[test]
    fn test_drop_table_if_exists() {
        // Documents current behavior with IF EXISTS
        let stmt = b"DROP TABLE IF EXISTS temp_data;";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::DropTable);
        // Current limitation: may extract "IF" as table name
        assert!(!name.is_empty());
    }

    #[test]
    fn test_drop_table_schema_qualified() {
        // Schema-qualified names extract just the table name (not the schema)
        let stmt = b"DROP TABLE db.temp_data;";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::DropTable);
        assert_eq!(name, "temp_data");
    }

    // B.6 Unknown and malformed statements

    #[test]
    fn test_select_statement_unknown() {
        let stmt = b"SELECT * FROM users;";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_comment_statement_unknown() {
        let stmt = b"-- This is a comment";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_empty_statement() {
        let stmt = b"";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_whitespace_only_statement() {
        let stmt = b"   \t\n   ";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_garbage_input() {
        let stmt = b"@#$%^&*";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_binary_garbage_no_panic() {
        let stmt = b"\xFF\xFF\x00\x01";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_utf8_bom_prefix_statement() {
        // BOM prefix may prevent statement recognition
        let stmt = b"\xEF\xBB\xBFCREATE TABLE t1 (id INT);";
        let (typ, _name) = Parser::<&[u8]>::parse_statement(stmt);
        // Current behavior: BOM not stripped, so likely Unknown
        // This documents the limitation
        assert!(typ == StatementType::CreateTable || typ == StatementType::Unknown);
    }

    #[test]
    fn test_very_short_statement() {
        let stmt = b"abc";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_partial_keyword() {
        let stmt = b"CREAT";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }

    #[test]
    fn test_keyword_only_no_table() {
        let stmt = b"CREATE TABLE";
        let (typ, name) = Parser::<&[u8]>::parse_statement(stmt);
        // Parser returns Unknown when it can't extract a table name
        // This is correct behavior for malformed SQL
        assert_eq!(typ, StatementType::Unknown);
        assert!(name.is_empty());
    }
}

// =========================================================================
// C. End-to-End Parsing Scenarios
// =========================================================================

mod e2e_tests {
    use super::*;

    #[test]
    fn test_real_mysqldump_header() {
        let sql = b"-- MySQL dump 10.13  Distrib 8.0.32, for macos13 (arm64)
--
-- Host: localhost    Database: mydb
-- ------------------------------------------------------
-- Server version\t8.0.32

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;

CREATE TABLE `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

INSERT INTO `users` VALUES (1,'Alice');
INSERT INTO `users` VALUES (2,'Bob');
";
        let mut parser = Parser::new(&sql[..], 1024);
        let mut statements = Vec::new();

        while let Some(stmt) = parser.read_statement().unwrap() {
            statements.push(stmt);
        }

        // Should have multiple statements
        assert!(statements.len() >= 3);

        // Find the CREATE TABLE statement
        let create_stmt = statements
            .iter()
            .find(|s| s.windows(12).any(|w| w == b"CREATE TABLE"));
        assert!(create_stmt.is_some());

        // Find INSERT statements
        let insert_count = statements
            .iter()
            .filter(|s| s.windows(11).any(|w| w == b"INSERT INTO"))
            .count();
        assert!(insert_count >= 2);
    }

    #[test]
    fn test_statement_with_all_quote_types() {
        let sql = b"INSERT INTO `table` VALUES (1, 'single', \"double\", `backtick`);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement(&stmt);

        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "table");
    }

    #[test]
    fn test_extended_insert() {
        // MySQL extended insert format
        let sql = b"INSERT INTO `users` VALUES (1,'Alice'),(2,'Bob'),(3,'Charlie');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement(&stmt);

        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_create_table_with_constraints() {
        let sql = b"CREATE TABLE `orders` (
  `id` int NOT NULL,
  `user_id` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user` (`user_id`),
  CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB;";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement(&stmt);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "orders");
    }
}

// =========================================================================
// PostgreSQL Dollar-Quoting Tests
// =========================================================================

mod postgres_dollar_quoting_tests {
    use super::*;

    #[test]
    fn test_postgres_empty_dollar_quote() {
        let sql = b"CREATE FUNCTION test() RETURNS text AS $$SELECT 1$$ LANGUAGE sql;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        assert!(stmt.unwrap().ends_with(b";"));
    }

    #[test]
    fn test_postgres_named_dollar_quote() {
        let sql = b"CREATE FUNCTION test() RETURNS text AS $_$SELECT 1$_$ LANGUAGE sql;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
    }

    #[test]
    fn test_postgres_dollar_quote_with_semicolon_inside() {
        let sql = b"CREATE FUNCTION test() RETURNS text AS $$SELECT 1; SELECT 2;$$ LANGUAGE sql;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        let s = stmt.unwrap();
        assert!(s.starts_with(b"CREATE FUNCTION"));
        assert!(s.ends_with(b";"));
    }

    #[test]
    fn test_postgres_mixed_dollar_quote_tags() {
        // This was the bug: $_$ followed by $$ would break parsing
        let sql = br#"
CREATE FUNCTION test1() RETURNS text AS $_$
SELECT 1;
$_$;

CREATE FUNCTION test2() RETURNS text AS $$
SELECT 2;
$$;

CREATE TABLE test (id INT);
"#;
        let mut parser = Parser::with_dialect(&sql[..], 4096, SqlDialect::Postgres);
        let mut statements = Vec::new();

        while let Some(stmt) = parser.read_statement().unwrap() {
            statements.push(String::from_utf8_lossy(&stmt).into_owned());
        }

        assert!(
            statements
                .iter()
                .any(|s| s.contains("CREATE FUNCTION test1")),
            "Should find test1 function"
        );
        assert!(
            statements
                .iter()
                .any(|s| s.contains("CREATE FUNCTION test2")),
            "Should find test2 function"
        );
        assert!(
            statements.iter().any(|s| s.contains("CREATE TABLE test")),
            "Should find CREATE TABLE"
        );
    }

    #[test]
    fn test_postgres_invalid_dollar_tag_not_matched() {
        // A $ followed by invalid chars then another $ should not be treated as dollar-quote
        let sql = b"SELECT $1 + $2;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        assert_eq!(stmt.unwrap(), b"SELECT $1 + $2;");
    }

    #[test]
    fn test_postgres_schema_qualified_table() {
        let sql = b"CREATE TABLE public.users (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) =
            Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::Postgres);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_postgres_copy_from_stdin() {
        let sql = b"COPY users FROM stdin;\n1\tAlice\n2\tBob\n\\.\nCREATE TABLE test (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt1 = parser.read_statement().unwrap();
        assert!(stmt1.is_some());
        assert!(stmt1.unwrap().starts_with(b"COPY users"));

        // COPY data block
        let stmt2 = parser.read_statement().unwrap();
        assert!(stmt2.is_some());

        let stmt3 = parser.read_statement().unwrap();
        assert!(stmt3.is_some());
        assert!(std::str::from_utf8(&stmt3.unwrap())
            .unwrap()
            .contains("CREATE TABLE"));
    }

    #[test]
    fn test_postgres_nested_dollar_quotes() {
        // Function containing $$ inside $_$ quotes
        let sql = b"CREATE FUNCTION test() AS $_$
            SELECT '$$not a quote$$';
        $_$;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        let s = stmt.unwrap();
        assert!(s.starts_with(b"CREATE FUNCTION"));
        assert!(s.ends_with(b";"));
    }

    #[test]
    fn test_postgres_insert_into_schema_qualified() {
        let sql = b"INSERT INTO public.users (id, name) VALUES (1, 'Alice');";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) =
            Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::Postgres);

        assert_eq!(typ, StatementType::Insert);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_postgres_double_quoted_identifiers() {
        let sql = b"CREATE TABLE \"My Table\" (\"Column One\" INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Postgres);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) =
            Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::Postgres);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "My Table");
    }
}

// =========================================================================
// SQLite-Specific Tests
// =========================================================================

mod sqlite_tests {
    use super::*;

    #[test]
    fn test_sqlite_create_table() {
        let sql = b"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Sqlite);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::Sqlite);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_sqlite_double_quoted_table() {
        let sql = b"CREATE TABLE \"my-table\" (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Sqlite);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::Sqlite);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "my-table");
    }

    #[test]
    fn test_sqlite_insert_replace() {
        let sql = b"INSERT OR REPLACE INTO users VALUES (1, 'Alice');";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Sqlite);

        let stmt = parser.read_statement().unwrap().unwrap();
        // Should still be recognized as an insert
        assert!(stmt.starts_with(b"INSERT"));
    }

    #[test]
    fn test_sqlite_pragma_ignored() {
        let sql = b"PRAGMA foreign_keys=ON; CREATE TABLE users (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::Sqlite);

        let stmt1 = parser.read_statement().unwrap();
        assert!(stmt1.is_some());

        let stmt2 = parser.read_statement().unwrap();
        assert!(stmt2.is_some());
        let (typ, name) =
            Parser::<&[u8]>::parse_statement_with_dialect(&stmt2.unwrap(), SqlDialect::Sqlite);
        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }
}

// =========================================================================
// MySQL-Specific Tests
// =========================================================================

mod mysql_tests {
    use super::*;

    #[test]
    fn test_mysql_backtick_with_spaces() {
        let sql = b"CREATE TABLE `my table` (`column name` INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::MySql);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "my table");
    }

    #[test]
    fn test_mysql_conditional_comment() {
        let sql = b"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; CREATE TABLE t (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let stmt1 = parser.read_statement().unwrap();
        assert!(stmt1.is_some());

        let stmt2 = parser.read_statement().unwrap();
        assert!(stmt2.is_some());
    }

    #[test]
    fn test_mysql_lock_unlock_tables() {
        let sql = b"LOCK TABLES `users` WRITE; INSERT INTO `users` VALUES (1); UNLOCK TABLES;";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let mut count = 0;
        while let Some(_) = parser.read_statement().unwrap() {
            count += 1;
        }
        assert_eq!(count, 3);
    }

    #[test]
    fn test_mysql_escaped_backtick_in_name() {
        let sql = b"CREATE TABLE `my``table` (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, _name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::MySql);

        assert_eq!(typ, StatementType::CreateTable);
    }

    #[test]
    fn test_mysql_multiline_insert() {
        let sql = b"INSERT INTO users VALUES
            (1, 'Alice'),
            (2, 'Bob'),
            (3, 'Charlie');";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        let s = stmt.unwrap();
        let text = std::str::from_utf8(&s).unwrap();
        assert!(text.contains("Alice"));
        assert!(text.contains("Charlie"));
    }

    #[test]
    fn test_mysql_create_table_if_not_exists() {
        let sql = b"CREATE TABLE IF NOT EXISTS users (id INT);";
        let mut parser = Parser::with_dialect(&sql[..], 1024, SqlDialect::MySql);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, SqlDialect::MySql);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, "users");
    }
}

// =========================================================================
// Cross-Dialect Edge Cases
// =========================================================================

mod cross_dialect_tests {
    use super::*;

    #[test]
    fn test_alter_table_all_dialects() {
        for dialect in [SqlDialect::MySql, SqlDialect::Postgres, SqlDialect::Sqlite] {
            let sql = b"ALTER TABLE users ADD COLUMN email VARCHAR(255);";
            let mut parser = Parser::with_dialect(&sql[..], 1024, dialect);

            let stmt = parser.read_statement().unwrap().unwrap();
            let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);

            assert_eq!(typ, StatementType::AlterTable);
            assert_eq!(name, "users");
        }
    }

    #[test]
    fn test_drop_table_all_dialects() {
        for dialect in [SqlDialect::MySql, SqlDialect::Postgres, SqlDialect::Sqlite] {
            let sql = b"DROP TABLE IF EXISTS users;";
            let mut parser = Parser::with_dialect(&sql[..], 1024, dialect);

            let stmt = parser.read_statement().unwrap().unwrap();
            let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);

            assert_eq!(typ, StatementType::DropTable);
            assert_eq!(name, "users");
        }
    }

    #[test]
    fn test_drop_table_simple() {
        let sql = b"DROP TABLE users;";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement(&stmt);

        assert_eq!(typ, StatementType::DropTable);
        assert_eq!(name, "users");
    }

    #[test]
    fn test_create_index_all_dialects() {
        for dialect in [SqlDialect::MySql, SqlDialect::Postgres, SqlDialect::Sqlite] {
            let sql = b"CREATE INDEX idx_email ON users (email);";
            let mut parser = Parser::with_dialect(&sql[..], 1024, dialect);

            let stmt = parser.read_statement().unwrap().unwrap();
            let (typ, name) = Parser::<&[u8]>::parse_statement_with_dialect(&stmt, dialect);

            assert_eq!(typ, StatementType::CreateIndex);
            assert_eq!(name, "users");
        }
    }

    #[test]
    fn test_very_long_table_name() {
        let long_name = "a".repeat(128);
        let sql = format!("CREATE TABLE {} (id INT);", long_name);
        let mut parser = Parser::new(sql.as_bytes(), 1024);

        let stmt = parser.read_statement().unwrap().unwrap();
        let (typ, name) = Parser::<&[u8]>::parse_statement(&stmt);

        assert_eq!(typ, StatementType::CreateTable);
        assert_eq!(name, long_name);
    }

    #[test]
    fn test_unicode_in_string_values() {
        let sql = "INSERT INTO users VALUES (1, '日本語テスト', 'émoji 🎉');".as_bytes();
        let mut parser = Parser::new(sql, 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
    }

    #[test]
    fn test_binary_data_in_blob() {
        // Binary data with null bytes in a string
        let sql = b"INSERT INTO files VALUES (1, X'00FF00FF');";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
    }

    #[test]
    fn test_empty_table_name_handling() {
        // Malformed SQL - should not crash
        let sql = b"CREATE TABLE  (id INT);";
        let mut parser = Parser::new(&sql[..], 1024);

        let stmt = parser.read_statement().unwrap();
        assert!(stmt.is_some());
        // parse_statement should return Unknown for malformed SQL
        let (typ, _) = Parser::<&[u8]>::parse_statement(&stmt.unwrap());
        assert_eq!(typ, StatementType::Unknown);
    }

    #[test]
    fn test_multiple_semicolons() {
        let sql = b"SELECT 1;; SELECT 2;;;";
        let mut parser = Parser::new(&sql[..], 1024);

        let mut count = 0;
        while let Some(_) = parser.read_statement().unwrap() {
            count += 1;
        }
        // Should handle empty statements between semicolons
        assert!(count >= 2);
    }
}