Skip to main content

binlog_inspect/
formatter.rs

1// Copyright (c) 2026 houseme
2// SPDX-License-Identifier: Apache-2.0
3
4//! Output formatters that operate on the independent event model.
5use crate::event::{EventPayload, ParsedEvent};
6use std::io::Write;
7/// Failures while writing formatted events.
8///
9/// This enum is `#[non_exhaustive]` (R45): downstream matches require a
10/// wildcard arm, so new variants can be added without a semver-major
11/// release.
12#[derive(Debug, thiserror::Error)]
13#[non_exhaustive]
14pub enum FormatterError {
15    /// JSON encoding of an event or payload failed.
16    #[error(transparent)]
17    Json(#[from] serde_json::Error),
18    /// The underlying writer failed.
19    #[error(transparent)]
20    Io(#[from] std::io::Error),
21}
22/// Formatter for one decoded event.
23///
24/// Formatters own their trailing newlines so that the bytes written are
25/// exactly the formatted output; the caller only selects the destination.
26pub trait Formatter {
27    /// Optional CSV header.
28    fn header(&self) -> Option<&'static str> {
29        None
30    }
31    /// Write the event; returns whether any output was produced.
32    fn format(&mut self, event: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError>;
33}
34/// One JSON value per event.
35pub struct JsonLinesFormatter;
36impl Formatter for JsonLinesFormatter {
37    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
38        // Serialize straight into the writer; no intermediate String per event.
39        serde_json::to_writer(&mut *out, e)?;
40        out.write_all(b"\n")?;
41        Ok(true)
42    }
43}
44/// Human-readable event summaries.
45pub struct TextFormatter;
46impl Formatter for TextFormatter {
47    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
48        write!(
49            out,
50            "{} {} server={} pos={} ",
51            e.timestamp,
52            e.event_type.as_str(),
53            e.server_id,
54            e.log_pos
55        )?;
56        serde_json::to_writer(&mut *out, &e.payload)?;
57        out.write_all(b"\n")?;
58        Ok(true)
59    }
60}
61/// One CSV record per decoded row image.
62pub struct CsvFormatter;
63
64/// Reuse the escaped string for its enclosing quotes, avoiding a second
65/// formatted String allocation for each field.
66fn quote(text: &str) -> String {
67    let mut quoted = text.replace('"', "\"\"");
68    quoted.reserve(2);
69    quoted.insert(0, '"');
70    quoted.push('"');
71    quoted
72}
73impl Formatter for CsvFormatter {
74    fn header(&self) -> Option<&'static str> {
75        Some("timestamp,event_type,database,table,before,after")
76    }
77    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
78        if let EventPayload::Rows {
79            database,
80            table,
81            changes,
82            ..
83        } = &e.payload
84        {
85            let database = quote(database);
86            let table = quote(table);
87            for change in changes {
88                // EventType's fixed names never contain CSV delimiters.
89                writeln!(
90                    out,
91                    "{},\"{}\",{},{},{},{}",
92                    e.timestamp,
93                    e.event_type.as_str(),
94                    database,
95                    table,
96                    quote(&serde_json::to_string(&change.before)?),
97                    quote(&serde_json::to_string(&change.after)?)
98                )?;
99            }
100            Ok(!changes.is_empty())
101        } else {
102            Ok(false)
103        }
104    }
105}