1use crate::col::Column;
6use crate::meta::{MetaBuildStats, MetaQueryResults, MetaQueryStats, MetaStore};
7use crate::type_utils::DataType;
8use chrono::DateTime;
9use std::fmt;
10
11pub struct AsciiTable {
13 headers: Vec<String>,
14 rows: Vec<Vec<String>>,
15 title: Option<String>,
16}
17
18impl AsciiTable {
19 pub fn new(headers: Vec<String>, rows: Vec<Vec<String>>) -> Self {
20 Self {
21 headers,
22 rows,
23 title: None,
24 }
25 }
26
27 pub fn with_title(mut self, title: String) -> Self {
28 self.title = Some(title);
29 self
30 }
31
32 pub fn render(&self) -> String {
33 if self.headers.is_empty() {
34 return String::new();
35 }
36
37 let cols = self.headers.len();
38 let mut widths: Vec<usize> = vec![0; cols];
39
40 for (i, h) in self.headers.iter().enumerate() {
41 widths[i] = widths[i].max(h.len());
42 }
43 for row in &self.rows {
44 for (i, cell) in row.iter().enumerate().take(cols) {
45 widths[i] = widths[i].max(cell.len());
46 }
47 }
48
49 let sep = {
50 let mut s = String::from("+");
51 for w in &widths {
52 s.push_str(&"-".repeat(*w + 2));
53 s.push('+');
54 }
55 s
56 };
57
58 let mut out = String::new();
59 if let Some(t) = &self.title {
60 out.push_str(t);
61 out.push('\n');
62 }
63 out.push_str(&sep);
64 out.push('\n');
65
66 out.push('|');
68 for (i, h) in self.headers.iter().enumerate() {
69 out.push(' ');
70 out.push_str(h);
71 out.push_str(&" ".repeat(widths[i] - h.len() + 1));
72 out.push('|');
73 }
74 out.push('\n');
75 out.push_str(&sep);
76 out.push('\n');
77
78 for row in &self.rows {
80 out.push('|');
81 for (i, _) in widths.iter().enumerate().take(cols) {
82 let cell = row.get(i).map(|s| s.as_str()).unwrap_or("");
83 out.push(' ');
84 out.push_str(cell);
85 out.push_str(&" ".repeat(widths[i] - cell.len() + 1));
86 out.push('|');
87 }
88 out.push('\n');
89 }
90 out.push_str(&sep);
91 out
92 }
93}
94
95impl fmt::Display for AsciiTable {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 write!(f, "{}", self.render())
98 }
99}
100
101fn format_cell(col: &Column, i: usize) -> String {
103 let is_null = col.null_mask().get(i).map(|b| *b).unwrap_or(false);
104 if is_null {
105 return "NULL".to_string();
106 }
107
108 match col.dtype() {
109 DataType::Int32 => col.i32_values().map(|v| v[i].to_string()).unwrap(),
110 DataType::Int64 => col.i64_values().map(|v| v[i].to_string()).unwrap(),
111 DataType::Float32 => col.f32_values().map(|v| format!("{:.4}", v[i])).unwrap(),
112 DataType::Float64 => col.f64_values().map(|v| format!("{:.4}", v[i])).unwrap(),
113 DataType::String => col.string_values().map(|v| v[i].clone()).unwrap(),
114 DataType::DateTime => col
115 .datetime_values()
116 .map(|v| {
117 DateTime::from_timestamp_millis(v[i])
118 .map(|dt| dt.format("%Y-%m-%d %H:%M:%S UTC").to_string())
119 .unwrap_or_else(|| format!("{}", v[i]))
120 })
121 .unwrap(),
122 }
123}
124
125pub fn metastore_head(meta: &MetaStore, n: usize) -> String {
127 let mut cols: Vec<String> = meta.schema().keys().cloned().collect();
128 cols.sort();
129
130 let total_rows = meta.columns().values().next().map(|c| c.len()).unwrap_or(0);
132 let limit = total_rows.min(n);
133
134 let mut headers: Vec<String> = Vec::with_capacity(cols.len() + 1);
136 headers.push("index".to_string());
137 headers.extend(cols.iter().cloned());
138
139 let mut rows: Vec<Vec<String>> = Vec::with_capacity(limit);
141 for i in 0..limit {
142 let mut row: Vec<String> = Vec::with_capacity(headers.len());
143 row.push(i.to_string());
144 for name in &cols {
145 if let Some(col) = meta.columns().get(name) {
146 row.push(format_cell(col, i));
147 } else {
148 row.push(String::new());
149 }
150 }
151 rows.push(row);
152 }
153
154 AsciiTable::new(headers, rows)
155 .with_title(format!(
156 "MetaStore • rows={} • chunks={} • chunk_size={}",
157 total_rows,
158 meta.n_chunks(),
159 meta.chunk_size()
160 ))
161 .render()
162}
163
164impl fmt::Display for MetaQueryResults {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 let mut headers = vec!["index".to_string(), "score".to_string()];
167 headers.extend(self.columns.iter().cloned());
168
169 let mut rows: Vec<Vec<String>> = Vec::with_capacity(self.len());
170 for i in 0..self.len() {
171 let mut line = vec![
172 self.indices[i].to_string(),
173 format!("{:.6}", self.scores[i]),
174 ];
175 for c in &self.columns {
176 if let Some(col) = self.data.get(c) {
177 line.push(format_cell(col, i));
178 } else {
179 line.push(String::new());
180 }
181 }
182 rows.push(line);
183 }
184
185 let table = AsciiTable::new(headers, rows).render();
186 write!(f, "{table}")
187 }
188}
189
190impl fmt::Debug for MetaQueryResults {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 write!(f, "{self}")
193 }
194}
195
196pub fn format_build_stats(b: &MetaBuildStats) -> String {
198 let headers = vec!["metric".to_string(), "value".to_string()];
199 let rows = vec![
200 vec!["rows".into(), b.n_rows.to_string()],
201 vec!["dimensions".into(), b.dim.to_string()],
202 vec!["chunks".into(), b.n_chunks.to_string()],
203 vec![
204 "vector_ingest_ms".into(),
205 format!("{:.3}", b.vectors_ingest_duration.as_secs_f64() * 1000.0),
206 ],
207 vec![
208 "zonemap_build_ms".into(),
209 format!("{:.3}", b.zonemap_build_duration.as_secs_f64() * 1000.0),
210 ],
211 vec![
212 "build_total_ms".into(),
213 format!("{:.3}", b.build_total_duration.as_secs_f64() * 1000.0),
214 ],
215 ];
216 AsciiTable::new(headers, rows)
217 .with_title("MetaStore Build Stats".to_string())
218 .to_string()
219}
220
221pub fn format_query_stats(s: &MetaQueryStats) -> String {
223 let headers = vec!["metric".to_string(), "value".to_string()];
224 let rows = vec![
225 vec!["total_chunks".into(), s.total_chunks.to_string()],
226 vec!["pruned_chunks".into(), s.pruned_chunks.to_string()],
227 vec!["evaluated_chunks".into(), s.evaluated_chunks.to_string()],
228 vec!["vectors_compared".into(), s.vectors_compared.to_string()],
229 vec![
230 "prune_ms".into(),
231 format!("{:.3}", s.prune_duration.as_secs_f64() * 1000.0),
232 ],
233 vec![
234 "score_ms".into(),
235 format!("{:.3}", s.score_duration.as_secs_f64() * 1000.0),
236 ],
237 vec![
238 "merge_ms".into(),
239 format!("{:.3}", s.merge_duration.as_secs_f64() * 1000.0),
240 ],
241 vec![
242 "total_ms".into(),
243 format!("{:.3}", s.total_duration.as_secs_f64() * 1000.0),
244 ],
245 ];
246 AsciiTable::new(headers, rows)
247 .with_title("Last Meta Query Stats".to_string())
248 .to_string()
249}