rowdy-db 0.3.0

A fast, modern, and rowdy TUI database management tool written in Rust.
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
use crossterm::event::KeyEvent;
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    widgets::{Block, Borders, Cell, Paragraph, Row as RatRow, Table, TableState},
    Frame,
};
use tui_textarea::{Input, Key, TextArea};
use crate::db::types::{DbQueryResult, Value};

// ── Focus ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq)]
pub enum EditorFocus {
    Editor,
    Results,
}

// ── Query result ──────────────────────────────────────────────────────────────

pub enum QueryResult {
    Rows(DbQueryResult),
    Affected(u64),
    Error(String),
}

// ── Actions ───────────────────────────────────────────────────────────────────

pub enum SqlEditorAction {
    None,
    Execute(String),
    Back,
}

// ── Screen ────────────────────────────────────────────────────────────────────

pub struct SqlEditorScreen {
    pub editor: TextArea<'static>,
    pub result: Option<QueryResult>,
    pub result_state: TableState,
    pub result_col_offset: usize,
    pub focus: EditorFocus,
    pub running: bool,
    pub db_info: String,
}

impl SqlEditorScreen {
    pub fn new(db_info: String) -> Self {
        let mut editor = TextArea::default();
        editor.set_cursor_line_style(Style::default());
        editor.set_placeholder_text("-- Write your SQL here…");
        editor.set_placeholder_style(Style::default().fg(Color::DarkGray));
        Self {
            editor,
            result: None,
            result_state: TableState::default(),
            result_col_offset: 0,
            focus: EditorFocus::Editor,
            running: false,
            db_info,
        }
    }

    pub fn set_rows(&mut self, result: DbQueryResult) {
        self.running = false;
        self.result_state = TableState::default();
        if !result.rows.is_empty() {
            self.result_state.select(Some(0));
        }
        self.result_col_offset = 0;
        self.result = Some(QueryResult::Rows(result));
    }

    pub fn set_affected(&mut self, n: u64) {
        self.running = false;
        self.result = Some(QueryResult::Affected(n));
        self.result_state = TableState::default();
    }

    pub fn set_error(&mut self, msg: String) {
        self.running = false;
        self.result = Some(QueryResult::Error(msg));
        self.result_state = TableState::default();
    }

    pub fn set_running(&mut self) {
        self.running = true;
        self.result = None;
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> SqlEditorAction {
        let input = Input::from(key);
        match self.focus {
            EditorFocus::Editor => {
                match input {
                    // Execute: F5 or Ctrl+Enter
                    Input { key: Key::F(5), .. }
                    | Input { key: Key::Enter, ctrl: true, .. } => {
                        let sql = self.editor.lines().join("\n");
                        let sql = sql.trim().to_string();
                        if !sql.is_empty() && !self.running {
                            return SqlEditorAction::Execute(sql);
                        }
                    }
                    // Back: Ctrl+Q
                    Input { key: Key::Char('q'), ctrl: true, .. } => {
                        return SqlEditorAction::Back;
                    }
                    // Switch focus to results (only when results exist)
                    Input { key: Key::Tab, .. } => {
                        if self.result.is_some() {
                            self.focus = EditorFocus::Results;
                        }
                    }
                    // Pass everything else to the textarea
                    _ => {
                        self.editor.input(input);
                    }
                }
            }
            EditorFocus::Results => {
                match input {
                    Input { key: Key::Tab, .. }
                    | Input { key: Key::Esc, .. } => {
                        self.focus = EditorFocus::Editor;
                    }
                    Input { key: Key::Char('j'), .. }
                    | Input { key: Key::Down, .. }   => self.result_move_row(1),
                    Input { key: Key::Char('k'), .. }
                    | Input { key: Key::Up, .. }     => self.result_move_row(-1),
                    Input { key: Key::Char('l'), .. }
                    | Input { key: Key::Right, .. }  => self.result_move_col(1),
                    Input { key: Key::Char('h'), .. }
                    | Input { key: Key::Left, .. }   => self.result_move_col(-1),
                    Input { key: Key::Char('g'), .. } => self.result_go_first(),
                    Input { key: Key::Char('G'), .. } => self.result_go_last(),
                    Input { key: Key::PageDown, .. } => self.result_move_row(10),
                    Input { key: Key::PageUp, .. }   => self.result_move_row(-10),
                    _ => {}
                }
            }
        }
        SqlEditorAction::None
    }

    fn result_row_count(&self) -> usize {
        match &self.result {
            Some(QueryResult::Rows(r)) => r.rows.len(),
            _ => 0,
        }
    }

    fn result_col_count(&self) -> usize {
        match &self.result {
            Some(QueryResult::Rows(r)) => r.columns.len(),
            _ => 0,
        }
    }

    fn result_selected_row(&self) -> usize {
        self.result_state.selected().unwrap_or(0)
    }

    fn result_move_row(&mut self, delta: i64) {
        let count = self.result_row_count();
        if count == 0 { return; }
        let next = (self.result_selected_row() as i64 + delta)
            .clamp(0, count as i64 - 1) as usize;
        self.result_state.select(Some(next));
    }

    fn result_move_col(&mut self, delta: i64) {
        let count = self.result_col_count();
        if count == 0 { return; }
        let next = (self.result_col_offset as i64 + delta)
            .clamp(0, count as i64 - 1) as usize;
        self.result_col_offset = next;
    }

    fn result_go_first(&mut self) {
        if self.result_row_count() > 0 {
            self.result_state.select(Some(0));
        }
    }

    fn result_go_last(&mut self) {
        let n = self.result_row_count();
        if n > 0 {
            self.result_state.select(Some(n - 1));
        }
    }

    pub fn draw(f: &mut Frame<'_>, screen: &mut SqlEditorScreen) {
        let area = f.size();

        let vertical = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Percentage(45),
                Constraint::Min(3),
                Constraint::Length(3),
            ])
            .split(area);

        draw_editor(f, screen, vertical[0]);
        draw_results(f, screen, vertical[1]);
        draw_help(f, screen, vertical[2]);
    }
}

// ── Editor pane ───────────────────────────────────────────────────────────────

fn draw_editor(f: &mut Frame<'_>, screen: &mut SqlEditorScreen, area: Rect) {
    let focused = screen.focus == EditorFocus::Editor;
    let border_style = if focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::DarkGray)
    };
    let status_label = if screen.running { "" } else { "" };
    let title = format!(" SQL Editor {}{} ", status_label, screen.db_info);
    screen.editor.set_block(
        Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_style(border_style),
    );
    screen.editor.set_selection_style(
        Style::default().bg(Color::DarkGray).fg(Color::White),
    );
    f.render_widget(&screen.editor, area);
}

// ── Results pane ──────────────────────────────────────────────────────────────

fn draw_results(f: &mut Frame<'_>, screen: &mut SqlEditorScreen, area: Rect) {
    let focused = screen.focus == EditorFocus::Results;
    let border_style = if focused {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default().fg(Color::DarkGray)
    };

    match &screen.result {
        None => {
            let msg = if screen.running {
                "Executing query…"
            } else {
                "Press F5 or Ctrl+Enter to run a query"
            };
            f.render_widget(
                Paragraph::new(msg)
                    .block(
                        Block::default()
                            .title(" Results ")
                            .borders(Borders::ALL)
                            .border_style(border_style),
                    )
                    .style(Style::default().fg(Color::DarkGray)),
                area,
            );
        }

        Some(QueryResult::Affected(n)) => {
            f.render_widget(
                Paragraph::new(format!("  {} row(s) affected", n))
                    .block(
                        Block::default()
                            .title(" Results ")
                            .borders(Borders::ALL)
                            .border_style(border_style),
                    )
                    .style(Style::default().fg(Color::Green)),
                area,
            );
        }

        Some(QueryResult::Error(msg)) => {
            let msg = msg.clone();
            f.render_widget(
                Paragraph::new(format!("  Error: {}", msg))
                    .block(
                        Block::default()
                            .title(" Results ")
                            .borders(Borders::ALL)
                            .border_style(border_style),
                    )
                    .style(Style::default().fg(Color::Red)),
                area,
            );
        }

        Some(QueryResult::Rows(result)) => {
            let col_count = result.columns.len();
            let col_offset = screen.result_col_offset.min(col_count.saturating_sub(1));
            let available_w = area.width.saturating_sub(4);

            let mut visible_cols: Vec<usize> = vec![];
            let mut used = 0u16;
            for i in col_offset..col_count {
                let w = col_display_width(result, i);
                if used + w + 1 > available_w {
                    break;
                }
                used += w + 1;
                visible_cols.push(i);
            }

            let widths: Vec<Constraint> = visible_cols
                .iter()
                .map(|&i| Constraint::Length(col_display_width(result, i)))
                .collect();

            let header_cells: Vec<Cell> = visible_cols
                .iter()
                .map(|&i| {
                    Cell::from(truncate_str(
                        &result.columns[i].name,
                        col_display_width(result, i) as usize,
                    ))
                    .style(Style::default().add_modifier(Modifier::BOLD))
                })
                .collect();

            let header = RatRow::new(header_cells)
                .style(Style::default().bg(Color::DarkGray))
                .height(1);

            // Clone rows/cols to avoid borrow issues with result_state below
            let rows_data: Vec<Vec<String>> = result
                .rows
                .iter()
                .map(|row| {
                    visible_cols
                        .iter()
                        .map(|&i| {
                            let val = row.values.get(i).unwrap_or(&Value::Null);
                            truncate_str(
                                &value_str(val),
                                col_display_width(result, i) as usize,
                            )
                        })
                        .collect()
                })
                .collect();

            let row_count = result.rows.len();
            let title = format!(
                " Results: {} row{} ",
                row_count,
                if row_count == 1 { "" } else { "s" }
            );

            let data_rows: Vec<RatRow> = rows_data
                .into_iter()
                .map(|cells| RatRow::new(cells).height(1))
                .collect();

            let table = Table::new(data_rows, widths)
                .header(header)
                .block(
                    Block::default()
                        .title(title)
                        .borders(Borders::ALL)
                        .border_style(border_style),
                )
                .highlight_style(
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                )
                .highlight_symbol("> ");

            f.render_stateful_widget(table, area, &mut screen.result_state);
        }
    }
}

// ── Help bar ──────────────────────────────────────────────────────────────────

fn draw_help(f: &mut Frame<'_>, screen: &SqlEditorScreen, area: Rect) {
    let text = match screen.focus {
        EditorFocus::Editor =>
            " F5 / Ctrl+Enter: execute   Tab: results pane   Ctrl+Q: back ",
        EditorFocus::Results =>
            " j/k: rows   h/l: cols   g/G: first/last   PgUp/Dn: page   Tab/Esc: editor ",
    };
    f.render_widget(
        Paragraph::new(text)
            .block(Block::default().borders(Borders::ALL))
            .style(Style::default().fg(Color::DarkGray)),
        area,
    );
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn col_display_width(result: &DbQueryResult, col_idx: usize) -> u16 {
    let header_w = result.columns[col_idx].name.len() as u16;
    let max_val_w = result
        .rows
        .iter()
        .map(|r| value_str(r.values.get(col_idx).unwrap_or(&Value::Null)).len() as u16)
        .max()
        .unwrap_or(0);
    (header_w.max(max_val_w) + 2).min(30)
}

fn value_str(v: &Value) -> String {
    match v {
        Value::Null     => "NULL".into(),
        Value::Bool(b)  => b.to_string(),
        Value::Int(i)   => i.to_string(),
        Value::Float(f) => format!("{f:.4}"),
        Value::Text(s)  => s.replace('\n', "").replace('\r', ""),
        Value::Bytes(b) => format!("<{} bytes>", b.len()),
    }
}

fn truncate_str(s: &str, max: usize) -> String {
    let cut = max.saturating_sub(1);
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let t: String = s.chars().take(cut).collect();
        format!("{t}")
    }
}