1use std::fmt::Write;
2
3use crate::constants::DESCRIPTIONS;
4use crate::display::colors::{themed_format, Theme};
5use crate::display::format::{
6 duration_to_string_themed, format_details, format_percent, format_tags,
7};
8use crate::display::tree::{
9 styled_node_joint, styled_output_terminator, styled_prefix_continuation, TreeStyle,
10};
11use crate::structure::data::explain::Explain;
12use crate::structure::data::plan::Plan;
13use crate::summary::PlanSummary;
14
15#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
22pub enum RenderMode {
23 #[default]
24 Default,
25 Condensed,
26 Verbose,
27}
28
29impl RenderMode {
30 pub fn parse(name: &str) -> Option<RenderMode> {
31 match name {
32 "default" | "normal" => Some(RenderMode::Default),
33 "condensed" | "compact" => Some(RenderMode::Condensed),
34 "verbose" | "full" => Some(RenderMode::Verbose),
35 _ => None,
36 }
37 }
38}
39
40#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
47pub enum SummaryStyle {
48 #[default]
49 Compact,
50 Detailed,
51}
52
53impl SummaryStyle {
54 pub fn parse(name: &str) -> Option<SummaryStyle> {
55 match name {
56 "compact" | "minimal" => Some(SummaryStyle::Compact),
57 "detailed" | "full" => Some(SummaryStyle::Detailed),
58 _ => None,
59 }
60 }
61}
62
63#[derive(Debug, Clone, Copy)]
65pub struct RenderOptions {
66 pub width: usize,
67 pub theme: Theme,
68 pub mode: RenderMode,
69 pub summary: SummaryStyle,
70 pub tree_style: TreeStyle,
71}
72
73impl RenderOptions {
74 pub fn new(width: usize) -> Self {
75 Self {
76 width,
77 theme: Theme::default(),
78 mode: RenderMode::default(),
79 summary: SummaryStyle::default(),
80 tree_style: TreeStyle::default(),
81 }
82 }
83
84 pub fn with_theme(mut self, theme: Theme) -> Self {
85 self.theme = theme;
86 self
87 }
88
89 pub fn with_mode(mut self, mode: RenderMode) -> Self {
90 self.mode = mode;
91 self
92 }
93
94 pub fn with_summary(mut self, summary: SummaryStyle) -> Self {
95 self.summary = summary;
96 self
97 }
98
99 pub fn with_tree_style(mut self, tree_style: TreeStyle) -> Self {
100 self.tree_style = tree_style;
101 self
102 }
103}
104
105impl Default for RenderOptions {
106 fn default() -> Self {
107 Self::new(60)
108 }
109}
110
111struct RenderContext<'a> {
115 buffer: &'a mut String,
116 explain: &'a Explain,
117 options: RenderOptions,
118}
119
120impl RenderContext<'_> {
121 fn paint<S: AsRef<str>>(&self, text: S, role: &str) -> colored::ColoredString {
122 themed_format(text, role, self.options.theme)
123 }
124}
125
126struct NodePosition {
128 prefix: String,
129 last_child: bool,
130}
131
132fn write_summary_block(buffer: &mut String, summary: &PlanSummary, options: RenderOptions) {
133 let theme = options.theme;
134 writeln!(buffer, "○ Total Cost {}", summary.total_cost).expect("write to string");
135 writeln!(
136 buffer,
137 "○ Planning Time: {}",
138 duration_to_string_themed(summary.planning_time, theme)
139 )
140 .expect("write to string");
141 writeln!(
142 buffer,
143 "○ Execution Time: {}",
144 duration_to_string_themed(summary.execution_time, theme)
145 )
146 .expect("write to string");
147
148 let detailed = options.summary == SummaryStyle::Detailed || options.mode == RenderMode::Verbose;
149 if !detailed {
150 return;
151 }
152
153 writeln!(buffer, "○ Total Loops: {}", summary.total_loops).expect("write to string");
154 writeln!(buffer, "○ Total Nodes: {}", summary.node_count).expect("write to string");
155
156 let buffers = &summary.buffers;
157 if !buffers.is_empty() {
158 writeln!(
159 buffer,
160 "○ Buffers: shared hit={} read={} written={} dirtied={}",
161 buffers.shared_hit_blocks,
162 buffers.shared_read_blocks,
163 buffers.shared_written_blocks,
164 buffers.shared_dirtied_blocks,
165 )
166 .expect("write to string");
167 if buffers.local_hit_blocks
168 + buffers.local_read_blocks
169 + buffers.local_written_blocks
170 + buffers.local_dirtied_blocks
171 > 0
172 {
173 writeln!(
174 buffer,
175 "○ Buffers: local hit={} read={} written={} dirtied={}",
176 buffers.local_hit_blocks,
177 buffers.local_read_blocks,
178 buffers.local_written_blocks,
179 buffers.local_dirtied_blocks,
180 )
181 .expect("write to string");
182 }
183 if buffers.temp_read_blocks + buffers.temp_written_blocks > 0 {
184 writeln!(
185 buffer,
186 "○ Buffers: temp read={} written={}",
187 buffers.temp_read_blocks, buffers.temp_written_blocks,
188 )
189 .expect("write to string");
190 }
191 }
192
193 if summary.total_io_read_time > 0.0 || summary.total_io_write_time > 0.0 {
194 writeln!(
195 buffer,
196 "○ I/O Time: read={} write={}",
197 duration_to_string_themed(summary.total_io_read_time, theme),
198 duration_to_string_themed(summary.total_io_write_time, theme),
199 )
200 .expect("write to string");
201 }
202}
203
204pub fn render_explain(explain: &Explain, options: RenderOptions) -> String {
206 let mut buffer = String::new();
207 let theme = options.theme;
208 let summary = PlanSummary::from_explain(explain);
209 write_summary_block(&mut buffer, &summary, options);
210 writeln!(
211 &mut buffer,
212 "{}",
213 themed_format(options.tree_style.root_marker, "output", theme)
214 )
215 .expect("write to string");
216 let mut ctx = RenderContext {
217 buffer: &mut buffer,
218 explain,
219 options,
220 };
221 let last_child = explain.plan.plans.len() == 1;
222 write_plan(
223 &mut ctx,
224 &explain.plan,
225 NodePosition {
226 prefix: String::new(),
227 last_child,
228 },
229 );
230 buffer
231}
232
233fn write_plan(ctx: &mut RenderContext<'_>, plan: &Plan, position: NodePosition) {
234 let explain = ctx.explain;
235 let width = ctx.options.width;
236 let mode = ctx.options.mode;
237 let style = ctx.options.tree_style;
238 let NodePosition { prefix, last_child } = position;
239 let mut source_prefix = prefix;
240
241 writeln!(
242 ctx.buffer,
243 "{}{}",
244 ctx.paint(&source_prefix, "prefix"),
245 ctx.paint(style.vertical, "prefix")
246 )
247 .expect("write to string");
248
249 let joint = styled_node_joint(&style, plan.plans.len(), last_child);
250
251 writeln!(
252 ctx.buffer,
253 "{}{} {}{} {}",
254 ctx.paint(&source_prefix, "prefix"),
255 ctx.paint(format!("{joint}{}", style.node_connector), "prefix"),
256 ctx.paint(&plan.identity.node_type, "bold"),
257 ctx.paint(format_details(plan), "muted"),
258 ctx.paint(format_tags(plan), "tag")
259 )
260 .expect("write to string");
261
262 let continuation = styled_prefix_continuation(&style, plan.plans.len(), last_child);
263 if continuation == style.vertical {
264 source_prefix.push_str(style.vertical);
265 source_prefix.push_str(style.vertical_pad);
266 } else {
267 source_prefix.push_str(continuation);
268 }
269
270 let mut current_prefix = String::with_capacity(source_prefix.len() + 4);
271 current_prefix.push_str(&source_prefix);
272 current_prefix.push_str(style.vertical);
273 current_prefix.push_str(style.vertical_pad);
274 let cols = width.saturating_sub(current_prefix.len());
275
276 if mode != RenderMode::Condensed {
277 for line in textwrap::fill(DESCRIPTIONS[plan.identity.node_type.as_str()], cols).split('\n')
278 {
279 writeln!(
280 ctx.buffer,
281 "{}{}",
282 ctx.paint(¤t_prefix, "prefix"),
283 ctx.paint(line, "muted")
284 )
285 .expect("write to string");
286 }
287 }
288
289 writeln!(
290 ctx.buffer,
291 "{}○ Duration: {} {}",
292 ctx.paint(¤t_prefix, "prefix"),
293 duration_to_string_themed(plan.actuals.actual_duration, ctx.options.theme),
294 format_percent(
295 (plan.actuals.actual_duration / explain.execution_time) * 100.0,
296 1
297 )
298 )
299 .expect("write to string");
300 writeln!(
301 ctx.buffer,
302 "{}○ Cost: {} {}",
303 ctx.paint(¤t_prefix, "prefix"),
304 duration_to_string_themed(plan.actuals.actual_cost, ctx.options.theme),
305 format_percent((plan.actuals.actual_cost / explain.total_cost) * 100.0, 1)
306 )
307 .expect("write to string");
308 writeln!(
309 ctx.buffer,
310 "{}○ Rows: {}",
311 ctx.paint(¤t_prefix, "prefix"),
312 plan.actuals.actual_rows
313 )
314 .expect("write to string");
315
316 if mode == RenderMode::Verbose {
317 writeln!(
318 ctx.buffer,
319 "{}○ Loops: {}",
320 ctx.paint(¤t_prefix, "prefix"),
321 plan.actuals.actual_loops
322 )
323 .expect("write to string");
324 let buffers = &plan.buffers;
325 let buffer_total = buffers.shared_hit_blocks
326 + buffers.shared_read_blocks
327 + buffers.shared_written_blocks
328 + buffers.shared_dirtied_blocks
329 + buffers.local_hit_blocks
330 + buffers.local_read_blocks
331 + buffers.local_written_blocks
332 + buffers.local_dirtied_blocks
333 + buffers.temp_read_blocks
334 + buffers.temp_written_blocks;
335 if buffer_total > 0 {
336 writeln!(
337 ctx.buffer,
338 "{}○ Buffers: shared hit={} read={} written={} dirtied={}",
339 ctx.paint(¤t_prefix, "prefix"),
340 buffers.shared_hit_blocks,
341 buffers.shared_read_blocks,
342 buffers.shared_written_blocks,
343 buffers.shared_dirtied_blocks,
344 )
345 .expect("write to string");
346 }
347 if plan.io_timing.io_read_time > 0.0 || plan.io_timing.io_write_time > 0.0 {
348 writeln!(
349 ctx.buffer,
350 "{}○ I/O: read={} write={}",
351 ctx.paint(¤t_prefix, "prefix"),
352 duration_to_string_themed(plan.io_timing.io_read_time, ctx.options.theme),
353 duration_to_string_themed(plan.io_timing.io_write_time, ctx.options.theme),
354 )
355 .expect("write to string");
356 }
357 }
358
359 current_prefix.push_str(" ");
360
361 if !plan.identity.join_type.is_empty() {
362 writeln!(
363 ctx.buffer,
364 "{}{} {}",
365 ctx.paint(¤t_prefix, "prefix"),
366 ctx.paint("join", "muted"),
367 ctx.paint(&plan.identity.join_type, "muted")
368 )
369 .expect("write to string");
370 }
371
372 if !plan.identity.relation_name.is_empty() {
373 writeln!(
374 ctx.buffer,
375 "{}{} {} {}",
376 ctx.paint(¤t_prefix, "prefix"),
377 ctx.paint("on", "muted"),
378 ctx.paint(&plan.identity.schema, "muted"),
379 ctx.paint(&plan.identity.relation_name, "muted")
380 )
381 .expect("write to string");
382 }
383
384 if !plan.identity.index_name.is_empty() {
385 writeln!(
386 ctx.buffer,
387 "{}{} {}",
388 ctx.paint(¤t_prefix, "prefix"),
389 ctx.paint("using", "muted"),
390 plan.identity.index_name
391 )
392 .expect("write to string");
393 }
394
395 if !plan.predicates.index_condition.is_empty() {
396 writeln!(
397 ctx.buffer,
398 "{}{} {}",
399 ctx.paint(¤t_prefix, "prefix"),
400 ctx.paint("condition", "muted"),
401 plan.predicates.index_condition
402 )
403 .expect("write to string");
404 }
405
406 if !plan.predicates.filter.is_empty() {
407 writeln!(
408 ctx.buffer,
409 "{}{} {} [-{} rows]",
410 ctx.paint(¤t_prefix, "prefix"),
411 ctx.paint("filter", "muted"),
412 plan.predicates.filter,
413 ctx.paint(plan.predicates.rows_removed_by_filter.to_string(), "muted")
414 )
415 .expect("write to string");
416 }
417
418 if !plan.predicates.hash_condition.is_empty() {
419 writeln!(
420 ctx.buffer,
421 "{}{} {}",
422 ctx.paint(¤t_prefix, "prefix"),
423 ctx.paint("on", "muted"),
424 plan.predicates.hash_condition
425 )
426 .expect("write to string");
427 }
428
429 if !plan.identity.cte_name.is_empty() {
430 writeln!(
431 ctx.buffer,
432 "{}CTE {}",
433 ctx.paint(¤t_prefix, "prefix"),
434 plan.identity.cte_name
435 )
436 .expect("write to string");
437 }
438
439 if plan.analysis_flags.planner_row_estimate_factor != 0.0 {
440 writeln!(
441 ctx.buffer,
442 "{}{} {}estimated {} {:.2}x",
443 ctx.paint(¤t_prefix, "prefix"),
444 ctx.paint("rows", "muted"),
445 plan.analysis_flags.planner_row_estimate_direction,
446 ctx.paint("by", "muted"),
447 plan.analysis_flags.planner_row_estimate_factor
448 )
449 .expect("write to string");
450 }
451
452 if mode != RenderMode::Condensed && !plan.predicates.output.is_empty() {
453 let joined_output = plan.predicates.output.join(" + ");
454 let wrapped_output = textwrap::fill(&joined_output, cols);
455 for (index, line) in wrapped_output.split('\n').enumerate() {
456 writeln!(
457 ctx.buffer,
458 "{}{}{}",
459 ctx.paint(&source_prefix, "prefix"),
460 ctx.paint(styled_output_terminator(&style, index, plan), "output"),
461 ctx.paint(line, "output")
462 )
463 .expect("write to string");
464 }
465 }
466
467 let last_index = plan.plans.len().saturating_sub(1);
468 let child_count = plan.plans.len();
469 for (index, child_plan) in plan.plans.iter().enumerate() {
470 let prefix = if index == child_count - 1 {
471 std::mem::take(&mut source_prefix)
472 } else {
473 source_prefix.clone()
474 };
475 write_plan(
476 ctx,
477 child_plan,
478 NodePosition {
479 prefix,
480 last_child: index == last_index,
481 },
482 );
483 }
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use crate::structure::data::actuals::PlanActuals;
490 use crate::structure::data::buffers::PlanBuffers;
491 use crate::structure::data::estimates::PlanEstimates;
492
493 fn child_plan(node_type: &str) -> Plan {
494 let mut plan = Plan::default();
495 plan.identity.node_type = node_type.to_string();
496 plan.actuals = PlanActuals {
497 actual_total_time: 1.0,
498 actual_duration: 1.0,
499 actual_rows: 5,
500 actual_loops: 1,
501 ..PlanActuals::default()
502 };
503 plan.estimates = PlanEstimates {
504 total_cost: 1.0,
505 ..PlanEstimates::default()
506 };
507 plan
508 }
509
510 fn sample_explain() -> Explain {
511 let mut root = child_plan("Hash Join");
512 root.plans.push(child_plan("Seq Scan"));
513 root.plans.push(child_plan("Index Scan"));
514 Explain {
515 execution_time: 5.0,
516 total_cost: 4.0,
517 plan: root,
518 ..Explain::default()
519 }
520 }
521
522 #[test]
523 fn render_context_threads_explain_and_options_into_recursion() {
524 let explain = sample_explain();
525
526 let rendered = render_explain(&explain, RenderOptions::new(80));
527
528 assert!(rendered.contains("Hash Join"));
529 assert!(rendered.contains("Seq Scan"));
530 assert!(rendered.contains("Index Scan"));
531 assert!(rendered.contains("○ Total Cost"));
532 }
533
534 #[test]
535 fn render_mode_parse_accepts_aliases() {
536 assert_eq!(RenderMode::parse("default"), Some(RenderMode::Default));
537 assert_eq!(RenderMode::parse("normal"), Some(RenderMode::Default));
538 assert_eq!(RenderMode::parse("condensed"), Some(RenderMode::Condensed));
539 assert_eq!(RenderMode::parse("compact"), Some(RenderMode::Condensed));
540 assert_eq!(RenderMode::parse("verbose"), Some(RenderMode::Verbose));
541 assert_eq!(RenderMode::parse("full"), Some(RenderMode::Verbose));
542 assert_eq!(RenderMode::parse("loud"), None);
543 }
544
545 #[test]
546 fn condensed_mode_omits_per_node_descriptions() {
547 let explain = sample_explain();
548
549 let default = render_explain(&explain, RenderOptions::new(80));
550 let condensed = render_explain(
551 &explain,
552 RenderOptions::new(80).with_mode(RenderMode::Condensed),
553 );
554
555 assert!(default.contains("Joins to record sets"));
556 assert!(!condensed.contains("Joins to record sets"));
557 }
558
559 #[test]
560 fn verbose_mode_includes_loops_and_buffers() {
561 let mut explain = sample_explain();
562 explain.plan.buffers = PlanBuffers {
563 shared_hit_blocks: 4,
564 shared_read_blocks: 2,
565 ..PlanBuffers::default()
566 };
567
568 let default = render_explain(&explain, RenderOptions::new(80));
569 let verbose = render_explain(
570 &explain,
571 RenderOptions::new(80).with_mode(RenderMode::Verbose),
572 );
573
574 assert!(!default.contains("○ Loops:"));
575 assert!(!default.contains("○ Buffers:"));
576 assert!(verbose.contains("○ Loops:"));
577 assert!(verbose.contains("○ Buffers:"));
578 assert!(verbose.contains("hit=4"));
579 }
580
581 #[test]
582 fn no_color_theme_strips_ansi_escapes() {
583 let explain = sample_explain();
584 let options = RenderOptions::new(80).with_theme(Theme::NoColor);
585
586 let rendered = render_explain(&explain, options);
587
588 assert!(!rendered.contains("\u{1b}["));
589 assert!(rendered.contains("Hash Join"));
590 }
591
592 #[test]
593 fn compact_summary_keeps_three_line_header() {
594 let explain = sample_explain();
595 let rendered = render_explain(&explain, RenderOptions::new(80).with_theme(Theme::NoColor));
596 assert!(rendered.contains("○ Total Cost"));
597 assert!(rendered.contains("○ Planning Time"));
598 assert!(rendered.contains("○ Execution Time"));
599 assert!(!rendered.contains("○ Total Loops"));
600 assert!(!rendered.contains("○ Total Nodes"));
601 }
602
603 #[test]
604 fn detailed_summary_emits_loops_nodes_buffers_and_io() {
605 let mut explain = sample_explain();
606 explain.plan.buffers = PlanBuffers {
607 shared_hit_blocks: 11,
608 shared_read_blocks: 2,
609 ..PlanBuffers::default()
610 };
611 explain.plan.io_timing.io_read_time = 0.5;
612 let options = RenderOptions::new(80)
613 .with_theme(Theme::NoColor)
614 .with_summary(SummaryStyle::Detailed);
615
616 let rendered = render_explain(&explain, options);
617
618 assert!(rendered.contains("○ Total Loops:"));
619 assert!(rendered.contains("○ Total Nodes: 3"));
620 assert!(rendered.contains("○ Buffers: shared hit=11"));
621 assert!(rendered.contains("○ I/O Time:"));
622 }
623
624 #[test]
625 fn verbose_render_mode_implies_detailed_summary() {
626 let mut explain = sample_explain();
627 explain.plan.buffers.shared_hit_blocks = 1;
628 let options = RenderOptions::new(80)
629 .with_theme(Theme::NoColor)
630 .with_mode(RenderMode::Verbose);
631
632 let rendered = render_explain(&explain, options);
633
634 assert!(rendered.contains("○ Total Loops:"));
635 assert!(rendered.contains("○ Total Nodes:"));
636 }
637
638 #[test]
639 fn summary_style_parse_accepts_aliases() {
640 assert_eq!(SummaryStyle::parse("compact"), Some(SummaryStyle::Compact));
641 assert_eq!(SummaryStyle::parse("minimal"), Some(SummaryStyle::Compact));
642 assert_eq!(
643 SummaryStyle::parse("detailed"),
644 Some(SummaryStyle::Detailed)
645 );
646 assert_eq!(SummaryStyle::parse("full"), Some(SummaryStyle::Detailed));
647 assert_eq!(SummaryStyle::parse("crazy"), None);
648 }
649
650 #[test]
651 fn ascii_tree_style_renders_pure_ascii_tree_glyphs() {
652 let explain = sample_explain();
653 let options = RenderOptions::new(80)
654 .with_theme(Theme::NoColor)
655 .with_tree_style(TreeStyle::ascii());
656
657 let rendered = render_explain(&explain, options);
658
659 assert!(!rendered.contains('│'));
660 assert!(!rendered.contains('└'));
661 assert!(!rendered.contains('├'));
662 assert!(rendered.contains('|'));
663 assert!(rendered.contains("+--"));
664 assert!(rendered.contains("Hash Join"));
665 }
666
667 #[test]
668 fn heavy_tree_style_uses_heavy_glyphs() {
669 let explain = sample_explain();
670 let options = RenderOptions::new(80)
671 .with_theme(Theme::NoColor)
672 .with_tree_style(TreeStyle::heavy());
673
674 let rendered = render_explain(&explain, options);
675
676 assert!(rendered.contains('┃'));
677 assert!(rendered.contains('┗') || rendered.contains('┣'));
678 assert!(rendered.contains("Hash Join"));
679 }
680
681 #[test]
682 fn unicode_tree_style_remains_default() {
683 let explain = sample_explain();
684 let default = render_explain(&explain, RenderOptions::new(80).with_theme(Theme::NoColor));
685 let unicode = render_explain(
686 &explain,
687 RenderOptions::new(80)
688 .with_theme(Theme::NoColor)
689 .with_tree_style(TreeStyle::unicode()),
690 );
691 assert_eq!(default, unicode);
692 }
693}