Skip to main content

sql_splitter/render/
sql.rs

1//! Streams a compiled generation run to dialect-correct SQL.
2//!
3//! [`SqlRenderer`] is a [`RowSink`]: [`crate::generate::GenerationEngine::run`]
4//! drives it one table at a time, and it writes DDL (unless `data_only`) plus
5//! batched `INSERT`/`COPY` statements (unless `schema_only`) straight to a
6//! [`BufWriter`], reusing one row buffer per active table so a long
7//! generation run never allocates a formatted string per cell or per row —
8//! every value is written through a [`std::fmt::Display`] wrapper straight
9//! into the destination buffer. See [`super::ddl`] for `CREATE TABLE`
10//! rendering.
11
12use std::fmt::{self, Write as _};
13use std::io::{self, BufWriter, Write};
14
15use crate::convert::{ConvertWarning, WarningCollector};
16use crate::generate::{GenerateError, GeneratedRow, GeneratedValue, PlannedTable, RowSink};
17use crate::parser::SqlDialect;
18use crate::synthetic::OutputMode;
19use crate::transform_common::quote_ident;
20
21use super::ddl;
22use super::row_batch::RowBatch;
23use super::sql_string::SqlString;
24
25/// Rendering knobs for [`SqlRenderer`], independent of the compiled
26/// [`crate::generate::GenerationPlan`] so a caller (the CLI, or a test) can
27/// render the same plan under several target dialects.
28#[derive(Debug, Clone, Copy)]
29pub struct RenderOptions {
30    /// The dialect to render SQL for.
31    pub dialect: SqlDialect,
32    /// The dialect the source schema's types/DDL were captured in, if known.
33    /// `None` when the model has no `source:` block (e.g. hand-authored).
34    pub source_dialect: Option<SqlDialect>,
35    /// Whether to render DDL, rows, or both.
36    pub mode: OutputMode,
37    /// Force multi-row `INSERT` for PostgreSQL instead of `COPY`.
38    pub no_copy: bool,
39    /// Rows per `INSERT`/`COPY` batch.
40    pub batch_size: usize,
41    /// Render MSSQL output in "production style": a `SET ANSI_NULLS ON;` +
42    /// `SET QUOTED_IDENTIFIER ON;` session header, `[dbo].[table]`-qualified
43    /// identifiers, a named `CONSTRAINT [PK_<table>] PRIMARY KEY CLUSTERED`
44    /// instead of an inline `PRIMARY KEY`, and an `ON [PRIMARY]` filegroup
45    /// clause on `CREATE TABLE`. No effect outside [`SqlDialect::Mssql`].
46    pub mssql_production_style: bool,
47    /// Emit a `GO` batch separator every N `INSERT` batches instead of after
48    /// every batch (MSSQL only; `None` keeps today's per-batch `GO`). `CREATE
49    /// TABLE` and `SET IDENTITY_INSERT` batches always get their own `GO`
50    /// regardless of this setting — only `INSERT` batch cadence changes.
51    pub mssql_go: Option<u64>,
52}
53
54impl Default for RenderOptions {
55    fn default() -> Self {
56        Self {
57            dialect: SqlDialect::MySql,
58            source_dialect: None,
59            mode: OutputMode::SchemaAndData,
60            no_copy: false,
61            batch_size: 1000,
62            mssql_production_style: false,
63            mssql_go: None,
64        }
65    }
66}
67
68/// Per-table render state, live between `begin_table` and `end_table`.
69struct TableState {
70    quoted_table: String,
71    /// Whether this run renders row data at all (`false` under `schema_only`).
72    data_enabled: bool,
73    /// Whether rows render as PostgreSQL `COPY` rather than `INSERT`.
74    use_copy: bool,
75    /// Rows per batch/statement.
76    batch_size: usize,
77    /// Column indices to render, in schema order, excluding every column
78    /// that renders `DEFAULT` for every row. `None` until the first row
79    /// (a `DEFAULT` column is a per-column, not per-row, decision - see
80    /// `SqlRenderer::classify_columns` - but the renderer only learns it by
81    /// inspecting the first generated row).
82    insert_columns: Option<Vec<usize>>,
83    /// Buffered `INSERT` row tuples, reused across batches.
84    row_batch: RowBatch,
85    /// Buffered `COPY` lines, reused across batches (`RowBatch` joins with
86    /// `,\n`, which is INSERT-tuple shaped; `COPY` wants one bare line per
87    /// row, so this is a plain reused buffer instead).
88    copy_batch: String,
89    /// Rows buffered in `copy_batch` since the last flush.
90    copy_rows: usize,
91    /// Whether the classified `insert_columns` carry an explicit value for an
92    /// `IDENTITY`/`GENERATED ALWAYS AS IDENTITY` column — the normal case for a
93    /// primary key referenced by generated foreign keys. Such a value is
94    /// rejected by MSSQL/PostgreSQL unless the load is wrapped
95    /// (`SET IDENTITY_INSERT ... ON`/`OVERRIDING SYSTEM VALUE`). `None` until the
96    /// first row classifies the columns.
97    identity_insert: Option<bool>,
98    /// Whether a `SET IDENTITY_INSERT <t> ON` has been emitted for this table
99    /// (MSSQL) and therefore an `OFF` must close it out in `end_table`.
100    identity_on: bool,
101    /// `INSERT` batches flushed for this table since the last `GO` (MSSQL,
102    /// only meaningful when [`RenderOptions::mssql_go`] is `Some`).
103    insert_batches_since_go: u64,
104}
105
106/// Streams generated rows to dialect-correct SQL as a [`RowSink`].
107pub struct SqlRenderer<W: Write> {
108    writer: BufWriter<W>,
109    options: RenderOptions,
110    warnings: WarningCollector,
111    table: Option<TableState>,
112    /// Whether the MSSQL production-style session header (`SET ANSI_NULLS
113    /// ON;` / `SET QUOTED_IDENTIFIER ON;`) has already been written; it is
114    /// emitted once, before the first table, not per table.
115    mssql_header_written: bool,
116}
117
118impl<W: Write> SqlRenderer<W> {
119    /// Wrap `writer` and render under `options`.
120    pub fn new(writer: W, options: RenderOptions) -> Self {
121        Self {
122            writer: BufWriter::new(writer),
123            options,
124            warnings: WarningCollector::new(),
125            table: None,
126            mssql_header_written: false,
127        }
128    }
129
130    /// Warnings collected while rendering DDL (e.g. a lossy cross-dialect
131    /// type conversion).
132    pub fn warnings(&self) -> &[ConvertWarning] {
133        self.warnings.warnings()
134    }
135
136    /// Flush and unwrap the underlying writer.
137    pub fn finish(mut self) -> Result<W, GenerateError> {
138        self.writer.flush().map_err(io_err)?;
139        self.writer
140            .into_inner()
141            .map_err(|err| io_err(err.into_error()))
142    }
143
144    /// Write the MSSQL production-style session header
145    /// (`SET ANSI_NULLS ON;` / `SET QUOTED_IDENTIFIER ON;`, `GO`-terminated)
146    /// once, before the first table. A no-op outside
147    /// [`RenderOptions::mssql_production_style`] + [`SqlDialect::Mssql`], and
148    /// idempotent (only ever writes once per renderer).
149    fn maybe_write_mssql_header(&mut self) -> Result<(), GenerateError> {
150        if self.mssql_header_written
151            || !self.options.mssql_production_style
152            || self.options.dialect != SqlDialect::Mssql
153        {
154            return Ok(());
155        }
156        writeln!(self.writer, "SET ANSI_NULLS ON;").map_err(io_err)?;
157        writeln!(self.writer, "SET QUOTED_IDENTIFIER ON;").map_err(io_err)?;
158        writeln!(self.writer, "GO").map_err(io_err)?;
159        self.mssql_header_written = true;
160        Ok(())
161    }
162
163    /// Render `table`'s DDL: the raw `create_statement` when the render
164    /// target matches the source dialect (see [`ddl::should_preserve_raw_ddl`]),
165    /// otherwise a normalized `CREATE TABLE` built from its [`PortableSchema`]
166    /// via [`ddl::render_create_table`].
167    ///
168    /// [`PortableSchema`]: crate::synthetic::schema::PortableSchema
169    fn render_ddl(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
170        let dialect = self.options.dialect;
171        if ddl::should_preserve_raw_ddl(&table.schema, self.options.source_dialect, dialect) {
172            let statement = table.schema.create_statement.as_deref().unwrap_or_default();
173            writeln!(self.writer, "{statement}").map_err(io_err)?;
174        } else {
175            let from = self.options.source_dialect.unwrap_or(dialect);
176            let sql = ddl::render_create_table(
177                &table.schema,
178                from,
179                dialect,
180                &mut self.warnings,
181                self.options.mssql_production_style,
182            );
183            write!(self.writer, "{sql}").map_err(io_err)?;
184        }
185        if dialect == SqlDialect::Mssql {
186            writeln!(self.writer, "GO").map_err(io_err)?;
187        }
188        Ok(())
189    }
190
191    /// Flush the buffered `INSERT` batch (a no-op if empty).
192    fn flush_insert(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
193        let dialect = self.options.dialect;
194        let mssql_go = self.options.mssql_go;
195        let state = self
196            .table
197            .as_mut()
198            .expect("flush_insert is only called while a table is active");
199        if state.row_batch.is_empty() {
200            return Ok(());
201        }
202        let indices = state
203            .insert_columns
204            .as_ref()
205            .expect("insert_columns is set before the first row is buffered");
206        let identity_insert = state.identity_insert.unwrap_or(false);
207        let column_list = quoted_column_list(dialect, table, indices);
208        // MSSQL rejects an explicit value for an IDENTITY column unless
209        // IDENTITY_INSERT is toggled on for the table; open it once, before the
210        // first batch, and close it in `end_table`.
211        if identity_insert && dialect == SqlDialect::Mssql && !state.identity_on {
212            writeln!(self.writer, "SET IDENTITY_INSERT {} ON", state.quoted_table)
213                .map_err(io_err)?;
214            writeln!(self.writer, "GO").map_err(io_err)?;
215            state.identity_on = true;
216        }
217        // PostgreSQL rejects an explicit value for a `GENERATED ALWAYS AS
218        // IDENTITY` column unless the statement declares `OVERRIDING SYSTEM
219        // VALUE`.
220        let overriding = if identity_insert && dialect == SqlDialect::Postgres {
221            " OVERRIDING SYSTEM VALUE"
222        } else {
223            ""
224        };
225        if indices.is_empty() && dialect != SqlDialect::MySql {
226            // Every column is a database default/identity: PostgreSQL, SQLite,
227            // and SQL Server reject `() VALUES ()`, so emit one `DEFAULT VALUES`
228            // row per buffered row (MySQL keeps the valid `() VALUES (),()` form).
229            for _ in 0..state.row_batch.row_count() {
230                writeln!(
231                    self.writer,
232                    "INSERT INTO {} DEFAULT VALUES;",
233                    state.quoted_table
234                )
235                .map_err(io_err)?;
236            }
237        } else {
238            writeln!(
239                self.writer,
240                "INSERT INTO {} ({column_list}){overriding} VALUES",
241                state.quoted_table
242            )
243            .map_err(io_err)?;
244            writeln!(self.writer, "{};", state.row_batch.as_str()).map_err(io_err)?;
245        }
246        if dialect == SqlDialect::Mssql {
247            let should_go = match mssql_go {
248                // Group `n` INSERT batches per GO instead of one-per-batch.
249                Some(n) => {
250                    state.insert_batches_since_go += 1;
251                    if state.insert_batches_since_go >= n.max(1) {
252                        state.insert_batches_since_go = 0;
253                        true
254                    } else {
255                        false
256                    }
257                }
258                // Default (and today's only) behavior: a GO after every batch.
259                None => true,
260            };
261            if should_go {
262                writeln!(self.writer, "GO").map_err(io_err)?;
263            }
264        }
265        state.row_batch.clear();
266        Ok(())
267    }
268
269    /// Flush the buffered `COPY` batch (a no-op if empty).
270    fn flush_copy(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
271        let state = self
272            .table
273            .as_mut()
274            .expect("flush_copy is only called while a table is active");
275        if state.copy_rows == 0 {
276            return Ok(());
277        }
278        let indices = state
279            .insert_columns
280            .as_ref()
281            .expect("insert_columns is set before the first row is buffered");
282        let column_list = quoted_column_list(SqlDialect::Postgres, table, indices);
283        writeln!(
284            self.writer,
285            "COPY {} ({column_list}) FROM stdin;",
286            state.quoted_table
287        )
288        .map_err(io_err)?;
289        write!(self.writer, "{}", state.copy_batch).map_err(io_err)?;
290        writeln!(self.writer, "\\.").map_err(io_err)?;
291        state.copy_batch.clear();
292        state.copy_rows = 0;
293        Ok(())
294    }
295
296    /// Determine, from the first generated row, which columns render
297    /// `DEFAULT` for every row of this table (see [`TableState::insert_columns`]),
298    /// and reject a `COPY` target for a `DEFAULT` column with no database
299    /// default/identity to fall back on (`COPY`'s column list can omit a
300    /// column, but every omitted column must have somewhere to get its value
301    /// from).
302    fn classify_columns(
303        table: &PlannedTable,
304        row: &GeneratedRow,
305        use_copy: bool,
306    ) -> Result<Vec<usize>, GenerateError> {
307        let is_default_column: Vec<bool> = row
308            .values
309            .iter()
310            .map(|value| matches!(value, GeneratedValue::Default))
311            .collect();
312        if use_copy {
313            for (i, column) in table.columns.iter().enumerate() {
314                if !is_default_column[i] {
315                    continue;
316                }
317                let schema = &column.schema;
318                if schema.default_sql.is_none() && !schema.identity && !schema.generated {
319                    return Err(GenerateError::diagnostic(
320                        &crate::diagnostic::codes::RENDER_COPY_DEFAULT,
321                        format!("tables.{}.columns.{}", table.name, schema.name),
322                        format!(
323                            "table `{}` column `{}` renders as DEFAULT but has no database \
324                             default/identity for PostgreSQL COPY to fall back on; render with \
325                             `no_copy` (multi-row INSERT) instead",
326                            table.name, schema.name
327                        ),
328                    ));
329                }
330            }
331        }
332        Ok((0..table.columns.len())
333            .filter(|&i| !is_default_column[i])
334            .collect())
335    }
336}
337
338impl<W: Write> RowSink for SqlRenderer<W> {
339    fn begin_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
340        self.maybe_write_mssql_header()?;
341        if self.options.mode != OutputMode::DataOnly {
342            self.render_ddl(table)?;
343        }
344        let data_enabled = self.options.mode != OutputMode::SchemaOnly;
345        // A table carrying an identity column that may receive explicit values
346        // must render as multi-row `INSERT` (not `COPY`) on PostgreSQL, so the
347        // load can add `OVERRIDING SYSTEM VALUE`; `COPY` has no such clause.
348        let has_identity = table.columns.iter().any(|column| column.schema.identity);
349        let use_copy = data_enabled
350            && self.options.dialect == SqlDialect::Postgres
351            && !self.options.no_copy
352            && !has_identity;
353        let batch_size = self.options.batch_size.max(1);
354        self.table = Some(TableState {
355            quoted_table: ddl::qualified_table(
356                self.options.dialect,
357                &table.name,
358                self.options.mssql_production_style,
359            ),
360            data_enabled,
361            use_copy,
362            batch_size,
363            insert_columns: None,
364            row_batch: RowBatch::with_capacity(batch_size, batch_size.saturating_mul(64)),
365            copy_batch: String::new(),
366            copy_rows: 0,
367            identity_insert: None,
368            identity_on: false,
369            insert_batches_since_go: 0,
370        });
371        Ok(())
372    }
373
374    fn write_row(&mut self, table: &PlannedTable, row: &GeneratedRow) -> Result<(), GenerateError> {
375        let dialect = self.options.dialect;
376        let (data_enabled, use_copy, needs_classification) = match &self.table {
377            Some(state) => (
378                state.data_enabled,
379                state.use_copy,
380                state.insert_columns.is_none(),
381            ),
382            None => return Ok(()),
383        };
384        if !data_enabled {
385            return Ok(());
386        }
387        if needs_classification {
388            let insert_columns = Self::classify_columns(table, row, use_copy)?;
389            // An identity column that survives classification (i.e. carries an
390            // explicit value rather than rendering `DEFAULT`) needs the
391            // engine-specific identity-insert wrapper to load.
392            let identity_insert = matches!(dialect, SqlDialect::Mssql | SqlDialect::Postgres)
393                && insert_columns
394                    .iter()
395                    .any(|&i| table.columns[i].schema.identity);
396            let state = self.table.as_mut().expect("checked above");
397            state.insert_columns = Some(insert_columns);
398            state.identity_insert = Some(identity_insert);
399        }
400
401        let state = self.table.as_mut().expect("checked above");
402        let indices = state
403            .insert_columns
404            .as_ref()
405            .expect("set just above on the first row");
406
407        if state.use_copy {
408            write!(
409                state.copy_batch,
410                "{}",
411                CopyRow {
412                    indices,
413                    values: &row.values,
414                }
415            )
416            .map_err(fmt_err)?;
417            state.copy_batch.push('\n');
418            state.copy_rows += 1;
419            if state.copy_rows >= state.batch_size {
420                self.flush_copy(table)?;
421            }
422        } else {
423            state
424                .row_batch
425                .push_fmt(format_args!(
426                    "{}",
427                    RowTuple {
428                        dialect,
429                        indices,
430                        values: &row.values,
431                    }
432                ))
433                .map_err(fmt_err)?;
434            if state.row_batch.row_count() >= state.batch_size {
435                self.flush_insert(table)?;
436            }
437        }
438        Ok(())
439    }
440
441    fn end_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
442        let (data_enabled, use_copy) = match &self.table {
443            Some(state) => (state.data_enabled, state.use_copy),
444            None => (false, false),
445        };
446        if data_enabled {
447            if use_copy {
448                self.flush_copy(table)?;
449            } else {
450                self.flush_insert(table)?;
451            }
452        }
453        // Under `--mssql-go N`, the last batch flushed above may not have
454        // reached the Nth-batch boundary that triggers a `GO`; close this
455        // table's batch out cleanly (rather than merging into whatever
456        // follows — the next table's DDL, or the IDENTITY_INSERT OFF below)
457        // by emitting the trailing `GO` here.
458        if self.options.dialect == SqlDialect::Mssql && self.options.mssql_go.is_some() {
459            if let Some(state) = &mut self.table {
460                if state.insert_batches_since_go > 0 {
461                    state.insert_batches_since_go = 0;
462                    writeln!(self.writer, "GO").map_err(io_err)?;
463                }
464            }
465        }
466        // Close the MSSQL identity-insert wrapper opened in `flush_insert`.
467        if let Some(state) = &self.table {
468            if state.identity_on {
469                writeln!(
470                    self.writer,
471                    "SET IDENTITY_INSERT {} OFF",
472                    state.quoted_table
473                )
474                .map_err(io_err)?;
475                writeln!(self.writer, "GO").map_err(io_err)?;
476            }
477        }
478        self.table = None;
479        Ok(())
480    }
481}
482
483/// Map an [`io::Error`] into the closed [`GenerateError`] set: the
484/// [`RowSink`] contract has no I/O variant, so a write
485/// failure surfaces as a `GEN-RENDER-IO` diagnostic rather than silently
486/// panicking or being swallowed.
487fn io_err(err: io::Error) -> GenerateError {
488    GenerateError::diagnostic(
489        &crate::diagnostic::codes::RENDER_IO,
490        "output",
491        err.to_string(),
492    )
493}
494
495/// Map a [`fmt::Error`] the same way as [`io_err`]; writing into an in-memory
496/// buffer is infallible in practice; this only exists so `?` type-checks.
497fn fmt_err(_: fmt::Error) -> GenerateError {
498    GenerateError::diagnostic(
499        &crate::diagnostic::codes::RENDER_IO,
500        "output",
501        "formatting error",
502    )
503}
504
505/// Quote and comma-join the table's column names at `indices`, in order.
506fn quoted_column_list(dialect: SqlDialect, table: &PlannedTable, indices: &[usize]) -> String {
507    indices
508        .iter()
509        .map(|&i| quote_ident(dialect, &table.columns[i].schema.name))
510        .collect::<Vec<_>>()
511        .join(", ")
512}
513
514/// One `INSERT` row tuple: `(v1, v2, ...)`, written straight into the
515/// destination [`RowBatch`] with no intermediate per-cell allocation.
516struct RowTuple<'a> {
517    dialect: SqlDialect,
518    indices: &'a [usize],
519    values: &'a [GeneratedValue],
520}
521
522impl fmt::Display for RowTuple<'_> {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        f.write_str("(")?;
525        for (position, &i) in self.indices.iter().enumerate() {
526            if position > 0 {
527                f.write_str(", ")?;
528            }
529            write!(
530                f,
531                "{}",
532                InsertValue {
533                    dialect: self.dialect,
534                    value: &self.values[i],
535                }
536            )?;
537        }
538        f.write_str(")")
539    }
540}
541
542/// A single value rendered as an `INSERT`-literal, dialect-correct via
543/// [`SqlString`] for text-like values.
544struct InsertValue<'a> {
545    dialect: SqlDialect,
546    value: &'a GeneratedValue,
547}
548
549impl fmt::Display for InsertValue<'_> {
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        match self.value {
552            GeneratedValue::Null => f.write_str("NULL"),
553            // Reachable only if a column classified as non-DEFAULT (from the
554            // first row) ever renders `Default` on a later row; the engine's
555            // per-table owner assignment makes that impossible today (see
556            // `SqlRenderer::classify_columns`), but this still renders a
557            // syntactically valid literal instead of corrupting the batch.
558            GeneratedValue::Default => f.write_str("DEFAULT"),
559            GeneratedValue::Boolean(value) => f.write_str(boolean_literal(self.dialect, *value)),
560            GeneratedValue::Integer(value) => write!(f, "{value}"),
561            GeneratedValue::Decimal { minor, scale } => write_decimal(f, *minor, *scale),
562            GeneratedValue::Text(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
563            GeneratedValue::Bytes(value) => write_bytes_literal(f, self.dialect, value),
564            GeneratedValue::DateTime(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
565            GeneratedValue::Json(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
566        }
567    }
568}
569
570/// The dialect-correct boolean literal. MySQL/SQLite have no boolean type and
571/// MSSQL's `BIT` only accepts `0`/`1`; PostgreSQL's `boolean` accepts (and
572/// pretty-prints as) `TRUE`/`FALSE`.
573fn boolean_literal(dialect: SqlDialect, value: bool) -> &'static str {
574    match (dialect, value) {
575        (SqlDialect::Postgres, true) => "TRUE",
576        (SqlDialect::Postgres, false) => "FALSE",
577        (_, true) => "1",
578        (_, false) => "0",
579    }
580}
581
582/// Render a fixed-point `{ minor, scale }` value as `123.45` (or a bare
583/// integer when `scale` is `0`), without going through floating point.
584fn write_decimal(f: &mut fmt::Formatter<'_>, minor: i128, scale: u32) -> fmt::Result {
585    if scale == 0 {
586        return write!(f, "{minor}");
587    }
588    let divisor = 10i128.pow(scale);
589    if minor < 0 {
590        f.write_str("-")?;
591    }
592    let magnitude = minor.unsigned_abs();
593    let whole = magnitude / divisor as u128;
594    let fraction = magnitude % divisor as u128;
595    write!(f, "{whole}.{fraction:0width$}", width = scale as usize)
596}
597
598/// Render a bytes value as the dialect's binary-string-literal syntax.
599fn write_bytes_literal(
600    f: &mut fmt::Formatter<'_>,
601    dialect: SqlDialect,
602    bytes: &[u8],
603) -> fmt::Result {
604    match dialect {
605        SqlDialect::MySql | SqlDialect::Sqlite => {
606            f.write_str("X'")?;
607            write_hex(f, bytes)?;
608            f.write_str("'")
609        }
610        SqlDialect::Postgres => {
611            f.write_str("'\\x")?;
612            write_hex(f, bytes)?;
613            f.write_str("'")
614        }
615        SqlDialect::Mssql => {
616            f.write_str("0x")?;
617            write_hex(f, bytes)
618        }
619    }
620}
621
622/// Write `bytes` as lowercase hex, two characters per byte, straight into
623/// the formatter (no intermediate hex-encoded `String`).
624fn write_hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
625    for byte in bytes {
626        write!(f, "{byte:02x}")?;
627    }
628    Ok(())
629}
630
631/// One `COPY` line: dialect-fixed to PostgreSQL's tab-delimited text format,
632/// which differs from `INSERT`-literal escaping (see [`CopyValue`]).
633struct CopyRow<'a> {
634    indices: &'a [usize],
635    values: &'a [GeneratedValue],
636}
637
638impl fmt::Display for CopyRow<'_> {
639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640        for (position, &i) in self.indices.iter().enumerate() {
641            if position > 0 {
642                f.write_str("\t")?;
643            }
644            write!(f, "{}", CopyValue(&self.values[i]))?;
645        }
646        Ok(())
647    }
648}
649
650/// A single value in PostgreSQL `COPY` text format: unquoted, tab/newline
651/// delimited, `NULL` spelled `\N`, and backslash-escaped rather than
652/// SQL-string-escaped (see the module docs for why this cannot reuse
653/// [`SqlString`]).
654struct CopyValue<'a>(&'a GeneratedValue);
655
656impl fmt::Display for CopyValue<'_> {
657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658        match self.0 {
659            GeneratedValue::Null => f.write_str("\\N"),
660            // `Default` cannot reach a COPY stream: `classify_columns` excludes
661            // every DEFAULT column from `indices` before any `CopyValue` is
662            // constructed. Fail loudly if that invariant is ever broken rather
663            // than silently corrupting a default into a NULL.
664            GeneratedValue::Default => Err(fmt::Error),
665            GeneratedValue::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
666            GeneratedValue::Integer(value) => write!(f, "{value}"),
667            GeneratedValue::Decimal { minor, scale } => write_decimal(f, *minor, *scale),
668            GeneratedValue::Text(value) => write_copy_escaped(f, value),
669            GeneratedValue::Bytes(value) => {
670                f.write_str("\\\\x")?;
671                write_hex(f, value)
672            }
673            GeneratedValue::DateTime(value) => write_copy_escaped(f, value),
674            GeneratedValue::Json(value) => write_copy_escaped(f, value),
675        }
676    }
677}
678
679/// Escape `value` for PostgreSQL `COPY` text format: backslash, tab,
680/// newline, and carriage return each get a backslash-letter escape; every
681/// other character (including `'`) is copied through unquoted.
682fn write_copy_escaped(f: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result {
683    for ch in value.chars() {
684        match ch {
685            '\\' => f.write_str("\\\\")?,
686            '\t' => f.write_str("\\t")?,
687            '\n' => f.write_str("\\n")?,
688            '\r' => f.write_str("\\r")?,
689            other => f.write_char(other)?,
690        }
691    }
692    Ok(())
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    #[test]
700    fn copy_value_default_is_a_hard_error_not_silent_null() {
701        // A `Default` reaching a COPY stream is an invariant violation and must
702        // fail, not silently corrupt into a NULL (`\N`). A real NULL still emits
703        // `\N`.
704        let mut buf = String::new();
705        assert!(
706            write!(&mut buf, "{}", CopyValue(&GeneratedValue::Default)).is_err(),
707            "Default in COPY must error, rendered `{buf}`"
708        );
709
710        let mut null = String::new();
711        write!(&mut null, "{}", CopyValue(&GeneratedValue::Null)).unwrap();
712        assert_eq!(null, "\\N");
713    }
714}