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
use rustyline::completion::{Completer, Pair};
use rustyline::config::CompletionType;
use rustyline::error::ReadlineError;
use rustyline::highlight::{CmdKind, Highlighter};
use rustyline::hint::Hinter;
use rustyline::history::DefaultHistory;
use rustyline::validate::{self, Validator};
use rustyline::{Config, Context, Editor, Helper};
use std::borrow::Cow;
use std::fmt;
use crate::config::AppConfig;
use crate::error::SqawkError;
use crate::sql_executor::SqlExecutor;
// Define a custom error type for the REPL
#[derive(Debug)]
pub enum ReplError {
SqlExecutor(anyhow::Error),
Readline(ReadlineError),
Io(std::io::Error),
Sqawk(SqawkError),
}
impl fmt::Display for ReplError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReplError::SqlExecutor(err) => write!(f, "SQL execution error: {}", err),
ReplError::Readline(err) => write!(f, "Input error: {}", err),
ReplError::Io(err) => write!(f, "I/O error: {}", err),
ReplError::Sqawk(err) => write!(f, "Sqawk error: {}", err),
}
}
}
impl std::error::Error for ReplError {}
impl From<anyhow::Error> for ReplError {
fn from(err: anyhow::Error) -> Self {
ReplError::SqlExecutor(err)
}
}
impl From<ReadlineError> for ReplError {
fn from(err: ReadlineError) -> Self {
ReplError::Readline(err)
}
}
impl From<std::io::Error> for ReplError {
fn from(err: std::io::Error) -> Self {
ReplError::Io(err)
}
}
impl From<SqawkError> for ReplError {
fn from(err: SqawkError) -> Self {
ReplError::Sqawk(err)
}
}
pub type Result<T> = std::result::Result<T, ReplError>;
const HISTORY_FILE: &str = ".sqawk_history";
/// Command completer for REPL commands
#[derive(Default)]
struct CommandCompleter {
/// List of available dot commands for auto-completion
commands: Vec<String>,
}
impl CommandCompleter {
/// Create a new command completer with the list of available commands
fn new() -> Self {
let commands = vec![
".cd", ".changes", ".exit", ".help", ".load", ".print", ".quit", ".save", ".schema",
".show", ".stats", ".tables", ".version", ".write",
]
.into_iter()
.map(|s| s.to_string())
.collect();
Self { commands }
}
}
// Implement the required traits for Helper
impl Completer for CommandCompleter {
type Candidate = Pair;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &Context<'_>,
) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
// Only provide completion for dot commands
if line.starts_with('.') {
// Split the input into command and argument parts
let parts: Vec<&str> = line.splitn(2, ' ').collect();
let partial_cmd = parts[0];
// We're completing a command (not an argument)
let start_pos = 0; // Start of the command
let candidates: Vec<Pair> = self
.commands
.iter()
.filter(|cmd| cmd.starts_with(partial_cmd))
.map(|cmd| Pair {
display: cmd.clone(),
replacement: cmd.clone(),
})
.collect();
Ok((start_pos, candidates))
} else {
// No completion for SQL statements for now
Ok((pos, vec![]))
}
}
}
// Implement minimal no-op versions of the other traits required by Helper
impl Hinter for CommandCompleter {
type Hint = String;
fn hint(&self, _line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<Self::Hint> {
None
}
}
impl Highlighter for CommandCompleter {
fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
Cow::Borrowed(line)
}
fn highlight_char(&self, _line: &str, _pos: usize, _kind: CmdKind) -> bool {
false
}
}
impl Validator for CommandCompleter {
fn validate(
&self,
ctx: &mut validate::ValidationContext,
) -> rustyline::Result<validate::ValidationResult> {
let input = ctx.input().trim();
// Empty input is valid (just press enter)
if input.is_empty() {
return Ok(validate::ValidationResult::Valid(None));
}
// Dot commands are complete on a single line
if input.starts_with('.') {
return Ok(validate::ValidationResult::Valid(None));
}
// SQL statements must end with semicolon
if input.ends_with(';') {
return Ok(validate::ValidationResult::Valid(None));
}
// Otherwise, we need more input (multiline SQL)
Ok(validate::ValidationResult::Incomplete)
}
}
impl Helper for CommandCompleter {}
/// Commands that can be executed in the REPL
#[derive(Debug)]
enum ReplCommand {
/// Execute SQL statement
Sql(String),
/// Load a file into a table
Load(String),
/// Show the list of tables matching an optional pattern
Tables(Option<String>),
/// Show the columns of a table or schema
Schema(Option<String>),
/// Toggle writing changes to files
WriteMode(Option<String>),
/// Show help message
Help,
/// Exit the REPL with optional exit code
Exit(Option<String>),
/// Change directory
ChangeDirectory(String),
/// Toggle showing number of changes
Changes(Option<String>),
/// Print a string literal
Print(String),
/// Show version information
Version,
/// Save changes to modified tables
Save(Option<String>),
/// Show current settings and metadata
Show(Option<String>),
/// Show statistics or toggle statistics mode
Stats(Option<String>),
/// Unknown command
Unknown(String),
}
/// REPL interface for interactive SQL entry
pub struct Repl<'a> {
/// SQL executor for running queries
executor: SqlExecutor<'a>,
/// Rustyline editor for command line editing
editor: Editor<CommandCompleter, DefaultHistory>,
/// Application configuration for global settings
config: AppConfig,
/// Whether the REPL is running
running: bool,
/// Whether to show number of rows changed by SQL statements
show_changes: bool,
/// Whether to show query statistics
show_stats: bool,
}
impl<'a> Repl<'a> {
/// Create a new REPL
pub fn new(executor: SqlExecutor<'a>, app_config: &AppConfig) -> Self {
// Create rustyline configuration with list-style completion
let rustyline_config = Config::builder()
.completion_type(CompletionType::List)
.build();
// Create editor with our custom command completer
let helper = CommandCompleter::new();
let mut editor = Editor::with_config(rustyline_config).expect("Failed to create editor");
// Set the helper manually
editor.set_helper(Some(helper));
// Load history if available
let _ = editor.load_history(HISTORY_FILE);
Self {
executor,
editor,
config: app_config.clone(),
running: true,
show_changes: false, // Default to not showing changes
show_stats: false, // Default to not showing stats
}
}
/// Run the REPL
pub fn run(&mut self) -> Result<()> {
println!("Welcome to Sqawk interactive mode!");
println!("Enter SQL statements or commands, terminate with ';'.");
println!("Type .help for available commands.");
while self.running {
match self.read_command() {
Ok(command) => {
if let Err(e) = self.execute_command(command) {
eprintln!("Error: {}", e);
}
}
Err(ReadlineError::Interrupted) => {
println!("CTRL-C");
break;
}
Err(ReadlineError::Eof) => {
println!("CTRL-D");
break;
}
Err(err) => {
eprintln!("Error: {:?}", err);
break;
}
}
}
self.editor.save_history(HISTORY_FILE).unwrap_or_else(|e| {
eprintln!("Failed to save history: {}", e);
});
Ok(())
}
/// Read a command from the user
fn read_command(&mut self) -> rustyline::Result<ReplCommand> {
let prompt = "sqawk> ";
let input = self.editor.readline(prompt)?;
if !input.trim().is_empty() {
let _ = self.editor.add_history_entry(&input);
}
Ok(self.parse_command(&input))
}
/// Parse a command from user input
fn parse_command(&self, input: &str) -> ReplCommand {
let input = input.trim();
if let Some(stripped) = input.strip_prefix('.') {
let parts: Vec<&str> = stripped.splitn(2, ' ').collect();
let command = parts[0].to_lowercase();
match command.as_str() {
"exit" => {
if parts.len() > 1 {
ReplCommand::Exit(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Exit(None)
}
}
"quit" => ReplCommand::Exit(None),
"tables" => {
if parts.len() > 1 {
ReplCommand::Tables(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Tables(None)
}
}
"schema" => {
if parts.len() > 1 {
ReplCommand::Schema(Some(parts[1].trim().to_string()))
} else {
// With no argument, show schema for all tables
ReplCommand::Schema(None)
}
}
"load" => {
if parts.len() > 1 {
ReplCommand::Load(parts[1].trim().to_string())
} else {
ReplCommand::Unknown("File path required for .load command".to_string())
}
}
"write" => {
if parts.len() > 1 {
ReplCommand::WriteMode(Some(parts[1].trim().to_string()))
} else {
ReplCommand::WriteMode(None)
}
}
"cd" => {
if parts.len() > 1 {
ReplCommand::ChangeDirectory(parts[1].trim().to_string())
} else {
ReplCommand::Unknown("Directory path required for .cd command".to_string())
}
}
"changes" => {
if parts.len() > 1 {
ReplCommand::Changes(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Changes(None)
}
}
"print" => {
if parts.len() > 1 {
ReplCommand::Print(parts[1].to_string())
} else {
ReplCommand::Print("".to_string()) // Print an empty line
}
}
"version" => ReplCommand::Version,
"help" => ReplCommand::Help,
"save" => {
if parts.len() > 1 {
ReplCommand::Save(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Save(None)
}
}
"show" => {
if parts.len() > 1 {
ReplCommand::Show(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Show(None)
}
}
"stats" => {
if parts.len() > 1 {
ReplCommand::Stats(Some(parts[1].trim().to_string()))
} else {
ReplCommand::Stats(None)
}
}
_ => ReplCommand::Unknown(format!("Unknown command: .{}", command)),
}
} else if !input.is_empty() {
ReplCommand::Sql(input.to_string())
} else {
ReplCommand::Unknown("Empty command".to_string())
}
}
/// Execute a command
fn execute_command(&mut self, command: ReplCommand) -> Result<()> {
match command {
ReplCommand::Sql(sql) => self.execute_sql(&sql),
ReplCommand::Load(file_spec) => self.load_file(&file_spec),
ReplCommand::Tables(pattern) => self.show_tables(pattern.as_deref()),
ReplCommand::Schema(table_name) => self.show_schema(table_name.as_deref()),
ReplCommand::WriteMode(arg) => self.toggle_write(arg.as_deref()),
ReplCommand::Help => self.show_help(),
ReplCommand::Exit(code) => self.exit_repl(code.as_deref()),
ReplCommand::ChangeDirectory(dir) => self.change_directory(&dir),
ReplCommand::Changes(arg) => self.toggle_changes(arg.as_deref()),
ReplCommand::Save(table_name) => self.save_tables(table_name.as_deref()),
ReplCommand::Show(option) => self.show_settings(option.as_deref()),
ReplCommand::Stats(option) => self.show_stats(option.as_deref()),
ReplCommand::Print(text) => {
println!("{}", text);
Ok(())
}
ReplCommand::Version => self.show_version(),
ReplCommand::Unknown(msg) => {
eprintln!("{}", msg);
Ok(())
}
}
}
/// Execute SQL statement
fn execute_sql(&mut self, sql: &str) -> Result<()> {
// Record start time if statistics are enabled
let start_time = if self.show_stats {
Some(std::time::Instant::now())
} else {
None
};
let result = match self.executor.execute_sql(sql) {
Ok(result) => result,
Err(err) => return Err(ReplError::SqlExecutor(err)),
};
// Print every statement's result set, each with its own header.
for result_set in &result {
if result_set.rows.is_empty() {
println!("Query returned no rows");
} else {
println!("Query returned {} rows", result_set.rows.len());
// Print column headers
println!("{}", result_set.columns.join(","));
// Print rows
for row in &result_set.rows {
println!("{}", row.join(","));
}
}
}
// The change count is reported independently of whether the line also
// produced rows. Gating it on "no result set" hid the count for a
// trailing DML on a line like `SELECT ...; DELETE ...`.
if self.show_changes && self.executor.last_statement_changed_rows() {
// For non-SELECT statements that don't return rows (INSERT, UPDATE, DELETE)
// Try to display the number of affected rows if show_changes is enabled
// Reported even when zero. With `.changes on` a statement that
// matched nothing otherwise produced no output at all, leaving it
// ambiguous whether it had run.
if let Ok(affected_rows) = self.executor.get_affected_row_count() {
println!("{} rows affected", affected_rows);
}
}
// Display query statistics if enabled
if let Some(start_time) = start_time {
let execution_time = start_time.elapsed();
println!("Run Time: {:.3} ms", execution_time.as_secs_f64() * 1000.0);
}
// Save changes if write mode is enabled
if self.config.write_changes() {
let saved_count = match self.executor.save_modified_tables() {
Ok(count) => count,
Err(err) => return Err(ReplError::SqlExecutor(err)),
};
if saved_count > 0 {
println!("Changes saved to {} tables", saved_count);
}
} else if self.executor.has_modified_tables() {
println!("Changes not saved: use .write to save changes to files");
}
Ok(())
}
/// Load a file into a table
fn load_file(&mut self, file_spec: &str) -> Result<()> {
// The file load now needs to pass the field separator
// Since our SqlExecutor's load_file method has been updated to handle it
let result = match self.executor.load_file(file_spec) {
Ok(result) => result,
Err(err) => return Err(ReplError::Sqawk(err)),
};
match result {
Some((table_name, file_path)) => {
println!("Loaded table '{}' from '{}'", table_name, file_path);
Ok(())
}
None => {
println!("No table created");
Ok(())
}
}
}
/// Show the list of tables, optionally filtered by a pattern
fn show_tables(&self, pattern: Option<&str>) -> Result<()> {
let tables = self.executor.table_names();
if tables.is_empty() {
println!("No tables loaded");
return Ok(());
}
println!("Tables:");
match pattern {
Some(pat) => {
// Filter tables matching the pattern (SQL LIKE pattern)
// Convert SQL LIKE pattern to regex
let regex_pattern = pat.replace("%", ".*").replace("_", ".");
let regex = regex::Regex::new(&format!("^{}$", regex_pattern))
.unwrap_or_else(|_| regex::Regex::new(".*").unwrap()); // Fallback to match all if regex is invalid
let matching_tables: Vec<&String> =
tables.iter().filter(|name| regex.is_match(name)).collect();
if matching_tables.is_empty() {
println!(" No tables match pattern: {}", pat);
} else {
for table in matching_tables {
let modified = if self.executor.is_table_modified(table) {
" (modified)"
} else {
""
};
println!(" {}{}", table, modified);
}
}
}
None => {
// Show all tables
for table in tables {
let modified = if self.executor.is_table_modified(&table) {
" (modified)"
} else {
""
};
println!(" {}{}", table, modified);
}
}
}
Ok(())
}
// The show_columns functionality is now handled by show_schema with a specific table name
/// Show help message
fn show_help(&self) -> Result<()> {
println!("Available commands:");
println!(" .cd DIRECTORY Change the working directory to DIRECTORY");
println!(
" .changes [on|off] Show number of rows changed by SQL (currently: {})",
if self.show_changes { "ON" } else { "OFF" }
);
println!(" .exit ?CODE? Exit the REPL with optional code");
println!(" .help Show this help message");
println!(" .load [TABLE=]FILE Load FILE into TABLE");
println!(" .print STRING... Print literal STRING");
println!(" .quit Exit the REPL");
println!(" .save ?TABLE? Save changes to all tables or a specific TABLE");
println!(" .schema ?TABLE? Show schema for a specific table or all tables");
println!(" .show ?WHAT? Show current settings and status information");
println!(
" .stats [on|off] Toggle statistics display (currently: {})",
if self.show_stats { "ON" } else { "OFF" }
);
println!(" .tables ?TABLE? List names of tables matching LIKE pattern TABLE");
println!(" .version Show source, library and compiler versions");
println!(
" .write [on|off] Toggle writing changes to files (currently: {})",
if self.config.write_changes() {
"ON"
} else {
"OFF"
}
);
println!(" SQL_STATEMENT Execute SQL statement");
Ok(())
}
/// Exit the REPL with an optional exit code
fn exit_repl(&mut self, code: Option<&str>) -> Result<()> {
self.running = false;
// If an exit code is provided, we'll just acknowledge it
// In a real program, this would set the process exit code
if let Some(code_str) = code {
match code_str.parse::<i32>() {
Ok(code) => {
println!("Exit code set to: {}", code);
}
Err(_) => {
eprintln!("Invalid exit code: {}", code_str);
}
}
}
Ok(())
}
/// Display schema information for a table or all tables
fn show_schema(&self, table_name: Option<&str>) -> Result<()> {
match table_name {
Some(name) => {
// Show schema for specific table
match self.executor.get_table_column_types(name) {
Ok(column_types) => {
println!("CREATE TABLE {} (", name);
for (i, (column_name, data_type)) in column_types.iter().enumerate() {
if i < column_types.len() - 1 {
println!(" {} {},", column_name, data_type);
} else {
println!(" {} {}", column_name, data_type);
}
}
println!(");");
}
Err(_) => {
eprintln!("No such table: {}", name);
}
}
}
None => {
// Show schema for all tables
for name in self.executor.table_names() {
if let Ok(column_types) = self.executor.get_table_column_types(&name) {
println!("CREATE TABLE {} (", name);
for (i, (column_name, data_type)) in column_types.iter().enumerate() {
if i < column_types.len() - 1 {
println!(" {} {},", column_name, data_type);
} else {
println!(" {} {}", column_name, data_type);
}
}
println!(");");
}
}
}
}
Ok(())
}
/// Change the current working directory
fn change_directory(&self, dir: &str) -> Result<()> {
match std::env::set_current_dir(dir) {
Ok(_) => {
println!("Changed directory to {}", dir);
Ok(())
}
Err(e) => {
eprintln!("Failed to change directory: {}", e);
Ok(())
}
}
}
/// Toggle showing number of rows changed by SQL statements
fn toggle_changes(&mut self, arg: Option<&str>) -> Result<()> {
match arg {
Some("on") => {
self.show_changes = true;
println!("Changes display enabled");
}
Some("off") => {
self.show_changes = false;
println!("Changes display disabled");
}
_ => {
// Toggle current state
self.show_changes = !self.show_changes;
println!(
"Changes display {}",
if self.show_changes {
"enabled"
} else {
"disabled"
}
);
}
}
Ok(())
}
/// Show version information
///
/// Read from the manifest rather than written out, so it cannot drift.
/// This reported 0.1.1 for a long time while the crate was at 0.8.0.
fn show_version(&self) -> Result<()> {
println!("Sqawk version {}", env!("CARGO_PKG_VERSION"));
println!("sqlparser {}", crate::vm::SQLPARSER_VERSION);
Ok(())
}
/// Save changes to tables
///
/// Explicitly writes changes to disk for all modified tables or a specific table
/// if one is specified. This is useful when write mode is off but you want to
/// save specific changes.
fn save_tables(&mut self, table_name: Option<&str>) -> Result<()> {
match table_name {
Some(name) => {
// Save a specific table if it exists and is modified
if !self.executor.table_exists(name) {
return Err(ReplError::Sqawk(crate::error::SqawkError::TableNotFound(
name.to_string(),
)));
}
if !self.executor.table_is_modified(name) {
println!("Table '{}' has no changes to save", name);
return Ok(());
}
match self.executor.save_table(name) {
Ok(_) => {
println!("Changes saved to table '{}'", name);
Ok(())
}
Err(err) => {
// Print specific guidance for NoFilePath errors related to CREATE TABLE usage
if let crate::error::SqawkError::NoFilePath(table) = &err {
eprintln!("Error: Table '{}' has no associated file path", table);
eprintln!("Hint: When creating tables with CREATE TABLE, use the LOCATION clause");
eprintln!(
"Example: CREATE TABLE {} (...) LOCATION './file.csv';",
table
);
} else {
eprintln!("Error saving table '{}': {}", name, err);
}
Err(ReplError::Sqawk(err))
}
}
}
None => {
// Save all modified tables
if !self.executor.has_modified_tables() {
println!("No modified tables to save");
return Ok(());
}
match self.executor.save_modified_tables() {
Ok(count) => {
println!("Changes saved to {} tables", count);
Ok(())
}
Err(err) => {
eprintln!("Error saving modified tables: {}", err);
Err(ReplError::SqlExecutor(err))
}
}
}
}
}
}
impl Repl<'_> {
/// Toggle writing changes to files
fn toggle_write(&mut self, arg: Option<&str>) -> Result<()> {
match arg {
Some("on") => {
self.config.set_write_changes(true);
println!("Write mode enabled - changes will be saved to files");
}
Some("off") => {
self.config.set_write_changes(false);
println!("Write mode disabled - changes will not be saved to files");
}
_ => {
// Toggle current state
let current = self.config.write_changes();
self.config.set_write_changes(!current);
println!(
"Write mode {}",
if self.config.write_changes() {
"enabled"
} else {
"disabled"
}
);
}
}
Ok(())
}
/// Show current settings and configuration
fn show_settings(&self, option: Option<&str>) -> Result<()> {
match option {
Some("tables") => {
// Show detailed table information
self.show_tables_metadata()
}
_ => {
// Show general settings
println!("Sqawk Settings:");
println!(
" Write Mode: {}",
if self.config.write_changes() {
"ON"
} else {
"OFF"
}
);
println!(
" Changes Display: {}",
if self.show_changes { "ON" } else { "OFF" }
);
println!(
" Statistics: {}",
if self.show_stats { "ON" } else { "OFF" }
);
println!(
" Verbose: {}",
if self.config.verbose() { "ON" } else { "OFF" }
);
// Show field separator if defined
if let Some(sep) = self.config.field_separator() {
println!(" Field Separator: '{}'", sep);
} else {
println!(" Field Separator: Default (auto-detect)");
}
// Show counts
let tables = self.executor.table_names();
let modified_count = tables
.iter()
.filter(|t| self.executor.is_table_modified(t))
.count();
println!(" Tables Loaded: {}", tables.len());
println!(" Modified Tables: {}", modified_count);
Ok(())
}
}
}
/// Show detailed metadata for all tables
fn show_tables_metadata(&self) -> Result<()> {
let tables = self.executor.table_names();
if tables.is_empty() {
println!("No tables loaded");
return Ok(());
}
println!("Table Information:");
for table_name in tables {
// Get table metadata
let is_modified = self.executor.is_table_modified(&table_name);
let column_count = match self.executor.get_table_columns(&table_name) {
Ok(cols) => cols.len(),
Err(_) => 0,
};
println!(" Table: {}", table_name);
println!(
" Status: {}",
if is_modified { "MODIFIED" } else { "Unchanged" }
);
println!(" Columns: {}", column_count);
// We don't have direct access to row count or filename in current implementation
// These would be good additions to the API in the future
println!();
}
Ok(())
}
/// Show statistics or toggle statistics mode
fn show_stats(&mut self, option: Option<&str>) -> Result<()> {
match option {
Some("on") => {
self.show_stats = true;
println!("Statistics display enabled");
Ok(())
}
Some("off") => {
self.show_stats = false;
println!("Statistics display disabled");
Ok(())
}
None => {
// Toggle the current state
self.show_stats = !self.show_stats;
println!(
"Statistics display {}",
if self.show_stats {
"enabled"
} else {
"disabled"
}
);
Ok(())
}
Some(_) => {
println!("Unknown option for .stats");
println!("Usage: .stats [on|off]");
Ok(())
}
}
}
}