sql-cli 1.73.0

SQL query tool for CSV/JSON with both interactive TUI and non-interactive CLI modes - perfect for exploration and automation
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
//! Shadow State Manager - Observes state transitions without controlling them
//!
//! This module runs in parallel to the existing state system, observing and
//! logging state changes to help us understand patterns before migrating to
//! centralized state management.

use crate::buffer::{AppMode, Buffer, BufferAPI};
use std::collections::VecDeque;
use std::time::Instant;
use tracing::{debug, info, warn};

/// Simplified application state for observation
#[derive(Debug, Clone, PartialEq)]
pub enum AppState {
    /// Command/query input mode
    Command,
    /// Results navigation mode
    Results,
    /// Any search mode active
    Search { search_type: SearchType },
    /// Help mode
    Help,
    /// Debug view
    Debug,
    /// History search mode
    History,
    /// Jump to row mode
    JumpToRow,
    /// Column statistics view
    ColumnStats,
}

/// Types of search that can be active
#[derive(Debug, Clone, PartialEq)]
pub enum SearchType {
    Vim,    // / search
    Column, // Column name search
    Data,   // Data content search
    Fuzzy,  // Fuzzy filter
}

/// Shadow state manager that observes but doesn't control
pub struct ShadowStateManager {
    /// Current observed state
    state: AppState,

    /// Previous state for transition tracking
    previous_state: Option<AppState>,

    /// History of state transitions
    history: VecDeque<StateTransition>,

    /// Count of transitions observed
    transition_count: usize,

    /// Track if we're in sync with actual state
    discrepancies: Vec<String>,
}

#[derive(Debug, Clone)]
struct StateTransition {
    timestamp: Instant,
    from: AppState,
    to: AppState,
    trigger: String,
}

impl ShadowStateManager {
    pub fn new() -> Self {
        info!(target: "shadow_state", "Shadow state manager initialized");

        Self {
            state: AppState::Command,
            previous_state: None,
            history: VecDeque::with_capacity(100),
            transition_count: 0,
            discrepancies: Vec::new(),
        }
    }

    /// Observe a mode change from the existing system
    pub fn observe_mode_change(&mut self, mode: AppMode, trigger: &str) {
        let new_state = self.mode_to_state(mode.clone());

        // Only log if state actually changed
        if new_state == self.state {
            debug!(target: "shadow_state", 
                "Redundant mode change to {:?} ignored", mode);
        } else {
            self.transition_count += 1;

            info!(target: "shadow_state",
                "[#{}] {} -> {} (trigger: {})",
                self.transition_count,
                self.state_display(&self.state),
                self.state_display(&new_state),
                trigger
            );

            // Record transition
            let transition = StateTransition {
                timestamp: Instant::now(),
                from: self.state.clone(),
                to: new_state.clone(),
                trigger: trigger.to_string(),
            };

            self.history.push_back(transition);
            if self.history.len() > 100 {
                self.history.pop_front();
            }

            // Update state
            self.previous_state = Some(self.state.clone());
            self.state = new_state;

            // Log what side effects should happen
            self.log_expected_side_effects();
        }
    }

    // ============= Write-Through Methods (Temporary) =============
    // These methods update both shadow state and buffer during migration
    // Eventually the buffer parameter will be removed

    /// Set mode - authoritative method that updates both shadow state and buffer
    pub fn set_mode(&mut self, mode: AppMode, buffer: &mut Buffer, trigger: &str) {
        let new_state = self.mode_to_state(mode.clone());

        // Only proceed if state actually changed
        if new_state == self.state {
            debug!(target: "shadow_state", 
                "Redundant mode change to {:?} ignored", mode);
        } else {
            self.transition_count += 1;

            info!(target: "shadow_state",
                "[#{}] {} -> {} (trigger: {})",
                self.transition_count,
                self.state_display(&self.state),
                self.state_display(&new_state),
                trigger
            );

            // Record transition
            let transition = StateTransition {
                timestamp: Instant::now(),
                from: self.state.clone(),
                to: new_state.clone(),
                trigger: trigger.to_string(),
            };

            self.history.push_back(transition);
            if self.history.len() > 100 {
                self.history.pop_front();
            }

            // Update shadow state
            self.previous_state = Some(self.state.clone());
            self.state = new_state;

            // Update buffer (temporary - will be removed)
            buffer.set_mode(mode);

            // Log what side effects should happen
            self.log_expected_side_effects();
        }
    }

    /// Switch to Results mode
    pub fn switch_to_results(&mut self, buffer: &mut Buffer) {
        self.set_mode(AppMode::Results, buffer, "switch_to_results");
    }

    /// Switch to Command mode
    pub fn switch_to_command(&mut self, buffer: &mut Buffer) {
        self.set_mode(AppMode::Command, buffer, "switch_to_command");
    }

    /// Start search with specific type
    pub fn start_search(&mut self, search_type: SearchType, buffer: &mut Buffer, trigger: &str) {
        let mode = match search_type {
            SearchType::Column => AppMode::ColumnSearch,
            SearchType::Data | SearchType::Vim => AppMode::Search,
            SearchType::Fuzzy => AppMode::FuzzyFilter,
        };

        // Update state
        self.state = AppState::Search {
            search_type: search_type.clone(),
        };
        self.transition_count += 1;

        info!(target: "shadow_state",
            "[#{}] Starting {:?} search (trigger: {})",
            self.transition_count, search_type, trigger
        );

        // Update buffer
        buffer.set_mode(mode);
    }

    /// Exit current mode to Results
    pub fn exit_to_results(&mut self, buffer: &mut Buffer) {
        self.set_mode(AppMode::Results, buffer, "exit_to_results");
    }

    // ============= Original Observer Methods =============

    /// Observe search starting
    pub fn observe_search_start(&mut self, search_type: SearchType, trigger: &str) {
        let new_state = AppState::Search {
            search_type: search_type.clone(),
        };

        if !matches!(self.state, AppState::Search { .. }) {
            self.transition_count += 1;

            info!(target: "shadow_state",
                "[#{}] {} -> {:?} search (trigger: {})",
                self.transition_count,
                self.state_display(&self.state),
                search_type,
                trigger
            );

            self.previous_state = Some(self.state.clone());
            self.state = new_state;

            // Note: When we see search start, other searches should be cleared
            warn!(target: "shadow_state",
                "⚠️  Search started - verify other search states were cleared!");
        }
    }

    /// Observe search ending
    pub fn observe_search_end(&mut self, trigger: &str) {
        if matches!(self.state, AppState::Search { .. }) {
            // Return to Results mode (assuming we were in results before search)
            let new_state = AppState::Results;

            info!(target: "shadow_state",
                "[#{}] Exiting search -> {} (trigger: {})",
                self.transition_count,
                self.state_display(&new_state),
                trigger
            );

            self.previous_state = Some(self.state.clone());
            self.state = new_state;

            // Log expected cleanup
            info!(target: "shadow_state", 
                "✓ Expected side effects: Clear search UI, restore navigation keys");
        }
    }

    /// Check if we're in search mode
    #[must_use]
    pub fn is_search_active(&self) -> bool {
        matches!(self.state, AppState::Search { .. })
    }

    /// Get current search type if active
    #[must_use]
    pub fn get_search_type(&self) -> Option<SearchType> {
        if let AppState::Search { ref search_type } = self.state {
            Some(search_type.clone())
        } else {
            None
        }
    }

    /// Get display string for status line
    #[must_use]
    pub fn status_display(&self) -> String {
        format!("[Shadow: {}]", self.state_display(&self.state))
    }

    /// Get debug info about recent transitions
    #[must_use]
    pub fn debug_info(&self) -> String {
        let mut info = format!(
            "Shadow State Debug (transitions: {})\n",
            self.transition_count
        );
        info.push_str(&format!("Current: {:?}\n", self.state));

        if !self.history.is_empty() {
            info.push_str("\nRecent transitions:\n");
            for transition in self.history.iter().rev().take(5) {
                info.push_str(&format!(
                    "  {:?} ago: {} -> {} ({})\n",
                    transition.timestamp.elapsed(),
                    self.state_display(&transition.from),
                    self.state_display(&transition.to),
                    transition.trigger
                ));
            }
        }

        if !self.discrepancies.is_empty() {
            info.push_str("\n⚠️  Discrepancies detected:\n");
            for disc in self.discrepancies.iter().rev().take(3) {
                info.push_str(&format!("  - {disc}\n"));
            }
        }

        info
    }

    /// Report a discrepancy between shadow and actual state
    pub fn report_discrepancy(&mut self, expected: &str, actual: &str) {
        let msg = format!("Expected: {expected}, Actual: {actual}");
        warn!(target: "shadow_state", "Discrepancy: {}", msg);
        self.discrepancies.push(msg);
    }

    // ============= Comprehensive Read Methods =============
    // These methods make shadow state easy to query and will eventually
    // replace all buffer().get_mode() calls

    /// Get the current state
    #[must_use]
    pub fn get_state(&self) -> &AppState {
        &self.state
    }

    /// Get the current mode (converts state to `AppMode` for compatibility)
    #[must_use]
    pub fn get_mode(&self) -> AppMode {
        match &self.state {
            AppState::Command => AppMode::Command,
            AppState::Results => AppMode::Results,
            AppState::Search { search_type } => match search_type {
                SearchType::Column => AppMode::ColumnSearch,
                SearchType::Data => AppMode::Search,
                SearchType::Fuzzy => AppMode::FuzzyFilter,
                SearchType::Vim => AppMode::Search, // Vim search uses Search mode
            },
            AppState::Help => AppMode::Help,
            AppState::Debug => AppMode::Debug,
            AppState::History => AppMode::History,
            AppState::JumpToRow => AppMode::JumpToRow,
            AppState::ColumnStats => AppMode::ColumnStats,
        }
    }

    /// Check if currently in Results mode
    #[must_use]
    pub fn is_in_results_mode(&self) -> bool {
        matches!(self.state, AppState::Results)
    }

    /// Check if currently in Command mode
    #[must_use]
    pub fn is_in_command_mode(&self) -> bool {
        matches!(self.state, AppState::Command)
    }

    /// Check if currently in any Search mode
    #[must_use]
    pub fn is_in_search_mode(&self) -> bool {
        matches!(self.state, AppState::Search { .. })
    }

    /// Check if currently in Help mode
    #[must_use]
    pub fn is_in_help_mode(&self) -> bool {
        matches!(self.state, AppState::Help)
    }

    /// Check if currently in Debug mode
    #[must_use]
    pub fn is_in_debug_mode(&self) -> bool {
        matches!(self.state, AppState::Debug)
    }

    /// Check if currently in History mode
    #[must_use]
    pub fn is_in_history_mode(&self) -> bool {
        matches!(self.state, AppState::History)
    }

    /// Check if currently in `JumpToRow` mode
    #[must_use]
    pub fn is_in_jump_mode(&self) -> bool {
        matches!(self.state, AppState::JumpToRow)
    }

    /// Check if currently in `ColumnStats` mode
    #[must_use]
    pub fn is_in_column_stats_mode(&self) -> bool {
        matches!(self.state, AppState::ColumnStats)
    }

    /// Check if in column search specifically
    #[must_use]
    pub fn is_in_column_search(&self) -> bool {
        matches!(
            self.state,
            AppState::Search {
                search_type: SearchType::Column
            }
        )
    }

    /// Check if in data search specifically
    #[must_use]
    pub fn is_in_data_search(&self) -> bool {
        matches!(
            self.state,
            AppState::Search {
                search_type: SearchType::Data
            }
        )
    }

    /// Check if in fuzzy filter mode specifically
    #[must_use]
    pub fn is_in_fuzzy_filter(&self) -> bool {
        matches!(
            self.state,
            AppState::Search {
                search_type: SearchType::Fuzzy
            }
        )
    }

    /// Check if in vim search mode specifically
    #[must_use]
    pub fn is_in_vim_search(&self) -> bool {
        matches!(
            self.state,
            AppState::Search {
                search_type: SearchType::Vim
            }
        )
    }

    /// Get the previous state if any
    #[must_use]
    pub fn get_previous_state(&self) -> Option<&AppState> {
        self.previous_state.as_ref()
    }

    /// Check if we can navigate (in Results mode)
    #[must_use]
    pub fn can_navigate(&self) -> bool {
        self.is_in_results_mode()
    }

    /// Check if we can edit (in Command mode or search modes)
    #[must_use]
    pub fn can_edit(&self) -> bool {
        self.is_in_command_mode() || self.is_in_search_mode()
    }

    /// Get transition count (useful for debugging)
    #[must_use]
    pub fn get_transition_count(&self) -> usize {
        self.transition_count
    }

    /// Get the last transition if any
    #[must_use]
    pub fn get_last_transition(&self) -> Option<&StateTransition> {
        self.history.back()
    }

    // Helper methods

    fn mode_to_state(&self, mode: AppMode) -> AppState {
        match mode {
            AppMode::Command => AppState::Command,
            AppMode::Results => AppState::Results,
            AppMode::Search | AppMode::ColumnSearch => {
                // Try to preserve search type if we're already in search
                if let AppState::Search { ref search_type } = self.state {
                    AppState::Search {
                        search_type: search_type.clone(),
                    }
                } else {
                    // Guess based on mode
                    let search_type = match mode {
                        AppMode::ColumnSearch => SearchType::Column,
                        _ => SearchType::Data,
                    };
                    AppState::Search { search_type }
                }
            }
            AppMode::Help => AppState::Help,
            AppMode::Debug | AppMode::PrettyQuery => AppState::Debug,
            AppMode::History => AppState::History,
            AppMode::JumpToRow => AppState::JumpToRow,
            AppMode::ColumnStats => AppState::ColumnStats,
            _ => self.state.clone(), // Preserve current for unknown modes
        }
    }

    fn state_display(&self, state: &AppState) -> String {
        match state {
            AppState::Command => "COMMAND".to_string(),
            AppState::Results => "RESULTS".to_string(),
            AppState::Search { search_type } => format!("SEARCH({search_type:?})"),
            AppState::Help => "HELP".to_string(),
            AppState::Debug => "DEBUG".to_string(),
            AppState::History => "HISTORY".to_string(),
            AppState::JumpToRow => "JUMP_TO_ROW".to_string(),
            AppState::ColumnStats => "COLUMN_STATS".to_string(),
        }
    }

    fn log_expected_side_effects(&self) {
        match (&self.previous_state, &self.state) {
            (Some(AppState::Command), AppState::Results) => {
                debug!(target: "shadow_state", 
                    "Expected side effects: Clear searches, reset viewport, enable nav keys");
            }
            (Some(AppState::Results), AppState::Search { .. }) => {
                debug!(target: "shadow_state",
                    "Expected side effects: Clear other searches, setup search UI");
            }
            (Some(AppState::Search { .. }), AppState::Results) => {
                debug!(target: "shadow_state",
                    "Expected side effects: Clear search UI, restore nav keys");
            }
            _ => {}
        }
    }
}

impl Default for ShadowStateManager {
    fn default() -> Self {
        Self::new()
    }
}