sql-cli 1.71.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
//! Debug context trait for extracting debug functionality from the main TUI
//!
//! This module provides a trait that encapsulates all debug-related operations,
//! allowing them to be organized separately from the main TUI logic.

use crate::app_state_container::AppStateContainer;
use crate::buffer::{AppMode, Buffer, BufferAPI, BufferManager};
use crate::ui::state::shadow_state::ShadowStateManager;
use crate::ui::viewport_manager::ViewportManager;
use crate::widgets::debug_widget::DebugWidget;
use std::cell::RefCell;

/// Context trait for debug-related functionality
/// This extracts debug operations into a cohesive interface
pub trait DebugContext {
    // Core accessors needed by debug operations
    fn buffer(&self) -> &dyn BufferAPI;
    fn buffer_mut(&mut self) -> &mut dyn BufferAPI;
    fn get_debug_widget(&self) -> &DebugWidget;
    fn get_debug_widget_mut(&mut self) -> &mut DebugWidget;
    fn get_shadow_state(&self) -> &RefCell<ShadowStateManager>;

    // Additional accessors for viewport and buffer management
    fn get_buffer_manager(&self) -> &BufferManager;
    fn get_viewport_manager(&self) -> &RefCell<Option<ViewportManager>>;
    fn get_state_container(&self) -> &AppStateContainer;
    fn get_state_container_mut(&mut self) -> &mut AppStateContainer;

    // Additional accessors for the full debug implementation
    fn get_navigation_timings(&self) -> &Vec<String>;
    fn get_render_timings(&self) -> &Vec<String>;
    fn debug_current_buffer(&mut self);
    fn get_input_cursor(&self) -> usize;
    fn get_visual_cursor(&self) -> (usize, usize);
    fn get_input_text(&self) -> String;

    // The complete toggle_debug_mode implementation from EnhancedTuiApp
    fn toggle_debug_mode(&mut self) {
        // Check if we're exiting debug mode
        if self.buffer().get_mode() == AppMode::Debug {
            // Exit debug mode - use a helper to avoid borrow issues
            self.set_mode_via_shadow_state(AppMode::Command, "debug_toggle_exit");
            return;
        }

        // Entering debug mode - collect all the data we need
        let (
            previous_mode,
            last_query,
            input_text,
            selected_row,
            current_column,
            results_count,
            filtered_count,
        ) = self.collect_current_state();

        // Switch to debug mode - use a helper to avoid borrow issues
        self.set_mode_via_shadow_state(AppMode::Debug, "debug_toggle_enter");

        // Generate full debug information
        self.debug_current_buffer();
        let cursor_pos = self.get_input_cursor();
        let visual_cursor = self.get_visual_cursor().1;
        let query = self.get_input_text();

        // Use the appropriate query for parser debug based on mode
        let query_for_parser = if previous_mode == AppMode::Results && !last_query.is_empty() {
            last_query.clone()
        } else if !query.is_empty() {
            query.clone()
        } else if !last_query.is_empty() {
            last_query.clone()
        } else {
            query.clone()
        };

        // Generate debug info using helper methods
        let mut debug_info = self.debug_generate_parser_info(&query_for_parser);

        // Add comprehensive buffer state
        debug_info.push_str(&self.debug_generate_buffer_state(
            previous_mode,
            &last_query,
            &input_text,
            cursor_pos,
            visual_cursor,
        ));

        // Add results state if in Results mode
        debug_info.push_str(&self.debug_generate_results_state(
            results_count,
            filtered_count,
            selected_row,
            current_column,
        ));

        // Add DataTable schema and DataView state
        debug_info.push_str(&self.debug_generate_datatable_schema());
        debug_info.push_str(&self.debug_generate_dataview_state());

        // Add memory tracking history
        debug_info.push_str(&self.debug_generate_memory_info());

        // Add navigation timing statistics
        debug_info.push_str(&self.format_navigation_timing());

        // Add render timing statistics
        debug_info.push_str(&self.format_render_timing());

        // Add viewport and navigation information
        debug_info.push_str(&self.debug_generate_viewport_state());
        debug_info.push_str(&self.debug_generate_navigation_state());

        // Add buffer manager state info
        debug_info.push_str(&self.format_buffer_manager_state());

        // Add viewport efficiency metrics
        debug_info.push_str(&self.debug_generate_viewport_efficiency());

        // Add key chord handler debug info
        debug_info.push_str(&self.debug_generate_key_chord_info());

        // Add search modes widget debug info
        debug_info.push_str(&self.debug_generate_search_modes_info());

        // Add column search state if active
        debug_info.push_str(&self.debug_generate_column_search_state());

        // Add trace logs from ring buffer
        debug_info.push_str(&self.debug_generate_trace_logs());

        // Add DebugService logs (our StateManager logs!)
        debug_info.push_str(&self.debug_generate_state_logs());

        // Add AppStateContainer debug dump if available
        debug_info.push_str(&self.debug_generate_state_container_info());

        // Add Shadow State debug info
        debug_info.push_str("\n========== SHADOW STATE MANAGER ==========\n");
        debug_info.push_str(&self.get_shadow_state().borrow().debug_info());
        debug_info.push_str("\n==========================================\n");

        // Store the debug info in the widget
        self.get_debug_widget_mut().set_content(debug_info.clone());

        // Copy to clipboard
        match self
            .get_state_container_mut()
            .write_to_clipboard(&debug_info)
        {
            Ok(()) => {
                let status_msg = format!(
                    "DEBUG INFO copied to clipboard ({} chars)!",
                    debug_info.len()
                );
                self.buffer_mut().set_status_message(status_msg);
            }
            Err(e) => {
                let status_msg = format!("Clipboard error: {e}");
                self.buffer_mut().set_status_message(status_msg);
            }
        }
    }

    // Required helper methods that implementations must provide
    fn get_buffer_mut_if_available(&mut self) -> Option<&mut Buffer>;
    fn set_mode_via_shadow_state(&mut self, mode: AppMode, trigger: &str);
    fn collect_current_state(
        &self,
    ) -> (AppMode, String, String, Option<usize>, usize, usize, usize);
    fn format_buffer_manager_state(&self) -> String;
    fn debug_generate_viewport_efficiency(&self) -> String;
    fn debug_generate_key_chord_info(&self) -> String;
    fn debug_generate_search_modes_info(&self) -> String;
    fn debug_generate_state_container_info(&self) -> String;

    // Helper methods with default implementations
    fn format_navigation_timing(&self) -> String {
        let mut result = String::from("\n========== NAVIGATION TIMING ==========\n");
        let timings = self.get_navigation_timings();
        if timings.is_empty() {
            result.push_str("No navigation timing data yet (press j/k to navigate)\n");
        } else {
            result.push_str(&format!("Last {} navigation timings:\n", timings.len()));
            for timing in timings {
                result.push_str(&format!("  {timing}\n"));
            }
            // Calculate average
            let total_ms: f64 = timings
                .iter()
                .filter_map(|s| self.debug_extract_timing(s))
                .sum();
            if !timings.is_empty() {
                let avg_ms = total_ms / timings.len() as f64;
                result.push_str(&format!("Average navigation time: {avg_ms:.3}ms\n"));
            }
        }
        result
    }

    fn format_render_timing(&self) -> String {
        let mut result = String::from("\n========== RENDER TIMING ==========\n");
        let timings = self.get_render_timings();
        if timings.is_empty() {
            result.push_str("No render timing data yet\n");
        } else {
            result.push_str(&format!("Last {} render timings:\n", timings.len()));
            for timing in timings {
                result.push_str(&format!("  {timing}\n"));
            }
            // Calculate average
            let total_ms: f64 = timings
                .iter()
                .filter_map(|s| self.debug_extract_timing(s))
                .sum();
            if !timings.is_empty() {
                let avg_ms = total_ms / timings.len() as f64;
                result.push_str(&format!("Average render time: {avg_ms:.3}ms\n"));
            }
        }
        result
    }

    fn debug_extract_timing(&self, s: &str) -> Option<f64> {
        // Extract timing value from a string like "Navigation: 1.234ms"
        if let Some(ms_pos) = s.find("ms") {
            let start = s[..ms_pos].rfind(' ').map_or(0, |p| p + 1);
            s[start..ms_pos].parse().ok()
        } else {
            None
        }
    }

    // Collect all debug information (simplified version for the trait default)
    fn collect_debug_info(&self) -> String;

    // Debug generation methods with default implementations where possible

    // Simple methods that don't need TUI state - can be default implementations
    fn debug_generate_memory_info(&self) -> String {
        let mut output = String::from("\n========== MEMORY USAGE ==========\n");

        // Get current memory
        let current_mb = crate::utils::memory_tracker::get_memory_mb();
        output.push_str(&format!("Current Memory: {current_mb} MB\n"));

        // Perform memory audit - we always have a buffer
        let buffer = self.buffer();
        let audits = crate::utils::memory_audit::perform_memory_audit(
            buffer.get_datatable(),
            buffer.get_original_source(),
            buffer.get_dataview(),
        );

        output.push_str("\nMemory Breakdown:\n");
        for audit in &audits {
            output.push_str(&format!(
                "  {}: {:.2} MB - {}\n",
                audit.component,
                audit.mb(),
                audit.description
            ));
        }

        // Check for duplication warning
        if audits.iter().any(|a| a.component.contains("DUPLICATE")) {
            output.push_str("\n⚠️  WARNING: Memory duplication detected!\n");
            output.push_str("  DataTable is being stored twice (datatable + original_source)\n");
            output.push_str("  Consider using Arc<DataTable> to share data\n");
        }

        // Add memory history
        output.push_str(&format!(
            "\nMemory History:\n{}",
            crate::utils::memory_tracker::format_memory_history()
        ));

        output
    }

    // Note: debug_extract_timing is already defined above

    // Simple formatting methods that can have default implementations
    fn debug_generate_buffer_state(
        &self,
        mode: AppMode,
        last_query: &str,
        input_text: &str,
        cursor_pos: usize,
        visual_cursor: usize,
    ) -> String {
        format!(
            "\n========== BUFFER STATE ==========\n\
            Current Mode: {mode:?}\n\
            Last Executed Query: '{last_query}'\n\
            Input Text: '{input_text}'\n\
            Input Cursor: {cursor_pos}\n\
            Visual Cursor: {visual_cursor}\n"
        )
    }

    fn debug_generate_results_state(
        &self,
        results_count: usize,
        filtered_count: usize,
        selected_row: Option<usize>,
        current_column: usize,
    ) -> String {
        format!(
            "\n========== RESULTS STATE ==========\n\
            Total Results: {results_count}\n\
            Filtered Results: {filtered_count}\n\
            Selected Row: {selected_row:?}\n\
            Current Column: {current_column}\n"
        )
    }

    // Viewport state can be a default implementation now that we have buffer_manager and viewport_manager
    fn debug_generate_viewport_state(&self) -> String {
        let mut debug_info = String::new();
        if let Some(buffer) = self.get_buffer_manager().current() {
            debug_info.push_str("\n========== VIEWPORT STATE ==========\n");
            let (scroll_row, scroll_col) = buffer.get_scroll_offset();
            debug_info.push_str(&format!(
                "Scroll Offset: row={scroll_row}, col={scroll_col}\n"
            ));
            debug_info.push_str(&format!(
                "Current Column: {}\n",
                buffer.get_current_column()
            ));
            debug_info.push_str(&format!("Selected Row: {:?}\n", buffer.get_selected_row()));
            debug_info.push_str(&format!("Viewport Lock: {}\n", buffer.is_viewport_lock()));
            if let Some(lock_row) = buffer.get_viewport_lock_row() {
                debug_info.push_str(&format!("Viewport Lock Row: {lock_row}\n"));
            }

            // Add ViewportManager crosshair position
            if let Some(ref viewport_manager) = *self.get_viewport_manager().borrow() {
                let visual_row = viewport_manager.get_crosshair_row();
                let visual_col = viewport_manager.get_crosshair_col();
                debug_info.push_str(&format!(
                    "ViewportManager Crosshair (visual): row={visual_row}, col={visual_col}\n"
                ));

                // Also show viewport-relative position
                if let Some((viewport_row, viewport_col)) =
                    viewport_manager.get_crosshair_viewport_position()
                {
                    debug_info.push_str(&format!(
                        "Crosshair in viewport (relative): row={viewport_row}, col={viewport_col}\n"
                    ));
                }
            }

            // Show visible area calculation
            if let Some(dataview) = buffer.get_dataview() {
                let total_rows = dataview.row_count();
                let total_cols = dataview.column_count();
                let visible_rows = buffer.get_last_visible_rows();
                debug_info.push_str("\nVisible Area:\n");
                debug_info.push_str(&format!(
                    "  Total Data: {total_rows} rows × {total_cols} columns\n"
                ));
                debug_info.push_str(&format!("  Visible Rows in Terminal: {visible_rows}\n"));

                // Calculate what section is being viewed
                if total_rows > 0 && visible_rows > 0 {
                    let start_row = scroll_row.min(total_rows.saturating_sub(1));
                    let end_row = (scroll_row + visible_rows).min(total_rows);
                    let percent_start = (start_row as f64 / total_rows as f64 * 100.0) as u32;
                    let percent_end = (end_row as f64 / total_rows as f64 * 100.0) as u32;
                    debug_info.push_str(&format!(
                        "  Viewing rows {}-{} ({}%-{}% of data)\n",
                        start_row + 1,
                        end_row,
                        percent_start,
                        percent_end
                    ));
                }

                if total_cols > 0 {
                    let visible_cols_estimate = 10; // Estimate based on typical column widths
                    let start_col = scroll_col.min(total_cols.saturating_sub(1));
                    let end_col = (scroll_col + visible_cols_estimate).min(total_cols);
                    debug_info.push_str(&format!(
                        "  Viewing columns {}-{} of {}\n",
                        start_col + 1,
                        end_col,
                        total_cols
                    ));
                }
            }
        }
        debug_info
    }

    // DataView state can be a default implementation now that we have buffer_manager
    fn debug_generate_dataview_state(&self) -> String {
        let mut debug_info = String::new();
        if let Some(buffer) = self.get_buffer_manager().current() {
            if let Some(dataview) = buffer.get_dataview() {
                debug_info.push_str("\n========== DATAVIEW STATE ==========\n");

                // Add the detailed column mapping info
                debug_info.push_str(&dataview.get_column_debug_info());
                debug_info.push('\n');

                // Show visible columns in order with both indices
                let visible_columns = dataview.column_names();
                let column_mappings = dataview.get_column_index_mapping();
                debug_info.push_str(&format!(
                    "Visible Columns ({}) with Index Mapping:\n",
                    visible_columns.len()
                ));
                for (visible_idx, col_name, datatable_idx) in &column_mappings {
                    debug_info.push_str(&format!(
                        "  V[{visible_idx:3}] → DT[{datatable_idx:3}] : {col_name}\n"
                    ));
                }

                // Show row information
                debug_info.push_str(&format!("\nVisible Rows: {}\n", dataview.row_count()));

                // Show internal visible_columns array (source column indices)
                debug_info.push_str("\n--- Internal State ---\n");

                // Get the visible_columns indices from DataView
                let visible_indices = dataview.get_visible_column_indices();
                debug_info.push_str(&format!("visible_columns array: {visible_indices:?}\n"));

                // Show pinned columns
                let pinned_names = dataview.get_pinned_column_names();
                if pinned_names.is_empty() {
                    debug_info.push_str("Pinned Columns: None\n");
                } else {
                    debug_info.push_str(&format!("Pinned Columns ({}):\n", pinned_names.len()));
                    for (idx, name) in pinned_names.iter().enumerate() {
                        // Find source index for this pinned column
                        let source_idx = dataview.source().get_column_index(name).unwrap_or(999);
                        debug_info
                            .push_str(&format!("  [{idx}] {name} (source_idx: {source_idx})\n"));
                    }
                }

                // Show sort state
                let sort_state = dataview.get_sort_state();
                match sort_state.order {
                    crate::data::data_view::SortOrder::None => {
                        debug_info.push_str("Sort State: None\n");
                    }
                    crate::data::data_view::SortOrder::Ascending => {
                        if let Some(col_idx) = sort_state.column {
                            let col_name = visible_columns
                                .get(col_idx)
                                .map_or("unknown", std::string::String::as_str);
                            debug_info.push_str(&format!(
                                "Sort State: Ascending on column '{col_name}' (idx: {col_idx})\n"
                            ));
                        }
                    }
                    crate::data::data_view::SortOrder::Descending => {
                        if let Some(col_idx) = sort_state.column {
                            let col_name = visible_columns
                                .get(col_idx)
                                .map_or("unknown", std::string::String::as_str);
                            debug_info.push_str(&format!(
                                "Sort State: Descending on column '{col_name}' (idx: {col_idx})\n"
                            ));
                        }
                    }
                }
            }
        }
        debug_info
    }

    // DataTable schema can be a default implementation now that we have buffer_manager
    fn debug_generate_datatable_schema(&self) -> String {
        let mut debug_info = String::new();
        if let Some(buffer) = self.get_buffer_manager().current() {
            if let Some(dataview) = buffer.get_dataview() {
                let datatable = dataview.source();
                debug_info.push_str("\n========== DATATABLE SCHEMA ==========\n");
                debug_info.push_str(&datatable.get_schema_summary());
            }
        }
        debug_info
    }

    // Rendering methods with default implementations
    fn render_debug(&self, f: &mut ratatui::Frame, area: ratatui::layout::Rect) {
        self.get_debug_widget().render(f, area, AppMode::Debug);
    }

    fn render_pretty_query(&self, f: &mut ratatui::Frame, area: ratatui::layout::Rect) {
        self.get_debug_widget()
            .render(f, area, AppMode::PrettyQuery);
    }

    // Methods that need to be implemented by the TUI (need access to TUI fields)
    fn debug_generate_parser_info(&self, query: &str) -> String;
    fn debug_generate_navigation_state(&self) -> String;
    fn debug_generate_column_search_state(&self) -> String;
    fn debug_generate_trace_logs(&self) -> String;
    fn debug_generate_state_logs(&self) -> String;
}