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#[derive(Debug, thiserror::Error)]
9pub enum FormatterError {
10    /// JSON encoding of an event or payload failed.
11    #[error(transparent)]
12    Json(#[from] serde_json::Error),
13    /// The underlying writer failed.
14    #[error(transparent)]
15    Io(#[from] std::io::Error),
16}
17/// Formatter for one decoded event.
18///
19/// Formatters own their trailing newlines so that the bytes written are
20/// exactly the formatted output; the caller only selects the destination.
21pub trait Formatter {
22    /// Optional CSV header.
23    fn header(&self) -> Option<&'static str> {
24        None
25    }
26    /// Write the event; returns whether any output was produced.
27    fn format(&mut self, event: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError>;
28}
29/// One JSON value per event.
30pub struct JsonLinesFormatter;
31impl Formatter for JsonLinesFormatter {
32    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
33        // Serialize straight into the writer; no intermediate String per event.
34        serde_json::to_writer(&mut *out, e)?;
35        out.write_all(b"\n")?;
36        Ok(true)
37    }
38}
39/// Human-readable event summaries.
40pub struct TextFormatter;
41impl Formatter for TextFormatter {
42    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
43        write!(
44            out,
45            "{} {} server={} pos={} ",
46            e.timestamp,
47            e.event_type.as_str(),
48            e.server_id,
49            e.log_pos
50        )?;
51        serde_json::to_writer(&mut *out, &e.payload)?;
52        out.write_all(b"\n")?;
53        Ok(true)
54    }
55}
56/// One CSV record per decoded row image.
57pub struct CsvFormatter;
58fn quote(s: &str) -> String {
59    format!("\"{}\"", s.replace('"', "\"\""))
60}
61impl Formatter for CsvFormatter {
62    fn header(&self) -> Option<&'static str> {
63        Some("timestamp,event_type,database,table,before,after")
64    }
65    fn format(&mut self, e: &ParsedEvent, out: &mut dyn Write) -> Result<bool, FormatterError> {
66        if let EventPayload::Rows {
67            database,
68            table,
69            changes,
70            ..
71        } = &e.payload
72        {
73            for change in changes {
74                writeln!(
75                    out,
76                    "{},{},{},{},{},{}",
77                    e.timestamp,
78                    quote(e.event_type.as_str()),
79                    quote(database),
80                    quote(table),
81                    quote(&serde_json::to_string(&change.before)?),
82                    quote(&serde_json::to_string(&change.after)?)
83                )?;
84            }
85            Ok(!changes.is_empty())
86        } else {
87            Ok(false)
88        }
89    }
90}