sql_splitter/render/row_batch.rs
1//! A reusable row buffer for multi-tenant SQL generation.
2//!
3//! `RowBatch` replaces a `Vec<String>` of formatted rows with a single
4//! [`String`] that is cleared and reused across batches, so a long-running
5//! generation only pays for its buffer's allocation once instead of once per
6//! flush.
7
8use std::fmt::{self, Write};
9
10/// Upper bound on the bytes reserved per row when sizing a batch's initial
11/// buffer. `estimated_bytes` may be derived from column-width metadata that a
12/// hostile or malformed schema could inflate; capping it relative to
13/// `batch_size` keeps a single `RowBatch::with_capacity` call from becoming
14/// an attacker-controlled allocation.
15const MAX_BYTES_PER_ROW_HINT: usize = 8 * 1024;
16
17/// A reusable buffer of formatted SQL row tuples, joined by `,\n`.
18pub struct RowBatch {
19 buf: String,
20 rows: usize,
21}
22
23impl RowBatch {
24 /// Create an empty batch sized for roughly `batch_size` rows, reserving
25 /// up to `estimated_bytes` for the initial buffer. The reservation is
26 /// capped at `batch_size * MAX_BYTES_PER_ROW_HINT` so a caller-supplied
27 /// estimate can't force an outsized single allocation; the buffer still
28 /// grows normally afterwards if rows exceed the estimate.
29 pub fn with_capacity(batch_size: usize, estimated_bytes: usize) -> Self {
30 let cap = estimated_bytes.min(batch_size.saturating_mul(MAX_BYTES_PER_ROW_HINT));
31 Self {
32 buf: String::with_capacity(cap),
33 rows: 0,
34 }
35 }
36
37 /// Append a formatted row, prefixing it with `,\n` unless it is the
38 /// first row in the batch.
39 ///
40 /// Writing to a `String` is infallible, but the signature mirrors
41 /// [`std::fmt::Write::write_fmt`] so callers can propagate the error with
42 /// `?` rather than reach for `unwrap`.
43 pub fn push_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
44 if self.rows > 0 {
45 self.buf.write_str(",\n")?;
46 }
47 self.buf.write_fmt(args)?;
48 self.rows += 1;
49 Ok(())
50 }
51
52 /// The batch's buffered rows, joined by `,\n`.
53 pub fn as_str(&self) -> &str {
54 &self.buf
55 }
56
57 /// How many rows have been pushed since the last [`RowBatch::clear`].
58 pub fn row_count(&self) -> usize {
59 self.rows
60 }
61
62 /// Whether any rows have been pushed since the last clear.
63 pub fn is_empty(&self) -> bool {
64 self.rows == 0
65 }
66
67 /// The buffer's current capacity in bytes.
68 pub fn capacity(&self) -> usize {
69 self.buf.capacity()
70 }
71
72 /// Reset the batch to empty without shrinking its buffer, so the next
73 /// batch reuses the same allocation.
74 pub fn clear(&mut self) {
75 self.buf.clear();
76 self.rows = 0;
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn row_batch_reuses_capacity_after_clear() {
86 let mut batch = RowBatch::with_capacity(4, 256);
87 batch.push_fmt(format_args!("(1, 'a')")).unwrap();
88 batch.push_fmt(format_args!("(2, 'b')")).unwrap();
89 let capacity = batch.capacity();
90 assert_eq!(batch.as_str(), "(1, 'a'),\n(2, 'b')");
91 assert_eq!(batch.row_count(), 2);
92 batch.clear();
93 assert!(batch.is_empty());
94 assert!(batch.capacity() >= capacity);
95 }
96
97 #[test]
98 fn with_capacity_caps_reservation_relative_to_batch_size() {
99 // A tiny batch_size must not honor a wildly inflated byte estimate;
100 // the reservation is capped well below the requested estimate.
101 let batch = RowBatch::with_capacity(1, usize::MAX / 2);
102 assert!(batch.capacity() < usize::MAX / 4);
103 }
104}