use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct QueryResultTextExportData { #[serde(default)] pub title: Option, pub columns: Vec, pub rows: Vec>, } pub fn format_json(data: &QueryResultTextExportData) -> Result { let rows = data .rows .iter() .map(|row| { let mut object = Map::new(); for (index, column) in data.columns.iter().enumerate() { if let Some(value) = row.get(index) { object.insert(column.clone(), value.clone()); } } Value::Object(object) }) .collect::>(); serde_json::to_string_pretty(&rows).map_err(|err| err.to_string()) } pub fn format_markdown(data: &QueryResultTextExportData) -> String { let normalized_columns = data.columns.iter().map(|column| markdown_cell(column)).collect::>(); let normalized_rows = data .rows .iter() .map(|row| row.iter().map(|cell| markdown_cell(&display_cell(cell))).collect::>()) .collect::>(); let widths = normalized_columns .iter() .enumerate() .map(|(index, column)| { let row_width = normalized_rows .iter() .map(|row| row.get(index).map(|cell| cell.chars().count()).unwrap_or(0)) .max() .unwrap_or(0); column.chars().count().max(row_width).max(3) }) .collect::>(); let header = format!( "| {} |", normalized_columns .iter() .enumerate() .map(|(index, column)| pad(column, widths[index])) .collect::>() .join(" | ") ); let separator = format!("| {} |", widths.iter().map(|width| "-".repeat(*width)).collect::>().join(" | ")); let body = normalized_rows .iter() .map(|row| { format!( "| {} |", row.iter() .enumerate() .map(|(index, cell)| pad(cell, widths.get(index).copied().unwrap_or(3))) .collect::>() .join(" | ") ) }) .collect::>() .join("\n"); [header, separator, body].into_iter().filter(|part| !part.is_empty()).collect::>().join("\n") + "\n" } fn display_cell(value: &Value) -> String { match value { Value::Null => "NULL".to_string(), Value::Bool(value) => value.to_string(), Value::Number(value) => value.to_string(), Value::String(value) => value.clone(), other => other.to_string(), } } fn markdown_cell(value: &str) -> String { value.replace('|', "\\|").replace("\r\n", "
").replace('\n', "
") } fn pad(value: &str, width: usize) -> String { let current = value.chars().count(); if current >= width { return value.to_string(); } format!("{value}{}", " ".repeat(width - current)) } pub fn format_html(data: &QueryResultTextExportData) -> String { let now = chrono_local_now(); let heading = data.title.as_deref().unwrap_or("Query Result"); let row_count = data.rows.len(); let col_count = data.columns.len(); let mut html = String::with_capacity(4096 + col_count * 64 + row_count * col_count * 48); html.push_str("\n\n\n"); html.push_str(" \n"); html.push_str(" \n"); html.push_str(&format!(" {}\n", html_escape(heading))); html.push_str( r#"
"# ); // Header html.push_str("
\n"); html.push_str(&format!("

{}

\n", html_escape(heading))); html.push_str(&format!( "
{} rows · {} columns · {} · DBX
\n", row_count, col_count, html_escape(&now) )); html.push_str("
\n"); // Table card html.push_str("
\n"); html.push_str("
\n"); html.push_str(" \n \n \n"); for col in &data.columns { html.push_str(&format!(" \n", html_escape(col))); } html.push_str(" \n \n \n"); for row in &data.rows { html.push_str(" \n"); for cell in row { let (text, css_class) = html_cell_value(cell); if css_class.is_empty() { html.push_str(&format!(" \n", html_escape(&text))); } else { html.push_str(&format!(" \n", css_class, html_escape(&text))); } } html.push_str(" \n"); } html.push_str(" \n
{}
{}{}
\n
\n
\n"); html.push_str("
Exported by DBX
\n"); html.push_str("
\n\n\n"); html } fn html_escape(value: &str) -> String { let mut out = String::with_capacity(value.len()); for ch in value.chars() { match ch { '<' => out.push_str("<"), '>' => out.push_str(">"), '&' => out.push_str("&"), '"' => out.push_str("""), '\'' => out.push_str("'"), '\n' => out.push_str("
"), '\r' => {} _ => out.push(ch), } } out } fn html_cell_value(value: &Value) -> (String, &'static str) { match value { Value::Null => ("NULL".to_string(), "null"), Value::Bool(true) => ("true".to_string(), "boolean true"), Value::Bool(false) => ("false".to_string(), "boolean false"), Value::Number(n) => (n.to_string(), "number"), Value::String(s) => (s.clone(), ""), other => (other.to_string(), ""), } } fn chrono_local_now() -> String { chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string() } #[cfg(test)] mod tests { use serde_json::{json, Value}; use super::{format_html, format_json, format_markdown, QueryResultTextExportData}; #[test] fn formats_json_rows_as_objects() { let out = format_json(&QueryResultTextExportData { title: None, columns: vec!["id".to_string(), "name".to_string(), "active".to_string(), "note".to_string()], rows: vec![vec![json!(1), json!("Ada"), json!(true), Value::Null]], }) .unwrap(); assert_eq!( out, r#"[ { "id": 1, "name": "Ada", "active": true, "note": null } ]"# ); } #[test] fn formats_markdown_with_escaped_pipes_and_newlines() { let out = format_markdown(&QueryResultTextExportData { title: None, columns: vec!["id".to_string(), "payload|kind".to_string()], rows: vec![vec![json!(1), json!("a|b")], vec![json!(2), json!("line one\nline two")]], }); assert_eq!( out, [ "| id | payload\\|kind |", "| --- | -------------------- |", "| 1 | a\\|b |", "| 2 | line one
line two |", "", ] .join("\n") ); } #[test] fn formats_html_document_structure() { let out = format_html(&QueryResultTextExportData { title: None, columns: vec!["id".to_string(), "name".to_string()], rows: vec![vec![json!(1), json!("Ada")]], }); assert!(out.starts_with(""), "must start with doctype"); assert!(out.ends_with("\n"), "must end with closing html tag"); assert!(out.contains("")); assert!(out.contains("