cqlite-cli 0.11.0

Command-line interface for CQLite — read Apache Cassandra 5.0 SSTables without a cluster
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
// TODO(M3): Address 105 clippy warnings in cqlite-cli
// See Issue #204 for tracking
#![allow(clippy::all)]

use anyhow::Result;
use clap::Parser;
use cqlite_core::{Config as CoreConfig, Database};
use std::path::PathBuf;
use tracing::info;

#[cfg(feature = "state_machine")]
use cqlite_core::ingestion::{ingest, IngestionConfig};

#[cfg(feature = "write-support")]
use cqlite_core::storage::write_engine::{WriteEngine, WriteEngineConfig};

mod cli;
mod cli_types;
mod commands;
mod config;
mod error;
mod formatter;
mod output;
mod script_executor;
mod status_metrics;

use cli_types::{AdminCommands, Cli, Commands, ExportSstableArgs, MaintenanceArgs, OutputMode};
use commands::info::execute_info_command;
// mod data_parser;
// mod formatter; // New cqlsh-compatible formatter
// mod interactive;
// mod pagination;
// mod query_executor;
mod repl; // Core REPL engine
mod tui; // TUI mode implementation (ratatui)

#[tokio::main]
async fn main() {
    // Run main logic and handle exit codes
    if let Err(e) = run_main().await {
        let exit_code = error::classify_error(&e);
        error::print_error(&e, exit_code);
        std::process::exit(exit_code.as_i32());
    }
}

/// Main CLI logic that returns Result for proper error handling
async fn run_main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize logging based on verbosity
    let log_level = match (cli.quiet, cli.verbose) {
        (true, _) => "error",
        (false, 0) => "info",
        (false, 1) => "debug",
        (false, _) => "trace",
    };

    // Configure logging to stderr only (Issue #129)
    // This prevents debug/warn logs from contaminating stdout JSON/CSV output
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(log_level))
        .target(env_logger::Target::Stderr)
        .init();

    info!("Starting CQLite CLI v{}", env!("CARGO_PKG_VERSION"));

    // Load configuration
    let config = config::Config::load(cli.config.clone(), &cli)?;

    // Issue #231: Validate required flags for one-shot query mode
    // When --execute and --schema are provided, --data-dir (or --dataset) is required
    // Exception: DML statements (INSERT/UPDATE/DELETE) in --writable mode don't need --data-dir
    #[cfg(feature = "state_machine")]
    if cli.execute.is_some() && cli.schema.is_some() {
        if cli.data_dir.is_none() && cli.dataset.is_none() {
            let is_writable_dml =
                cli.writable && cli.execute.as_ref().map_or(false, |q| is_dml_statement(q));
            if !is_writable_dml {
                return Err(anyhow::anyhow!(
                    "Missing required flag: --data-dir\n\n\
                     One-shot query execution requires both --schema and --data-dir.\n\n\
                     Example:\n\
                     cqlite --schema schema.cql --data-dir /path/to/sstables -e 'SELECT * FROM table'"
                ));
            }
        }
    }

    // Initialize database connection
    let db_path = cli
        .database
        .or(config.default_database.clone())
        .unwrap_or_else(|| PathBuf::from("cqlite.db"));

    // Initialize the database engine - check for ingestion path first
    // Returns (Database, Option<SchemaRegistry>) to preserve schema info for REPL
    #[cfg(feature = "state_machine")]
    let (database, startup_schema_registry) = if cli.schema.is_some()
        && (cli.data_dir.is_some() || cli.dataset.is_some())
    {
        // One-shot ingestion path: load schema and discover SSTables
        info!("Using one-shot ingestion mode");

        if let Some(dataset_name) = &cli.dataset {
            // SECURITY: Validate dataset name to prevent directory traversal attacks
            if dataset_name.contains("..")
                || dataset_name.contains('/')
                || dataset_name.contains('\\')
                || dataset_name.starts_with('.')
            {
                return Err(anyhow::anyhow!(
                    "Invalid dataset name '{}': must not contain '..', '/', '\\', or start with '.'",
                    dataset_name
                ));
            }

            // Dataset mode: use sstables directory path directly
            // The dataset structure is: datasets_root/sstables/{dataset_name}/
            // which is flat (not production keyspace/table-uuid layout)
            info!("Dataset mode: using dataset '{}'", dataset_name);

            // Get datasets root from environment variable or use default
            let datasets_root = std::env::var("CQLITE_DATASETS_ROOT")
                .ok()
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("test-data/datasets"));

            info!("Using datasets root: {}", datasets_root.display());

            // For dataset mode, use the sstables/{dataset_name} directory as the data_dir
            // The DiscoveryService will scan this flat structure
            let dataset_data_dir = datasets_root.join("sstables").join(dataset_name);

            // SECURITY: Canonicalize and verify the path stays within datasets_root
            let canonical_dir = dataset_data_dir.canonicalize().map_err(|e| {
                anyhow::anyhow!(
                    "Dataset '{}' not found or inaccessible: {}. Check CQLITE_DATASETS_ROOT={}",
                    dataset_name,
                    e,
                    datasets_root.display()
                )
            })?;

            let canonical_root = datasets_root.canonicalize().map_err(|e| {
                anyhow::anyhow!(
                    "Datasets root directory not found: {}. Check CQLITE_DATASETS_ROOT={}",
                    e,
                    datasets_root.display()
                )
            })?;

            if !canonical_dir.starts_with(&canonical_root) {
                return Err(anyhow::anyhow!(
                    "Security violation: dataset path '{}' escaped datasets root directory",
                    dataset_name
                ));
            }

            info!("Dataset data directory: {}", dataset_data_dir.display());

            // DATASET MODE FIX: The dataset directory IS the keyspace directory with table subdirectories
            // Use DiscoveryService, but pass the parent (sstables/) so scanner finds dataset as keyspace
            let dataset_parent = datasets_root.join("sstables");

            // Use standard ingestion with the PARENT directory and filter by dataset name
            let dataset_segment = format!("/{}/", dataset_name);
            let ingestion_config = IngestionConfig {
                schema_paths: vec![cli.schema.clone().unwrap()],
                data_dir: dataset_parent, // Scanner will find all datasets as keyspaces
                version_hint: cli.cassandra_version.clone(),
                core_config: create_core_config(&config)?,
                table_directory_filter: Some(dataset_segment), // Filter to this dataset only
            };

            // Ingest - filtering happens inside ingestion module
            match ingest(ingestion_config).await {
                Ok(result) => {
                    info!(
                        "Dataset ingestion complete: {} schemas loaded, {} table directories from '{}'",
                        result.schema_load_result.schemas_loaded,
                        result.discovery_summary.table_directories.len(),
                        dataset_name
                    );
                    (result.database, Some(result.schema_registry))
                }
                Err(e) => {
                    return Err(anyhow::anyhow!("Dataset ingestion failed: {}", e));
                }
            }
        } else {
            // Production mode: use standard ingestion with DiscoveryService (no filter)
            let ingestion_config = IngestionConfig {
                schema_paths: vec![cli.schema.clone().unwrap()],
                data_dir: cli.data_dir.clone().unwrap(),
                version_hint: cli.cassandra_version.clone(),
                core_config: create_core_config(&config)?,
                table_directory_filter: None,
            };

            match ingest(ingestion_config).await {
                Ok(result) => {
                    info!(
                        "Ingestion complete: {} schemas loaded, {} SSTables found",
                        result.schema_load_result.schemas_loaded,
                        result.discovery_summary.sstables_found
                    );
                    (result.database, Some(result.schema_registry))
                }
                Err(e) => {
                    // Error will be classified by error.rs for proper exit codes
                    return Err(anyhow::anyhow!("Ingestion failed: {}", e));
                }
            }
        }
    } else {
        // Original Database::open() path for backward compatibility
        (initialize_database(&db_path, &config).await?, None)
    };

    #[cfg(not(feature = "state_machine"))]
    let (database, startup_schema_registry): (
        _,
        Option<std::sync::Arc<tokio::sync::RwLock<cqlite_core::schema::registry::SchemaRegistry>>>,
    ) = (initialize_database(&db_path, &config).await?, None);

    // Create output config for query execution
    let output_config = config::OutputConfig::from_cli(
        &config,
        cli.no_color,
        cli.limit,
        cli.page_size,
        cli.output.clone(),
        cli.overwrite,
    );

    // Issue #223: Determine effective output format
    // Precedence: --out (query-specific) > --format (global)
    // PRD usage example: cqlite --query "SELECT ..." --out json
    let effective_format = if let Some(out_mode) = cli.out {
        match out_mode {
            OutputMode::Table => cli::OutputFormat::Table,
            OutputMode::Json => cli::OutputFormat::Json,
            OutputMode::Csv => cli::OutputFormat::Csv,
            OutputMode::Parquet => cli::OutputFormat::Parquet,
        }
    } else {
        cli.format
    };

    // Issue #279: Validate Parquet format requires file output
    // Parquet is a binary format that cannot be meaningfully written to stdout
    if matches!(effective_format, cli::OutputFormat::Parquet) && !output_config.target.is_file() {
        return Err(anyhow::anyhow!(
            "{}",
            crate::output::OutputError::ParquetRequiresFile
        ));
    }

    // Issue #392: Initialize WriteEngine if write mode is enabled
    #[cfg(feature = "write-support")]
    let mut write_engine = if cli.writable {
        let write_dir = cli
            .write_dir
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("--write-dir required with --writable"))?;

        // Determine target table from mutations to select correct schema
        let target_table: Option<(String, String)> = if !cli.mutation.is_empty() {
            // Peek at first --mutation to get target table
            let first: serde_json::Value = serde_json::from_str(&cli.mutation[0])
                .map_err(|e| anyhow::anyhow!("Failed to parse mutation JSON: {}", e))?;
            let table = first
                .get("table")
                .ok_or_else(|| anyhow::anyhow!("Mutation missing 'table' field"))?;
            let ks = table
                .get("keyspace")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let tbl = table
                .get("table")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            Some((ks, tbl))
        } else if let Some(ref file_path) = cli.mutations_file {
            // Peek at first line of mutations file to get target table
            use std::io::BufRead;
            let file = std::fs::File::open(file_path)
                .map_err(|e| anyhow::anyhow!("Failed to open mutations file: {}", e))?;
            let reader = std::io::BufReader::new(file);
            let mut target = None;
            for line in reader.lines() {
                let line =
                    line.map_err(|e| anyhow::anyhow!("Failed to read mutations file: {}", e))?;
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') {
                    continue;
                }
                let first: serde_json::Value = serde_json::from_str(trimmed)
                    .map_err(|e| anyhow::anyhow!("Failed to parse first mutation: {}", e))?;
                let table = first
                    .get("table")
                    .ok_or_else(|| anyhow::anyhow!("First mutation missing 'table' field"))?;
                let ks = table
                    .get("keyspace")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let tbl = table
                    .get("table")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                target = Some((ks, tbl));
                break;
            }
            target
        } else {
            None
        };

        // Get schema from startup ingestion result
        let schema = if let Some(ref registry) = startup_schema_registry {
            if let Some((ref ks, ref tbl)) = target_table {
                // Look up specific table schema matching mutation target
                registry
                    .read()
                    .await
                    .get_schema(ks, tbl)
                    .await
                    .map_err(|e| {
                        anyhow::anyhow!(
                            "No schema found for {}.{}. Check --schema file contains this table: {}",
                            ks,
                            tbl,
                            e
                        )
                    })?
            } else {
                // No mutations specified yet, fall back to first available schema
                let schemas = registry
                    .read()
                    .await
                    .list_schemas(None)
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to list schemas: {}", e))?;

                schemas.into_iter().next().ok_or_else(|| {
                    anyhow::anyhow!(
                        "No schema available for write operations. \
                         Provide --schema to load a schema."
                    )
                })?
            }
        } else if let Some(ref schema_path) = cli.schema {
            // Write-only mode: parse schema directly from CQL file
            use cqlite_core::schema::cql_parser::{
                classify_statement, parse_create_table, split_cql_statements, StatementType,
            };
            let content = std::fs::read_to_string(schema_path)
                .map_err(|e| anyhow::anyhow!("Failed to read schema file: {}", e))?;
            let statements = split_cql_statements(&content);

            // Extract keyspace from CREATE KEYSPACE statement (simple parser)
            let mut file_keyspace: Option<String> = None;
            let mut table_schemas = Vec::new();

            for stmt in &statements {
                match classify_statement(stmt) {
                    StatementType::Other(ref kind) if kind == "use" => {
                        // Extract keyspace from USE <keyspace>;
                        let name = stmt
                            .trim()
                            .strip_prefix("USE")
                            .or_else(|| stmt.trim().strip_prefix("use"))
                            .unwrap_or("")
                            .trim()
                            .trim_end_matches(';')
                            .trim()
                            .to_string();
                        if !name.is_empty() {
                            file_keyspace = Some(name);
                        }
                    }
                    StatementType::Other(ref kind) if kind == "create" => {
                        // Extract keyspace from CREATE KEYSPACE IF NOT EXISTS <name>
                        let lower = stmt.to_lowercase();
                        if lower.contains("create keyspace") {
                            let after = if let Some(pos) = lower.find("exists") {
                                &stmt[pos + 6..]
                            } else if let Some(pos) = lower.find("keyspace") {
                                &stmt[pos + 8..]
                            } else {
                                ""
                            };
                            let name = after
                                .trim()
                                .split(|c: char| c.is_whitespace() || c == '{' || c == ';')
                                .next()
                                .unwrap_or("")
                                .trim()
                                .to_string();
                            if !name.is_empty() {
                                file_keyspace = Some(name);
                            }
                        }
                    }
                    StatementType::CreateTable => {
                        if let Ok((_, mut ts)) = parse_create_table(stmt) {
                            // Apply file-level keyspace if table doesn't have one
                            if ts.keyspace.is_empty()
                                || ts.keyspace == "unknown"
                                || ts.keyspace == "default"
                            {
                                if let Some(ref ks) = file_keyspace {
                                    ts.keyspace = ks.clone();
                                }
                            }
                            table_schemas.push(ts);
                        }
                    }
                    _ => {}
                }
            }

            // Find matching schema
            if let Some((ref ks, ref tbl)) = target_table {
                table_schemas
                    .into_iter()
                    .find(|ts| ts.keyspace == *ks && ts.table == *tbl)
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "No schema found for {}.{} in {}",
                            ks,
                            tbl,
                            schema_path.display()
                        )
                    })?
            } else {
                table_schemas.into_iter().next().ok_or_else(|| {
                    anyhow::anyhow!(
                        "No CREATE TABLE statements found in {}",
                        schema_path.display()
                    )
                })?
            }
        } else {
            return Err(anyhow::anyhow!(
                "Schema required for write operations. \
                 Provide --schema to load a schema."
            ));
        };

        let config = WriteEngineConfig::new(write_dir.join("data"), write_dir.join("wal"), schema);
        Some(
            WriteEngine::new(config)
                .map_err(|e| anyhow::anyhow!("Failed to initialize WriteEngine: {}", e))?,
        )
    } else {
        None
    };

    // Issue #392: Handle --mutation flags
    #[cfg(feature = "write-support")]
    if !cli.mutation.is_empty() {
        let engine = write_engine
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("Mutations require --writable mode"))?;

        for mutation_json in &cli.mutation {
            let result = commands::write::handle_mutation_write(engine, mutation_json).await?;
            result.display();
        }
    }

    // Issue #392: Handle --mutations-file flag
    #[cfg(feature = "write-support")]
    if let Some(ref file_path) = cli.mutations_file {
        let engine = write_engine
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("Mutations file requires --writable mode"))?;

        let result = commands::write::handle_mutations_file(engine, file_path).await?;
        result.display();
    }

    // Issue #392: Handle --flush flag
    #[cfg(feature = "write-support")]
    if cli.flush {
        if let Some(engine) = write_engine.as_mut() {
            let info = commands::write::handle_flush(engine).await?;
            commands::write::display_flush_result(info.as_ref());
        }
    }

    // Handle --file flag (script execution) - takes precedence over subcommands
    if let Some(file_path) = cli.file {
        return script_executor::execute_script_file(
            &file_path,
            &database,
            &output_config,
            effective_format,
        )
        .await;
    }

    // Handle --execute flag (single statement execution) - takes precedence over subcommands
    if let Some(query) = cli.execute {
        // Route DML statements (INSERT/UPDATE/DELETE) to WriteEngine when --writable is set
        #[cfg(feature = "write-support")]
        {
            if is_dml_statement(&query) {
                let engine = write_engine.as_mut().ok_or_else(|| {
                    anyhow::anyhow!(
                        "DML statements require --writable mode. \
                         Use: cqlite --writable --write-dir <DIR> --schema <SCHEMA> --execute \"INSERT ...\""
                    )
                })?;

                engine
                    .execute(&query)
                    .map_err(|e| anyhow::anyhow!("DML execution failed: {}", e))?;

                println!("OK");
                return Ok(());
            }
        }

        // Issue #142: Experimental fallback to read-sstable for SELECT when ingestion unavailable
        // This is a temporary feature (disabled by default) that will be removed in M3
        // Check this FIRST before schema validation to avoid false negatives
        let will_use_fallback = if cli.enable_select_fallback {
            // Check if ingestion is unavailable (no schema or no data source)
            let ingestion_unavailable =
                cli.schema.is_none() || (cli.data_dir.is_none() && cli.dataset.is_none());

            // Check if query is a SELECT statement
            let is_select_query = query.trim().to_uppercase().starts_with("SELECT");

            ingestion_unavailable && is_select_query
        } else {
            false
        };

        // Issue #199: Pre-flight schema validation to fail-fast on schema/data mismatch
        // Only validate if NOT using fallback (fallback doesn't use schema)
        #[cfg(feature = "state_machine")]
        if !will_use_fallback {
            // Extract table name from query for validation
            // This uses a simple pattern match - for full parsing see query planner
            let table_name_result = extract_table_name_from_query(&query);

            if let Ok(table_name) = table_name_result {
                // Check schema availability before query execution
                if !database.has_schema_for_table(&table_name).await {
                    // Get detailed status for error message
                    let status = database.schema_status(&table_name).await;

                    match status {
                        cqlite_core::SchemaStatus::Missing { reason, .. } => {
                            return Err(anyhow::anyhow!(
                                "Schema not found for table '{}'\n\n\
                                 Cause: {}\n\n\
                                 Troubleshooting:\n\
                                 1. Verify table name matches schema definition\n\
                                 2. Check that schema file was loaded correctly\n\
                                 3. Use 'read-sstable' command to inspect SSTable contents directly",
                                table_name,
                                reason
                            ));
                        }
                        cqlite_core::SchemaStatus::ExtractionFailed {
                            cause, suggestion, ..
                        } => {
                            return Err(anyhow::anyhow!(
                                "Schema extraction failed for table '{}'\n\n\
                                 Cause: {}\n\n\
                                 Troubleshooting:\n\
                                 1. {}\n\
                                 2. Verify SSTable files are valid Cassandra 5.0 format\n\
                                 3. Check that Statistics.db contains SerializationHeader\n\
                                 4. Try regenerating SSTables from CQL schema",
                                table_name,
                                cause,
                                suggestion
                            ));
                        }
                        _ => {} // Schema available, continue to query execution
                    }
                }
            }
            // If table name extraction fails, let query planner handle it
        }

        // Execute the fallback if conditions are met
        if will_use_fallback {
            eprintln!("⚠️  Using experimental read-sstable fallback (temporary feature, disabled by default)");

            // Extract table path from SELECT query using simple regex
            // Supports patterns like: SELECT * FROM /path/to/table or SELECT * FROM path/to/table
            let table_path_result = extract_table_path_from_select(&query);

            match table_path_result {
                Ok(table_path) => {
                    eprintln!("📂 Extracted table path: {}", table_path.display());

                    // Call read-sstable command with extracted path
                    return commands::read_sstable::execute_read_sstable_command(
                        &table_path,
                        effective_format,
                        cli.limit,
                        0,     // skip
                        false, // keys_only
                        false, // raw
                        cli.verbose > 0,
                    )
                    .await;
                }
                Err(e) => {
                    return Err(anyhow::anyhow!(
                        "SELECT fallback failed: {}. \
                             Provide schema and data-dir for full query engine support.",
                        e
                    ));
                }
            }
        }

        return commands::execute_query(
            &database,
            &query,
            false, // explain
            false, // timing
            effective_format,
            &output_config,
        )
        .await;
    }

    match cli.command {
        Some(Commands::Repl) => {
            // Check if we need to run ingestion from config file
            // Returns (Database, Option<SchemaRegistry>) to preserve schema info
            #[cfg(feature = "state_machine")]
            let (database, repl_schema_registry) = if !config.schema_paths.is_empty()
                && config.data_directory.is_some()
            {
                info!("REPL: Running ingestion from config file");
                info!(
                    "REPL: Loading {} schema file(s) from config",
                    config.schema_paths.len()
                );
                info!(
                    "REPL: Discovering SSTables in: {}",
                    config.data_directory.as_ref().unwrap().display()
                );

                let ingestion_config = IngestionConfig {
                    schema_paths: config.schema_paths.clone(),
                    data_dir: config.data_directory.clone().unwrap(),
                    version_hint: config.cassandra_version.clone(),
                    core_config: create_core_config(&config)?,
                    table_directory_filter: None, // REPL doesn't filter tables
                };

                match ingest(ingestion_config).await {
                    Ok(result) => {
                        info!(
                            "REPL ingestion complete: {} schema(s) loaded, {} SSTable(s) discovered, {} keyspace(s) found",
                            result.schema_load_result.schemas_loaded,
                            result.discovery_summary.sstables_found,
                            result.discovery_summary.keyspaces.len()
                        );
                        (result.database, Some(result.schema_registry))
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!(
                            "REPL ingestion failed: {}. Check schema paths and data directory in config file.",
                            e
                        ));
                    }
                }
            } else {
                // No config-based ingestion, use existing database and startup schema registry
                (database, startup_schema_registry)
            };

            #[cfg(not(feature = "state_machine"))]
            let (database, repl_schema_registry) = (database, startup_schema_registry);

            // REPL mode (interactive with line editing and history)
            // Create REPL configuration from loaded config (not hardcoded!)
            let repl_config = repl::ReplConfig {
                mode: repl::ReplMode::Interactive,
                // Use config.repl settings with CLI flag overrides
                enable_history: config.repl.enable_history,
                enable_completion: config.repl.enable_completion,
                enable_colors: if cli.no_color {
                    false
                } else {
                    config.repl.enable_colors
                },
                output_format: repl::OutputFormat::Table,
                max_history_size: config.repl.max_history_size,
                page_size: cli.page_size.unwrap_or(config.repl.page_size),
                show_timing: config.repl.show_timing,
                enable_paging: config.repl.enable_paging,
                prompt: config.repl.prompt.clone(),
                prompt_continuation: config.repl.prompt_continuation.clone(),
                show_status_line: true, // Issue #242: Enable status line by default
            };

            // Initialize and run REPL engine with schema registry from startup ingestion
            let mut engine = repl::ReplEngine::with_schema_registry(
                repl_config,
                &db_path,
                config,
                database,
                repl_schema_registry,
            )
            .map_err(|e| anyhow::anyhow!("Failed to initialize REPL: {}", e))?;

            // Run REPL and convert ReplError to proper exit codes
            engine.run().await.map_err(|e| {
                // Convert ReplError to anyhow::Error while preserving exit code information
                match &e {
                    repl::ReplError::SchemaError(msg) => {
                        anyhow::anyhow!("Schema error: {}", msg)
                    }
                    repl::ReplError::DataDirectoryError(msg) => {
                        anyhow::anyhow!("Data directory error: {}", msg)
                    }
                    repl::ReplError::UnsupportedFeature(msg) => {
                        anyhow::anyhow!("Unsupported feature: {}", msg)
                    }
                    _ => anyhow::anyhow!("REPL error: {}", e),
                }
            })
        }
        Some(Commands::Tui) => {
            // Check if we need to run ingestion from config file
            // Returns (Database, Option<SchemaRegistry>) to preserve schema info
            #[cfg(feature = "state_machine")]
            let (database, _tui_schema_registry) = if !config.schema_paths.is_empty()
                && config.data_directory.is_some()
            {
                info!("TUI: Running ingestion from config file");
                info!(
                    "TUI: Loading {} schema file(s) from config",
                    config.schema_paths.len()
                );
                info!(
                    "TUI: Discovering SSTables in: {}",
                    config.data_directory.as_ref().unwrap().display()
                );

                let ingestion_config = IngestionConfig {
                    schema_paths: config.schema_paths.clone(),
                    data_dir: config.data_directory.clone().unwrap(),
                    version_hint: config.cassandra_version.clone(),
                    core_config: create_core_config(&config)?,
                    table_directory_filter: None, // TUI doesn't filter tables
                };

                match ingest(ingestion_config).await {
                    Ok(result) => {
                        info!(
                            "TUI ingestion complete: {} schema(s) loaded, {} SSTable(s) discovered, {} keyspace(s) found",
                            result.schema_load_result.schemas_loaded,
                            result.discovery_summary.sstables_found,
                            result.discovery_summary.keyspaces.len()
                        );
                        (result.database, Some(result.schema_registry))
                    }
                    Err(e) => {
                        return Err(anyhow::anyhow!(
                            "TUI ingestion failed: {}. Check schema paths and data directory in config file.",
                            e
                        ));
                    }
                }
            } else {
                // No config-based ingestion, use existing database and startup schema registry
                (database, startup_schema_registry)
            };

            #[cfg(not(feature = "state_machine"))]
            let database = database;

            // TUI mode (full-screen terminal UI)
            tui::start_tui_mode(&db_path, &config, database)
                .await
                .map_err(|e| anyhow::anyhow!("TUI error: {}", e))
        }
        Some(Commands::Query {
            query,
            explain,
            timing,
        }) => {
            commands::execute_query(
                &database,
                &query,
                explain,
                timing,
                effective_format,
                &output_config,
            )
            .await
        }
        Some(Commands::Import {
            file,
            format,
            table,
            mapping: _,
            batch_size: _,
        }) => commands::import_data(&database, &file, format, Some(&table)).await,
        Some(Commands::Export {
            file,
            format,
            table,
            query,
            limit,
        }) => {
            commands::export_data(
                &database,
                &table,
                &file,
                format,
                query.as_deref(),
                limit,
                cli.quiet,
            )
            .await
        }
        Some(Commands::Admin { command }) => {
            commands::admin::handle_admin_command(&database, command).await
        }
        Some(Commands::Schema { command }) => {
            commands::schema::handle_schema_command(&database, command).await
        }
        Some(Commands::Bench { command }) => {
            commands::bench::handle_bench_command(&database, command).await
        }
        Some(Commands::ReadSstable {
            file,
            format,
            limit,
            skip,
            keys_only,
            raw,
            verbose,
        }) => {
            commands::read_sstable::execute_read_sstable_command(
                &file, format, limit, skip, keys_only, raw, verbose,
            )
            .await
        }
        Some(Commands::Info {
            path,
            format,
            detailed,
        }) => {
            match path {
                Some(path) => {
                    execute_info_command(
                        &path,
                        detailed,
                        format,
                        false, // validate - default to false
                        cli.schema.as_deref(),
                        cli.auto_detect,
                        cli.cassandra_version.clone(),
                    )
                    .await
                }
                None => {
                    println!("📋 Displaying database information");
                    commands::admin::handle_admin_command(&database, AdminCommands::Info).await
                }
            }
        }
        // Issue #392: Write support subcommands
        Some(Commands::Maintenance(MaintenanceArgs { budget_ms })) => {
            #[cfg(feature = "write-support")]
            {
                let engine = write_engine
                    .as_mut()
                    .ok_or_else(|| anyhow::anyhow!("Maintenance requires --writable mode"))?;
                let report = commands::write::handle_maintenance(engine, budget_ms)?;
                commands::write::display_maintenance_report(&report);
                Ok(())
            }
            #[cfg(not(feature = "write-support"))]
            {
                let _ = budget_ms;
                Err(anyhow::anyhow!(
                    "Write support is not enabled. Build with --features write-support to enable write operations."
                ))
            }
        }
        Some(Commands::WriteStats) => {
            #[cfg(feature = "write-support")]
            {
                let engine = write_engine
                    .as_ref()
                    .ok_or_else(|| anyhow::anyhow!("Write stats requires --writable mode"))?;
                let stats = commands::write::handle_write_stats(engine)?;
                stats.display();
                Ok(())
            }
            #[cfg(not(feature = "write-support"))]
            {
                Err(anyhow::anyhow!(
                    "Write support is not enabled. Build with --features write-support to enable write operations."
                ))
            }
        }
        Some(Commands::ExportSstable(ExportSstableArgs {
            output,
            keyspace,
            table,
            compact,
            skip_validate,
        })) => {
            #[cfg(feature = "write-support")]
            {
                let engine = write_engine
                    .as_mut()
                    .ok_or_else(|| anyhow::anyhow!("Export requires --writable mode"))?;
                let result = commands::write::handle_export(
                    engine,
                    &output,
                    &keyspace,
                    &table,
                    compact,
                    skip_validate,
                )
                .await?;
                result.display();
                Ok(())
            }
            #[cfg(not(feature = "write-support"))]
            {
                let _ = (output, keyspace, table, compact, skip_validate);
                Err(anyhow::anyhow!(
                    "Write support is not enabled. Build with --features write-support to enable write operations."
                ))
            }
        }
        None => {
            // Default to help message for now
            println!("CQLite CLI v{}", env!("CARGO_PKG_VERSION"));
            println!("Use --help for available commands");
            Ok(())
        }
    }
}

/// Initialize the database engine with proper configuration
async fn initialize_database(db_path: &PathBuf, config: &config::Config) -> Result<Database> {
    // Create the database directory if it doesn't exist
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    // Convert CLI config to core config
    let core_config = create_core_config(config)?;

    info!("Initializing database at: {}", db_path.display());

    // Open the database with the core configuration
    let database = Database::open(db_path, core_config)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to initialize database: {}", e))?;

    info!("Database initialized successfully");

    Ok(database)
}

/// Check if a query string is a DML statement (INSERT, UPDATE, DELETE, or BEGIN BATCH).
///
/// Delegates to `cqlite_core::cql::is_dml_statement` — see that function for
/// the canonical definition and semantics.
fn is_dml_statement(query: &str) -> bool {
    cqlite_core::cql::is_dml_statement(query)
}

/// Convert CLI configuration to core database configuration
fn create_core_config(cli_config: &config::Config) -> Result<CoreConfig> {
    let mut core_config = CoreConfig::default();

    // Apply CLI configuration settings to core config
    if let Some(memory_limit_mb) = cli_config.performance.memory_limit_mb {
        core_config.memory.max_memory = memory_limit_mb * 1024 * 1024; // Convert MB to bytes
    }

    // Set cache size from CLI config
    core_config.memory.block_cache.max_size = cli_config.performance.cache_size_mb * 1024 * 1024; // Convert MB to bytes

    // Set query timeout
    core_config.query.max_execution_time =
        std::time::Duration::from_millis(cli_config.performance.query_timeout_ms);

    // Enable optimizations for better performance
    core_config.query.enable_optimization = true;
    core_config.storage.enable_bloom_filters = true;

    // Validate the configuration
    core_config
        .validate()
        .map_err(|e| anyhow::anyhow!("Invalid database configuration: {}", e))?;

    Ok(core_config)
}

/// Extract table name from query for schema validation (Issue #199)
///
/// This is a simple pattern match for pre-flight validation.
/// The query planner will do full parsing during execution.
fn extract_table_name_from_query(query: &str) -> Result<String> {
    let normalized = query.trim().to_uppercase();

    // Handle SELECT statements
    if let Some(from_pos) = normalized.find("FROM") {
        let after_from = query[from_pos + 4..].trim();
        let table_name = after_from
            .split_whitespace()
            .next()
            .ok_or_else(|| anyhow::anyhow!("No table name found after FROM clause"))?;

        // Remove trailing semicolon or WHERE clause
        let cleaned = table_name
            .trim_end_matches(';')
            .split_whitespace()
            .next()
            .unwrap_or(table_name);

        // Handle qualified table names (keyspace.table) - extract just the table part
        let table_only = cleaned.split('.').last().unwrap_or(cleaned);

        return Ok(table_only.to_string());
    }

    // Handle INSERT statements
    if let Some(into_pos) = normalized.find("INTO") {
        let after_into = query[into_pos + 4..].trim();
        let table_name = after_into
            .split_whitespace()
            .next()
            .ok_or_else(|| anyhow::anyhow!("No table name found after INTO clause"))?;

        // Handle qualified table names (keyspace.table)
        let cleaned = table_name.trim_end_matches(';');
        let table_only = cleaned.split('.').last().unwrap_or(cleaned);
        return Ok(table_only.to_string());
    }

    // Handle UPDATE statements
    if let Some(update_pos) = normalized.find("UPDATE") {
        let after_update = query[update_pos + 6..].trim();
        let table_name = after_update
            .split_whitespace()
            .next()
            .ok_or_else(|| anyhow::anyhow!("No table name found after UPDATE clause"))?;

        // Handle qualified table names (keyspace.table)
        let cleaned = table_name.trim_end_matches(';');
        let table_only = cleaned.split('.').last().unwrap_or(cleaned);
        return Ok(table_only.to_string());
    }

    // Handle DELETE statements
    if normalized.find("DELETE").is_some() {
        if let Some(from_pos) = normalized.find("FROM") {
            let after_from = query[from_pos + 4..].trim();
            let table_name = after_from
                .split_whitespace()
                .next()
                .ok_or_else(|| anyhow::anyhow!("No table name found after FROM clause"))?;

            // Handle qualified table names (keyspace.table)
            let cleaned = table_name.trim_end_matches(';');
            let table_only = cleaned.split('.').last().unwrap_or(cleaned);
            return Ok(table_only.to_string());
        }
    }

    Err(anyhow::anyhow!("Unable to extract table name from query"))
}

/// Extract table path from SELECT query for fallback routing (Issue #142)
/// Supports simple patterns: SELECT * FROM /path/to/table
fn extract_table_path_from_select(query: &str) -> Result<PathBuf> {
    // Remove extra whitespace and normalize
    let normalized_query = query
        .trim()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let uppercase_query = normalized_query.to_uppercase();

    // Find FROM clause
    if let Some(from_pos) = uppercase_query.find("FROM") {
        // Extract text after FROM
        let after_from = &normalized_query[from_pos + 4..].trim();

        // Find first token after FROM (this should be the path)
        let path_token = after_from
            .split_whitespace()
            .next()
            .ok_or_else(|| anyhow::anyhow!("No table path found after FROM clause"))?;

        // Remove trailing semicolon if present
        let cleaned_path = path_token.trim_end_matches(';');

        // SECURITY: Check for directory traversal attempts before canonicalization
        // Issue #142: Defense-in-depth for temporary fallback feature
        if cleaned_path.contains("..") {
            return Err(anyhow::anyhow!(
                "Security violation: path contains '..' which could indicate directory traversal attempt: {}",
                cleaned_path
            ));
        }

        let path = PathBuf::from(cleaned_path);

        // SECURITY: Canonicalize to resolve symlinks and validate path exists
        let canonical_path = path.canonicalize().map_err(|e| {
            anyhow::anyhow!(
                "Table path does not exist or is inaccessible: {}. Ensure the path points to a valid SSTable file or directory. Error: {}",
                path.display(),
                e
            )
        })?;

        Ok(canonical_path)
    } else {
        Err(anyhow::anyhow!(
            "Invalid SELECT query: missing FROM clause. Use format: SELECT * FROM /path/to/table"
        ))
    }
}