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_identifier;
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, mut 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            // PostgreSQL cannot express an all-default row as `COPY t ()`.
389            // Select the valid `INSERT ... DEFAULT VALUES` path before COPY's
390            // per-column fallback validation runs.
391            use_copy &= row
392                .values
393                .iter()
394                .any(|value| !matches!(value, GeneratedValue::Default));
395            let insert_columns = Self::classify_columns(table, row, use_copy)?;
396            // An identity column that survives classification (i.e. carries an
397            // explicit value rather than rendering `DEFAULT`) needs the
398            // engine-specific identity-insert wrapper to load.
399            let identity_insert = matches!(dialect, SqlDialect::Mssql | SqlDialect::Postgres)
400                && insert_columns
401                    .iter()
402                    .any(|&i| table.columns[i].schema.identity);
403            let state = self.table.as_mut().expect("checked above");
404            state.insert_columns = Some(insert_columns);
405            state.identity_insert = Some(identity_insert);
406            state.use_copy = use_copy;
407        }
408
409        let state = self.table.as_mut().expect("checked above");
410        let indices = state
411            .insert_columns
412            .as_ref()
413            .expect("set just above on the first row");
414
415        if state.use_copy {
416            write!(
417                state.copy_batch,
418                "{}",
419                CopyRow {
420                    indices,
421                    values: &row.values,
422                }
423            )
424            .map_err(fmt_err)?;
425            state.copy_batch.push('\n');
426            state.copy_rows += 1;
427            if state.copy_rows >= state.batch_size {
428                self.flush_copy(table)?;
429            }
430        } else {
431            state
432                .row_batch
433                .push_fmt(format_args!(
434                    "{}",
435                    RowTuple {
436                        dialect,
437                        indices,
438                        values: &row.values,
439                    }
440                ))
441                .map_err(fmt_err)?;
442            if state.row_batch.row_count() >= state.batch_size {
443                self.flush_insert(table)?;
444            }
445        }
446        Ok(())
447    }
448
449    fn end_table(&mut self, table: &PlannedTable) -> Result<(), GenerateError> {
450        let (data_enabled, use_copy) = match &self.table {
451            Some(state) => (state.data_enabled, state.use_copy),
452            None => (false, false),
453        };
454        if data_enabled {
455            if use_copy {
456                self.flush_copy(table)?;
457            } else {
458                self.flush_insert(table)?;
459            }
460        }
461        // Under `--mssql-go N`, the last batch flushed above may not have
462        // reached the Nth-batch boundary that triggers a `GO`; close this
463        // table's batch out cleanly (rather than merging into whatever
464        // follows — the next table's DDL, or the IDENTITY_INSERT OFF below)
465        // by emitting the trailing `GO` here.
466        if self.options.dialect == SqlDialect::Mssql && self.options.mssql_go.is_some() {
467            if let Some(state) = &mut self.table {
468                if state.insert_batches_since_go > 0 {
469                    state.insert_batches_since_go = 0;
470                    writeln!(self.writer, "GO").map_err(io_err)?;
471                }
472            }
473        }
474        // Close the MSSQL identity-insert wrapper opened in `flush_insert`.
475        if let Some(state) = &self.table {
476            if state.identity_on {
477                writeln!(
478                    self.writer,
479                    "SET IDENTITY_INSERT {} OFF",
480                    state.quoted_table
481                )
482                .map_err(io_err)?;
483                writeln!(self.writer, "GO").map_err(io_err)?;
484            }
485        }
486        self.table = None;
487        Ok(())
488    }
489}
490
491/// Map an [`io::Error`] into the closed [`GenerateError`] set: the
492/// [`RowSink`] contract has no I/O variant, so a write
493/// failure surfaces as a `GEN-RENDER-IO` diagnostic rather than silently
494/// panicking or being swallowed.
495fn io_err(err: io::Error) -> GenerateError {
496    GenerateError::diagnostic(
497        &crate::diagnostic::codes::RENDER_IO,
498        "output",
499        err.to_string(),
500    )
501}
502
503/// Map a [`fmt::Error`] the same way as [`io_err`]; writing into an in-memory
504/// buffer is infallible in practice; this only exists so `?` type-checks.
505fn fmt_err(_: fmt::Error) -> GenerateError {
506    GenerateError::diagnostic(
507        &crate::diagnostic::codes::RENDER_IO,
508        "output",
509        "formatting error",
510    )
511}
512
513/// Quote and comma-join the table's column names at `indices`, in order.
514fn quoted_column_list(dialect: SqlDialect, table: &PlannedTable, indices: &[usize]) -> String {
515    indices
516        .iter()
517        .map(|&i| quote_identifier(dialect, &table.columns[i].schema.name))
518        .collect::<Vec<_>>()
519        .join(", ")
520}
521
522/// One `INSERT` row tuple: `(v1, v2, ...)`, written straight into the
523/// destination [`RowBatch`] with no intermediate per-cell allocation.
524struct RowTuple<'a> {
525    dialect: SqlDialect,
526    indices: &'a [usize],
527    values: &'a [GeneratedValue],
528}
529
530impl fmt::Display for RowTuple<'_> {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        f.write_str("(")?;
533        for (position, &i) in self.indices.iter().enumerate() {
534            if position > 0 {
535                f.write_str(", ")?;
536            }
537            write!(
538                f,
539                "{}",
540                InsertValue {
541                    dialect: self.dialect,
542                    value: &self.values[i],
543                }
544            )?;
545        }
546        f.write_str(")")
547    }
548}
549
550/// A single value rendered as an `INSERT`-literal, dialect-correct via
551/// [`SqlString`] for text-like values.
552struct InsertValue<'a> {
553    dialect: SqlDialect,
554    value: &'a GeneratedValue,
555}
556
557impl fmt::Display for InsertValue<'_> {
558    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559        match self.value {
560            GeneratedValue::Null => f.write_str("NULL"),
561            // Reachable only if a column classified as non-DEFAULT (from the
562            // first row) ever renders `Default` on a later row; the engine's
563            // per-table owner assignment makes that impossible today (see
564            // `SqlRenderer::classify_columns`), but this still renders a
565            // syntactically valid literal instead of corrupting the batch.
566            GeneratedValue::Default => f.write_str("DEFAULT"),
567            GeneratedValue::Boolean(value) => f.write_str(boolean_literal(self.dialect, *value)),
568            GeneratedValue::Integer(value) => write!(f, "{value}"),
569            GeneratedValue::Decimal { minor, scale } => write_decimal(f, *minor, *scale),
570            GeneratedValue::Text(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
571            GeneratedValue::Bytes(value) => write_bytes_literal(f, self.dialect, value),
572            GeneratedValue::DateTime(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
573            GeneratedValue::Json(value) => write!(f, "{}", SqlString::new(self.dialect, value)),
574        }
575    }
576}
577
578/// The dialect-correct boolean literal. MySQL/SQLite have no boolean type and
579/// MSSQL's `BIT` only accepts `0`/`1`; PostgreSQL's `boolean` accepts (and
580/// pretty-prints as) `TRUE`/`FALSE`.
581fn boolean_literal(dialect: SqlDialect, value: bool) -> &'static str {
582    match (dialect, value) {
583        (SqlDialect::Postgres, true) => "TRUE",
584        (SqlDialect::Postgres, false) => "FALSE",
585        (_, true) => "1",
586        (_, false) => "0",
587    }
588}
589
590/// Render a fixed-point `{ minor, scale }` value as `123.45` (or a bare
591/// integer when `scale` is `0`), without going through floating point.
592fn write_decimal(f: &mut fmt::Formatter<'_>, minor: i128, scale: u32) -> fmt::Result {
593    if scale == 0 {
594        return write!(f, "{minor}");
595    }
596    let divisor = 10i128.pow(scale);
597    if minor < 0 {
598        f.write_str("-")?;
599    }
600    let magnitude = minor.unsigned_abs();
601    let whole = magnitude / divisor as u128;
602    let fraction = magnitude % divisor as u128;
603    write!(f, "{whole}.{fraction:0width$}", width = scale as usize)
604}
605
606/// Render a bytes value as the dialect's binary-string-literal syntax.
607fn write_bytes_literal(
608    f: &mut fmt::Formatter<'_>,
609    dialect: SqlDialect,
610    bytes: &[u8],
611) -> fmt::Result {
612    match dialect {
613        SqlDialect::MySql | SqlDialect::Sqlite => {
614            f.write_str("X'")?;
615            write_hex(f, bytes)?;
616            f.write_str("'")
617        }
618        SqlDialect::Postgres => {
619            f.write_str("'\\x")?;
620            write_hex(f, bytes)?;
621            f.write_str("'")
622        }
623        SqlDialect::Mssql => {
624            f.write_str("0x")?;
625            write_hex(f, bytes)
626        }
627    }
628}
629
630/// Write `bytes` as lowercase hex, two characters per byte, straight into
631/// the formatter (no intermediate hex-encoded `String`).
632fn write_hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
633    for byte in bytes {
634        write!(f, "{byte:02x}")?;
635    }
636    Ok(())
637}
638
639/// One `COPY` line: dialect-fixed to PostgreSQL's tab-delimited text format,
640/// which differs from `INSERT`-literal escaping (see [`CopyValue`]).
641struct CopyRow<'a> {
642    indices: &'a [usize],
643    values: &'a [GeneratedValue],
644}
645
646impl fmt::Display for CopyRow<'_> {
647    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648        for (position, &i) in self.indices.iter().enumerate() {
649            if position > 0 {
650                f.write_str("\t")?;
651            }
652            write!(f, "{}", CopyValue(&self.values[i]))?;
653        }
654        Ok(())
655    }
656}
657
658/// A single value in PostgreSQL `COPY` text format: unquoted, tab/newline
659/// delimited, `NULL` spelled `\N`, and backslash-escaped rather than
660/// SQL-string-escaped (see the module docs for why this cannot reuse
661/// [`SqlString`]).
662struct CopyValue<'a>(&'a GeneratedValue);
663
664impl fmt::Display for CopyValue<'_> {
665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666        match self.0 {
667            GeneratedValue::Null => f.write_str("\\N"),
668            // `Default` cannot reach a COPY stream: `classify_columns` excludes
669            // every DEFAULT column from `indices` before any `CopyValue` is
670            // constructed. Fail loudly if that invariant is ever broken rather
671            // than silently corrupting a default into a NULL.
672            GeneratedValue::Default => Err(fmt::Error),
673            GeneratedValue::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
674            GeneratedValue::Integer(value) => write!(f, "{value}"),
675            GeneratedValue::Decimal { minor, scale } => write_decimal(f, *minor, *scale),
676            GeneratedValue::Text(value) => write_copy_escaped(f, value),
677            GeneratedValue::Bytes(value) => {
678                f.write_str("\\\\x")?;
679                write_hex(f, value)
680            }
681            GeneratedValue::DateTime(value) => write_copy_escaped(f, value),
682            GeneratedValue::Json(value) => write_copy_escaped(f, value),
683        }
684    }
685}
686
687/// Escape `value` for PostgreSQL `COPY` text format: backslash, tab,
688/// newline, and carriage return each get a backslash-letter escape; every
689/// other character (including `'`) is copied through unquoted.
690fn write_copy_escaped(f: &mut fmt::Formatter<'_>, value: &str) -> fmt::Result {
691    for ch in value.chars() {
692        match ch {
693            '\\' => f.write_str("\\\\")?,
694            '\t' => f.write_str("\\t")?,
695            '\n' => f.write_str("\\n")?,
696            '\r' => f.write_str("\\r")?,
697            other => f.write_char(other)?,
698        }
699    }
700    Ok(())
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    #[test]
708    fn copy_value_default_is_a_hard_error_not_silent_null() {
709        // A `Default` reaching a COPY stream is an invariant violation and must
710        // fail, not silently corrupt into a NULL (`\N`). A real NULL still emits
711        // `\N`.
712        let mut buf = String::new();
713        assert!(
714            write!(&mut buf, "{}", CopyValue(&GeneratedValue::Default)).is_err(),
715            "Default in COPY must error, rendered `{buf}`"
716        );
717
718        let mut null = String::new();
719        write!(&mut null, "{}", CopyValue(&GeneratedValue::Null)).unwrap();
720        assert_eq!(null, "\\N");
721    }
722}