Skip to content

Commit 8bb5379

Browse files
committed
simplify table array formatting logic
1 parent c6c2dfa commit 8bb5379

2 files changed

Lines changed: 21 additions & 15 deletions

File tree

src/query.rs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,19 @@ pub struct QueryResponse {
1313
pub warning: Option<String>,
1414
}
1515

16-
fn format_array(arr: &[Value]) -> String {
17-
if arr.len() > 6 {
18-
let head: Vec<String> = arr[..3].iter().map(|v| v.to_string()).collect();
19-
let tail: Vec<String> = arr[arr.len()-3..].iter().map(|v| v.to_string()).collect();
20-
format!("[{}, ..., {}] ({} items)", head.join(", "), tail.join(", "), arr.len())
21-
} else {
22-
format!("[{}]", arr.iter().map(|v| value_to_string(v)).collect::<Vec<_>>().join(", "))
23-
}
24-
}
25-
2616
fn value_to_string(v: &Value) -> String {
2717
match v {
2818
Value::Null => "NULL".to_string(),
2919
Value::Bool(b) => b.to_string(),
3020
Value::Number(n) => n.to_string(),
3121
Value::String(s) => s.clone(),
32-
Value::Array(arr) => format_array(arr),
22+
Value::Array(arr) => {
23+
let (formatted, count) = crate::table::truncate_array(arr);
24+
match count {
25+
Some(n) => format!("{formatted} ({n} items)"),
26+
None => formatted,
27+
}
28+
}
3329
Value::Object(_) => v.to_string(),
3430
}
3531
}

src/table.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,24 @@ use tabled::settings::{
66
};
77

88
/// Truncate arrays to first 3 + last 3 when over 6 elements.
9-
fn format_array(arr: &[serde_json::Value]) -> String {
10-
use crossterm::style::Stylize;
9+
/// Returns (formatted_values, total_count) where total_count is Some when truncated.
10+
pub fn truncate_array(arr: &[serde_json::Value]) -> (String, Option<usize>) {
1111
if arr.len() > 6 {
1212
let head: Vec<String> = arr[..3].iter().map(|v| v.to_string()).collect();
1313
let tail: Vec<String> = arr[arr.len()-3..].iter().map(|v| v.to_string()).collect();
14-
format!("[{}, ..., {}] {}", head.join(", "), tail.join(", "), format!("({} items)", arr.len()).dark_grey())
14+
(format!("[{}, ..., {}]", head.join(", "), tail.join(", ")), Some(arr.len()))
1515
} else {
16-
format!("[{}]", arr.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
16+
(format!("[{}]", arr.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", ")), None)
17+
}
18+
}
19+
20+
/// Format an array for styled table output.
21+
fn format_array(arr: &[serde_json::Value]) -> String {
22+
use crossterm::style::Stylize;
23+
let (formatted, count) = truncate_array(arr);
24+
match count {
25+
Some(n) => format!("{formatted} {}", format!("({n} items)").dark_grey()),
26+
None => formatted,
1727
}
1828
}
1929

0 commit comments

Comments
 (0)