innodb-utils 5.0.0

InnoDB file analysis toolkit
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
use clap::{Parser, Subcommand, ValueEnum};

/// Top-level CLI definition for the `inno` binary.
#[derive(Parser)]
#[command(name = "inno")]
#[command(about = "InnoDB file analysis toolkit")]
#[command(version)]
pub struct Cli {
    /// Control colored output
    #[arg(long, default_value = "auto", global = true)]
    pub color: ColorMode,

    /// Write output to a file instead of stdout
    #[arg(short, long, global = true)]
    pub output: Option<String>,

    /// Number of threads for parallel page processing (0 = auto-detect CPU count)
    #[arg(long, default_value = "0", global = true)]
    pub threads: usize,

    /// Use memory-mapped I/O for file access (can be faster for large files)
    #[arg(long, global = true)]
    pub mmap: bool,

    /// Output format (text, json, or csv); overrides per-subcommand --json
    #[arg(long, global = true, default_value = "text")]
    pub format: OutputFormat,

    /// Write NDJSON audit events to a file for all write operations
    #[arg(long = "audit-log", global = true)]
    pub audit_log: Option<String>,

    #[command(subcommand)]
    pub command: Commands,
}

/// Controls when colored output is emitted.
#[derive(Clone, Copy, ValueEnum)]
pub enum ColorMode {
    Auto,
    Always,
    Never,
}

/// Global output format selection.
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    Text,
    Json,
    Csv,
}

/// Available subcommands for the `inno` CLI.
#[derive(Subcommand)]
pub enum Commands {
    /// Parse .ibd file and display page summary
    ///
    /// Reads the 38-byte FIL header of every page in a tablespace, decodes the
    /// page type, checksum, LSN, prev/next pointers, and space ID, then prints
    /// a per-page breakdown followed by a page-type frequency summary table.
    /// Page 0 additionally shows the FSP header (space ID, size, flags).
    /// Use `--no-empty` to skip zero-checksum allocated pages, or `-p` to
    /// inspect a single page in detail. With `--verbose`, checksum validation
    /// and LSN consistency results are included for each page.
    Parse {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Display a specific page number
        #[arg(short, long)]
        page: Option<u64>,

        /// Display additional information
        #[arg(short, long)]
        verbose: bool,

        /// Skip empty/allocated pages
        #[arg(short = 'e', long = "no-empty")]
        no_empty: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Stream results incrementally for lower memory usage (disables parallel processing)
        #[arg(long)]
        streaming: bool,
    },

    /// Detailed page structure analysis
    ///
    /// Goes beyond FIL headers to decode the internal structure of each page
    /// type: INDEX pages show the B+Tree index header, FSEG inode pointers, and
    /// infimum/supremum system records; UNDO pages show the undo page header
    /// and segment state; BLOB/LOB pages show chain pointers and data lengths;
    /// and page 0 shows extended FSP header fields including compression and
    /// encryption flags. Use `-l` for a compact one-line-per-page listing,
    /// `-t INDEX` to filter by page type, or `-p` for a single page deep dive.
    Pages {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Display a specific page number
        #[arg(short, long)]
        page: Option<u64>,

        /// Display additional information
        #[arg(short, long)]
        verbose: bool,

        /// Show empty/allocated pages
        #[arg(short = 'e', long = "show-empty")]
        show_empty: bool,

        /// Compact list mode (one line per page)
        #[arg(short, long)]
        list: bool,

        /// Filter by page type (e.g., INDEX)
        #[arg(short = 't', long = "type")]
        filter_type: Option<String>,

        /// Show delete-marked record statistics for INDEX pages
        #[arg(long)]
        deleted: bool,

        /// Traverse and display LOB/BLOB chain details for LOB first pages
        #[arg(long = "lob-chain")]
        lob_chain: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Hex dump of raw page bytes
    ///
    /// Operates in two modes: **page mode** (default) reads a full page by
    /// number and produces a formatted hex dump with file-relative offsets;
    /// **offset mode** (`--offset`) reads bytes at an arbitrary file position,
    /// useful for inspecting structures that cross page boundaries. Use
    /// `--length` to limit the number of bytes shown, or `--raw` to emit
    /// unformatted binary bytes suitable for piping to other tools.
    Dump {
        /// Path to InnoDB data file
        #[arg(short, long)]
        file: String,

        /// Page number to dump (default: 0)
        #[arg(short, long)]
        page: Option<u64>,

        /// Absolute byte offset to start dumping (bypasses page mode)
        #[arg(long)]
        offset: Option<u64>,

        /// Number of bytes to dump (default: page size or 256 for offset mode)
        #[arg(short, long)]
        length: Option<usize>,

        /// Output raw binary bytes (no formatting)
        #[arg(long)]
        raw: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Decrypt page before dumping (requires --keyring)
        #[arg(long)]
        decrypt: bool,
    },

    /// Intentionally corrupt pages for testing
    ///
    /// Writes random bytes into a tablespace file to simulate data corruption.
    /// Targets can be the FIL header (`-k`), the record data area (`-r`), or
    /// an absolute byte offset (`--offset`). If no page is specified, one is
    /// chosen at random. Use `--verify` to print before/after checksum
    /// comparisons confirming the page is now invalid — useful for verifying
    /// that `inno checksum` correctly detects the damage.
    Corrupt {
        /// Path to data file
        #[arg(short, long)]
        file: String,

        /// Page number to corrupt (random if not specified)
        #[arg(short, long)]
        page: Option<u64>,

        /// Number of bytes to corrupt
        #[arg(short, long, default_value = "1")]
        bytes: usize,

        /// Corrupt the FIL header area
        #[arg(short = 'k', long = "header")]
        header: bool,

        /// Corrupt the record data area
        #[arg(short, long)]
        records: bool,

        /// Absolute byte offset to corrupt (bypasses page calculation)
        #[arg(long)]
        offset: Option<u64>,

        /// Show before/after checksum comparison
        #[arg(long)]
        verify: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,
    },

    /// Export record-level data from a tablespace
    ///
    /// Extracts user records from clustered index leaf pages and outputs
    /// them as CSV, JSON, or raw hex. Uses SDI metadata (MySQL 8.0+) to
    /// decode field types and column names. Without SDI, falls back to
    /// hex-only output.
    ///
    /// Supported types: integers (TINYINT–BIGINT), FLOAT, DOUBLE,
    /// DATE, DATETIME, TIMESTAMP, YEAR, VARCHAR, CHAR. Unsupported
    /// types (DECIMAL, BLOB, JSON, etc.) are exported as hex strings.
    ///
    /// Use `--where-delete-mark` to include only delete-marked records
    /// (useful for forensic recovery). Use `--system-columns` to include
    /// DB_TRX_ID and DB_ROLL_PTR in the output.
    Export {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Export records from a specific page only
        #[arg(short, long)]
        page: Option<u64>,

        /// Output format: csv, json, or hex
        #[arg(long, default_value = "csv")]
        format: String,

        /// Include only delete-marked records
        #[arg(long = "where-delete-mark")]
        where_delete_mark: bool,

        /// Include system columns (DB_TRX_ID, DB_ROLL_PTR) in output
        #[arg(long = "system-columns")]
        system_columns: bool,

        /// Show additional details
        #[arg(short, long)]
        verbose: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Search for pages across data directory
    ///
    /// Recursively discovers all `.ibd` files under a MySQL data directory,
    /// opens each as a tablespace, and reads the FIL header of every page
    /// looking for a matching `page_number` field. Optional `--checksum` and
    /// `--space-id` filters narrow results when the same page number appears
    /// in multiple tablespaces. Use `--first` to stop after the first match
    /// for faster lookups.
    ///
    /// With `--corrupt`, scans all pages for checksum mismatches instead of
    /// searching by page number. Reports corrupt pages with their stored and
    /// calculated checksums plus corruption pattern classification.
    Find {
        /// MySQL data directory path
        #[arg(short, long)]
        datadir: String,

        /// Page number to search for
        #[arg(short, long)]
        page: Option<u64>,

        /// Checksum to match (page-number search only)
        #[arg(short, long)]
        checksum: Option<u32>,

        /// Space ID to match
        #[arg(short, long)]
        space_id: Option<u32>,

        /// Scan for pages with checksum mismatches
        #[arg(long)]
        corrupt: bool,

        /// Stop at first match
        #[arg(long)]
        first: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Maximum directory recursion depth (default: 2, 0 = unlimited)
        #[arg(long)]
        depth: Option<u32>,
    },

    /// List/find tablespace IDs
    ///
    /// Scans `.ibd` and `.ibu` files under a MySQL data directory and reads
    /// the space ID from the FSP header (page 0, offset 38) of each file.
    /// In **list mode** (`-l`) it prints every file and its space ID; in
    /// **lookup mode** (`-t <id>`) it finds the file that owns a specific
    /// tablespace ID. Useful for mapping a space ID seen in error logs or
    /// `INFORMATION_SCHEMA` back to a physical file on disk.
    Tsid {
        /// MySQL data directory path
        #[arg(short, long)]
        datadir: String,

        /// List all tablespace IDs
        #[arg(short, long)]
        list: bool,

        /// Find table file by tablespace ID
        #[arg(short = 't', long = "tsid")]
        tablespace_id: Option<u32>,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Maximum directory recursion depth (default: 2, 0 = unlimited)
        #[arg(long)]
        depth: Option<u32>,
    },

    /// Extract SDI metadata (MySQL 8.0+)
    ///
    /// Locates SDI (Serialized Dictionary Information) pages in a tablespace
    /// by scanning for page type 17853, then reassembles multi-page SDI
    /// records by following the page chain. The zlib-compressed payload is
    /// decompressed and printed as JSON. Each tablespace in MySQL 8.0+
    /// embeds its own table/column/index definitions as SDI records,
    /// eliminating the need for the `.frm` files used in older versions.
    /// Use `--pretty` for indented JSON output.
    Sdi {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Pretty-print JSON output
        #[arg(short, long)]
        pretty: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Extract schema and reconstruct DDL from tablespace metadata
    ///
    /// Reads SDI (Serialized Dictionary Information) from MySQL 8.0+
    /// tablespaces, parses the embedded data dictionary JSON into typed
    /// column, index, and foreign key definitions, and reconstructs a
    /// complete `CREATE TABLE` DDL statement. For pre-8.0 tablespaces
    /// that lack SDI, scans INDEX pages to infer basic index structure
    /// and record format (compact vs. redundant).
    ///
    /// Use `--verbose` for a structured breakdown of columns, indexes,
    /// and foreign keys above the DDL. Use `--json` for machine-readable
    /// output including the full schema definition and DDL as a JSON object.
    Schema {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Show structured schema breakdown above the DDL
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Analyze InnoDB redo log files
    ///
    /// Opens an InnoDB redo log file (`ib_logfile0`/`ib_logfile1` for
    /// MySQL < 8.0.30, or `#ib_redo*` files for 8.0.30+) and displays
    /// the log file header, both checkpoint records, and per-block details
    /// including block number, data length, checkpoint number, and CRC-32C
    /// checksum status. With `--verbose`, MLOG record types within each
    /// data block are decoded and summarized. Use `--blocks N` to limit
    /// output to the first N data blocks, or `--no-empty` to skip blocks
    /// that contain no redo data.
    Log {
        /// Path to redo log file (ib_logfile0, ib_logfile1, or #ib_redo*)
        #[arg(short, long)]
        file: String,

        /// Limit to first N data blocks
        #[arg(short, long)]
        blocks: Option<u64>,

        /// Skip empty blocks
        #[arg(long)]
        no_empty: bool,

        /// Display additional information
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,
    },

    /// Show InnoDB file and system information
    ///
    /// Operates in three modes. **`--ibdata`** reads the `ibdata1` page 0
    /// FIL header and redo log checkpoint LSNs. **`--lsn-check`** compares
    /// the `ibdata1` header LSN with the latest redo log checkpoint LSN to
    /// detect whether the system tablespace and redo log are in sync (useful
    /// for diagnosing crash-recovery state). **`-D`/`-t`** queries a live
    /// MySQL instance via `INFORMATION_SCHEMA.INNODB_TABLES` and
    /// `INNODB_INDEXES` for tablespace IDs, table IDs, index root pages,
    /// and key InnoDB status metrics (requires the `mysql` feature).
    Info {
        /// Inspect ibdata1 page 0 header
        #[arg(long)]
        ibdata: bool,

        /// Compare ibdata1 and redo log LSNs
        #[arg(long = "lsn-check")]
        lsn_check: bool,

        /// MySQL data directory path
        #[arg(short, long)]
        datadir: Option<String>,

        /// Database name (for table/index info)
        #[arg(short = 'D', long)]
        database: Option<String>,

        /// Table name (for table/index info)
        #[arg(short, long)]
        table: Option<String>,

        /// MySQL host
        #[arg(long)]
        host: Option<String>,

        /// MySQL port
        #[arg(long)]
        port: Option<u16>,

        /// MySQL user
        #[arg(long)]
        user: Option<String>,

        /// MySQL password
        #[arg(long)]
        password: Option<String>,

        /// Path to MySQL defaults file (.my.cnf)
        #[arg(long = "defaults-file")]
        defaults_file: Option<String>,

        /// Scan data directory and produce a tablespace ID mapping
        #[arg(long = "tablespace-map")]
        tablespace_map: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,
    },

    /// Recover data from corrupt/damaged tablespace files
    ///
    /// Scans a tablespace file and classifies each page as intact, corrupt,
    /// empty, or unreadable. For INDEX pages, counts recoverable user records
    /// by walking the compact record chain. Produces a recovery assessment
    /// showing how many pages and records can be salvaged.
    ///
    /// Use `--force` to also extract records from pages with bad checksums
    /// but valid-looking headers — useful when data is partially damaged
    /// but the record chain is still intact. Use `--page-size` to override
    /// page size detection when page 0 is corrupt.
    ///
    /// With `--verbose`, per-page details are shown including page type,
    /// status, LSN, and record count. With `--json`, a structured report
    /// is emitted including optional per-record detail when combined with
    /// `--verbose`.
    Recover {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Analyze a single page instead of full scan
        #[arg(short, long)]
        page: Option<u64>,

        /// Show per-page details
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Extract records from corrupt pages with valid headers
        #[arg(long)]
        force: bool,

        /// Override page size (critical when page 0 is corrupt)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Stream results incrementally for lower memory usage (disables parallel processing)
        #[arg(long)]
        streaming: bool,

        /// Write a new tablespace from recoverable pages to the given path
        #[arg(long)]
        rebuild: Option<String>,
    },

    /// Validate page checksums
    ///
    /// Reads every page in a tablespace and validates its stored checksum
    /// against both CRC-32C (MySQL 5.7.7+) and legacy InnoDB algorithms.
    /// Also checks that the header LSN low-32 bits match the FIL trailer.
    /// All-zero pages are counted as empty and skipped. With `--verbose`,
    /// per-page results are printed including the detected algorithm and
    /// stored vs. calculated values. Exits with code 1 if any page has an
    /// invalid checksum, making it suitable for use in scripts and CI.
    Checksum {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Show per-page checksum details
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Stream results incrementally for lower memory usage (disables parallel processing)
        #[arg(long)]
        streaming: bool,
    },

    /// Monitor a tablespace file for page-level changes
    ///
    /// Polls an InnoDB tablespace file at a configurable interval and reports
    /// which pages have been modified, added, or removed since the last poll.
    /// Change detection is based on LSN comparison — if a page's LSN changes
    /// between polls, it was modified by a write. Checksums are validated for
    /// each changed page to detect corruption during writes.
    ///
    /// The tablespace is re-opened each cycle to detect file growth and avoid
    /// stale file handles. Use `--verbose` for per-field diffs on changed
    /// pages, or `--json` for NDJSON streaming output (one JSON object per
    /// line). Press Ctrl+C for a clean exit with a summary of total changes.
    Watch {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Polling interval in milliseconds
        #[arg(short, long, default_value = "1000")]
        interval: u64,

        /// Show per-field diffs for changed pages
        #[arg(short, long)]
        verbose: bool,

        /// Output in NDJSON streaming format
        #[arg(long)]
        json: bool,

        /// Emit per-page NDJSON change events (audit-log compatible)
        #[arg(long)]
        events: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Repair corrupt page checksums
    ///
    /// Recalculates and writes correct checksums for pages with invalid checksums
    /// or LSN mismatches. By default, auto-detects the checksum algorithm from
    /// page 0 and creates a `.bak` backup before modifying the file. Use
    /// `--algorithm` to force a specific algorithm, `--dry-run` to preview
    /// repairs without modifying the file, or `--no-backup` to skip the backup.
    Repair {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: Option<String>,

        /// Repair all .ibd files under a data directory
        #[arg(long)]
        batch: Option<String>,

        /// Repair only a specific page number
        #[arg(short, long)]
        page: Option<u64>,

        /// Checksum algorithm: auto, crc32c, innodb, full_crc32
        #[arg(short, long, default_value = "auto")]
        algorithm: String,

        /// Skip creating a backup before repair
        #[arg(long)]
        no_backup: bool,

        /// Preview repairs without modifying the file
        #[arg(long)]
        dry_run: bool,

        /// Show per-page repair details
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Compare two tablespace files page-by-page
    ///
    /// Reads two InnoDB tablespace files and compares them page-by-page,
    /// reporting which pages are identical, modified, or only present in
    /// one file. With `--verbose`, per-page FIL header field diffs are
    /// shown for modified pages, highlighting changes to checksums, LSNs,
    /// page types, and space IDs. Add `--byte-ranges` (with `-v`) to see
    /// the exact byte offsets where page content differs. Use `-p` to
    /// compare a single page, or `--json` for machine-readable output.
    ///
    /// When files have different page sizes, only FIL headers (first 38
    /// bytes) are compared and a warning is displayed.
    Diff {
        /// First InnoDB data file (.ibd)
        file1: String,

        /// Second InnoDB data file (.ibd)
        file2: String,

        /// Show per-page header field diffs
        #[arg(short, long)]
        verbose: bool,

        /// Show byte-range diffs for changed pages (requires -v)
        #[arg(short = 'b', long = "byte-ranges")]
        byte_ranges: bool,

        /// Compare a single page only
        #[arg(short, long)]
        page: Option<u64>,

        /// Annotate diff with MySQL version information from SDI metadata
        #[arg(long = "version-aware")]
        version_aware: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Copy specific pages from a donor tablespace into a target
    ///
    /// Reads pages from the donor file and writes them into the target file at
    /// the same page number. Safety checks ensure page sizes and space IDs
    /// match. Page 0 (FSP_HDR) is rejected unless `--force` is used. Donor
    /// pages with invalid checksums are skipped unless `--force` is used.
    ///
    /// A backup of the target is created by default. Use `--dry-run` to preview
    /// which pages would be transplanted without modifying the target.
    Transplant {
        /// Path to donor tablespace file (source of pages)
        donor: String,

        /// Path to target tablespace file (destination)
        target: String,

        /// Page numbers to transplant (comma-separated)
        #[arg(short, long, value_delimiter = ',')]
        pages: Vec<u64>,

        /// Skip creating a backup of the target
        #[arg(long)]
        no_backup: bool,

        /// Allow space ID mismatch, corrupt donor pages, and page 0 transplant
        #[arg(long)]
        force: bool,

        /// Preview without modifying the target file
        #[arg(long)]
        dry_run: bool,

        /// Show per-page details
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Per-index B+Tree health metrics
    ///
    /// Scans all INDEX pages in a tablespace and computes per-index health
    /// metrics including fill factor (average, min, max), garbage ratio,
    /// fragmentation, tree depth, and page counts. Optionally resolves
    /// index names from SDI metadata (MySQL 8.0+).
    ///
    /// Use `--verbose` for additional detail including total records and
    /// empty leaf page counts. Use `--json` for machine-readable output.
    Health {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Show additional detail (records, empty leaves)
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long, conflicts_with = "prometheus")]
        json: bool,

        /// Output metrics in Prometheus exposition format
        #[arg(long, conflicts_with = "json")]
        prometheus: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Audit a MySQL data directory for integrity, health, or corruption
    ///
    /// Scans all `.ibd` files under a data directory and validates checksums,
    /// computes health metrics, or lists corrupt pages — replacing the need
    /// to run `inno checksum` or `inno health` file-by-file. Three modes:
    ///
    /// **Default (integrity)**: validates checksums across all tablespace files
    /// and reports per-file pass/fail with a directory-wide integrity percentage.
    ///
    /// **`--health`**: computes per-tablespace fill factor, fragmentation, and
    /// garbage ratio, ranked worst-first. Use `--min-fill-factor` and
    /// `--max-fragmentation` to filter for unhealthy tablespaces only.
    ///
    /// **`--checksum-mismatch`**: compact listing of only corrupt pages with
    /// stored vs. calculated checksums, suitable for piping to `inno repair`.
    ///
    /// `--health` and `--checksum-mismatch` are mutually exclusive.
    Audit {
        /// MySQL data directory path
        #[arg(short, long)]
        datadir: String,

        /// Show per-tablespace health metrics instead of checksum validation
        #[arg(long)]
        health: bool,

        /// List only pages with checksum mismatches (compact output)
        #[arg(long = "checksum-mismatch", conflicts_with = "prometheus")]
        checksum_mismatch: bool,

        /// Show additional details (per-page results in default mode)
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long, conflicts_with = "prometheus")]
        json: bool,

        /// Output metrics in Prometheus exposition format
        #[arg(long, conflicts_with = "json", conflicts_with = "checksum_mismatch")]
        prometheus: bool,

        /// Override page size (default: auto-detect per file)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Show tables with fill factor below this threshold (0-100, --health only)
        #[arg(long = "min-fill-factor")]
        min_fill_factor: Option<f64>,

        /// Show tables with fragmentation above this threshold (0-100, --health only)
        #[arg(long = "max-fragmentation")]
        max_fragmentation: Option<f64>,

        /// Maximum directory recursion depth (default: 2, 0 = unlimited)
        #[arg(long)]
        depth: Option<u32>,
    },

    /// Check tablespace compatibility with a target MySQL version
    ///
    /// Analyzes tablespace files to determine whether they are compatible
    /// with a target MySQL version. Checks include page size support, row
    /// format, encryption, compression, SDI presence, and vendor
    /// compatibility (MariaDB tablespaces are flagged as incompatible).
    ///
    /// **Single-file mode** (`--file`): checks one tablespace and reports
    /// all compatibility findings with severity levels (info/warning/error).
    ///
    /// **Directory scan mode** (`--scan`): discovers all `.ibd` files under
    /// a data directory, runs compatibility checks on each in parallel, and
    /// produces a per-file summary plus an overall compatible/incompatible
    /// count.
    ///
    /// `--file` and `--scan` are mutually exclusive.
    Compat {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: Option<String>,

        /// Scan a data directory for compatibility issues (mutually exclusive with --file)
        #[arg(short, long)]
        scan: Option<String>,

        /// Target MySQL version (e.g., "8.4.0", "9.0.0")
        #[arg(short, long)]
        target: String,

        /// Show detailed check information
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Maximum directory recursion depth (default: 2, 0 = unlimited)
        #[arg(long)]
        depth: Option<u32>,
    },

    /// Defragment a tablespace by reclaiming free space and reordering pages
    ///
    /// Reads all pages from a source tablespace, removes empty and corrupt
    /// pages, sorts INDEX pages by (index_id, level, page_number), fixes
    /// prev/next chain pointers within each index group, renumbers pages
    /// sequentially, rebuilds page 0, recalculates all checksums, and writes
    /// the result to a new output file. The source file is never modified.
    Defrag {
        /// Path to source InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Path to output file (required — always writes a new file)
        #[arg(short, long)]
        output: String,

        /// Show per-page details
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Cross-validate tablespace files against live MySQL metadata
    ///
    /// Scans a data directory for .ibd files and compares their space IDs
    /// against MySQL's INFORMATION_SCHEMA.INNODB_TABLESPACES. Detects
    /// orphan files (on disk but not in MySQL), missing tablespaces (in
    /// MySQL but not on disk), and space ID mismatches. Requires --host
    /// and --user for MySQL connection (mysql feature must be compiled).
    Validate {
        /// Path to MySQL data directory
        #[arg(short, long)]
        datadir: String,

        /// Database name to filter (optional)
        #[arg(short = 'D', long)]
        database: Option<String>,

        /// Deep-validate a specific table (format: db.table or db/table)
        #[arg(short = 't', long)]
        table: Option<String>,

        /// MySQL host
        #[arg(long)]
        host: Option<String>,

        /// MySQL port
        #[arg(long)]
        port: Option<u16>,

        /// MySQL user
        #[arg(short, long)]
        user: Option<String>,

        /// MySQL password
        #[arg(short, long)]
        password: Option<String>,

        /// Path to MySQL defaults file (.my.cnf)
        #[arg(long = "defaults-file")]
        defaults_file: Option<String>,

        /// Show detailed output
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Maximum directory recursion depth (default: 2, 0 = unlimited)
        #[arg(long)]
        depth: Option<u32>,
    },

    /// Verify structural integrity of a tablespace
    ///
    /// Runs pure structural checks on a tablespace file without requiring
    /// valid checksums. Checks page number sequence, space ID consistency,
    /// LSN monotonicity, B+Tree level validity, page chain bounds, and
    /// trailer LSN matching. Exits with code 1 if any check fails.
    Verify {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Show per-page findings
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,

        /// Path to redo log file to verify LSN continuity against the tablespace
        #[arg(long)]
        redo: Option<String>,

        /// Verify backup chain continuity across multiple tablespace files
        #[arg(long = "chain", num_args = 1..)]
        chain: Vec<String>,
    },

    /// Parse and analyze MySQL binary log files
    ///
    /// Reads the format description event, then iterates all events in the
    /// binary log to produce type distribution statistics, table map details,
    /// and an event listing. Supports filtering by event type and limiting
    /// the number of events displayed.
    Binlog {
        /// Path to MySQL binary log file
        #[arg(short, long)]
        file: String,

        /// Maximum number of events to display
        #[arg(short, long)]
        limit: Option<usize>,

        /// Filter events by type name (e.g. TABLE_MAP, WRITE_ROWS)
        #[arg(long = "filter-type")]
        filter_type: Option<String>,

        /// Show additional detail (column types for TABLE_MAP events)
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,
    },

    /// Analyze undo tablespace files (.ibu or .ibd)
    ///
    /// Reads rollback segment arrays, rollback segment headers, and undo
    /// segment pages to report transaction history and segment states.
    /// Supports MySQL 8.0+ dedicated undo tablespaces (.ibu) and legacy
    /// system tablespace undo logs.
    Undo {
        /// Path to InnoDB undo tablespace file (.ibu or .ibd)
        #[arg(short, long)]
        file: String,

        /// Show a specific undo page only
        #[arg(short, long)]
        page: Option<u64>,

        /// Show additional detail including undo records
        #[arg(short, long)]
        verbose: bool,

        /// Output in JSON format
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Recover deleted records from a tablespace
    ///
    /// Scans InnoDB tablespace files for deleted records using three strategies:
    /// delete-marked records still in the active B+Tree chain (confidence 1.0),
    /// records in the page free list (confidence 0.3-0.7), and optionally
    /// DEL_MARK_REC entries in undo log pages (confidence 0.1-0.3).
    ///
    /// Output formats include CSV (default), JSON array of record objects,
    /// SQL INSERT statements, or hex dump. Use `--json` for a full metadata
    /// envelope including summary statistics.
    ///
    /// With `--undo-file`, provide an undo tablespace (ibdata1 or .ibu) to
    /// enable undo log scanning for additional PK-only recovery.
    Undelete {
        /// Path to InnoDB data file (.ibd)
        #[arg(short, long)]
        file: String,

        /// Path to undo tablespace (ibdata1 or .ibu) for undo log scanning
        #[arg(long = "undo-file")]
        undo_file: Option<String>,

        /// Filter by table name
        #[arg(short, long)]
        table: Option<String>,

        /// Minimum transaction ID to include
        #[arg(long = "min-trx-id")]
        min_trx_id: Option<u64>,

        /// Minimum confidence threshold (0.0-1.0, default: 0.0)
        #[arg(long, default_value = "0.0")]
        confidence: f64,

        /// Record output format: csv, json, sql, hex
        #[arg(long, default_value = "csv")]
        format: String,

        /// Show additional details
        #[arg(short, long)]
        verbose: bool,

        /// Recover from a specific page only
        #[arg(short, long)]
        page: Option<u64>,

        /// Output full metadata JSON envelope
        #[arg(long)]
        json: bool,

        /// Override page size (default: auto-detect)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Path to MySQL keyring file for decrypting encrypted tablespaces
        #[arg(long)]
        keyring: Option<String>,
    },

    /// Generate shell completion scripts
    Completions {
        /// Shell to generate completions for
        shell: clap_complete::Shell,
    },
}