Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ clap = { version = "4.5.27" , features = ["derive"]}
color-eyre = "0.6.3"
crossterm = "0.28.1"
ratatui = { version = "0.29.0", features = ["serde"] }
rusqlite = "0.33.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }
sqlparser = "0.54.0"
sqlformat = "0.1"
strum = "0.26.3"
36 changes: 24 additions & 12 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,27 +39,39 @@ impl App {
Ok(())
}

/// Select * from a given Table, Returns (Vec Column Names, Vec Row Data)
/// Select a page of rows from a given Table.
pub fn select(
&self,
table: &Table,
limit: usize,
offset: usize,
) -> Result<(Vec<String>, Vec<Vec<String>>), rusqlite::Error> {
let sql = format!("SELECT * FROM {};", table.name);
let sql = format!(
"SELECT * FROM {} LIMIT {} OFFSET {};",
table.name, limit, offset
);
if let Some(db) = &self.current_db {
let con = Connection::open(&db.path)?;
let mut stmt = con.prepare(&sql)?;
let num_cols = stmt.column_names().len();
let rows: Vec<_> = stmt
.query_map([], |row| map_row(num_cols, row))?
.collect::<Result<_, _>>()?;
let cols = stmt.column_names().iter().map(|s| s.to_string()).collect();
return Ok((cols, rows));
}
Ok((Vec::new(), Vec::new()))
}

let num_of_columns = stmt.column_names().len();
let data: Vec<Vec<String>> = stmt
.query_map([], |row| map_row(num_of_columns, row))?
.map(|x| (x.unwrap_or_default()))
.collect();
return Ok((
stmt.column_names().iter().map(|x| x.to_string()).collect(),
data,
));
pub fn prepare_total_rows(&self, table: &Table) -> Result<usize, rusqlite::Error> {
let count_sql = format!("SELECT COUNT(*) FROM {};", table.name);

if let Some(db) = &self.current_db {
let total = Connection::open(&db.path)?.query_row(&count_sql, [], |r| r.get(0))?;
Ok(total)
} else {
Ok(0)
}
Ok((Vec::default(), Vec::default()))
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ use ratatui::{
};
use std::io;
use string_list::StringList;
use talbe_view::TableView;
use table_view::TableView;

pub mod colors;
pub mod file_menu;
pub mod help_view;
pub mod string_list;
pub mod talbe_view;
pub mod table_view;
pub mod utils;

const APP_NAME: &str = " JDbrowser ";
Expand Down
6 changes: 4 additions & 2 deletions src/ui/help_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const NAV_LIST_KEYS: [[&str; 2]; 3] = [
];

const TABLE_VIEW_TITLE: &str = " Table View ";
const TABLE_KEYS: [[&str; 2]; 8] = [
const TABLE_KEYS: [[&str; 2]; 10] = [
["View Schema - Browse Data", "SHIFT + h - l"],
["Page Up Half", "u"],
["Page Down Half", "d"],
Expand All @@ -31,6 +31,8 @@ const TABLE_KEYS: [[&str; 2]; 8] = [
["Move Cell Left", "h"],
["Move Cell Right", "l"],
["Yank Cell to Clipboard", "y"],
["Prev Page", "p"],
["Next Page", "n"],
];

const GENERAL_TITLE: &str = " General ";
Expand All @@ -48,7 +50,7 @@ pub fn draw_help_window(frame: &mut Frame, lay: Rect) {
frame.render_widget(background, lay);

let area = center(lay, Constraint::Length(60), Constraint::Length(60));
let split_area = Layout::vertical(Constraint::from_lengths([5, 5, 10, 4]))
let split_area = Layout::vertical(Constraint::from_lengths([5, 5, 12, 4]))
.margin(2)
.split(area);
let widths = Constraint::from_lengths([40, 14]);
Expand Down
129 changes: 104 additions & 25 deletions src/ui/talbe_view.rs → src/ui/table_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ratatui::{
},
Frame,
};
use sqlformat::{format, FormatOptions, Indent, QueryParams};
use strum::{Display, EnumIter, IntoEnumIterator};

#[derive(Clone, Copy, Default, Debug, Display, EnumIter)]
Expand Down Expand Up @@ -125,7 +126,10 @@ pub struct TableView {
pub data: (Vec<String>, Vec<Vec<String>>),
pub table_state: TableState,
table_scroll_height: u16,
clipboard: Clipboard,
clipboard: Option<Clipboard>,
page_size: usize,
offset: usize,
pub total_rows: Option<usize>,
}

impl Default for TableView {
Expand All @@ -138,7 +142,10 @@ impl Default for TableView {
data: (Vec::default(), Vec::default()),
table_state: TableState::default(),
table_scroll_height: 0,
clipboard: Clipboard::new().unwrap(),
clipboard: Clipboard::new().ok(),
page_size: 50,
offset: 0,
total_rows: None,
}
}
}
Expand Down Expand Up @@ -229,17 +236,68 @@ impl TableView {
let lay = Layout::vertical([Constraint::Fill(1)])
.margin(margin)
.split(r);
/*
let p = Paragraph::new(table.sql.trim())
.wrap(Wrap { trim: true })
.fg(TEXT_COLOR);
frame.render_widget(p, lay[0]);
*/

let raw_sql = table.sql.trim();

// build your options
let opts = FormatOptions {
indent: Indent::Spaces(4), // 4‑space indent
uppercase: false, // keep keywords lower‑case
lines_between_queries: 1, // default
};

// call the formatter (no Dialect parameter)
let formatted = format(raw_sql, &QueryParams::None, opts);

// then render `formatted` instead of `raw`
let p = Paragraph::new(formatted)
.wrap(Wrap { trim: false })
.fg(TEXT_COLOR);
frame.render_widget(p, lay[0]);
}
SelectedTableTab::Browse => {
let lay = Layout::vertical([Constraint::Fill(1), Constraint::Length(3)])
.margin(margin)
.split(r);
// new: table, then preview, then footer for page‑info
let lay = Layout::vertical([
Constraint::Fill(1), // table takes all leftover space
Constraint::Length(3), // preview box height
Constraint::Length(1), // exactly one row for page info
])
.margin(margin)
.split(r);

// draw the data table
self.draw_table(frame, lay[0], table.name.as_str());

// draw the preview inside a bordered box
self.draw_preview(frame, lay[1]);

// draw the page‑info *below* the preview
if let Some(total) = self.total_rows {
let page = (self.offset / self.page_size) + 1;
let last_page = ((total + self.page_size - 1) / self.page_size).max(1);
let start = self.offset + 1;
let end = (self.offset + self.page_size).min(total);
let info = format!(
"displaying records {start}-{end} of {total} (page {page}/{last_page})"
);

use ratatui::layout::Alignment;
use ratatui::widgets::Paragraph;

// render it centered/right‑aligned in that one‑row footer
frame.render_widget(
Paragraph::new(info)
.alignment(Alignment::Right)
.wrap(ratatui::widgets::Wrap { trim: true }),
lay[2],
);
}
}
}
}
Expand Down Expand Up @@ -332,6 +390,21 @@ impl TableView {
} else if key.code == KeyCode::Char('y') {
self.yank_cell()?;
return Ok(());
} else if key.code == KeyCode::Char('n') {
// next page: only if there’s more data
if let Some(total) = self.total_rows {
let next_off = self.offset + self.page_size;
if next_off < total {
self.offset = next_off;
}
}
} else if key.code == KeyCode::Char('p') {
// prev page: never go below zero
if self.offset >= self.page_size {
self.offset -= self.page_size;
} else {
self.offset = 0;
}
}
self.load_table_data(app, db)?;
}
Expand All @@ -342,36 +415,42 @@ impl TableView {
Ok(if let Some((x, y)) = self.table_state.selected_cell() {
if let Some(row) = self.data.1.get(x) {
if let Some(val) = row.get(y) {
self.clipboard.set_text(val)?;
if let Some(cb) = &mut self.clipboard {
if let Err(e) = cb.set_text(val) {
eprintln!("Clipboard warning: {}", e);
}
}
return Ok(());
}
}
})
}

fn load_table_data(&mut self, app: &App, db: &Db) -> Result<(), Box<dyn std::error::Error>> {
// always reset the cursor to top-left of the page
self.table_state.select_cell(Some((0, 0)));

if self.selected_table_tab as usize == SelectedTableTab::Browse as usize {
match self.table_nav_tab {
NavigationTab::Tables => {
if let Some(table) = db
.tables
.iter()
.find(|x| x.name == self.tables_list.get_selected().unwrap_or(""))
{
self.data = app.select(table)?;
}
}
NavigationTab::Views => {
if let Some(table) = db
.views
.iter()
.find(|x| x.name == self.view_list.get_selected().unwrap_or(""))
{
self.data = app.select(table)?;
}
}
// pick the currently selected Table or View
let maybe_table = match self.table_nav_tab {
NavigationTab::Tables => db
.tables
.iter()
.find(|t| t.name == self.tables_list.get_selected().unwrap_or("")),
NavigationTab::Views => db
.views
.iter()
.find(|v| v.name == self.view_list.get_selected().unwrap_or("")),
};

if let Some(table) = maybe_table {
// load just one page of data
let (cols, rows) = app.select(table, self.page_size, self.offset)?;
self.data = (cols, rows);

// now fetch and remember the grand total
self.total_rows = Some(app.prepare_total_rows(table)?);
}
}
Ok(())
}
Expand Down