Skip to main content

razeri_plugin_contract/
renderer.rs

1// Copyright (C) 2026 Gabriel Shea
2// Licensed under either of the Apache License, Version 2.0 or the MIT
3// license, at your option.
4
5//! Layered rendering traits for SQL generation.
6//!
7//! The hierarchy is designed so that implementing [`SqlRenderer`] (4 methods)
8//! gives you ANSI-standard defaults for all higher-level traits.
9
10use crate::DataType;
11use crate::bulk_load_form::BulkLoadForm;
12use crate::constraint_enforcement::ConstraintEnforcement;
13use crate::date_format::DateFormat;
14use crate::evolution::{ColumnEvolution, Written, WrittenObject};
15use crate::flatten::{Flatten, FlattenRequest};
16use crate::large_object::{HeldAs, TextLengthUnit};
17use crate::number_format::NumberFormat;
18use crate::procedure_log_level::ProcedureLogLevel;
19use crate::routine_form::{ProcedureForm, ScalarFunctionForm, TableFunctionForm};
20use crate::routine_spec::RoutineSpec;
21use crate::sid_spelling::{SidHelperBody, SidSpelling, UNSPELLED_SID};
22
23/// **Where the aggregated expression goes** in a form returned by
24/// [`SqlRenderer::median_aggregate_form`].
25///
26/// The form is a template rather than finished SQL so that *which function*
27/// and *how a column is written* stay in different hands — the dialect answers
28/// the first, the query renderer the second. A form must carry this token
29/// exactly once.
30pub const AGGREGATE_ARGUMENT: &str = "{argument}";
31
32/// **What kind of value an aggregate would have to collapse** — the axis
33/// [`SqlRenderer::render_single_row_aggregate`] varies on, held to three arms
34/// because three is what the measurements distinguish.
35///
36/// Not the full type lattice: `MAX` behaves identically across every numeric,
37/// textual and temporal type on every platform razeri reaches, and splitting
38/// them would invite per-type arms nothing has measured.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum AggregableKind {
41    /// Numeric, textual and temporal — every platform orders these and every
42    /// platform has `MAX` for them.
43    Orderable,
44    /// A truth value. `PostgreSQL` and SQL Server have no `MAX` for it and each
45    /// spells the collapse differently.
46    Boolean,
47    /// `uuid`, JSON, binary, interval, array, map — the families with no
48    /// ordering to borrow. Availability is per platform and is measured, never
49    /// assumed.
50    Opaque,
51}
52
53/// **A clock bound once for a whole load script** — what
54/// [`SqlRenderer::render_inline_clock_binding`] answers on an engine whose
55/// loads ship as flat statement lists rather than procedure bodies.
56///
57/// The `statements` run first and capture the engine's current moment under
58/// one name; `reference` is the expression every later statement of the same
59/// run reads it back by. One binding, many readers, is what makes a version's
60/// close and its successor's open the same instant by construction.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct InlineClockBinding {
63    /// The statement(s) that bind the moment, in run order, each terminated.
64    pub statements: Vec<String>,
65    /// The expression that reads the bound moment back.
66    pub reference: String,
67}
68
69/// **One delimited source file, in every spelling an engine's file relation may
70/// ask for it in** — what
71/// [`SqlRenderer::delimited_file_relation_for`] is handed.
72///
73/// One struct rather than several arguments, because a slot that grows an
74/// argument is a slot every dialect has to be recompiled for; one that grows a
75/// field is not. Each is composed once, by the caller that knows the answer,
76/// so no dialect has to take a path apart to find a file name in it.
77///
78/// A dialect reads the fields. One that builds a value, in its own tests,
79/// starts from [`DelimitedFile::new`] and the `with_` methods, which is also
80/// why it cannot be written out field by field outside this crate: the next
81/// thing Razeri learns to say about a file arrives as a field with a default,
82/// and no dialect's tests break for it.
83#[derive(Debug, Clone, Copy)]
84#[non_exhaustive]
85pub struct DelimitedFile<'a> {
86    /// The whole path to the file, already a single-quoted SQL string literal
87    /// and already escaped. Put it where the relation takes a path, and do not
88    /// quote it again.
89    pub path_literal: &'a str,
90    /// The directory the file sits in, already a single-quoted SQL string
91    /// literal — for an engine that resolves a file name against a directory
92    /// rather than opening a path.
93    pub directory_literal: &'a str,
94    /// The file's own name inside that directory, bare: no quotes and no path
95    /// in front of it.
96    pub name: &'a str,
97    /// **The file's columns, in the order the file writes them**, spelled
98    /// exactly as its header row spells them and with no quoting applied.
99    ///
100    /// Empty where the caller measured no header — a bundle assembled by hand.
101    /// An engine that cannot read a file without its columns declared answers
102    /// `None` to an empty list rather than guessing at one.
103    ///
104    /// A file with no header line ([`header`](Self::header) `false`) has no
105    /// names of its own, and its columns arrive as `column0`, `column1` and
106    /// on, counted from zero: the names `DuckDB` gives such a file, and the
107    /// names a header cell with no name is read under everywhere.
108    pub columns: &'a [String],
109    /// **How the file's lines end**, as Razeri measured it when it read the
110    /// file: [`LineEnding::CrLf`] for a carriage return and a newline,
111    /// [`LineEnding::Lf`] for a newline alone.
112    ///
113    /// Put it wherever the engine's read names a record delimiter. An engine
114    /// told `\n` for a file whose lines end `\r\n` either keeps the carriage
115    /// return on the last field, so a name is stored one character too long
116    /// and a number cannot be read, or, where the last field is quoted, reads
117    /// past the closing quote into the next line. An engine whose read finds
118    /// the ending itself can leave this alone, and should say so where it
119    /// states its read.
120    pub line_ending: LineEnding,
121    /// **The character between the file's fields**, as the design declares
122    /// it. Never a guess: an engine whose reader would otherwise sniff the
123    /// delimiter is told this one.
124    ///
125    /// The four ASCII separators ([`FileDelimiter::is_control`]) are bytes no
126    /// text editor shows, and engines differ in how a statement may name
127    /// them: an escape, a hexadecimal literal, a function call, or not at
128    /// all. Spell the one your engine was measured to take. Where it takes
129    /// none, answer `None`: Razeri then declines the file by name and says
130    /// which delimiter your engine does read.
131    pub delimiter: FileDelimiter,
132    /// **The character a field is quoted with**: `"` unless the design
133    /// declares another. A field inside two of them may hold the delimiter
134    /// and a line break, and two of them together inside it stand for one.
135    pub quote: char,
136    /// **Whether the file's first line names its columns.** `true` unless the
137    /// design declares `header: false`; a file without one has its first row
138    /// of values on its first line, and its
139    /// [`columns`](Self::columns) are named by position.
140    pub header: bool,
141    /// **The encoding to read the bytes as**, where they are not UTF-8: the
142    /// one name the encoding standard files it under (`windows-1252`,
143    /// `shift_jis`). `None` on the ordinary day, which means UTF-8.
144    ///
145    /// Razeri asks
146    /// [`delimited_file_relation_in_encoding`](SqlRenderer::delimited_file_relation_in_encoding)
147    /// whether your engine has a word for the encoding before it hands one
148    /// over here, so a dialect that answers that one `None` never meets an
149    /// encoding in this field. One that answers it, and also overrides
150    /// [`delimited_file_relation_for`](SqlRenderer::delimited_file_relation_for),
151    /// reads this field there.
152    pub encoding: Option<&'a str>,
153}
154
155impl<'a> DelimitedFile<'a> {
156    /// **A file at `path_literal`, read the way every engine reads a file by
157    /// default**: no columns measured, lines ending `\n`, split on commas,
158    /// quoted with `"`, a header on its first line, and UTF-8.
159    ///
160    /// `path_literal` and `directory_literal` are finished single-quoted SQL
161    /// string literals; `name` is the file's own name, bare.
162    #[must_use]
163    pub const fn new(path_literal: &'a str, directory_literal: &'a str, name: &'a str) -> Self {
164        Self {
165            path_literal,
166            directory_literal,
167            name,
168            columns: &[],
169            line_ending: LineEnding::Lf,
170            delimiter: FileDelimiter::Comma,
171            quote: '"',
172            header: true,
173            encoding: None,
174        }
175    }
176
177    /// The same file, with its columns in the order the file writes them.
178    #[must_use]
179    pub const fn with_columns(mut self, columns: &'a [String]) -> Self {
180        self.columns = columns;
181        self
182    }
183
184    /// The same file, its lines ending as `line_ending` says.
185    #[must_use]
186    pub const fn with_line_ending(mut self, line_ending: LineEnding) -> Self {
187        self.line_ending = line_ending;
188        self
189    }
190
191    /// The same file, its fields split by `delimiter`.
192    #[must_use]
193    pub const fn with_delimiter(mut self, delimiter: FileDelimiter) -> Self {
194        self.delimiter = delimiter;
195        self
196    }
197
198    /// The same file, its fields quoted with `quote`.
199    #[must_use]
200    pub const fn with_quote(mut self, quote: char) -> Self {
201        self.quote = quote;
202        self
203    }
204
205    /// The same file, with a header line or without one.
206    #[must_use]
207    pub const fn with_header(mut self, header: bool) -> Self {
208        self.header = header;
209        self
210    }
211
212    /// The same file, its bytes read as `encoding`, or as UTF-8 for `None`.
213    #[must_use]
214    pub const fn with_encoding(mut self, encoding: Option<&'a str>) -> Self {
215        self.encoding = encoding;
216        self
217    }
218
219    /// **Whether the file is written the way a read that is told nothing
220    /// reads it**: split on commas, quoted with `"`, and headed.
221    ///
222    /// The default [`delimited_file_relation_for`](SqlRenderer::delimited_file_relation_for)
223    /// answers only for such a file, because the path-only
224    /// [`delimited_file_relation`](SqlRenderer::delimited_file_relation) it
225    /// hands over to has no way to be told anything else.
226    #[must_use]
227    pub fn is_plain(&self) -> bool {
228        self.delimiter == FileDelimiter::Comma && self.quote == '"' && self.header
229    }
230}
231
232/// **The character between a delimited file's fields** — one of the eight a
233/// design names with a word, or any other single ASCII character.
234///
235/// The words are `comma`, `tab`, `pipe`, `semicolon`, and the four ASCII
236/// separators `fs`, `gs`, `rs` and `us` (bytes `0x1C` to `0x1F`). A character
237/// one of the words names always arrives as that word, never as
238/// [`FileDelimiter::Literal`].
239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
240pub enum FileDelimiter {
241    /// `,`
242    #[default]
243    Comma,
244    /// The tab character.
245    Tab,
246    /// `|`
247    Pipe,
248    /// `;`
249    Semicolon,
250    /// The file separator, `0x1C`.
251    Fs,
252    /// The group separator, `0x1D`.
253    Gs,
254    /// The record separator, `0x1E`.
255    Rs,
256    /// The unit separator, `0x1F`.
257    Us,
258    /// Any other single ASCII character, written as itself.
259    Literal(char),
260}
261
262impl FileDelimiter {
263    /// The character itself.
264    #[must_use]
265    pub const fn as_char(self) -> char {
266        match self {
267            Self::Comma => ',',
268            Self::Tab => '\t',
269            Self::Pipe => '|',
270            Self::Semicolon => ';',
271            Self::Fs => '\u{1c}',
272            Self::Gs => '\u{1d}',
273            Self::Rs => '\u{1e}',
274            Self::Us => '\u{1f}',
275            Self::Literal(c) => c,
276        }
277    }
278
279    /// The character as the one byte a reader splits on. Every delimiter a
280    /// design can declare is ASCII.
281    #[must_use]
282    pub const fn as_byte(self) -> u8 {
283        // ASCII for every value a design can declare.
284        self.as_char() as u8
285    }
286
287    /// The word a design writes for this delimiter, or `None` for a literal.
288    #[must_use]
289    pub const fn word(self) -> Option<&'static str> {
290        Some(match self {
291            Self::Comma => "comma",
292            Self::Tab => "tab",
293            Self::Pipe => "pipe",
294            Self::Semicolon => "semicolon",
295            Self::Fs => "fs",
296            Self::Gs => "gs",
297            Self::Rs => "rs",
298            Self::Us => "us",
299            Self::Literal(_) => return None,
300        })
301    }
302
303    /// **Whether this is one of the four ASCII separators**, `0x1C` to
304    /// `0x1F` — the delimiters no text editor shows, which an engine's
305    /// statement names, if at all, by an escape of its own.
306    #[must_use]
307    pub const fn is_control(self) -> bool {
308        matches!(self, Self::Fs | Self::Gs | Self::Rs | Self::Us)
309    }
310}
311
312/// **One setting a statement was written with, for the engine it names.**
313///
314/// Razeri's statement builders carry settings written for one engine — a
315/// view's `security_barrier` for `PostgreSQL`, a table's data compression for
316/// SQL Server. They reach every dialect tagged with the engine they were
317/// written for, as that engine's dialect names itself
318/// ([`SqlRenderer::dialect_name`]), and a dialect spells the ones written for
319/// it and passes over the rest. Nothing in Razeri reads an engine's name to
320/// decide which settings apply.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322#[non_exhaustive]
323pub struct EngineSetting<'a> {
324    /// The engine the setting was written for, as its dialect names itself.
325    pub engine: &'a str,
326    /// The setting's name, in the engine's own words.
327    pub name: &'a str,
328    /// Its value, as the engine writes it.
329    pub value: &'a str,
330}
331
332impl<'a> EngineSetting<'a> {
333    /// One setting.
334    #[must_use]
335    pub const fn new(engine: &'a str, name: &'a str, value: &'a str) -> Self {
336        Self { engine, name, value }
337    }
338}
339
340/// **How the lines of a delimited file end.**
341///
342/// Measured, never assumed: [`LineEnding::of`] reads it off the file's own
343/// bytes, and a file with no line break at all reads as [`LineEnding::Lf`],
344/// which is what every engine reads by default.
345#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
346pub enum LineEnding {
347    /// A newline alone, `\n`: every system but Windows.
348    #[default]
349    Lf,
350    /// A carriage return and then a newline, `\r\n`: a file written on
351    /// Windows.
352    CrLf,
353}
354
355impl LineEnding {
356    /// **How the lines of this text end**, decided by its first line break.
357    ///
358    /// The first break ends the header row, so it is written the way the rest
359    /// of the file is. Text with no newline at all is [`LineEnding::Lf`].
360    #[must_use]
361    pub fn of(text: &[u8]) -> Self {
362        match text.iter().position(|&byte| byte == b'\n') {
363            Some(at) if at > 0 && text[at - 1] == b'\r' => Self::CrLf,
364            _ => Self::Lf,
365        }
366    }
367
368    /// The ending's characters, as they stand in the file.
369    #[must_use]
370    pub const fn as_str(self) -> &'static str {
371        match self {
372            Self::Lf => "\n",
373            Self::CrLf => "\r\n",
374        }
375    }
376
377    /// The ending spelled with backslashes, `\n` or `\r\n`: the two or four
378    /// characters an engine that reads backslash escapes in a string literal
379    /// takes for it. Put it inside the quotes of a record delimiter, on an
380    /// engine that reads them that way.
381    #[must_use]
382    pub const fn escaped(self) -> &'static str {
383        match self {
384            Self::Lf => "\\n",
385            Self::CrLf => "\\r\\n",
386        }
387    }
388}
389
390/// **What a table's `CREATE TABLE` is about to say** — what
391/// [`SqlRenderer::render_table_suffix`] is handed to decide the clause after
392/// the column list.
393///
394/// One struct rather than several arguments, so the slot can learn more about a
395/// table without changing its signature. Razeri builds it; a dialect reads it.
396/// A dialect's own tests build one with [`TableSuffixRequest::new`] and the
397/// `with_` methods, which is also why it cannot be written out field by field
398/// outside this crate.
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400#[non_exhaustive]
401pub struct TableSuffixRequest<'a> {
402    /// Whether the table is dropped at the end of its session, its transaction
403    /// or its batch. A transient table that outlives its session is not
404    /// temporary.
405    pub temporary: bool,
406    /// The table's primary-key columns in key order, unquoted. Empty on a table
407    /// with no primary key.
408    pub primary_key: &'a [String],
409    /// The columns the design's storage plan asked this table be clustered
410    /// by, unquoted, and only those this table has. Empty on most tables.
411    pub clustering_columns: &'a [String],
412    /// The column whose greatest value survives when rows share a key, on the
413    /// one table Razeri versions that way: the target of an engine whose
414    /// [`MergeShape`](crate::MergeShape) is
415    /// [`InsertDedup`](crate::InsertDedup). `None` on every other table.
416    pub version_column: Option<&'a str>,
417}
418
419impl<'a> TableSuffixRequest<'a> {
420    /// A persistent table with no primary key, no clustering columns and no
421    /// version column.
422    #[must_use]
423    pub const fn new() -> Self {
424        Self { temporary: false, primary_key: &[], clustering_columns: &[], version_column: None }
425    }
426
427    /// The same table, temporary or not.
428    #[must_use]
429    pub const fn with_temporary(mut self, temporary: bool) -> Self {
430        self.temporary = temporary;
431        self
432    }
433
434    /// The same table, with these primary-key columns.
435    #[must_use]
436    pub const fn with_primary_key(mut self, columns: &'a [String]) -> Self {
437        self.primary_key = columns;
438        self
439    }
440
441    /// The same table, with these clustering columns.
442    #[must_use]
443    pub const fn with_clustering_columns(mut self, columns: &'a [String]) -> Self {
444        self.clustering_columns = columns;
445        self
446    }
447
448    /// The same table, with this version column.
449    #[must_use]
450    pub const fn with_version_column(mut self, column: Option<&'a str>) -> Self {
451        self.version_column = column;
452        self
453    }
454}
455
456impl Default for TableSuffixRequest<'_> {
457    fn default() -> Self {
458        Self::new()
459    }
460}
461
462/// Level 1 — Core SQL rendering. REQUIRED: every dialect must implement these 4 methods.
463///
464/// These methods define the absolute minimum surface for rendering SQL:
465/// data types, identifier quoting, qualified names, and timestamps.
466pub trait SqlRenderer: Send + Sync {
467    /// Render a [`DataType`] as platform-specific SQL.
468    fn render_data_type(&self, dt: &DataType) -> String;
469
470    /// **The type text for a routine's PARAMETER**, which is not always the text
471    /// a column carries.
472    ///
473    /// Most engines spell a type one way wherever it appears, and for those this
474    /// hook is [`Self::render_data_type`] under another name — which is the
475    /// default, so a dialect with nothing to say says nothing.
476    ///
477    /// **Oracle is the reason it exists.** A column there takes
478    /// `NUMBER(19, 0)` and `VARCHAR2(100)`; the same types in a parameter list
479    /// are a compile error (`PLS-00103`, reported at the opening parenthesis),
480    /// and the bare `NUMBER` and `VARCHAR2` are what a parameter clause takes.
481    /// The length and the precision belong on the local declaration instead,
482    /// which keeps them. A dialect there answers:
483    ///
484    /// ```rust,ignore
485    /// fn render_parameter_data_type(&self, dt: &DataType) -> String {
486    ///     let column = self.render_data_type(dt);
487    ///     match column.find('(') {
488    ///         Some(at) => column[..at].trim_end().to_owned(),
489    ///         None => column,
490    ///     }
491    /// }
492    /// ```
493    ///
494    /// It is what fills
495    /// [`RoutineParameter::data_type`](crate::routine_spec::RoutineParameter::data_type),
496    /// so a dialect that answers it does not also post-process the string
497    /// Razeri handed it.
498    ///
499    /// Parameters:
500    /// - `dt`: the type the design declared.
501    fn render_parameter_data_type(&self, dt: &DataType) -> String {
502        self.render_data_type(dt)
503    }
504
505    /// **The type text for a column that ADMITS NULL** — the whole type, not a
506    /// modifier appended to one.
507    ///
508    /// Most engines spell nullability by SILENCE: a column declared without
509    /// `NOT NULL` admits one, and its type text is the same text a required
510    /// column carries. That is the default here, and for those engines this
511    /// hook is [`SqlRenderer::render_data_type`] under another name.
512    ///
513    /// **`ClickHouse` is the exception, and it is the reason this hook exists.**
514    /// There a bare type is NOT NULL — nullability is a property OF the type,
515    /// spelled `Nullable(T)` — so a renderer that expresses *nullable* by
516    /// omitting a keyword expresses nothing at all, and every `nullable:` a
517    /// design declares is discarded on that engine.
518    ///
519    /// # What a discarded `nullable:` costs, measured rather than assumed
520    ///
521    /// Not a loud refusal. `insert_null_as_default` **defaults to `1`** on
522    /// `ClickHouse` (24.10.2, server default, `changed = 0`), so
523    /// `INSERT … SELECT NULL` into a bare column does not raise — it writes the
524    /// TYPE'S DEFAULT, silently: `''` for `String`, `0` for `Int64`,
525    /// `1900-01-01` for `Date32` (which is razeri's own unknown-member date, so
526    /// an unknown attribute comes back indistinguishable from a deliberately
527    /// seeded one). Only with `insert_null_as_default = 0` does the engine
528    /// answer `Code: 70 … Cannot convert NULL to a non-nullable type`. **A
529    /// design's own data would be fabricated on that engine and honest on
530    /// every other**, and the DDL is where that is prevented.
531    ///
532    /// # A dialect overriding this owes a measurement
533    ///
534    /// Not every type can be wrapped. `ClickHouse` refuses
535    /// `Nullable(Array(…))`, `Nullable(Map(…))` and `Nullable(JSON)` outright,
536    /// so its override declines those and says so in its own rustdoc. A
537    /// wrapper that cannot be applied must be DECLINED by name, never applied
538    /// and hoped for: an unwrappable type rendered `Nullable(…)` turns a silent
539    /// wrong value into a `CREATE TABLE` that does not run.
540    fn render_nullable_data_type(&self, dt: &DataType) -> String {
541        self.render_data_type(dt)
542    }
543
544    /// **A comment, written as this engine reads one.**
545    ///
546    /// Every comment Razeri writes into a script goes through here: the note
547    /// over a statement, the heading of each part of a load, the banner at the
548    /// top of a file. The default is [`crate::comment::block_comment`], `/* … */`,
549    /// which closes itself, so a script whose line endings a tool turns into
550    /// spaces still runs. A line comment, `-- …`, would turn every statement
551    /// after it into comment.
552    ///
553    /// Override it only for an engine that cannot read a block comment, and
554    /// say which in the override's own doc comment. No engine Razeri carries
555    /// does: each of them reads `/* … */`. What comes back stands on lines of
556    /// its own; Razeri indents it with the statement it describes.
557    ///
558    /// Parameters:
559    /// - `text`: the comment's words, one or more lines, with no comment marks.
560    fn render_comment(&self, text: &str) -> String {
561        crate::comment::block_comment(text)
562    }
563
564    /// Quote an identifier using platform conventions.
565    ///
566    /// `PostgreSQL`: `"name"`, `MySQL`: `` `name` ``, SQL Server: `[name]`
567    fn quote_identifier(&self, name: &str) -> String;
568
569    /// Render a fully qualified name (optional schema + name).
570    fn qualify_name(&self, schema: Option<&str>, name: &str) -> String;
571
572    /// Whether this dialect uses schemas in qualified names.
573    ///
574    /// `ClickHouse` uses only `database.object` (no schema level).
575    /// Default: `true` (most platforms use `catalog.schema.object`).
576    fn uses_schema_in_qualified_names(&self) -> bool {
577        true
578    }
579
580    /// **The name an object takes on an engine with no schemas**, where this
581    /// dialect keeps a design's layers apart by folding the schema into it —
582    /// `sales_raw` and `customers` become `sales_raw_customers` — or `None`,
583    /// the default, where the schema is dropped.
584    ///
585    /// It is asked only of a dialect whose
586    /// [`DialectCapabilities::supports_schemas`](crate::DialectCapabilities::supports_schemas)
587    /// is `false`. With `None`, every object of every layer lives under its
588    /// own bare name, so a design whose Raw and Core layers both hold a
589    /// `customers` is refused: each load would write over the other's rows.
590    /// Answer with a fold and Razeri keeps each object's schema and writes
591    /// what this returns wherever it names the object — its `CREATE`, every
592    /// statement that reads or writes it, every reference to it — so the same
593    /// design renders, and two objects are refused only where their folded
594    /// names are the same.
595    ///
596    /// Return the name unquoted; Razeri quotes it with
597    /// [`Self::quote_identifier`]. [`Self::qualify_name`] given a schema has
598    /// to answer the same object, quoted, because some statements are named
599    /// through it; the conformance report checks that the two agree.
600    fn fold_schema_into_name(&self, schema: &str, name: &str) -> Option<String> {
601        let _ = (schema, name);
602        None
603    }
604
605    /// Whether this dialect is the "agnostic" pseudo-dialect.
606    ///
607    /// Agnostic rendering produces unquoted, platform-neutral DDL.
608    /// Real dialect implementations should not override this.
609    fn is_agnostic_dialect(&self) -> bool {
610        false
611    }
612
613    /// Whether this dialect supports `SECURE VIEW` (Snowflake).
614    fn supports_secure_view(&self) -> bool {
615        false
616    }
617
618    /// Whether this dialect supports `GLOBAL TEMPORARY VIEW` (Databricks).
619    fn supports_global_temporary_view(&self) -> bool {
620        false
621    }
622
623    /// Render the platform's `CURRENT_TIMESTAMP` expression.
624    fn render_current_timestamp(&self) -> String;
625
626    /// **The schemas a catalog scan passes over** — the engine's own
627    /// bookkeeping, never a warehouse's contents.
628    ///
629    /// Read by [`Self::render_catalog_columns_query`] and
630    /// [`Self::render_catalog_object_times_query`] when no single schema was
631    /// named, so a scan of a whole warehouse sees the tables somebody created
632    /// and not the catalog describing them. The default names the one schema
633    /// the SQL standard puts the catalog in; an engine that keeps more of its
634    /// own next to it adds them.
635    fn catalog_system_schemas(&self) -> &'static [&'static str] {
636        &["information_schema"]
637    }
638
639    /// **The query that lists what the warehouse holds** — one row per column,
640    /// as `(schema, object, column)`.
641    ///
642    /// Razeri asks it to answer a question it cannot answer from a design: how
643    /// much of this warehouse razeri itself rendered. Columns rather than
644    /// object names alone, because the answer is read off both — a name carries
645    /// the tier razeri mints (`…_staging`, `…_current`), and a column carries
646    /// the bookkeeping only razeri writes (`…_sid`, `_loaded_at`). A scan that
647    /// saw names alone would either miss an entity whose target table is a
648    /// plain noun or count a table razeri never touched.
649    ///
650    /// The three columns are positional and in that order: every caller reads
651    /// row `0`, `1`, `2` and nothing reads a column by name, so an engine whose
652    /// catalog spells the headings differently needs no special case.
653    ///
654    /// `None` means **this engine states no catalog razeri can scan**, which is
655    /// an answer rather than an omission: the caller says so by name instead of
656    /// reporting an empty warehouse.
657    ///
658    /// Parameters:
659    /// - `schema`: the one schema to look in. `None` means the whole warehouse,
660    ///   minus [`Self::catalog_system_schemas`].
661    fn render_catalog_columns_query(&self, schema: Option<&str>) -> Option<String> {
662        Some(format!(
663            "SELECT table_schema, table_name, column_name\nFROM \
664             information_schema.columns\n{}\nORDER BY table_schema, table_name, column_name",
665            self.catalog_scope_predicate("table_schema", schema)
666        ))
667    }
668
669    /// **The query that says when each object was created**, as
670    /// `(schema, object, created_at)` — where the engine records it at all.
671    ///
672    /// A second, independent reading of the same question
673    /// [`Self::render_catalog_columns_query`] opens: the earliest moment razeri
674    /// can prove it was here. It is a `None` on most engines, and deliberately
675    /// so — `PostgreSQL` and `DuckDB` keep no creation time for a relation, and
676    /// inventing one would be worse than having none.
677    ///
678    /// Parameters:
679    /// - `schema`: the one schema to look in, or `None` for the whole
680    ///   warehouse.
681    fn render_catalog_object_times_query(&self, schema: Option<&str>) -> Option<String> {
682        let _ = schema;
683        None
684    }
685
686    /// The `WHERE` clause both catalog queries share: one named schema, or
687    /// every schema that is not the engine's own.
688    ///
689    /// Parameters:
690    /// - `column`: the catalog's own name for the schema column.
691    /// - `schema`: the one schema to look in, or `None` for the whole
692    ///   warehouse.
693    fn catalog_scope_predicate(&self, column: &str, schema: Option<&str>) -> String {
694        if let Some(one) = schema {
695            return format!("WHERE {column} = '{}'", one.replace('\'', "''"));
696        }
697        let excluded: Vec<String> = self
698            .catalog_system_schemas()
699            .iter()
700            .map(|name| format!("'{}'", name.replace('\'', "''")))
701            .collect();
702        format!("WHERE {column} NOT IN ({})", excluded.join(", "))
703    }
704
705    /// Return a stable string identifier for this dialect.
706    ///
707    /// A human-readable label in diagnostics and error messages, for **every
708    /// dialect** registered in the `PlatformRegistry` (e.g. `"postgresql"`,
709    /// `"sqlite"`, `"cockroachdb"`). For the engines Razeri ships, two
710    /// renderings are chosen by this name rather than asked of a trait method —
711    /// a bulk load's statement and a query's own syntax. Any other name gets
712    /// the generic form: the bulk load in ANSI, the query spelled through your
713    /// renderer. Keep it stable once a dialect is published.
714    ///
715    /// Convention: lowercase, hyphen-separated (e.g. `"postgresql"`,
716    /// `"sql-server"`, `"snowflake"`, `"sqlite"`).
717    ///
718    /// The default returns `"ansi"`.
719    fn dialect_name(&self) -> &'static str {
720        "ansi"
721    }
722
723    /// **How this engine spells a surrogate key.**
724    ///
725    /// Razeri derives every key one way — cast each part to text, escape and
726    /// join the parts of a composite, hash the result, guard NULLs with a
727    /// sentinel — and composes that derivation in exactly one place
728    /// ([`crate::sid`]). What a dialect decides is the *vocabulary*: how this
729    /// engine writes a replacement and a Unicode literal, how it joins
730    /// strings, how it casts a value to text, and how it spells a 64-bit hash.
731    ///
732    /// The default is [`UNSPELLED_SID`] — ANSI's vocabulary under a name that
733    /// says it is a guess. **A dialect that leaves it there is telling Razeri it
734    /// has not decided**, and the emitted SQL will call an `xxhash64` its engine
735    /// very likely does not have. Override it.
736    ///
737    /// If your engine has no portable 64-bit hash, say so rather than reaching
738    /// for the nearest-looking function: a hash that is deterministic within one
739    /// warehouse and equal to nothing outside it is the lock-in a portable key
740    /// exists to end. Name an artifact your dialect's prerequisites install, or
741    /// refuse the key and orient the reader.
742    fn sid_spelling(&self) -> SidSpelling {
743        UNSPELLED_SID
744    }
745
746    /// **The body of the surrogate-key helper, where SQL cannot spell it.**
747    ///
748    /// Razeri emits one function per warehouse — `generate_sid` — and normally
749    /// builds its body itself, from the vocabulary
750    /// [`sid_spelling`](Self::sid_spelling) states. The default here is `None`,
751    /// which says exactly that: *compose the derivation in my own SQL*.
752    ///
753    /// Answer with [`SidHelperBody`] only when there is no SQL that could hold
754    /// the derivation — the engine has no 64-bit hash under any name, so the
755    /// vocabulary has nothing to spell the hash with and the definition has to
756    /// be written in another language. `BigQuery` is the case Razeri ships:
757    /// `GoogleSQL` has no XXH64, and the function that looks like the answer
758    /// (`FARM_FINGERPRINT`) is a different number, so the body is JavaScript.
759    ///
760    /// **Do not use this to change the key.** The body computes the same number
761    /// every other engine computes — XXH64, seed 0, over the UTF-8 bytes of the
762    /// one argument, as given — and [`SidHelperBody`] says what it owes
763    /// in full. Reaching for a native hash that is merely deterministic keys a
764    /// warehouse to numbers nothing outside it can reproduce.
765    ///
766    /// A dialect that answers here should also state a
767    /// [`SidSpelling::hash`](crate::SidSpelling::hash) that no engine has, so
768    /// that any path which fell back to composing SQL fails loudly at deploy
769    /// time rather than hashing nothing and handing back the value.
770    fn sid_helper_body(&self) -> Option<SidHelperBody> {
771        None
772    }
773
774    /// **How this engine reads a delimited text file as a relation**, or `None`
775    /// where it cannot.
776    ///
777    /// A design can bind an entity to a source file, and Razeri then generates
778    /// the staging fill: an `INSERT … SELECT … FROM <this>`. That only works on
779    /// an engine that can open a file from inside a query. `DuckDB` can
780    /// (`read_csv_auto`); most cannot — `PostgreSQL` wants `COPY`, Snowflake a
781    /// stage, `SQLite` has nothing at all. Each of those is a bulk-load design
782    /// decision rather than a rendering detail, so the default is `None` and
783    /// the generated bundle says which platform declined and why instead of
784    /// emitting SQL the engine would refuse.
785    ///
786    /// `path_literal` arrives as a finished single-quoted SQL string literal,
787    /// already escaped — put it where the relation takes a path and do not
788    /// quote it again.
789    ///
790    /// **What the returned relation owes**, because the fill is written against
791    /// it and nothing checks these at render time:
792    ///
793    /// - the file's first row is its header, and the column names come from it,
794    ///   spelled exactly as the file spells them;
795    /// - every column reads as **text**, unparsed. The fill casts nothing: a
796    ///   date's layout and a currency's prefix are the source's business, and a
797    ///   reader that guessed a type would fail the load on its first row;
798    /// - it is a relation usable in a `FROM` clause, not a statement.
799    ///
800    /// The path is embedded in the generated file as it was spelled when the
801    /// bundle was built, so it must be one the engine resolves at run time.
802    fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
803        let _ = path_literal;
804        None
805    }
806
807    /// **How this engine reads a delimited text file as a relation, told
808    /// everything Razeri knows about the file** — or `None` where it cannot.
809    ///
810    /// The richer spelling of
811    /// [`delimited_file_relation`](Self::delimited_file_relation), and the one
812    /// the staging fill asks. The default hands the path to that method — or,
813    /// for a file in a named [`encoding`](DelimitedFile::encoding), to
814    /// [`delimited_file_relation_in_encoding`](Self::delimited_file_relation_in_encoding)
815    /// — so a dialect that has stated those has stated this too, and its
816    /// renders are byte for byte what they were.
817    ///
818    /// **The default reads only a plain file** ([`DelimitedFile::is_plain`]):
819    /// split on commas, quoted with `"`, and headed. Neither method it hands
820    /// over to can be told a delimiter, a quote or a missing header, so for
821    /// any other file it answers `None`, and Razeri declines that file by name
822    /// rather than reading a pipe-delimited file as one column. Override this
823    /// method to read the others: put the file's
824    /// [`delimiter`](DelimitedFile::delimiter),
825    /// [`quote`](DelimitedFile::quote) and [`header`](DelimitedFile::header)
826    /// where your engine's read takes them, and answer `None` for one it
827    /// cannot be told.
828    ///
829    /// Override it, too, where the path alone is not enough. Two engines' file
830    /// reads need more and cannot be given it any other way:
831    ///
832    /// - **the file's columns declared in the statement.** Oracle's external
833    ///   table answers `ORA-00906: missing left parenthesis` without them, and
834    ///   has no form that takes its column names from a header row;
835    /// - **a directory rather than a path.** The same engine answers
836    ///   `KUP-04125: no directory object specified for location 1 in LOCATION
837    ///   clause` to an absolute path, and resolves a file name against a named
838    ///   directory object instead — which
839    ///   [`delimited_file_prerequisites`](Self::delimited_file_prerequisites)
840    ///   is where such an object is made.
841    ///
842    /// Everything the returned relation owes, it owes for the reasons
843    /// [`delimited_file_relation`](Self::delimited_file_relation) states:
844    /// header from the first row, every column as text and unparsed, usable in
845    /// a `FROM` clause. **Declaring the columns does not license declaring
846    /// their types**: they are the source's text, and a reader that guessed
847    /// would fail the load on its first row.
848    fn delimited_file_relation_for(&self, file: &DelimitedFile<'_>) -> Option<String> {
849        if !file.is_plain() {
850            return None;
851        }
852        match file.encoding {
853            None => self.delimited_file_relation(file.path_literal),
854            Some(encoding) => self.delimited_file_relation_in_encoding(file.path_literal, encoding),
855        }
856    }
857
858    /// **How this engine reads a parquet file as a relation of text** — or
859    /// `None` where it cannot, which is the default.
860    ///
861    /// The relation owes what a delimited file's does: the file's own column
862    /// names, every column as **text**, usable in a `FROM` clause. A parquet
863    /// file carries its types, and the fill still reads each value as text so
864    /// that one set of conversions, cleanings and checks serves every file;
865    /// the text is the engine's own cast of each value (`2024-01-01 00:57:55`
866    /// for a timestamp, `2.0` for a whole double), which is also the text
867    /// Razeri counts and totals the file by before a build.
868    ///
869    /// `path_literal` arrives as a finished single-quoted SQL string literal,
870    /// already escaped. An engine that answers `None` has its parquet sources
871    /// declined by name, with the conversion that would load them.
872    fn parquet_file_relation(&self, path_literal: &str) -> Option<String> {
873        let _ = path_literal;
874        None
875    }
876
877    /// **Statements this engine needs run once before any of its file relations
878    /// resolve**, in order — and none by default.
879    ///
880    /// An engine that opens a path needs nothing here. An engine that opens a
881    /// file only through an object somebody made — Oracle's `DIRECTORY` — needs
882    /// that object made first, and the generated staging file is where it
883    /// belongs: it is the one file that knows which directory the sources were
884    /// read from.
885    ///
886    /// Each string is one statement without its terminator. Every one must be
887    /// safe to run again, because the file it lands in runs on every deploy.
888    ///
889    /// `directory_literal` arrives as a finished single-quoted SQL string
890    /// literal, already escaped.
891    ///
892    /// **Say what the statement costs.** An object like this is often
893    /// privileged, and a statement an operator cannot run is better read than
894    /// guessed at — put the privilege in a comment inside the statement, where
895    /// it travels with it.
896    fn delimited_file_prerequisites(&self, directory_literal: &str) -> Vec<String> {
897        let _ = directory_literal;
898        Vec::new()
899    }
900
901    /// **Statements this engine needs run before it can read THIS file**, in
902    /// order — and none by default.
903    ///
904    /// The per-file companion of
905    /// [`delimited_file_prerequisites`](Self::delimited_file_prerequisites),
906    /// and the slot an engine with no file relation at all reads a file
907    /// through. Where that method makes what every read shares — a directory
908    /// object, a permitted path — this one makes what belongs to one file, and
909    /// the staging fill emits it directly in front of the fill that reads it.
910    ///
911    /// Two kinds of engine answer it.
912    ///
913    /// - One whose file read is a **statement rather than a relation**. SAP
914    ///   HANA's is `IMPORT FROM CSV FILE`, which writes into a table that
915    ///   already exists; there is nothing to put in a `FROM` clause. Such a
916    ///   dialect lands the file's rows in a table here and answers that table
917    ///   from
918    ///   [`delimited_file_relation_for`](Self::delimited_file_relation_for).
919    /// - One whose relation needs a per-file object made first — a format, an
920    ///   external stage, a descriptor.
921    ///
922    /// Each string is one statement without its terminator. **Every one must be
923    /// safe to run again**, because the file it lands in runs on every deploy,
924    /// and safe to run beside the others: a second deploy stages what the
925    /// source holds now rather than adding a second copy of it.
926    ///
927    /// **Say what the statement costs.** A read like this is often privileged,
928    /// and a statement an operator cannot run is better read than guessed at —
929    /// put the privilege in a comment inside the statement, where it travels
930    /// with it.
931    fn delimited_file_statements_for(&self, file: &DelimitedFile<'_>) -> Vec<String> {
932        let _ = file;
933        Vec::new()
934    }
935
936    /// **The one-row table a query reads when it has nothing else to read**,
937    /// or `None` on an engine that takes a `SELECT` with no `FROM` at all.
938    ///
939    /// Some of what Razeri measures is a value rather than a row of a table —
940    /// the grand total a reconciliation compares against its sources is a sum
941    /// of counts, and there is nothing to select it from. Most engines take
942    /// `SELECT <value>` as it stands. SAP HANA refuses it at the next word and
943    /// wants `FROM DUMMY`, the one-row table it keeps for exactly this; Oracle
944    /// kept `DUAL` for the same reason until it began accepting the bare form.
945    ///
946    /// Answer the table's name, as a query would write it after `FROM`. Every
947    /// engine that answers `None` renders exactly what it rendered before.
948    fn render_one_row_source(&self) -> Option<String> {
949        None
950    }
951
952    /// **How this engine reads a delimited text file whose bytes are not
953    /// UTF-8**, or `None` where it states no way to.
954    ///
955    /// UTF-8 is the canonical form and every engine reads it, so
956    /// [`delimited_file_relation`](Self::delimited_file_relation) answers for
957    /// it and this is asked only about the other days. A design can name the
958    /// encoding to fall back to when a file's bytes are not UTF-8, and razeri
959    /// resolves that name once, to the one name the encoding standard files it
960    /// under — `windows-1252`, `shift_jis`, `koi8-r`. That name arrives here,
961    /// and an engine that has its own word for the same encoding translates it
962    /// the way an engine translates every other name razeri hands it.
963    ///
964    /// Everything the returned relation owes, it owes for the same reasons
965    /// [`delimited_file_relation`](Self::delimited_file_relation) says: header
966    /// from the first row, every column as text, usable in a `FROM` clause.
967    ///
968    /// **`None` is a complete answer, and the common one.** An engine that
969    /// reads no file at all says nothing here; so does an engine that reads
970    /// files but has no word for this particular encoding. Razeri then declines
971    /// that source by name and says what to do instead — convert the file to
972    /// UTF-8, or write the load by hand — rather than pointing the engine at
973    /// bytes it will read as some other language.
974    ///
975    /// **Answer only for encodings you have run.** An engine that accepts the
976    /// name and reads the bytes as something else is worse than one that
977    /// refuses the name: the first is a warehouse of plausible nonsense and the
978    /// second is a sentence on a terminal.
979    ///
980    /// **Razeri asks it two ways.** First with a path of `''`, to learn
981    /// whether your engine has a word for the encoding at all; a file it has
982    /// none for is declined there. Then the read itself goes through
983    /// [`delimited_file_relation_for`](Self::delimited_file_relation_for)
984    /// with the file's [`encoding`](DelimitedFile::encoding) set, whose
985    /// default hands a plain file back here.
986    ///
987    /// `path_literal` arrives as a finished single-quoted SQL string literal,
988    /// already escaped — put it where the relation takes a path and do not
989    /// quote it again. `encoding` does not: it is a bare name, and an engine
990    /// that puts it in a string literal writes the quotes itself.
991    fn delimited_file_relation_in_encoding(
992        &self,
993        path_literal: &str,
994        encoding: &str,
995    ) -> Option<String> {
996        let _ = (path_literal, encoding);
997        None
998    }
999
1000    /// **The `CAST` target spelling for a [`DataType`] on this engine.**
1001    ///
1002    /// A column declaration and a `CAST` target are two grammars on most
1003    /// engines, so this is a separate answer from
1004    /// [`render_data_type`](Self::render_data_type) and not a synonym for it.
1005    /// `MySQL` takes `SIGNED` where it declares `BIGINT`; T-SQL takes
1006    /// `NVARCHAR(MAX)` where ANSI says `TEXT`.
1007    ///
1008    /// Where the two *are* the same on your engine — which is the common case
1009    /// on engines with one type vocabulary — say so by delegating:
1010    ///
1011    /// ```rust,ignore
1012    /// fn render_cast_type(&self, dt: &DataType) -> String {
1013    ///     self.render_data_type(dt)
1014    /// }
1015    /// ```
1016    ///
1017    /// The default is ANSI's cast vocabulary. Razeri's generated load opens
1018    /// with a CTE that casts every source column to its declared type, so a
1019    /// wrong name here fails the load on its first statement.
1020    fn render_cast_type(&self, dt: &DataType) -> String {
1021        crate::agnostic::render_cast_type_ansi(dt)
1022    }
1023
1024    /// **Which stored-procedure grammar this engine speaks.**
1025    ///
1026    /// Razeri composes the procedure — its parameters, its steps, its comment —
1027    /// and spells it in the form this returns. The default is
1028    /// [`ProcedureForm::Agnostic`], which parses on no engine: it is the honest
1029    /// answer for a dialect that has not said, and it is what an unlisted
1030    /// platform has always been handed.
1031    ///
1032    /// It lives on `SqlRenderer` rather than on
1033    /// [`ProcedureRenderer`] because the composer
1034    /// holds the renderer as a [`DdlRenderer`], and a decision reachable only
1035    /// through a trait the caller does not hold is a decision the caller makes
1036    /// instead.
1037    fn procedure_form(&self) -> ProcedureForm {
1038        ProcedureForm::Agnostic
1039    }
1040
1041    /// **Which scalar-function grammar this engine speaks.**
1042    ///
1043    /// The default is [`ScalarFunctionForm::PostgreSql`] — what an unlisted
1044    /// dialect has always been handed, and a dangerous inheritance on a near
1045    /// neighbour: `LANGUAGE SQL IMMUTABLE PARALLEL SAFE` is a *"syntax error at
1046    /// or near `PARALLEL`"* on an engine that descends from `PostgreSQL` and
1047    /// reports itself as one.
1048    fn scalar_function_form(&self) -> ScalarFunctionForm {
1049        ScalarFunctionForm::PostgreSql
1050    }
1051
1052    /// **Which of Razeri's bulk-load grammars this engine speaks**, or `None`
1053    /// where it speaks none of them.
1054    ///
1055    /// The bulk-load builder writes its statement in the form named here. The
1056    /// default is `None`, and the builder then writes Razeri's own annotated
1057    /// form, which no engine runs: name a form only where your engine takes
1058    /// that statement as written.
1059    fn bulk_load_form(&self) -> Option<BulkLoadForm> {
1060        None
1061    }
1062
1063    /// **The clause a view's settings are written in**, between its name and
1064    /// `AS` — `PostgreSQL`'s `WITH (security_barrier = true)` — or `None` where
1065    /// none of `settings` is this engine's, which is the default.
1066    ///
1067    /// See [`EngineSetting`]: spell the settings written for your engine and
1068    /// pass over the rest.
1069    fn render_view_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
1070        let _ = settings;
1071        None
1072    }
1073
1074    /// **The words a join's settings are written in**, in front of its join
1075    /// keyword — `ClickHouse`'s `GLOBAL ANY` — or `None` where none of
1076    /// `settings` is this engine's, which is the default.
1077    fn render_join_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
1078        let _ = settings;
1079        None
1080    }
1081
1082    /// **Which table-valued-function grammar this engine speaks, and — where it
1083    /// has none — the words it refuses in.**
1084    ///
1085    /// The default is [`TableFunctionForm::PostgreSql`], what an unlisted
1086    /// dialect has always been handed. If your engine has no routine a query
1087    /// selects `FROM`, answer [`TableFunctionForm::Unsupported`] with your own
1088    /// sentence: Razeri then declines to build the routine at all and prints
1089    /// **your** words rather than another engine's. A refusal written once per
1090    /// artifact kind tells every author about whichever engine happened to need
1091    /// it first, and the near form an author will otherwise find on their own
1092    /// is exactly what costs them a day.
1093    fn table_function_form(&self) -> TableFunctionForm {
1094        TableFunctionForm::PostgreSql
1095    }
1096
1097    // ═══════════════════════════════════════════════════════════════
1098    // Routines this dialect spells itself
1099    // ═══════════════════════════════════════════════════════════════
1100
1101    /// **Spell a whole stored procedure in this engine's own grammar** — the
1102    /// method [`ProcedureForm::Custom`] promises.
1103    ///
1104    /// Razeri composes the routine and hands it over as a [`RoutineSpec`]: the
1105    /// name, the parameters with their types already in your spelling, the
1106    /// declarations, the body's statements, the comment. What comes back is the
1107    /// complete `CREATE`, punctuation and all, and Razeri emits it unchanged.
1108    ///
1109    /// The default is `None`, which means *"I did not write one"*. It is only
1110    /// ever reached by a dialect that answered
1111    /// [`ProcedureForm::Custom`] and then did not override this — the
1112    /// conformance kit reports that as blocking, and the emitted SQL carries a
1113    /// comment saying the same thing where the procedure would have been.
1114    ///
1115    /// It lives on `SqlRenderer` rather than on [`ProcedureRenderer`] for the
1116    /// reason [`Self::procedure_form`] does: the composer holds the renderer as
1117    /// a [`DdlRenderer`], and an answer reachable only through a trait the
1118    /// caller does not hold is an answer the caller makes up instead.
1119    ///
1120    /// Parameters:
1121    /// - `routine`: the procedure Razeri composed.
1122    fn render_procedure(&self, routine: &RoutineSpec) -> Option<String> {
1123        let _ = routine;
1124        None
1125    }
1126
1127    /// **Spell a whole scalar function in this engine's own grammar** — the
1128    /// method [`ScalarFunctionForm::Custom`] promises.
1129    ///
1130    /// The same contract as [`Self::render_procedure`]: a composed
1131    /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
1132    /// dialect claimed a custom grammar and did not write the method.
1133    ///
1134    /// Parameters:
1135    /// - `routine`: the function Razeri composed.
1136    fn render_scalar_function(&self, routine: &RoutineSpec) -> Option<String> {
1137        let _ = routine;
1138        None
1139    }
1140
1141    /// **Spell a whole table-valued function in this engine's own grammar** —
1142    /// the method [`TableFunctionForm::Custom`] promises.
1143    ///
1144    /// The same contract as [`Self::render_procedure`]: a composed
1145    /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
1146    /// dialect claimed a custom grammar and did not write the method.
1147    ///
1148    /// Parameters:
1149    /// - `routine`: the function Razeri composed.
1150    fn render_table_function(&self, routine: &RoutineSpec) -> Option<String> {
1151        let _ = routine;
1152        None
1153    }
1154
1155    // ═══════════════════════════════════════════════════════════════
1156    // Expression rendering extensions
1157    // ═══════════════════════════════════════════════════════════════
1158
1159    /// Platform's `CURRENT_DATE` expression.
1160    ///
1161    /// `SqlServer`: `CAST(GETDATE() AS DATE)`, `ClickHouse`: `today()`, others: `CURRENT_DATE`
1162    fn render_current_date(&self) -> String {
1163        "CURRENT_DATE".to_string()
1164    }
1165
1166    /// Render a boolean literal.
1167    ///
1168    /// SqlServer/ClickHouse: `1`/`0`, others: `TRUE`/`FALSE`
1169    fn render_boolean_literal(&self, value: bool) -> String {
1170        if value { "TRUE".to_string() } else { "FALSE".to_string() }
1171    }
1172
1173    /// **Collapse a subquery that selects AT MOST ONE ROW into an aggregate**,
1174    /// for the engines that will not accept an unaggregated correlated scalar.
1175    ///
1176    /// Razeri's SCD-2 and SCD-1 re-opens assign `col = (SELECT … WHERE
1177    /// {correlation})`. Databricks refuses that shape by name
1178    /// (`MUST_AGGREGATE_CORRELATED_SCALAR_SUBQUERY`) and Snowflake stopped
1179    /// unnesting it the day the guard beside it became uncorrelated, so the
1180    /// emission wraps the projection in an aggregate. **Which** aggregate is a
1181    /// dialect fact and **whether one exists at all** is a dialect × type fact,
1182    /// which is why this hook takes the kind and may answer `None`:
1183    ///
1184    /// - `MAX` is the obvious choice and is wrong for a BOOLEAN on two of the
1185    ///   platforms razeri reaches. Measured on the running
1186    ///   containers: `PostgreSQL` and Citus raise
1187    ///   *"function max(boolean) does not exist"*, SQL Server raises
1188    ///   *"Msg 8117: Operand data type bit is invalid for max operator"*, while
1189    ///   `MariaDB` (`MAX(TRUE)` → `1`) and `ClickHouse` (`max(true)` → `true`)
1190    ///   answer it happily;
1191    /// - `PostgreSQL` has no `max()` for `uuid`, `jsonb` or `bytea` either
1192    ///   (measured, same run), and SQL Server has one for both
1193    ///   `uniqueidentifier` and `varbinary` (measured).
1194    ///
1195    /// **`None` means *this dialect cannot aggregate this kind* and is not a
1196    /// failure.** The caller then emits the bare correlated scalar — the
1197    /// prior shape, measured green on the whole
1198    /// `PostgreSQL` family — and says so on the output, because that shape is
1199    /// the one Databricks refuses.
1200    ///
1201    /// **Correctness does not come from the aggregate's meaning.** The subquery
1202    /// is under a guard that is false for the entire load if any member
1203    /// disagrees with itself, so it selects one row; `MAX`, `BOOL_OR` and
1204    /// `BOOLOR_AGG` of one value are all that value. The choice between them is
1205    /// availability, not semantics.
1206    fn render_single_row_aggregate(
1207        &self,
1208        expression: &str,
1209        kind: AggregableKind,
1210    ) -> Option<String> {
1211        let _ = kind;
1212        Some(format!("MAX({expression})"))
1213    }
1214
1215    /// **Take any one value of `expression` from a group**, for the engines
1216    /// that cannot group on the column itself.
1217    ///
1218    /// A load collapses staged rows that repeat. Where the engine will not
1219    /// group on a nested column
1220    /// ([`crate::DialectCapabilities::groups_nested_values`]) the collapse
1221    /// groups on the remaining columns and takes one value of that one, which
1222    /// is what this renders.
1223    ///
1224    /// `ANY_VALUE` is the spelling `BigQuery`, Snowflake, Redshift, Databricks
1225    /// and `MySQL` all use, so it is the default; an engine that spells it
1226    /// differently, or reaches it through `FIRST`, says so here.
1227    ///
1228    /// Unlike [`Self::render_single_row_aggregate`] this one cannot decline:
1229    /// it is asked only where the dialect has already said it cannot group on
1230    /// the column, so there is no second shape to fall back to.
1231    ///
1232    /// Parameters:
1233    /// - `expression`: the column reference, already spelled by the renderer
1234    ///   that lays out the query.
1235    fn render_any_value(&self, expression: &str) -> String {
1236        format!("ANY_VALUE({expression})")
1237    }
1238
1239    /// **The AGGREGATE median this engine has for `expression`, or `None` when
1240    /// it has none.**
1241    ///
1242    /// Aggregate is the load-bearing word, and it is why this cannot be
1243    /// answered from a function-name table. Four spellings are in the wild:
1244    ///
1245    /// - a plain `median(x)` aggregate — `duckdb`, `clickhouse`, `snowflake`;
1246    /// - the SQL ordered-set aggregate
1247    ///   `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)` — `postgres` and its
1248    ///   family (measured on a running instance: it groups);
1249    /// - a two-argument `PERCENTILE(x, 0.5)` — `databricks`;
1250    /// - and a WINDOW function wearing one of those names, which is **not**
1251    ///   this. `mariadb` has `MEDIAN(x) OVER (…)` and `sqlserver` has
1252    ///   `PERCENTILE_CONT(…) OVER (…)`, and both are a syntax error in a
1253    ///   `GROUP BY` select list (measured: `MariaDB` raises `ERROR 1064` and
1254    ///   SQL Server raises *"Msg 10753: The function `PERCENTILE_CONT` must
1255    ///   have an OVER clause"*). A window function returns one value per ROW,
1256    ///   not one per group, so it is a different answer and not a fallback.
1257    ///
1258    /// **The default declines**, so a dialect that has never been asked the
1259    /// question is never assumed to have the answer, and a dialect added
1260    /// tomorrow opts in deliberately with a form somebody measured. The caller
1261    /// turns `None` into a build-time refusal naming the column and the target
1262    /// — razeri does not emit SQL its target cannot run.
1263    ///
1264    /// # Why a TEMPLATE rather than finished SQL
1265    ///
1266    /// The aggregated expression is a column reference, and how a column
1267    /// reference is spelled — quoted, bracketed, upper-cased — belongs to the
1268    /// renderer that lays out the query, not to this answer. Handing back a
1269    /// form with [`AGGREGATE_ARGUMENT`] where the expression goes keeps the
1270    /// two apart: this trait owns *which function*, the query renderer owns
1271    /// *how the column is written*, and neither has to reimplement the other.
1272    fn median_aggregate_form(&self) -> Option<&'static str> {
1273        None
1274    }
1275
1276    /// Render a date literal.
1277    ///
1278    /// `ClickHouse`: `toDate('2024-01-15')`, others: `DATE '2024-01-15'`
1279    fn render_date_literal(&self, date: &str) -> String {
1280        format!("DATE '{date}'")
1281    }
1282
1283    /// Render a timestamp literal.
1284    ///
1285    /// `ClickHouse`: `toDateTime('...')`, others: `TIMESTAMP '...'`
1286    fn render_timestamp_literal(&self, ts: &str) -> String {
1287        format!("TIMESTAMP '{ts}'")
1288    }
1289
1290    /// Render an interval literal.
1291    ///
1292    /// `SqlServer`: `'P1Y2M3D'`, `ClickHouse`: `INTERVAL 1 YEAR`, others: `INTERVAL '1 year'`
1293    fn render_interval_literal(&self, interval: &str) -> String {
1294        format!("INTERVAL '{interval}'")
1295    }
1296
1297    /// Render the string concatenation operator.
1298    ///
1299    /// `SqlServer`: `+`, others: `||`
1300    fn concat_operator(&self) -> &'static str {
1301        "||"
1302    }
1303
1304    /// Render a NaN literal for a floating-point type.
1305    ///
1306    /// `PostgreSQL`: `'NaN'::float`, others: `NULL`
1307    fn render_nan_literal(&self, _dt: &DataType) -> String {
1308        "NULL".to_string()
1309    }
1310
1311    /// Render an infinity literal for a floating-point type.
1312    ///
1313    /// `PostgreSQL`: `'Infinity'::float` / `'-Infinity'::float`, others: `NULL`
1314    fn render_infinity_literal(&self, _positive: bool, _dt: &DataType) -> String {
1315        "NULL".to_string()
1316    }
1317
1318    /// Render the NULL-coalescing function name.
1319    ///
1320    /// `SqlServer`: `ISNULL`, `ClickHouse`: `ifNull`, others: `COALESCE`
1321    fn ifnull_function_name(&self) -> &'static str {
1322        "COALESCE"
1323    }
1324
1325    /// Render an IIF expression (or CASE WHEN equivalent).
1326    ///
1327    /// `SqlServer`: `IIF(cond, then, else)`, others: `CASE WHEN cond THEN then ELSE else END`
1328    fn render_iif(&self, cond: &str, then_val: &str, else_val: &str) -> String {
1329        format!("CASE WHEN {cond} THEN {then_val} ELSE {else_val} END")
1330    }
1331
1332    /// Render a `DATE_TRUNC` expression.
1333    ///
1334    /// `SqlServer`: `DATETRUNC(field, expr)`, `ClickHouse`: `toStartOfMonth(expr)`, others: `DATE_TRUNC('field', expr)`
1335    fn render_date_trunc(&self, field: &str, expr: &str) -> String {
1336        format!("DATE_TRUNC('{field}', {expr})")
1337    }
1338
1339    /// **One part of a date or a timestamp, as a whole number.**
1340    ///
1341    /// A design's `date_part('<part>', <column>)` hands this one of ten words,
1342    /// and each must answer the number named here, the same on every engine:
1343    ///
1344    /// | `field` | the number |
1345    /// |---|---|
1346    /// | `YEAR` | the year, such as 2026 |
1347    /// | `QUARTER` | 1 to 4 |
1348    /// | `MONTH` | 1 to 12 |
1349    /// | `ISOWEEK` | the ISO 8601 week, 1 to 53, weeks starting on Monday |
1350    /// | `DAY` | the day of the month, 1 to 31 |
1351    /// | `HOUR` | 0 to 23 |
1352    /// | `MINUTE` | 0 to 59 |
1353    /// | `SECOND` | 0 to 59, the whole second |
1354    /// | `ISODOW` | the ISO day of the week, Monday 1 to Sunday 7 |
1355    /// | `DOY` | the day of the year, 1 to 366 |
1356    ///
1357    /// The default writes `EXTRACT(<field> FROM <column>)`, which most engines
1358    /// refuse for `ISOWEEK`, `ISODOW` or `DOY`: override it, spelling each word
1359    /// your engine's way — `DATEPART(ISO_WEEK, c)` on SQL Server,
1360    /// `toISOWeek(c)` on `ClickHouse` — and run each of the ten on your engine.
1361    fn render_date_extract(&self, field: &str, column: &str) -> String {
1362        format!("EXTRACT({field} FROM {column})")
1363    }
1364
1365    /// Render a `TRY_CAST` expression.
1366    ///
1367    /// `ClickHouse`: `accurateCastOrNull(expr, 'Type')`, others: `TRY_CAST(expr AS Type)`
1368    fn render_try_cast(&self, expr: &str, target: &DataType) -> String {
1369        format!("TRY_CAST({} AS {})", expr, self.render_data_type(target))
1370    }
1371
1372    /// Render a named parameter placeholder.
1373    ///
1374    /// `SqlServer`: `@name`, `PostgreSQL`: `:name`, Databricks: `{name}`
1375    fn render_named_parameter(&self, name: &str) -> String {
1376        format!(":{name}")
1377    }
1378
1379    /// Keyword emitted for MERGE NOT MATCHED branch.
1380    ///
1381    /// SqlServer/Databricks: `WHEN NOT MATCHED BY TARGET`, others: `WHEN NOT MATCHED`.
1382    fn merge_not_matched_keyword(&self) -> &'static str {
1383        "WHEN NOT MATCHED"
1384    }
1385
1386    /// Whether MERGE supports `WHEN NOT MATCHED BY SOURCE`.
1387    fn supports_merge_not_matched_by_source(&self) -> bool {
1388        false
1389    }
1390
1391    /// Whether this platform takes a `MERGE` statement.
1392    ///
1393    /// **This is `DialectCapabilities::merge_shape().merges()`, restated where
1394    /// only a `SqlRenderer` is in hand** — the standalone `MergeStatement`
1395    /// builder takes this trait alone and cannot ask the capability surface.
1396    /// The two must answer identically; the capability/renderer consistency
1397    /// gate holds them to equality with no exceptions, so a dialect that
1398    /// overrides one and not the other is refused before it ships. An engine
1399    /// whose shape is an upsert statement, an engine-deduplicated insert, or a
1400    /// refusal answers `false` here.
1401    fn merge_supported(&self) -> bool {
1402        true
1403    }
1404
1405    /// Whether `WITH SCHEMA EVOLUTION` is supported for MERGE.
1406    fn merge_supports_schema_evolution_keyword(&self) -> bool {
1407        false
1408    }
1409
1410    /// Whether table hints are supported in MERGE target.
1411    fn merge_supports_table_hints(&self) -> bool {
1412        false
1413    }
1414
1415    /// Whether OUTPUT clause should be used for MERGE result projection.
1416    fn merge_uses_output_clause(&self) -> bool {
1417        false
1418    }
1419
1420    /// Whether RETURNING clause is supported for MERGE.
1421    fn merge_supports_returning_clause(&self) -> bool {
1422        false
1423    }
1424
1425    /// **The longest line this engine's own client reads intact from a script
1426    /// file**, or `None` where it reads any line.
1427    ///
1428    /// A generated statement can put a long expression on one line. An engine
1429    /// whose client misreads a line past some length is handed its scripts
1430    /// with every longer line broken between two words, outside any quoted
1431    /// text and outside any comment, which changes nothing the statement
1432    /// says.
1433    fn longest_script_line(&self) -> Option<usize> {
1434        None
1435    }
1436
1437    /// **How this engine writes a short name for a relation.**
1438    ///
1439    /// A composed load gives a table, a view, a common table expression or a
1440    /// subquery a short name and then addresses it by that name for the rest
1441    /// of the statement. Most engines take the word `AS` in front of it, and
1442    /// most of those also take the name on its own. One takes only the name:
1443    /// `FROM orders AS src` is refused outright, in a `FROM` and again in a
1444    /// `MERGE`.
1445    ///
1446    /// So the two words are the dialect's to write. `relation` arrives already
1447    /// quoted and qualified; `alias` arrives already quoted. Nothing here
1448    /// changes what the statement means — only how this engine spells it.
1449    fn render_relation_alias(&self, relation: &str, alias: &str) -> String {
1450        format!("{relation} AS {alias}")
1451    }
1452
1453    /// **Whether this engine reserves `word`**, so a name spelled that way
1454    /// has to be quoted to be read as a name.
1455    ///
1456    /// Razeri writes a few short names of its own inside a statement: the
1457    /// marker column a load's anti-join selects (`1 AS matched`), and the
1458    /// relation that carries it (`standing.matched`). It writes them bare,
1459    /// and asks this first: a word the engine reserves is written through
1460    /// [`render_alias`](Self::render_alias), quoted.
1461    ///
1462    /// The default is the SQL standard's list,
1463    /// [`SQL_STANDARD_RESERVED_WORDS`](crate::reserved_words::SQL_STANDARD_RESERVED_WORDS),
1464    /// in any case. An engine that reserves a word the standard leaves free
1465    /// answers `true` for it too, and keeps the standard's answer for the
1466    /// rest:
1467    ///
1468    /// ```text
1469    /// fn is_reserved_word(&self, word: &str) -> bool {
1470    ///     word.eq_ignore_ascii_case("matched")
1471    ///         || razeri_plugin_contract::reserved_words::is_standard_reserved_word(word)
1472    /// }
1473    /// ```
1474    fn is_reserved_word(&self, word: &str) -> bool {
1475        crate::reserved_words::is_standard_reserved_word(word)
1476    }
1477
1478    /// **A short name Razeri gives a column or a relation inside one
1479    /// statement, written so this engine reads it as a name.**
1480    ///
1481    /// Bare where [`is_reserved_word`](Self::is_reserved_word) says the word
1482    /// is free, and through [`quote_identifier`](Self::quote_identifier)
1483    /// where it is reserved. Every place a statement writes the name asks
1484    /// this, so the name and every reference to it are spelled alike.
1485    fn render_alias(&self, alias: &str) -> String {
1486        if self.is_reserved_word(alias) { self.quote_identifier(alias) } else { alias.to_owned() }
1487    }
1488
1489    /// **How a statement that changes the shape of the warehouse is written
1490    /// inside a routine's body.**
1491    ///
1492    /// A generated load empties its landing table when it is finished, and on
1493    /// most engines that statement stands in the body exactly as it would
1494    /// stand on its own. One engine runs no such statement directly in a
1495    /// block: `TRUNCATE TABLE …` there is a parse error, and the same words
1496    /// handed back to the SQL engine as a string run. `statement` arrives
1497    /// terminated the way the rest of the body is.
1498    fn render_ddl_within_routine_body(&self, statement: &str) -> String {
1499        statement.to_owned()
1500    }
1501
1502    /// **How this engine empties a table and keeps it.**
1503    ///
1504    /// A generated load empties the staging table it fills before it writes
1505    /// the next batch into it. Most engines do that with `TRUNCATE TABLE`, and
1506    /// that is the default. One has no such statement and answers a syntax
1507    /// error at the word; it empties a table with `DELETE FROM` instead.
1508    ///
1509    /// `relation` arrives already quoted and qualified. The answer is one whole
1510    /// statement, ended with `;`.
1511    fn render_empty_table(&self, relation: &str) -> String {
1512        format!("TRUNCATE TABLE {relation};")
1513    }
1514
1515    /// **Whether this engine lets a `MERGE` target carry an alias.**
1516    ///
1517    /// Most do, and the composed load addresses the target through a short
1518    /// `tgt`. An engine that answers `false` gets the target's own qualified
1519    /// name in every position the alias would have stood — dropping the
1520    /// qualifier instead makes the shared column names ambiguous.
1521    fn merge_target_accepts_alias(&self) -> bool {
1522        true
1523    }
1524
1525    /// **How this engine writes the condition a `MERGE` matches rows on.**
1526    ///
1527    /// Most take the condition after the word `ON` and nothing else. One
1528    /// requires it in parentheses and answers `ORA-00969: missing ON keyword`
1529    /// without them — pointing at the condition rather than at the word, which
1530    /// is there.
1531    ///
1532    /// `condition` is the whole predicate, which may run over several lines.
1533    fn render_merge_on(&self, condition: &str) -> String {
1534        format!("ON {condition}")
1535    }
1536
1537    /// **Whether this engine refuses a `WITH` clause in front of `MERGE`.**
1538    ///
1539    /// The composed load types its staging rows in one common table expression
1540    /// and hashes them in a second. Where a leading `WITH` parses, the two sit
1541    /// in front of the statement and the source is the second one by name.
1542    /// Where it does not, the same two move inside the `USING` subquery, which
1543    /// is the same query in a position the grammar accepts.
1544    ///
1545    /// Answer `true` if `WITH … MERGE INTO …` is a syntax error on your engine.
1546    fn merge_source_requires_inlined_ctes(&self) -> bool {
1547        false
1548    }
1549
1550    /// **Whether a `WITH` clause parses in front of this engine's `INSERT`.**
1551    ///
1552    /// A load that writes rows without matching them — one slice replaced, or
1553    /// rows appended — types its staging rows in one common table expression
1554    /// and hashes them in a second, exactly as the matching load does. Most
1555    /// engines take those two inside the statement, after the column list and
1556    /// in front of the `SELECT`, which is where Razeri puts them by default.
1557    ///
1558    /// Answer `true` where the same two have to lead instead, because the
1559    /// engine reads a `WITH` after a table name as something else entirely:
1560    /// T-SQL parses it as a table hint and rejects the statement. Nothing here
1561    /// changes the query — only where the engine will accept it written down.
1562    fn insert_accepts_leading_ctes(&self) -> bool {
1563        false
1564    }
1565
1566    /// **Whether this engine can be given a function by `CREATE FUNCTION`.**
1567    ///
1568    /// Razeri derives a surrogate key through a small emitted function, and an
1569    /// engine whose SQL surface has no `CREATE FUNCTION` at all can never
1570    /// receive it — the definition has to come from application code instead.
1571    /// Such an engine gets no emitted helper and no per-entity key function,
1572    /// and its dialect states the substitute in its own words.
1573    ///
1574    /// This is about the **grammar**, not about who owns the name: an engine
1575    /// that can define functions but takes its key function from an installed
1576    /// artifact still answers `true` here.
1577    fn supports_sql_function_ddl(&self) -> bool {
1578        true
1579    }
1580
1581    /// **Whether a scalar function's body is a bare expression.**
1582    ///
1583    /// Most engines want a full `SELECT` in front of the value a function
1584    /// returns. Some take the expression alone and reject the `SELECT`.
1585    fn scalar_function_body_is_expression(&self) -> bool {
1586        false
1587    }
1588
1589    /// **Whether a scalar function belongs to a schema.**
1590    ///
1591    /// On most engines a function lives in a schema and both its definition and
1592    /// its call sites name it. On an engine that answers `false`, functions are
1593    /// server-global: `CREATE FUNCTION` takes no qualifier, and a qualified
1594    /// call names a function that does not exist.
1595    fn scalar_function_names_are_schema_qualified(&self) -> bool {
1596        true
1597    }
1598
1599    /// **Whether an unqualified scalar-function call resolves.**
1600    ///
1601    /// Most engines resolve a bare function name through a search path. An
1602    /// engine that answers `true` resolves none, so a call with no schema in
1603    /// front of it has to be given one — [`DialectCapabilities::default_schema`]
1604    /// is the
1605    /// schema the function was created in when the caller named none.
1606    ///
1607    /// [`DialectCapabilities::default_schema`]: crate::DialectCapabilities::default_schema
1608    fn scalar_function_call_requires_schema(&self) -> bool {
1609        false
1610    }
1611
1612    /// **How this engine invokes a stored procedure**, as a whole statement.
1613    ///
1614    /// The composed load calls its own identity step, and a deploy script that
1615    /// has no procedures at all has to recognise these calls in order to inline
1616    /// what they would have run — so the call is spelled once, here.
1617    fn render_procedure_call(&self, qualified_name: &str) -> String {
1618        format!("CALL {qualified_name}();")
1619    }
1620
1621    /// The schema separator for qualified names.
1622    ///
1623    /// Almost always `.`, but could differ for some platforms.
1624    fn schema_separator(&self) -> &'static str {
1625        "."
1626    }
1627
1628    /// The statement separator for scripts.
1629    ///
1630    /// Almost all platforms: `;\n`, `SqlServer`: `;\nGO\n`
1631    fn statement_separator(&self) -> &'static str {
1632        ";\n"
1633    }
1634
1635    // ═══════════════════════════════════════════════════════════════
1636    // UPDATE behavior hooks
1637    // ═══════════════════════════════════════════════════════════════
1638
1639    /// Whether the platform supports compound assignment operators (e.g., `col += value`).
1640    ///
1641    /// `SqlServer`: `true`, others: `false`.
1642    fn supports_compound_assignment(&self) -> bool {
1643        false
1644    }
1645
1646    /// Whether UPDATE supports FROM clause for join-based updates.
1647    ///
1648    /// `PostgreSQL`, `SqlServer`, Snowflake, `CitusDB`: `true`, others: `false`.
1649    fn supports_update_from(&self) -> bool {
1650        false
1651    }
1652
1653    /// **Whether an `UPDATE … FROM` takes a joined source whose columns carry
1654    /// the target's own names**, under an unqualified `SET`:
1655    /// `UPDATE t SET v = source.v FROM (SELECT k, v FROM s) source WHERE
1656    /// t.k = source.k`.
1657    ///
1658    /// Asked only where [`supports_update_from`](Self::supports_update_from)
1659    /// is `true`. The default is `true`. Oracle refuses that shape as
1660    /// ambiguous (*"ORA-00918: column ambiguously specified"*) and `PostgreSQL`
1661    /// refuses the qualified `SET` that would cure it, so an engine like
1662    /// Oracle answers `false` and Razeri writes the correlated update, which
1663    /// every engine runs.
1664    fn update_from_takes_a_source_naming_the_targets_columns(&self) -> bool {
1665        true
1666    }
1667
1668    /// **The statement that tells this engine's planner what a table now
1669    /// holds**, after Razeri wrote it in bulk, or `None` where the engine needs
1670    /// none.
1671    ///
1672    /// `table` is spelled and qualified as the statement names it. Razeri runs
1673    /// the answer after a staging fill and at the end of every load, inside
1674    /// the load's transaction, so answer only with a statement your engine
1675    /// takes there. The default is `None`: an engine that keeps what its
1676    /// planner needs as it writes. `PostgreSQL` answers `ANALYZE <table>;` —
1677    /// with nothing to go on, its planner joins a hundred thousand rows to a
1678    /// hundred thousand one pair at a time.
1679    fn render_refresh_statistics(&self, table: &str) -> Option<String> {
1680        let _ = table;
1681        None
1682    }
1683
1684    /// Whether the platform uses ALTER TABLE ... UPDATE syntax (`ClickHouse` mutations).
1685    fn uses_alter_table_update(&self) -> bool {
1686        false
1687    }
1688
1689    /// **Whether a mutation on this platform can read only the row it is
1690    /// mutating.**
1691    ///
1692    /// `uses_alter_table_update` above says how the mutation is SPELLED; this
1693    /// says what the mutation may LOOK AT, and the two are independent facts
1694    /// that happen to be true of the same engine today. A platform answering
1695    /// `true` here cannot express *assign this column from another relation*
1696    /// at all: neither the `SET` list nor the `WHERE` may correlate out to a
1697    /// second table, so no re-spelling of a correlated `UPDATE` compiles —
1698    /// what is available instead is `INSERT … SELECT` over a join and a
1699    /// mutation whose predicate is an uncorrelated `IN`.
1700    ///
1701    /// **Measured, and it is the reason the seam exists.** `ClickHouse`
1702    /// 24.10.2 answered razeri's emitted re-open with
1703    /// `Code: 47 … UNKNOWN_IDENTIFIER` while resolving the assignment's own
1704    /// subquery — after the statement PARSED, which is what made the
1705    /// distinction visible: the syntax was right and the reach was not.
1706    ///
1707    /// It sits here on [`SqlRenderer`] and **only** here, deliberately not
1708    /// duplicated onto `DialectCapabilities`: `SqlRenderer` is the trait
1709    /// razeri's generators call, so this is the definition that decides, and a
1710    /// second declaration of the same fact is one that can drift.
1711    ///
1712    /// Default `false`: every engine razeri reaches except `ClickHouse` lets a
1713    /// mutation correlate, and the ANSI correlated `UPDATE` those nine compile
1714    /// is unchanged by this flag existing.
1715    fn mutation_reads_only_its_own_rows(&self) -> bool {
1716        false
1717    }
1718
1719    /// **The spelling a SQL statement inside a generated procedure body reads
1720    /// a declared local variable by.**
1721    ///
1722    /// A versioning load binds its clock ONCE — a `Declare` step at the top of
1723    /// the procedure — and every close and every open reads the variable
1724    /// instead of the engine's clock, so there is no daylight between the
1725    /// close of one version and the open of the next. The DECLARATION is the
1726    /// procedure renderer's business; what the load generators need is the
1727    /// reference spelling to embed in the raw statements they compose, and
1728    /// that differs by procedure language:
1729    ///
1730    /// - bare `name` — PL/pgSQL, MySQL/MariaDB, and the default;
1731    /// - `@name` — T-SQL;
1732    /// - `:name` — Snowflake Scripting's bind syntax inside SQL statements;
1733    /// - `$name` — the agnostic format's marker.
1734    ///
1735    /// It mirrors the variable-reference spelling of Razeri's own procedure
1736    /// renderers — the two must agree, and each override says so beside the
1737    /// spelling.
1738    fn render_procedure_variable_reference(&self, name: &str) -> String {
1739        name.to_owned()
1740    }
1741
1742    /// **The statement that binds one query's answer to a declared local.**
1743    ///
1744    /// A procedure body asks a question — how many rows arrived, what the
1745    /// latest timestamp is — and keeps the answer in a variable the rest of the
1746    /// body reads. Every procedural language has that statement and no two
1747    /// spell it alike:
1748    ///
1749    /// - `SELECT COUNT(*) FROM stage INTO v_seen;` — PL/pgSQL;
1750    /// - `SELECT @v_seen = (SELECT COUNT(*) FROM stage);` — T-SQL;
1751    /// - `v_seen := (SELECT COUNT(*) FROM stage);` — Snowflake Scripting;
1752    /// - `EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM stage' INTO v_seen;` —
1753    ///   Oracle's PL/SQL.
1754    ///
1755    /// `query` is the question, already carrying this dialect's variable
1756    /// spelling and with no trailing terminator; `variable` is the bare name of
1757    /// the local, so a grammar that wants the reference spelling asks
1758    /// [`Self::render_procedure_variable_reference`] for it and one that wants
1759    /// the bare name has it already. The answer is a whole statement,
1760    /// terminator included.
1761    ///
1762    /// The default names the query and the target in a form that belongs to no
1763    /// engine, because there is no spelling every engine shares. A dialect
1764    /// rendering its own routine grammar answers this and the body arrives
1765    /// ready to compile.
1766    fn render_procedure_query_into_variable(&self, variable: &str, query: &str) -> String {
1767        format!("EXECUTE {query} INTO {};", self.render_procedure_variable_reference(variable))
1768    }
1769
1770    /// **The statement that stops a procedure body with an error of its own.**
1771    ///
1772    /// A generated load checks what it was given and refuses to go on when the
1773    /// answer is wrong. Every procedural language can stop that way and no two
1774    /// write it alike:
1775    ///
1776    /// - `RAISE EXCEPTION '%', 'the run brought no rows';` — PL/pgSQL;
1777    /// - `THROW 50000, 'the run brought no rows', 1;` — T-SQL;
1778    /// - `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'the run brought no rows';`
1779    ///   — `MySQL` and `MariaDB`;
1780    /// - `RAISE_APPLICATION_ERROR(-20001, 'the run brought no rows');` —
1781    ///   Oracle's PL/SQL.
1782    ///
1783    /// `message` is the message **already rendered as a SQL expression in this
1784    /// dialect's spelling**: a literal arrives quoted and escaped, and a
1785    /// variable arrives named the way
1786    /// [`Self::render_procedure_variable_reference`] names one, because a body
1787    /// may raise what it read rather than what it was written with. Put it
1788    /// where the statement wants it and do not quote it again. `error_code` is
1789    /// the number the design gave, if it gave one; an engine whose statement
1790    /// takes a number supplies its own when this is `None`. The answer is a
1791    /// whole statement, terminator included.
1792    ///
1793    /// The default names the raise in a form that belongs to no engine. A
1794    /// dialect rendering its own routine grammar answers this and the body
1795    /// arrives ready to compile.
1796    fn render_procedure_raise(&self, message: &str, error_code: Option<i32>) -> String {
1797        match error_code {
1798            Some(code) => format!("RAISE EXCEPTION [{code}] {message};"),
1799            None => format!("RAISE EXCEPTION {message};"),
1800        }
1801    }
1802
1803    /// **The statement that writes a message where an operator can read it.**
1804    ///
1805    /// A load says how it is going, and where that message goes is an engine's
1806    /// own business — a client notice, a print stream, an event table, a
1807    /// result set nobody reads:
1808    ///
1809    /// - `RAISE NOTICE '%', 'loaded';` — PL/pgSQL;
1810    /// - `PRINT 'loaded';` — T-SQL;
1811    /// - `SYSTEM$LOG('INFO', 'loaded');` — Snowflake Scripting;
1812    /// - `DBMS_OUTPUT.PUT_LINE('loaded');` — Oracle's PL/SQL, which has no
1813    ///   levels and ignores the one it is given.
1814    ///
1815    /// `message` arrives the same way [`Self::render_procedure_raise`] takes
1816    /// it: already a SQL expression in this dialect's spelling, quoted where it
1817    /// is a literal. `level` is the severity the design wrote; an engine whose
1818    /// statement carries one reads
1819    /// [`ProcedureLogLevel::as_str`] and spells it the way that statement
1820    /// wants. The answer is a whole statement, terminator included.
1821    ///
1822    /// The default names the level and the message in a form that belongs to no
1823    /// engine. A dialect rendering its own routine grammar answers this and the
1824    /// body arrives ready to compile. **An engine with no statement that
1825    /// writes a message answers `None`**, and the line is left out of the
1826    /// routine rather than written as a comment or a statement it refuses.
1827    fn render_procedure_log(&self, level: ProcedureLogLevel, message: &str) -> Option<String> {
1828        let word = match level {
1829            ProcedureLogLevel::Debug => "DEBUG",
1830            ProcedureLogLevel::Info => "NOTICE",
1831            ProcedureLogLevel::Warning => "WARNING",
1832            ProcedureLogLevel::Error => "EXCEPTION",
1833        };
1834        Some(format!("LOG {word} {message};"))
1835    }
1836
1837    /// **The statement a generated load asks a scalar question with and throws
1838    /// the answer away.**
1839    ///
1840    /// A load's guard evaluates one scalar and reads nothing back: it either
1841    /// passes silently or stops the load on the engine's own error. What
1842    /// differs between engines is not the question but the STATEMENT that may
1843    /// carry it, and the difference is a procedure-language rule rather than a
1844    /// SQL one:
1845    ///
1846    /// - a bare `SELECT` is a legal script statement everywhere, and is legal
1847    ///   inside the procedure bodies `MySQL`, `MariaDB` and T-SQL accept, where it
1848    ///   simply hands the caller a result set nobody reads — so that is the
1849    ///   default;
1850    /// - **PL/pgSQL refuses it.** A `SELECT` with no destination inside a
1851    ///   procedure body is `query has no destination for result data`, raised
1852    ///   the moment the procedure is called. PL/pgSQL's own discard form is
1853    ///   `PERFORM`, and the Postgres family overrides this to spell it.
1854    ///
1855    /// The engines that ship no stored procedure inline the same statement into
1856    /// a script, where the default is the only form that runs — and every such
1857    /// engine takes the default, so one answer per dialect is unambiguous.
1858    ///
1859    /// `alias` names the answered column for the forms that answer one; a
1860    /// discard form that answers nothing ignores it.
1861    fn render_discarded_scalar(&self, expression: &str, alias: &str) -> String {
1862        format!("SELECT {expression} AS {alias};")
1863    }
1864
1865    /// **How a script with no stored procedures binds the load's clock once**
1866    /// — same rule as [`Self::render_procedure_variable_reference`], on the
1867    /// engines where a load ships as a flat statement list rather than a
1868    /// procedure body.
1869    ///
1870    /// The statements run FIRST and bind the engine's current moment to
1871    /// `name`; the reference is the expression every close and open in the
1872    /// same run then reads, so a version's `record_end_timestamp` and its
1873    /// successor's `record_start_timestamp` are one value by construction.
1874    /// Every spelling must be RE-RUNNABLE in one session — a second load in
1875    /// the same session rebinds rather than failing — because a load script is
1876    /// run whole and run again.
1877    ///
1878    /// The default is a one-row temporary table capturing
1879    /// [`Self::render_current_timestamp`], read back through a scalar
1880    /// subquery. Not every engine takes it: `CockroachDB` 24.3 answers
1881    /// *"temporary tables are only supported experimentally"*, and an engine
1882    /// like that overrides this with a session value of its own (`set_config`
1883    /// and `current_setting` there). Engines with a native variable idiom
1884    /// override it too (`DuckDB`'s `SET VARIABLE`, Databricks' session
1885    /// variables); `ClickHouse` overrides only the temporary-table spelling its
1886    /// own DDL requires.
1887    fn render_inline_clock_binding(&self, name: &str, moment: &str) -> InlineClockBinding {
1888        InlineClockBinding {
1889            statements: vec![
1890                format!("DROP TABLE IF EXISTS {name};"),
1891                format!("CREATE TEMPORARY TABLE {name} AS SELECT {moment} AS load_clock;"),
1892            ],
1893            reference: format!("(SELECT load_clock FROM {name})"),
1894        }
1895    }
1896
1897    /// Whether UPDATE supports TOP(n) clause (`SqlServer`).
1898    fn update_supports_top_clause(&self) -> bool {
1899        false
1900    }
1901
1902    /// Whether UPDATE supports table hints (e.g., `WITH (NOLOCK)`) (`SqlServer`).
1903    fn update_supports_table_hints(&self) -> bool {
1904        false
1905    }
1906
1907    /// Whether UPDATE uses OUTPUT clause positioned before FROM (`SqlServer`).
1908    ///
1909    /// When `true`, RETURNING/OUTPUT is rendered between SET and FROM.
1910    /// When `false`, RETURNING is rendered at the end of the statement.
1911    fn update_uses_output_clause(&self) -> bool {
1912        false
1913    }
1914
1915    /// Whether UPDATE supports a RETURNING clause at the end of the statement.
1916    ///
1917    /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
1918    fn update_supports_returning(&self) -> bool {
1919        false
1920    }
1921
1922    // ========================================================================
1923    // INSERT behavior hooks
1924    // ========================================================================
1925
1926    /// Whether INSERT uses OUTPUT clause positioned before VALUES/SELECT (`SqlServer`).
1927    ///
1928    /// When `true`, RETURNING/OUTPUT is rendered between column list and source.
1929    /// When `false`, RETURNING is rendered at the end of the statement.
1930    fn insert_uses_output_clause(&self) -> bool {
1931        false
1932    }
1933
1934    /// Whether INSERT supports RETURNING at the end (`PostgreSQL`, `CitusDB`).
1935    fn insert_supports_returning(&self) -> bool {
1936        false
1937    }
1938
1939    /// Whether INSERT supports table hints (e.g., `WITH (TABLOCK)`) (`SqlServer`).
1940    fn insert_supports_table_hints(&self) -> bool {
1941        false
1942    }
1943
1944    /// Whether INSERT OVERWRITE is supported (Snowflake, Databricks).
1945    fn supports_insert_overwrite(&self) -> bool {
1946        false
1947    }
1948
1949    /// Whether INSERT ... ON CONFLICT is supported (`PostgreSQL`, `CitusDB`).
1950    fn supports_on_conflict(&self) -> bool {
1951        false
1952    }
1953
1954    /// Whether OVERRIDING SYSTEM/USER VALUE clause is supported (`PostgreSQL`).
1955    fn supports_overriding_clause(&self) -> bool {
1956        false
1957    }
1958
1959    /// The keyword for returning data from DML: "OUTPUT" (`SqlServer`) or "RETURNING" (others).
1960    fn returning_clause_keyword(&self) -> &'static str {
1961        "RETURNING"
1962    }
1963
1964    /// Whether OUTPUT ... INTO is supported (`SqlServer`).
1965    fn supports_returning_into(&self) -> bool {
1966        false
1967    }
1968
1969    /// Whether multi-table INSERT (INSERT ALL) is supported (Snowflake).
1970    fn supports_multi_table_insert(&self) -> bool {
1971        false
1972    }
1973
1974    // ========================================================================
1975    // Function/procedure parameter behavior hooks
1976    // ========================================================================
1977
1978    /// Render the security mode clause for function/procedure definitions.
1979    ///
1980    /// Standard SQL: `SECURITY INVOKER`/`SECURITY DEFINER`.
1981    /// T-SQL: `EXECUTE AS CALLER`/`EXECUTE AS OWNER`.
1982    fn render_security_mode(&self, is_definer: bool) -> &'static str {
1983        if is_definer { "SECURITY DEFINER" } else { "SECURITY INVOKER" }
1984    }
1985
1986    /// Render a function parameter name.
1987    ///
1988    /// Standard SQL uses the bare name. T-SQL prefixes with `@`.
1989    fn render_function_parameter_name(&self, name: &str) -> String {
1990        name.to_string()
1991    }
1992
1993    /// Render explicit nullability for a function parameter, if the platform requires it.
1994    ///
1995    /// Most platforms omit nullability in parameter lists. T-SQL native
1996    /// compilation requires explicit `NULL`/`NOT NULL`.
1997    fn render_function_parameter_nullable(&self, _nullable: bool) -> Option<&'static str> {
1998        None
1999    }
2000
2001    /// Render the default-value clause for a function parameter.
2002    ///
2003    /// Standard SQL: `DEFAULT value`. T-SQL: `= value`.
2004    fn render_function_parameter_default(&self, value: &str) -> String {
2005        format!("DEFAULT {value}")
2006    }
2007
2008    /// Render a column name inside a table-valued function definition.
2009    ///
2010    /// Standard SQL uses the bare name. T-SQL uses bracket quoting `[name]`.
2011    fn render_function_column_name(&self, name: &str) -> String {
2012        name.to_string()
2013    }
2014
2015    // ========================================================================
2016    // Partition & generated column rendering hooks
2017    // ========================================================================
2018
2019    /// Render a time partition expression for a column and granularity.
2020    ///
2021    /// Granularity values: `"hourly"`, `"daily"`, `"weekly"`, `"monthly"`,
2022    /// `"quarterly"`, `"yearly"`.
2023    ///
2024    /// Default: `date_trunc('unit', column)` (ANSI / `PostgreSQL` style),
2025    /// mapping granularity names to `date_trunc` units.
2026    fn render_time_partition_expr(&self, column: &str, granularity: &str) -> String {
2027        let unit = match granularity {
2028            "hourly" => "hour",
2029            "daily" => "day",
2030            "weekly" => "week",
2031            "monthly" => "month",
2032            "quarterly" => "quarter",
2033            "yearly" => "year",
2034            other => other,
2035        };
2036        format!("date_trunc('{unit}', {column})")
2037    }
2038
2039    /// Render a DDL partition clause wrapping the expression list.
2040    ///
2041    /// Default: `PARTITION BY (expr)`. Snowflake: `CLUSTER BY (expr)`,
2042    /// Databricks: `PARTITIONED BY (expr)`, `ClickHouse`: `PARTITION BY expr` (no parens).
2043    fn render_partition_clause(&self, expr: &str) -> String {
2044        format!("PARTITION BY ({expr})")
2045    }
2046
2047    /// Render a generated column declaration.
2048    ///
2049    /// Default: `name GENERATED ALWAYS AS (expr) STORED` (`PostgreSQL` style).
2050    fn render_generated_column(&self, name: &str, expr: &str) -> String {
2051        format!("{name} GENERATED ALWAYS AS ({expr}) STORED")
2052    }
2053
2054    // ========================================================================
2055    // Window function capability hooks
2056    // ========================================================================
2057
2058    /// Whether the platform supports the EXCLUDE clause in window frame specifications.
2059    ///
2060    /// `PostgreSQL`, Snowflake, Databricks: `true`. Others: `false`.
2061    fn supports_window_frame_exclude(&self) -> bool {
2062        false
2063    }
2064
2065    /// Whether the platform supports the GROUPS frame mode in window functions.
2066    ///
2067    /// `PostgreSQL`, Databricks: `true`. Others: `false`.
2068    fn supports_window_frame_groups(&self) -> bool {
2069        false
2070    }
2071
2072    /// Whether the platform supports named windows (WINDOW clause).
2073    ///
2074    /// Most platforms: `true`. `ClickHouse`, `DuckDB`, `MariaDB`: `false`.
2075    fn supports_named_windows(&self) -> bool {
2076        true
2077    }
2078
2079    // ========================================================================
2080    // DDL table-scope capability hooks
2081    // ========================================================================
2082
2083    /// Whether the platform uses a `#` prefix for session-scoped temporary table names.
2084    ///
2085    /// SQL Server: `true`. Others: `false`.
2086    fn uses_hash_temp_table_prefix(&self) -> bool {
2087        false
2088    }
2089
2090    /// Whether the platform supports `DECLARE @name TABLE (...)` table variables.
2091    ///
2092    /// SQL Server: `true`. Others: `false`.
2093    fn supports_table_variables(&self) -> bool {
2094        false
2095    }
2096
2097    /// The full CREATE keyword for session-scoped temporary tables.
2098    ///
2099    /// Default: `"CREATE TEMPORARY"`.
2100    /// SQL Server: `"CREATE"` (uses `#name` instead of TEMPORARY keyword).
2101    /// Databricks: `"CREATE OR REPLACE TEMPORARY"`.
2102    fn render_create_temp_table_keyword(&self) -> &'static str {
2103        "CREATE TEMPORARY"
2104    }
2105
2106    /// Whether the platform supports transient tables (e.g. `CREATE TRANSIENT TABLE`).
2107    ///
2108    /// Snowflake: `true`. Others: `false`.
2109    fn supports_transient_tables(&self) -> bool {
2110        false
2111    }
2112
2113    /// Whether the platform supports `ON COMMIT DROP` for transaction-scoped temp tables.
2114    ///
2115    /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
2116    fn supports_on_commit_drop(&self) -> bool {
2117        false
2118    }
2119
2120    /// **The clause written after a table's column list**, or `None` on an
2121    /// engine whose `CREATE TABLE` is complete at the closing parenthesis.
2122    ///
2123    /// Most engines take `CREATE TABLE t (…)` as it stands. Some refuse it
2124    /// without a clause the column list cannot carry — `ClickHouse` answers
2125    /// `ORDER BY or PRIMARY KEY clause is missing` — so its dialect answers the
2126    /// table's engine and sorting key here: `ENGINE = MergeTree()` and
2127    /// `ORDER BY (…)`, `ReplacingMergeTree(<version column>)` on a versioned
2128    /// table, and `ENGINE = Memory` on a temporary one. An engine with a
2129    /// mandatory clause of its own spells it here too.
2130    ///
2131    /// Razeri writes the answer on its own line, directly after the closing
2132    /// parenthesis of every `CREATE TABLE` it renders, and before the storage
2133    /// plan's clause from
2134    /// [`render_table_storage_clause`](crate::StorageRenderer::render_table_storage_clause).
2135    /// **What you answer here, the storage clause must not repeat**, and the
2136    /// reverse: two engine clauses in one statement is `Code: 62 … Syntax
2137    /// error` on `ClickHouse`. A sorting key belongs here rather than there,
2138    /// because it usually has to begin with the table's primary key, and only
2139    /// this method is handed it.
2140    ///
2141    /// Answer without a terminator; more than one line is fine.
2142    ///
2143    /// ```
2144    /// use razeri_plugin_contract::{SqlRenderer, TableSuffixRequest};
2145    ///
2146    /// struct Columnar;
2147    ///
2148    /// impl SqlRenderer for Columnar {
2149    ///     # fn render_data_type(&self, _: &razeri_plugin_contract::DataType) -> String { "TEXT".into() }
2150    ///     # fn quote_identifier(&self, name: &str) -> String { format!("\"{name}\"") }
2151    ///     # fn qualify_name(&self, _: Option<&str>, name: &str) -> String { self.quote_identifier(name) }
2152    ///     # fn render_current_timestamp(&self) -> String { "CURRENT_TIMESTAMP".into() }
2153    ///     fn render_table_suffix(&self, table: &TableSuffixRequest<'_>) -> Option<String> {
2154    ///         if table.temporary {
2155    ///             return Some("USING MEMORY".to_owned());
2156    ///         }
2157    ///         let key: Vec<String> =
2158    ///             table.primary_key.iter().map(|c| self.quote_identifier(c)).collect();
2159    ///         Some(format!("USING COLUMNSTORE\nSORT KEY ({})", key.join(", ")))
2160    ///     }
2161    /// }
2162    ///
2163    /// let key = ["id".to_owned()];
2164    /// let table = TableSuffixRequest::new().with_primary_key(&key);
2165    /// assert_eq!(
2166    ///     Columnar.render_table_suffix(&table).as_deref(),
2167    ///     Some("USING COLUMNSTORE\nSORT KEY (\"id\")"),
2168    /// );
2169    /// ```
2170    fn render_table_suffix(&self, table: &TableSuffixRequest<'_>) -> Option<String> {
2171        let _ = table;
2172        None
2173    }
2174
2175    /// Whether this platform's table sorting key refuses nullable columns.
2176    ///
2177    /// `ClickHouse`: `true` — a `MergeTree` sorting key containing a
2178    /// `Nullable(…)` column answers `Code: 44 … Sorting key contains nullable
2179    /// columns, but merge tree setting allow_nullable_key is disabled`, measured
2180    /// on 24.10.2 against the control (the same key over a non-nullable column
2181    /// of the same type is accepted). Others: `false`.
2182    ///
2183    /// The materializer asks this before it lets a design's clustering columns
2184    /// into a sorting key, so the answer is a refusal the author can act on
2185    /// rather than a deployment failure they cannot.
2186    fn sorting_key_refuses_nullable_columns(&self) -> bool {
2187        false
2188    }
2189
2190    /// Whether the platform requires a primary key on every table.
2191    ///
2192    /// `ClickHouse` (MergeTree): `true`. Others: `false`.
2193    fn requires_primary_key_in_create_table(&self) -> bool {
2194        false
2195    }
2196
2197    /// Create a boxed [`FormulaRenderer`](crate::FormulaRenderer) for this dialect.
2198    ///
2199    /// Real dialect implementations override this to return `Box::new(Self)`.
2200    /// The default returns an ANSI dialect with standard function names.
2201    fn to_formula_renderer(&self) -> Box<dyn crate::FormulaRenderer> {
2202        Box::new(crate::AnsiDialect)
2203    }
2204}
2205
2206/// Level 2 — Expression rendering with ANSI SQL defaults.
2207pub trait ExpressionRenderer: SqlRenderer {
2208    /// **Render a conversion of `expr` to `target`** — the expression the
2209    /// generated load's typed projection writes for every column.
2210    ///
2211    /// The default is `CAST(expr AS …)` over
2212    /// [`render_cast_type`](SqlRenderer::render_cast_type), the cast vocabulary
2213    /// rather than the column vocabulary: a column may be declared `STRING(36)`
2214    /// where a cast may name only `STRING`, and `TINYINT` where a cast must say
2215    /// `SMALLINT`. Override it where a conversion is not a `CAST` at all —
2216    /// `GoogleSQL` has no cast from `STRING` to `JSON` ("Invalid cast from
2217    /// STRING to JSON") and converts with `PARSE_JSON(expr)` instead.
2218    fn render_cast(&self, expr: &str, target: &DataType) -> String {
2219        format!("CAST({} AS {})", expr, self.render_cast_type(target))
2220    }
2221
2222    /// **This engine's canonical text for a value**: the same characters on
2223    /// every engine, whatever the session is set to.
2224    ///
2225    /// `expr` holds a value of `value_type`. The answer is its text as
2226    /// [`CanonicalText::of`](crate::CanonicalText::of) defines it for that
2227    /// type — `2026-01-05` for a date, `2026-01-05 12:34:56.12` for a
2228    /// timestamp, `2026-01-05 12:34:56.12+00:00` for a zoned moment, `10.00`
2229    /// for a `DECIMAL(12, 2)` ten, `10` for a floating ten, `true` for a truth
2230    /// value — and `NULL` where `expr` is `NULL`. `text` is the text type the value would otherwise be cast
2231    /// to, and every type written by the engine's own cast is cast to it.
2232    ///
2233    /// A load that refuses its rows names their values in this text, and a
2234    /// reconciliation writes a decimal measurement in it before comparing it
2235    /// with the source's by string equality. So an engine that writes a date
2236    /// by a format its session sets, drops a decimal's trailing zeros, writes
2237    /// every digit of a timestamp's precision, writes a zoned moment in the
2238    /// session's zone, writes a floating number to more or fewer digits, or
2239    /// holds a truth value as a number answers here with an explicit format. The default is the plain cast to `text`, which is the
2240    /// canonical text on an engine that does none of those things.
2241    fn render_value_text(&self, expr: &str, value_type: &DataType, text: &DataType) -> String {
2242        let _ = value_type;
2243        self.render_cast(expr, text)
2244    }
2245
2246    /// **The functions [`Self::render_value_text`] calls, and the statements
2247    /// that create them**, or `None` where it calls none.
2248    ///
2249    /// An engine with no `printf` computes a floating number's text from its
2250    /// own arithmetic ([`computed_float_text`](crate::computed_float_text)),
2251    /// and that arithmetic is several thousand characters long. Written into
2252    /// every place a value is named, it makes a statement hard to read and a
2253    /// line some clients misread. So such an engine writes it once, as
2254    /// [`FLOAT_TEXT_FUNCTION`](crate::FLOAT_TEXT_FUNCTION) and
2255    /// [`SINGLE_FLOAT_TEXT_FUNCTION`](crate::SINGLE_FLOAT_TEXT_FUNCTION), and
2256    /// its value text calls them by those names.
2257    ///
2258    /// A generated script creates them before anything that calls them, and
2259    /// only where something does. The default is `None`: the engine writes
2260    /// every value's text inline.
2261    fn value_text_functions(&self) -> Option<crate::ValueTextFunctions> {
2262        None
2263    }
2264
2265    /// **An expression that stops the statement with `sentence`**, where
2266    /// `sentence` is not `NULL`, and is `NULL` where it is.
2267    ///
2268    /// A generated load refuses rows it cannot write honestly by building a
2269    /// sentence about them and asking the engine for this expression. The
2270    /// engine's error then carries the sentence to whoever reads it. The
2271    /// default converts the sentence to a whole number, which most engines
2272    /// refuse and quote back: *Could not convert string '…' to INT64*. An
2273    /// engine that answers that conversion without an error spells a refusal
2274    /// of its own here, or says through
2275    /// [`DialectCapabilities::refusal_stops_the_statement`](crate::DialectCapabilities::refusal_stops_the_statement)
2276    /// that its refusal only warns.
2277    fn render_refusal(&self, sentence: &str) -> String {
2278        self.render_cast(sentence, &DataType::bigint())
2279    }
2280
2281    /// **A statement that reads `relation`, changes nothing, and stops with
2282    /// `sentence` where a row meets `condition`** — or `None`, the default,
2283    /// where the engine has none, and a load's refusal stays a statement that
2284    /// would write and stops on [`Self::render_refusal`].
2285    ///
2286    /// `condition` is true of a row holding a value the load refuses, and
2287    /// `sentence` is a text expression over that row: the words the engine's
2288    /// error should carry, and nothing around them. A statement that only
2289    /// reads is one an engine may run on several workers, which a statement
2290    /// that writes is not; the refusal ahead of a load reads every staged row,
2291    /// so on a large file that is most of what it costs. And an error raised
2292    /// with its own message carries the sentence alone, where a failed
2293    /// conversion wraps it in the engine's words about a type the column is
2294    /// not.
2295    fn render_read_only_refusal(
2296        &self,
2297        relation: &str,
2298        condition: &str,
2299        sentence: &str,
2300    ) -> Option<String> {
2301        let _ = (relation, condition, sentence);
2302        None
2303    }
2304
2305    /// **Whether a number written as text fits a decimal column, asked in
2306    /// this engine's own words** — or `None`, the default, where Razeri asks
2307    /// it portably: the digits stripped one `REPLACE` at a time to see what is
2308    /// left, and nine `LIKE` patterns, one for each digit but `0`, wherever a
2309    /// digit's place is asked.
2310    ///
2311    /// `text` is a text expression, the value as the file wrote it with its
2312    /// surrounding spaces and the marks a plain number may carry already
2313    /// taken out. The column is `decimal(precision, scale)`. The answer is
2314    /// three conditions over `text`; see [`DecimalFit`] for what each is true
2315    /// of. A load refuses a value too large for the column and one with more
2316    /// places than it keeps, in sentences of their own, rather than letting
2317    /// the engine cap, round or refuse it in its own words. Each condition is
2318    /// asked of every staged value, so an engine whose `LIKE` takes a
2319    /// character class, or which matches a regular expression, answers here
2320    /// in one or two tests where the portable form takes thirty.
2321    ///
2322    /// A try-conversion (`TRY_CONVERT`, `TRY_CAST`, `SAFE_CAST`) is no
2323    /// answer: it rounds a value with more places than the type keeps, so it
2324    /// cannot say that it has them.
2325    fn render_decimal_fit(&self, text: &str, precision: u8, scale: u8) -> Option<DecimalFit> {
2326        let _ = (text, precision, scale);
2327        None
2328    }
2329
2330    /// **How many characters `expr` holds**, counted the way a person counts
2331    /// them: one for each character, whatever the bytes that store it, and
2332    /// every space inside or at either end of the value included.
2333    ///
2334    /// A reconciliation totals this over a text column and compares the total
2335    /// with the one razeri counted in the source file, so a value that gained
2336    /// a carriage return, lost its last letters or was padded on the way in
2337    /// shows up as a different number. `expr` is a text value; `NULL` counts
2338    /// as `NULL`, which a total leaves out.
2339    ///
2340    /// The default is the standard `CHAR_LENGTH`. An engine without it
2341    /// answers with its own function, and an engine whose usual length leaves
2342    /// out trailing spaces, counts bytes, or counts a character outside the
2343    /// basic plane as two answers with one that does none of those.
2344    fn render_text_length(&self, expr: &str) -> String {
2345        format!("CHAR_LENGTH({expr})")
2346    }
2347
2348    /// **The unit [`render_text_length`](Self::render_text_length) counts a
2349    /// value of this type in**, held where `held` says.
2350    ///
2351    /// A reconciliation compares the total with one counted from the source
2352    /// file, and counts the file in the same unit, so the two agree and the
2353    /// engine is asked for nothing it does not do quickly. The default is
2354    /// [`TextLengthUnit::Characters`]. An engine whose length of a large
2355    /// object counts UTF-16 code units — a character outside the basic plane
2356    /// counting two — answers [`TextLengthUnit::Utf16CodeUnits`] for the types
2357    /// it holds as one.
2358    fn text_length_unit(&self, data_type: &DataType, held: HeldAs) -> TextLengthUnit {
2359        let _ = (data_type, held);
2360        TextLengthUnit::Characters
2361    }
2362
2363    /// **The expression a load compares in place of `value`**, a column of
2364    /// this type held where `held` says, or `None` where this engine cannot
2365    /// compare such a value at all.
2366    ///
2367    /// A load looks for a row that arrives twice: it collapses the rows it
2368    /// reads with `SELECT DISTINCT` and counts each column's distinct values,
2369    /// so every column it reads is compared. The default answers `value`
2370    /// itself, which is right wherever the engine compares the type
2371    /// directly. An engine that holds the type as a large object it cannot
2372    /// group or compare answers `None`, and Razeri refuses such a column by
2373    /// name when it writes the load, saying to give it a length; or it answers
2374    /// an expression that stands for the value wherever two values are
2375    /// compared — the same text for the same value, and different text for
2376    /// different values.
2377    fn render_comparable(&self, value: &str, data_type: &DataType, held: HeldAs) -> Option<String> {
2378        let _ = (data_type, held);
2379        Some(value.to_owned())
2380    }
2381
2382    /// **A test that is true where a value of a date or timestamp column is
2383    /// not written as an ISO 8601 date**, on an engine that holds such a
2384    /// column as text it does not check — or `None`, the default, where the
2385    /// engine's date type checks every value written into it.
2386    ///
2387    /// On such an engine a fill written by hand can put `17/09/2026` in a
2388    /// load's day column and nothing refuses it: the load matches no row, the
2389    /// day loads empty, and every count agrees with itself. The reconciliation
2390    /// counts the values this test finds, and expects none. `value` is the
2391    /// column as the statement names it; `data_type` is the type the design
2392    /// declares, a date or a timestamp.
2393    fn render_not_an_iso_day(&self, value: &str, data_type: &DataType) -> Option<String> {
2394        let _ = (value, data_type);
2395        None
2396    }
2397
2398    /// **`text`, or a missing value where it is exactly one of `words`**: how
2399    /// a load reads a source field that holds a word meaning "no value", such
2400    /// as `NULL`, `n/a` or `?`.
2401    ///
2402    /// A source file names its own words for a missing value, and one design
2403    /// has to load the same warehouse on every engine, so a word matches
2404    /// letter for letter and in the same case, whatever the engine's usual
2405    /// comparison. `text` is a text value, already trimmed; `words` are the
2406    /// words as the file writes them, and the empty word is among them.
2407    ///
2408    /// The default writes each word as a standard string literal, its quotes
2409    /// doubled, and compares with the standard `IN`. An engine whose usual
2410    /// comparison ignores case or accents answers with a comparison that does
2411    /// not, and one whose string literals treat a backslash as an escape
2412    /// writes each word so that a backslash in it stays a backslash.
2413    fn render_missing_value(&self, text: &str, words: &[&str]) -> String {
2414        let listed = words
2415            .iter()
2416            .map(|word| format!("'{}'", word.replace('\'', "''")))
2417            .collect::<Vec<_>>()
2418            .join(", ");
2419        format!("CASE WHEN {text} IN ({listed}) THEN NULL ELSE {text} END")
2420    }
2421
2422    /// **Read a value the source spells its own way** into `target`, which is
2423    /// a date or a timestamp.
2424    ///
2425    /// An import arrives with `1/1/2015` in one column and
2426    /// `2015-01-01T00:00:00Z` in the next, and no engine reads either of them
2427    /// the same way as the engine beside it. So the design states the
2428    /// spelling, razeri reads it once into a [`DateFormat`], and this
2429    /// translates that list into whatever this engine's own pattern language
2430    /// is — `MM/DD/YYYY`, `MM/dd/yyyy`, a style number, or a format string
2431    /// this engine calls its own.
2432    ///
2433    /// **A value that is not spelled that way has to come back as NULL.**
2434    /// razeri reads the NULL as *this row did not parse* and writes the row
2435    /// into the table it sets rows aside in, naming the column and the format
2436    /// it was told to expect. An expression that stops the load instead leaves
2437    /// a warehouse half-loaded over one bad row, and one that answers a
2438    /// different day than the value says is worse than either. An engine whose
2439    /// parse reads a value it cannot read — rolling the forty-fifth of a month
2440    /// forward rather than answering nothing — writes its own guard beside the
2441    /// parse; [`DateFormat::shape_pattern`] and
2442    /// [`DateFormat::capture_pattern`] come from the same directive list, so
2443    /// the guard and the parse cannot hold two opinions about one spelling.
2444    ///
2445    /// **A directive this engine cannot say is a refusal, not a guess.**
2446    /// [`DateFormat::translate`] hands back the first directive this engine
2447    /// answered nothing for, and answering `None` here is how that reaches
2448    /// the author — by name, at the door, rather than as a wrong day in the
2449    /// warehouse.
2450    ///
2451    /// `None` — the default — is this engine stating nothing about how it
2452    /// reads a spelled value. razeri then refuses the column and names the
2453    /// engine.
2454    fn render_parse_datetime(
2455        &self,
2456        _expr: &str,
2457        _format: &DateFormat,
2458        _target: &DataType,
2459    ) -> Option<String> {
2460        None
2461    }
2462
2463    /// **Read a value the source writes its own way** into `target`, which is
2464    /// a number.
2465    ///
2466    /// A file writes a price `$2,899.99 `. The symbol, the thousands mark and
2467    /// the space around it are not part of the number, and no two engines
2468    /// agree about what to do with them — one converts the text to nothing,
2469    /// one to `2`, one raises. So the design states the picture, razeri reads
2470    /// it once into a [`NumberFormat`], and this renders the reading in
2471    /// whatever this engine's own words for *take this out* and *convert this*
2472    /// are.
2473    ///
2474    /// **A value that is not written that way has to come back as NULL.**
2475    /// razeri reads the NULL as *this row did not parse* and writes the row
2476    /// into the table it sets rows aside in, naming the column and the picture
2477    /// it was told to expect. An expression that stops the load instead leaves
2478    /// a warehouse half-loaded over one bad row, and one that answers `0` for
2479    /// text that was never a number is worse than either. An engine whose
2480    /// conversion raises, or answers a number for text that is not one, writes
2481    /// a guard in front of it; [`NumberFormat::shape_pattern`] is built from
2482    /// the same picture the marks come from, so the guard and the reading
2483    /// cannot hold two opinions about one spelling.
2484    ///
2485    /// `None` — the default — is this engine stating nothing about how it
2486    /// reads a written amount. razeri then refuses the column and names the
2487    /// engine. `None` is also the right answer for a target that is not a
2488    /// number: a picture says how an amount is written, and there is nothing
2489    /// else for it to be about.
2490    ///
2491    /// [`NumberFormat`]: crate::number_format::NumberFormat
2492    /// [`NumberFormat::shape_pattern`]: crate::number_format::NumberFormat::shape_pattern
2493    fn render_parse_number(
2494        &self,
2495        _expr: &str,
2496        _format: &NumberFormat,
2497        _target: &DataType,
2498    ) -> Option<String> {
2499        None
2500    }
2501
2502    /// Render string concatenation.
2503    fn render_concat(&self, parts: &[String]) -> String {
2504        format!("CONCAT({})", parts.join(", "))
2505    }
2506
2507    /// Render a COALESCE expression.
2508    fn render_coalesce(&self, parts: &[String]) -> String {
2509        format!("COALESCE({})", parts.join(", "))
2510    }
2511
2512    /// Render a string aggregation function.
2513    fn render_string_agg(&self, expr: &str, separator: &str) -> String {
2514        format!("STRING_AGG({expr}, '{separator}')")
2515    }
2516}
2517
2518/// A foreign key's referential action — SQL's own five words, no synonyms.
2519///
2520/// Lives here (rather than in the table model) so a dialect can answer
2521/// [`DdlRenderer::supports_foreign_key_action`] about a specific action
2522/// without depending on the modeling crate.
2523#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2524pub enum ReferentialAction {
2525    /// Also delete or update the referencing rows
2526    Cascade,
2527    /// Set the referencing columns to NULL
2528    SetNull,
2529    /// Reject the delete or update; some engines defer the check
2530    Restrict,
2531    /// Reject the delete or update (the SQL default)
2532    NoAction,
2533    /// Set the referencing columns to their default values
2534    SetDefault,
2535}
2536
2537impl ReferentialAction {
2538    /// Parses the SQL words, case-insensitively; underscores read as spaces
2539    /// so `set_null` and `SET NULL` both land.
2540    ///
2541    /// # Errors
2542    /// Returns a plain message listing the valid words when the input is not
2543    /// one of them.
2544    pub fn from_sql_word(word: &str) -> Result<Self, String> {
2545        match word.trim().replace('_', " ").to_uppercase().as_str() {
2546            "CASCADE" => Ok(Self::Cascade),
2547            "SET NULL" => Ok(Self::SetNull),
2548            "RESTRICT" => Ok(Self::Restrict),
2549            "NO ACTION" => Ok(Self::NoAction),
2550            "SET DEFAULT" => Ok(Self::SetDefault),
2551            _ => Err(format!(
2552                "'{word}' is not a referential action. Use one of: CASCADE, SET NULL, \
2553                 RESTRICT, NO ACTION, SET DEFAULT."
2554            )),
2555        }
2556    }
2557}
2558
2559impl std::fmt::Display for ReferentialAction {
2560    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2561        match self {
2562            Self::Cascade => write!(f, "CASCADE"),
2563            Self::SetNull => write!(f, "SET NULL"),
2564            Self::Restrict => write!(f, "RESTRICT"),
2565            Self::NoAction => write!(f, "NO ACTION"),
2566            Self::SetDefault => write!(f, "SET DEFAULT"),
2567        }
2568    }
2569}
2570
2571/// Level 3 — DDL rendering with reasonable defaults.
2572pub trait DdlRenderer: SqlRenderer {
2573    /// Prefix for CREATE TABLE statements.
2574    fn render_create_table_prefix(&self) -> &'static str {
2575        "CREATE TABLE"
2576    }
2577
2578    /// **Whether a column's `DEFAULT` is written before its `NOT NULL`.**
2579    ///
2580    /// The default, `false`, writes `NOT NULL DEFAULT …`, which is what every
2581    /// engine that does not override this has always been given. An engine
2582    /// that refuses that order and takes only `DEFAULT … NOT NULL` answers
2583    /// `true`.
2584    fn column_default_precedes_not_null(&self) -> bool {
2585        false
2586    }
2587
2588    /// Whether this engine carries the given foreign-key referential action
2589    /// (`ON DELETE …` / `ON UPDATE …`) in `CREATE TABLE` DDL.
2590    ///
2591    /// The ANSI default says yes to all five words. A dialect answers `false`
2592    /// for an action its engine rejects or silently never enforces; the
2593    /// renderer then keeps the author's declaration visible as a plain
2594    /// comment instead of emitting a clause the engine would refuse — a
2595    /// declared action never vanishes without a trace.
2596    fn supports_foreign_key_action(&self, action: ReferentialAction) -> bool {
2597        let _ = action;
2598        true
2599    }
2600
2601    /// Prefix for CREATE VIEW statements.
2602    fn render_create_view_prefix(&self) -> &'static str {
2603        "CREATE OR REPLACE VIEW"
2604    }
2605
2606    /// **Whether `CREATE OR REPLACE VIEW` replaces a view that other objects
2607    /// read.**
2608    ///
2609    /// The default, `true`, is what most engines do, and Razeri writes each
2610    /// view's statement as it stands. Answer `false` for an engine that
2611    /// refuses to replace a view while a later view, function or procedure
2612    /// depends on it, and Razeri asks
2613    /// [`render_view_replacement`](Self::render_view_replacement) for each
2614    /// view instead, naming the objects that read it. See
2615    /// [`view_replacement`](crate::view_replacement).
2616    fn replaces_a_view_that_is_read(&self) -> bool {
2617        true
2618    }
2619
2620    /// **The statements that make a view other objects read**, on an engine
2621    /// that answers `false` to
2622    /// [`replaces_a_view_that_is_read`](Self::replaces_a_view_that_is_read).
2623    ///
2624    /// The default drops each reader, the last made first, and then writes
2625    /// the view's own statement. The file makes every reader again when it
2626    /// reaches it. A view is dropped with
2627    /// [`render_drop_view`](Self::render_drop_view), a function with
2628    /// [`render_drop_function`](Self::render_drop_function), and a procedure
2629    /// with `DROP PROCEDURE IF EXISTS`; a routine's parameter types are
2630    /// written where
2631    /// [`supports_drop_function_arg_types`](Self::supports_drop_function_arg_types)
2632    /// says the engine takes them. Each statement but the last ends with
2633    /// [`statement_separator`](SqlRenderer::statement_separator); the caller
2634    /// ends the last.
2635    ///
2636    /// Override it for an engine that replaces such a view some other way.
2637    fn render_view_replacement(&self, replacement: &crate::ViewReplacement<'_>) -> String {
2638        let separator = self.statement_separator();
2639        let mut statements = String::new();
2640        for reader in replacement.readers {
2641            let types: Vec<&str> = if self.supports_drop_function_arg_types() {
2642                reader.parameter_types.iter().map(String::as_str).collect()
2643            } else {
2644                Vec::new()
2645            };
2646            let drop = match reader.kind {
2647                crate::ReaderKind::View => {
2648                    self.render_drop_view(reader.object(), true).map_or_else(
2649                        || format!("{} {}", self.render_drop_view_prefix(true), reader.relation),
2650                        |written| written.text().to_owned(),
2651                    )
2652                }
2653                crate::ReaderKind::Function => {
2654                    self.render_drop_function(&reader.relation, &types, true)
2655                }
2656                crate::ReaderKind::Procedure => {
2657                    let keyword = self.render_drop_object_keyword("procedure");
2658                    if types.is_empty() {
2659                        format!("DROP {keyword} IF EXISTS {}", reader.relation)
2660                    } else {
2661                        format!(
2662                            "DROP {keyword} IF EXISTS {}({})",
2663                            reader.relation,
2664                            types.join(", ")
2665                        )
2666                    }
2667                }
2668            };
2669            statements.push_str(drop.trim_end().trim_end_matches(';'));
2670            statements.push_str(separator);
2671        }
2672        statements.push_str(replacement.create);
2673        statements
2674    }
2675
2676    /// Render a column definition (name, type, nullability).
2677    fn render_column_definition(&self, name: &str, dt: &DataType, nullable: bool) -> String {
2678        let quoted = self.quote_identifier(name);
2679        let (type_str, null_str) = if nullable {
2680            (self.render_nullable_data_type(dt), "")
2681        } else {
2682            (self.render_data_type(dt), " NOT NULL")
2683        };
2684        format!("{quoted} {type_str}{null_str}")
2685    }
2686
2687    /// **The statement this engine takes for one change to a table that
2688    /// already holds rows**, or `None` where it has none.
2689    ///
2690    /// Razeri classifies every difference between two deploys and hands the
2691    /// ones that lose nothing to this method, one at a time. What comes back
2692    /// goes into the file an operator runs; `None` means the change is named in
2693    /// the plan with this engine's name beside it, so the reader learns which
2694    /// engine has no statement rather than that no engine does.
2695    ///
2696    /// # The default, and why it is the only one
2697    ///
2698    /// `ALTER TABLE … ADD COLUMN … <type>` is the spelling most engines take,
2699    /// so a dialect that answers nothing still writes the commonest evolution
2700    /// there is: a column that was not there yesterday. Some engines write
2701    /// `ADD` without `COLUMN` and refuse this one — Firebird answers *"Token
2702    /// unknown"* at `COLUMN` — so run it on yours, and override this method
2703    /// where it is refused.
2704    /// The column is declared without `NOT NULL`, which is the only form that
2705    /// can be added to a table that already holds rows.
2706    ///
2707    /// Every other change answers `None` by default. A widening and a record
2708    /// that gained a field are each spelled three or four ways across the
2709    /// engines Razeri reaches, and a default picked from one of them writes SQL
2710    /// the others reject — a statement handed to an operator who then finds out
2711    /// their engine will not take it. A dialect that has measured its engine
2712    /// says so here, and the ones that have not say nothing.
2713    ///
2714    /// The statement comes back without a terminator; the caller separates
2715    /// statements the way this engine separates them.
2716    fn render_column_evolution(&self, change: &ColumnEvolution<'_>) -> Option<String> {
2717        match change {
2718            ColumnEvolution::AddColumn { schema, table, column, data_type } => {
2719                let target = self.qualify_name(*schema, table);
2720                let name = self.quote_identifier(column);
2721                let rendered = self.render_nullable_data_type(data_type);
2722                Some(format!("ALTER TABLE {target} ADD COLUMN {name} {rendered}"))
2723            }
2724            ColumnEvolution::WidenColumn { .. }
2725            | ColumnEvolution::AddNestedField { .. }
2726            | ColumnEvolution::RequireColumn { .. } => None,
2727        }
2728    }
2729
2730    /// Render the surrogate identity column — a plain, ungenerated `NOT NULL`
2731    /// column of the type it is given, on **every** dialect.
2732    ///
2733    /// **razeri's surrogate keys are logical and DETERMINATE, never
2734    /// engine-generated.** The identity value is a hash
2735    /// derived from the entity's identity grain, WRITTEN BY THE LOAD
2736    /// (`materialize_core`, `sid_expression`), so the same design loaded with the
2737    /// same data converges to the same key on `Postgres`, `Snowflake`, `MariaDB`,
2738    /// `ClickHouse` — every target. A database-assigned `AUTO_INCREMENT` /
2739    /// `IDENTITY(1,1)` / `GENERATED ALWAYS AS IDENTITY` would be sequential,
2740    /// load-order-dependent and **non-portable** — a different key per database
2741    /// for the same row — which is the one thing a portable key may not be. So no
2742    /// dialect emits a generator here; every one renders a plain column and the
2743    /// load fills it.
2744    ///
2745    /// `SQLite` narrows the type to `INTEGER` and `ClickHouse`/`DuckDB` carry
2746    /// their own overrides only to document the same plain shape; no override
2747    /// re-introduces a generator.
2748    ///
2749    /// # The type is the engine's own word for it
2750    ///
2751    /// The word `BIGINT` is not written here, because not every engine has it:
2752    /// Oracle refuses it outright — `ORA-00902: invalid datatype` — so the
2753    /// table holding the column could not be created and nothing downstream
2754    /// of it could load. The shape is the decision here, a plain ungenerated
2755    /// column; how this engine spells a 64-bit integer is the dialect's answer
2756    /// to [`render_data_type`](SqlRenderer::render_data_type), asked for
2757    /// rather than assumed. An engine whose word for it *is* `BIGINT` gets a
2758    /// `BIGINT` column.
2759    fn render_identity_column(&self, name: &str, data_type: &DataType) -> String {
2760        let quoted = self.quote_identifier(name);
2761        let rendered = self.render_data_type(data_type);
2762        format!("{quoted} {rendered} NOT NULL")
2763    }
2764
2765    /// Whether this platform's engine actually **assigns** an identity column's
2766    /// value, rather than merely tolerating the declaration.
2767    ///
2768    /// **This is a dialect fact, not a field fact, and the difference is a
2769    /// deploy-time failure.** `Field::identity` says razeri intends the engine
2770    /// to generate the value; whether it does depends entirely on the target.
2771    /// `render_identity_column`'s own table above records that `DuckDB`,
2772    /// `SQLite` and `ClickHouse` have **no native identity** — there the column
2773    /// comes out as a plain `NOT NULL` and **the writer must supply it.**
2774    ///
2775    /// The default is `false` because the default `render_identity_column`
2776    /// emits no generation clause: a dialect that overrides the rendering to
2777    /// generate values must override this too, and
2778    /// `the_identity_capability_matches_what_each_dialect_renders` holds the two
2779    /// in step so they cannot drift.
2780    ///
2781    /// Read by the deploy bundle's write contract: a column
2782    /// the engine does not generate is a column a hand-written `INSERT` owes.
2783    fn generates_identity_values(&self) -> bool {
2784        false
2785    }
2786
2787    /// **The latest instant this platform can hold EXACTLY in the column it
2788    /// renders for `data_type`** — the ceiling the refuse-by-name rule compares
2789    /// against, or `None` for *no declared ceiling*.
2790    ///
2791    /// Spelled `YYYY-MM-DD HH:MM:SS`, which is how razeri writes a timestamp
2792    /// literal (`razeri_materialize::convert::OPEN_INTERVAL_SENTINEL`), so the
2793    /// comparison is a string comparison over a format that sorts
2794    /// chronologically. A ceiling and a value in the same spelling cannot be
2795    /// compared wrongly by a parser neither of them goes through.
2796    ///
2797    /// # What the refusal contract asks of this
2798    ///
2799    /// > A value razeri cannot store exactly on a target platform is a
2800    /// > deploy-time refusal naming the value, the column, the platform and the
2801    /// > ceiling — never a truncation, never a saturated write.
2802    ///
2803    /// The *refusal* lives in `razeri_materialize::bundle`, which is the one
2804    /// place it is built — the function is `refuse_unrepresentable_values`, and
2805    /// it is reached from `generate_bundle` before a single file is rendered.
2806    /// This is only where a platform declares the number.
2807    ///
2808    /// # A stated variance from the decision's original wording
2809    ///
2810    /// The refusal was decided as a *deploy-time* act, homed in the
2811    /// prerequisites step. Razeri refuses **earlier**: at bundle
2812    /// generation, by declining to emit the bundle at all. That is strictly
2813    /// ahead of deploy time and cannot be skipped by an operator who never runs
2814    /// the script — a deliberate strengthening, recorded rather
2815    /// than glossed. The consequence worth knowing: a *hand-assembled* bundle,
2816    /// or one from an older razeri, is not re-checked at deploy time by
2817    /// anything. **The default is `None`, which
2818    /// means "razeri has no measured ceiling for this platform and type" and not
2819    /// "this platform holds everything"** — an unmeasured platform gets no
2820    /// refusal rather than an invented one.
2821    ///
2822    /// # The ceiling is a property of the TYPE, not of the platform
2823    ///
2824    /// That is the half a platform-flat capability would get wrong, and it is
2825    /// measured rather than assumed (reading the renderers):
2826    ///
2827    /// | platform | `Timestamp(p)` renders | ceiling | `TimestampTz(p)` renders | ceiling |
2828    /// |---|---|---|---|---|
2829    /// | `MySQL`, `MariaDB` | `DATETIME(p)` | `None` — the end of the four-digit calendar is not a constraint | `TIMESTAMP(p)` | **`2038-01-19 03:14:07`** |
2830    /// | `ClickHouse` | `DateTime64(p)` | `2299-12-31 23:59:59` at p ≤ 6, **`2262-04-11 23:47:16`** at p ≥ 7 | `DateTime64(p,'UTC')` | the same |
2831    /// | everything else | — | not measured → `None` | — | `None` |
2832    ///
2833    /// On `MySQL` the two razeri type variants land on *different engine types*
2834    /// and get different answers: `Timestamp` renders as the
2835    /// non-converting `DATETIME` — the type whose semantics match the declared
2836    /// non-tz timestamp — which runs to the end of the calendar and so
2837    /// declares no ceiling at all, while `TimestampTz` keeps `TIMESTAMP` and its
2838    /// 32-bit epoch boundary. A check keyed on the platform alone would either
2839    /// miss the real ceiling or refuse a column that is fine. On `ClickHouse`
2840    /// the ceiling moves with the **declared precision** of one type:
2841    /// `DateTime64(9)` is int64 nanoseconds from the epoch and stops at
2842    /// 2262-04-11, while `DateTime64(6)` reaches 2299.
2843    ///
2844    /// Parameters:
2845    /// - `data_type`: the column's declared type, as the design carries it —
2846    ///   not the rendered string, because the precision is what moves the answer
2847    ///   and re-parsing it back out of `DateTime64(9)` would be a second reading
2848    ///   of what the dialect already knows.
2849    fn representable_timestamp_ceiling(&self, data_type: &DataType) -> Option<&'static str> {
2850        let _ = data_type;
2851        None
2852    }
2853
2854    /// Whether the platform requires every auto-increment / identity column to
2855    /// be the leading column of an index (PK or KEY).
2856    ///
2857    /// `MySQL` / `MariaDB`: `true` (otherwise error 1075). Others: `false`.
2858    ///
2859    /// When this is `true` and an identity column is not already the leading
2860    /// column of the primary key, the DDL renderer must emit an additional
2861    /// `KEY (identity_col)` clause on the table.
2862    fn auto_increment_requires_key(&self) -> bool {
2863        false
2864    }
2865
2866    /// Prefix for DROP TABLE statements.
2867    fn render_drop_table_prefix(&self, if_exists: bool) -> String {
2868        if if_exists { "DROP TABLE IF EXISTS".to_string() } else { "DROP TABLE".to_string() }
2869    }
2870
2871    /// Prefix for DROP VIEW statements.
2872    fn render_drop_view_prefix(&self, if_exists: bool) -> String {
2873        if if_exists { "DROP VIEW IF EXISTS".to_string() } else { "DROP VIEW".to_string() }
2874    }
2875
2876    /// Prefix for CREATE SCHEMA / CREATE NAMESPACE.
2877    fn render_create_schema_prefix(&self, if_not_exists: bool) -> String {
2878        if if_not_exists {
2879            "CREATE SCHEMA IF NOT EXISTS".to_string()
2880        } else {
2881            "CREATE SCHEMA".to_string()
2882        }
2883    }
2884
2885    /// Render a complete CREATE SCHEMA statement.
2886    ///
2887    /// Dialects that need fundamentally different syntax (e.g. T-SQL wrapping
2888    /// in `IF SCHEMA_ID(...) IS NULL EXEC(...)`) should override this method.
2889    /// The default concatenates [`Self::render_create_schema_prefix`] with the name.
2890    fn render_create_schema_statement(&self, name: &str, if_not_exists: bool) -> String {
2891        let prefix = self.render_create_schema_prefix(if_not_exists);
2892        format!("{prefix} {name}")
2893    }
2894
2895    /// Render a table comment (platform-specific syntax).
2896    ///
2897    /// Like [`Self::render_column_comment`], nothing in the tree calls this and
2898    /// no dialect overrides it — **and unlike its sibling it has not been
2899    /// measured.** Read that method's table before wiring either: the ANSI
2900    /// spelling is a hard syntax error on five of the ten platforms it was
2901    /// measured on at the column level, and this form was not probed.
2902    fn render_table_comment(&self, table: &str, comment: &str) -> Option<String> {
2903        Some(format!("COMMENT ON TABLE {table} IS '{comment}'"))
2904    }
2905
2906    /// Render a column comment — **not wired to anything, and measured**.
2907    ///
2908    /// # Nothing calls this
2909    ///
2910    /// No caller in the tree, no dialect override, and, until measured, no
2911    /// execution against a live engine — the exact state the column `DEFAULT`
2912    /// clause was in when it turned out to be refused outright on four platforms
2913    /// of ten and silently wrong on a fifth. Moving the open
2914    /// interval's meaning here was proposed **on the condition that it be measured first**,
2915    /// because *"a comment that fails to compile is a worse outcome than the
2916    /// clause it replaced"*.
2917    ///
2918    /// # It was measured, on ten platforms, and this ANSI form is right on five
2919    ///
2920    /// Executed against six containers, in-process `DuckDB` and
2921    /// `SQLite`, and both live cloud accounts:
2922    ///
2923    /// | platform | this `COMMENT ON COLUMN` | inline `COMMENT` in `CREATE TABLE` | what it does take |
2924    /// |---|---|---|---|
2925    /// | `PostgreSQL`, Citus | ✅ | ❌ syntax error | this, as a separate statement |
2926    /// | `DuckDB` | ✅ | ❌ syntax error | this, as a separate statement |
2927    /// | Snowflake, Databricks | ✅ | ✅ | either |
2928    /// | `ClickHouse` | ❌ `SYNTAX_ERROR` (code 62) | ✅ | inline, or `ALTER TABLE … COMMENT COLUMN c '…'` |
2929    /// | `MySQL`, `MariaDB` | ❌ `ERROR 1064` | ✅ | inline, or `ALTER TABLE … MODIFY <whole column definition> COMMENT '…'` |
2930    /// | SQL Server | ❌ `Msg 156, Incorrect syntax near the keyword 'ON'` | ❌ `Msg 102` | `EXEC sp_addextendedproperty …` — a stored procedure, not DDL |
2931    /// | `SQLite` | ❌ syntax error | ❌ syntax error | **nothing at all** |
2932    ///
2933    /// Four mechanisms across the ten platforms measured, and two of them carry
2934    /// a hazard the `DEFAULT` clause never had:
2935    ///
2936    /// - `MySQL`'s and `MariaDB`'s only `ALTER` route **redefines the column**.
2937    ///   Measured: a `MODIFY` that did not restate `NOT NULL` left
2938    ///   `is_nullable = YES` behind it. A documentation mechanism that can
2939    ///   silently de-constrain a column is strictly worse than the clause it
2940    ///   replaces.
2941    /// - SQL Server's `sp_addextendedproperty` **is not idempotent**:
2942    ///   `Msg 15233 — Property 'MS_Description' already exists`. Razeri emits
2943    ///   `CREATE TABLE IF NOT EXISTS` so a deploy bundle can be re-applied; a
2944    ///   comment mechanism that fails on the second run takes that away.
2945    ///
2946    /// # So the escape hatch was taken
2947    ///
2948    /// Q1's answer included its own fall-back — *"if the measurement comes back
2949    /// ugly, take the simpler answer: no comment, and the bundle README carries
2950    /// the contract"* — and the measurement is ugly. **Razeri emits no column
2951    /// comment.** The open interval's meaning ships instead in the deploy
2952    /// bundle's generated *write contract*
2953    /// (`razeri_materialize::bundle::write_contract`, Q5), which is prose an
2954    /// operator reads, is right on every platform because no engine parses
2955    /// it, and is owed regardless of how this measurement came out.
2956    ///
2957    /// The hook stays, unchanged and unwired, for the same reason
2958    /// `render_column_default` stays: a dialect that genuinely wants to emit one
2959    /// has somewhere to say so. **A dialect that overrides this owes a
2960    /// measurement first** — the ANSI spelling below is a hard syntax error on
2961    /// five of the ten platforms it was measured on.
2962    fn render_column_comment(&self, table: &str, column: &str, comment: &str) -> Option<String> {
2963        Some(format!("COMMENT ON COLUMN {table}.{column} IS '{comment}'"))
2964    }
2965
2966    /// Whether to render IF NOT EXISTS on CREATE TABLE.
2967    fn supports_if_not_exists(&self) -> bool {
2968        true
2969    }
2970
2971    /// Render a column's `DEFAULT` clause — **keyword included** — or decline it.
2972    ///
2973    /// `None` means *this dialect renders no default clause for this value*,
2974    /// and Razeri's column renderer omits the whole clause. The ANSI default
2975    /// returns `None` for every value, which
2976    /// is the write-contract rule expressed where the renderer can see it:
2977    /// **razeri emits no
2978    /// column `DEFAULT` clause in rendered DDL, on any platform, for any value —
2979    /// a value the generated load owns is written by the load, never by the
2980    /// schema.**
2981    ///
2982    /// *Read that qualifier deliberately.* The sentence is about the DDL an engine
2983    /// executes. The `.raz.sql` **agnostic interchange** form —
2984    /// `Table::to_ddl()`, which `Table::from_ddl()` parses back — still
2985    /// serializes `Field::default_value` as `DEFAULT <value>`, because that is
2986    /// where a design's declared default survives a save and a load.
2987    ///
2988    /// **That exception is a serializer, not a platform, and the word "agnostic"
2989    /// names both.** `to_ddl()` renders through a free function and consults no
2990    /// dialect; you reach it by calling it, never by choosing a target.
2991    /// `SchemaObject::render_ddl` short-circuits to it only for a renderer whose
2992    /// [`SqlRenderer::is_agnostic_dialect`] answers `true` — which defaults to
2993    /// `false` here and is overridden by exactly one type in the tree,
2994    /// `AnsiDialect`, which no registration hands out. The platform the registry
2995    /// publishes under the name `agnostic` is `AgnosticDialect`; it does **not**
2996    /// override the method, so it declines the clause like every other target.
2997    /// The rule therefore holds on every registered platform, `agnostic`
2998    /// included, on every rendering path, and a regression test pins it.
2999    ///
3000    /// # Why the keyword lives in here
3001    ///
3002    /// The answer carries the keyword so that the hook can **decline a clause**
3003    /// as well as rewrite a value. Were the caller to add `DEFAULT` in front of
3004    /// whatever came back, a dialect returning `""` would emit a bare dangling
3005    /// `DEFAULT`. The same holds for statement boundaries: *the emission
3006    /// declares the boundary; a consumer never infers it.*
3007    ///
3008    /// # Why the hook survives the decision
3009    ///
3010    /// `Field::default_value` stays on the struct, so the design
3011    /// still knows what a column's intended default is, and a future dialect that
3012    /// genuinely wants to emit one has somewhere to say so. The distinction being
3013    /// bought is between **what razeri knows** and **what razeri emits**.
3014    ///
3015    /// A dialect that overrides this owes the whole clause, keyword and all —
3016    /// `Some(format!("DEFAULT {value}"))` — because there is nowhere else it is
3017    /// added.
3018    fn render_column_default(&self, value: &str) -> Option<String> {
3019        let _ = value;
3020        None
3021    }
3022
3023    /// **Spell an author's OWN declared default in this engine's words.**
3024    ///
3025    /// This is the other sense of "default", and the seam where a dialect
3026    /// translates it. [`render_column_default`](Self::render_column_default)
3027    /// governs the tables Razeri's generated load owns, and it declines
3028    /// everywhere by design. A `tile: base` table is the exception: the author
3029    /// owns every column, no generated statement writes into it, and the
3030    /// declared default is an engine constraint they asked for — so it is
3031    /// rendered, on every platform.
3032    ///
3033    /// Rendered **verbatim**, it is a portability hole with the design's own
3034    /// words in it. A design declaring `default: CURRENT_TIMESTAMP` is asking
3035    /// for *the current moment*, not for those eighteen characters; on `BigQuery` those
3036    /// characters name the zone-aware type, the column Razeri builds is
3037    /// `DATETIME`, and the `CREATE TABLE` is refused outright — *"Column
3038    /// default expression has type TIMESTAMP which cannot be assigned to column
3039    /// type DATETIME"*. The design is right, and this is where it is
3040    /// translated.
3041    ///
3042    /// The default returns the value unchanged, so a dialect that says nothing
3043    /// renders the author's words as written.
3044    ///
3045    /// # A dialect overriding this owes a measurement, and owes restraint
3046    ///
3047    /// Translate an expression whose *meaning* your engine spells differently.
3048    /// Do not rewrite an author's literal, do not widen a type, and do not
3049    /// silently drop a default you cannot express — an author who declared one
3050    /// and got none has a column that fills with NULL and a document that says
3051    /// otherwise. Where the engine has no equivalent at all, leave the value
3052    /// alone and let the engine refuse it: a loud failure belongs to the value
3053    /// the author wrote, and a quiet substitution belongs to nobody.
3054    ///
3055    /// Parameters:
3056    /// - `value`: the default exactly as the design declares it.
3057    /// - `column_type`: the type of the column it is being assigned to —
3058    ///   load-bearing, because the same expression is legal against one type
3059    ///   and refused against another on the same engine.
3060    fn render_declared_column_default(&self, value: &str, column_type: &DataType) -> String {
3061        let _ = column_type;
3062        value.to_owned()
3063    }
3064
3065    // ═══════════════════════════════════════════════════════════════
3066    // DDL Extensions
3067    // ═══════════════════════════════════════════════════════════════
3068
3069    /// Render a BEGIN transaction statement.
3070    ///
3071    /// `PostgreSQL`: `BEGIN`, `SqlServer`: `BEGIN TRANSACTION`, `ClickHouse`: empty (no DDL transactions)
3072    fn render_begin_transaction(&self) -> &'static str {
3073        "BEGIN"
3074    }
3075
3076    /// Render a COMMIT transaction statement.
3077    fn render_commit(&self) -> &'static str {
3078        "COMMIT"
3079    }
3080
3081    /// Whether the platform supports DDL transactions.
3082    fn supports_ddl_transactions(&self) -> bool {
3083        true
3084    }
3085
3086    /// Render a DROP FUNCTION statement with optional parameter types for overloaded functions.
3087    fn render_drop_function(&self, name: &str, param_types: &[&str], if_exists: bool) -> String {
3088        let exists = if if_exists { " IF EXISTS" } else { "" };
3089        if param_types.is_empty() {
3090            format!("DROP FUNCTION{exists} {name}")
3091        } else {
3092            format!("DROP FUNCTION{exists} {name}({})", param_types.join(", "))
3093        }
3094    }
3095
3096    /// Render the drop keyword for a SQL object type.
3097    fn render_drop_object_keyword(&self, obj_type: &str) -> String {
3098        obj_type.to_uppercase()
3099    }
3100
3101    /// Render the CREATE VIEW keyword/prefix with `secure/global_temp` modifiers.
3102    fn render_create_view_keyword(&self, secure: bool, global_temp: bool) -> String {
3103        let mut parts = vec!["CREATE OR REPLACE"];
3104        if secure {
3105            parts.push("SECURE");
3106        }
3107        if global_temp {
3108            parts.push("GLOBAL TEMPORARY");
3109        }
3110        parts.push("VIEW");
3111        parts.join(" ")
3112    }
3113
3114    /// Whether `ALTER TABLE … DROP COLUMN IF EXISTS` is part of the grammar.
3115    ///
3116    /// The default [`render_drop_column`](Self::render_drop_column) reads it:
3117    /// where it is `false`, a drop asked to run only where the column stands
3118    /// is one the default cannot write.
3119    fn supports_alter_drop_if_exists(&self) -> bool {
3120        true
3121    }
3122
3123    /// **The statement that drops one column of a table that holds rows.**
3124    ///
3125    /// `table` is spelled as the statement writes it, and `column` too.
3126    /// `only_where_it_stands` asks for a drop that does nothing where the
3127    /// column is already gone, so a file of drops that stopped part way runs
3128    /// again whole: Razeri asks for it on an engine that commits each
3129    /// statement on its own. Answer `None` where this engine cannot say
3130    /// that, and Razeri writes the plain drop and tells the operator to run
3131    /// the file again from the statement that stopped.
3132    ///
3133    /// The default writes `ALTER TABLE … DROP COLUMN …`, with `IF EXISTS`
3134    /// where [`supports_alter_drop_if_exists`](Self::supports_alter_drop_if_exists)
3135    /// says the engine takes it. An engine with neither `IF EXISTS` nor the
3136    /// `COLUMN` word answers in its own words: a guard over its catalogue, a
3137    /// prepared statement chosen by `information_schema`, or a block.
3138    fn render_drop_column(
3139        &self,
3140        table: WrittenObject<'_>,
3141        column: &str,
3142        only_where_it_stands: bool,
3143    ) -> Option<Written> {
3144        let relation = table.relation;
3145        if !only_where_it_stands {
3146            return Some(Written::Statement(format!(
3147                "ALTER TABLE {relation} DROP COLUMN {column}"
3148            )));
3149        }
3150        self.supports_alter_drop_if_exists().then(|| {
3151            Written::Statement(format!("ALTER TABLE {relation} DROP COLUMN IF EXISTS {column}"))
3152        })
3153    }
3154
3155    /// **The statement that drops one of Razeri's views**, spelled as the
3156    /// statement writes it.
3157    ///
3158    /// `only_where_it_stands` asks for a drop that does nothing where the
3159    /// view is already gone. The default is
3160    /// [`render_drop_view_prefix`](Self::render_drop_view_prefix) and the
3161    /// view; an engine with no `DROP VIEW IF EXISTS` answers with a guard of
3162    /// its own, or `None` where it has none.
3163    fn render_drop_view(
3164        &self,
3165        view: WrittenObject<'_>,
3166        only_where_it_stands: bool,
3167    ) -> Option<Written> {
3168        Some(Written::Statement(format!(
3169            "{} {}",
3170            self.render_drop_view_prefix(only_where_it_stands),
3171            view.relation
3172        )))
3173    }
3174
3175    /// **A `CREATE TABLE` that runs only where the table is not there yet**,
3176    /// on an engine whose grammar has no `CREATE TABLE IF NOT EXISTS`.
3177    ///
3178    /// A deploy runs again over the warehouse it made, so each table it makes
3179    /// has to pass over one that already stands. Where
3180    /// [`supports_if_not_exists`](Self::supports_if_not_exists) is `true` the
3181    /// statement says so itself and this is never asked. Where it is `false`,
3182    /// `create` is the whole plain statement and `table` its name as written:
3183    /// answer with the statement behind a question of your engine's
3184    /// catalogue, or `None` — the default — where you have none, and a second
3185    /// deploy is refused at the first table by the engine, with nothing
3186    /// changed.
3187    fn render_create_table_if_absent(
3188        &self,
3189        table: WrittenObject<'_>,
3190        create: &str,
3191    ) -> Option<Written> {
3192        let _ = (table, create);
3193        None
3194    }
3195
3196    /// **The statement that copies a table, every row it holds, into a new
3197    /// table beside it.**
3198    ///
3199    /// Razeri asks for it before a change destroys data, where the operator
3200    /// asks to keep a copy first (`razeri evolve --rescue`): `source` is the
3201    /// table, `copy` the new table's name, both spelled as the statement
3202    /// writes them. The copy takes the source's columns and types as the
3203    /// engine reads them; it needs no key, no index and no constraint.
3204    ///
3205    /// The default is `CREATE TABLE … AS SELECT * FROM …`, with
3206    /// [`render_create_table_prefix`](Self::render_create_table_prefix) and,
3207    /// on its own line before `AS`, the clause
3208    /// [`render_table_suffix`](crate::SqlRenderer::render_table_suffix)
3209    /// answers for a plain table with no key — so an engine that needs an
3210    /// engine clause on every table has it here too. An engine with no
3211    /// `CREATE TABLE … AS` answers in its own words: SQL Server's
3212    /// `SELECT * INTO … FROM …`, or SAP HANA's `AS (…) WITH DATA`.
3213    fn render_copy_table(&self, source: WrittenObject<'_>, copy: WrittenObject<'_>) -> Written {
3214        let suffix = self
3215            .render_table_suffix(&TableSuffixRequest::new())
3216            .map(|clause| format!("\n{clause}"))
3217            .unwrap_or_default();
3218        Written::Statement(format!(
3219            "{} {}{suffix}\nAS SELECT * FROM {}",
3220            self.render_create_table_prefix(),
3221            copy.relation,
3222            source.relation
3223        ))
3224    }
3225
3226    /// **The clause a table's storage settings are written in**, after its
3227    /// column list — SQL Server's `WITH (DATA_COMPRESSION = PAGE)` — or `None`
3228    /// where none of `settings` is this engine's, which is the default.
3229    ///
3230    /// See [`EngineSetting`]: spell the settings written for your engine and
3231    /// pass over the rest.
3232    fn render_table_storage_options(&self, settings: &[EngineSetting<'_>]) -> Option<String> {
3233        let _ = settings;
3234        None
3235    }
3236
3237    // ═══════════════════════════════════════════════════════════════
3238    // Drop Behavior Hooks
3239    // ═══════════════════════════════════════════════════════════════
3240
3241    /// Whether DROP INDEX uses ON syntax: `DROP INDEX idx ON table` (`SqlServer`).
3242    fn drop_index_uses_on_syntax(&self) -> bool {
3243        false
3244    }
3245
3246    /// **Whether this engine checks the constraints it accepts.**
3247    ///
3248    /// The default is [`ConstraintEnforcement::Enforced`] — eight of Razeri's
3249    /// registered platforms, and the safe assumption for a dialect that has not
3250    /// said, because *"this engine guarantees nothing"* is the unusual claim.
3251    ///
3252    /// Answer [`ConstraintEnforcement::DeclaredOnly`] where a `PRIMARY KEY`,
3253    /// `FOREIGN KEY` or `UNIQUE` is accepted and never checked. Two engines are
3254    /// that, in two different ways, and the type carries both:
3255    ///
3256    /// - `BigQuery` has the words. `NOT ENFORCED` is the only legal spelling,
3257    ///   so the keyword goes on the constraint line and the engine makes the
3258    ///   declaration honest by itself.
3259    /// - `Redshift` has no words. It takes all three constraints, checks none,
3260    ///   and renders DDL a reader cannot tell from `PostgreSQL`'s — so the note
3261    ///   is written above the constraint list instead, and it is the only place
3262    ///   that DDL says what it means.
3263    ///
3264    /// [`key_constraint_suffix`](Self::key_constraint_suffix) reads this, so
3265    /// stating enforcement states the suffix too.
3266    fn constraint_enforcement(&self) -> ConstraintEnforcement {
3267        ConstraintEnforcement::Enforced
3268    }
3269
3270    /// **The words a key constraint must carry to be accepted at all.**
3271    ///
3272    /// Appended to a table-level `PRIMARY KEY (…)` and to a
3273    /// `FOREIGN KEY (…) REFERENCES …`. Empty on every engine that enforces its
3274    /// keys, and empty on a declaring engine that has no keyword for it.
3275    ///
3276    /// The default reads
3277    /// [`constraint_enforcement`](Self::constraint_enforcement), so the two are
3278    /// one fact rather than two that must be kept in step. Override this only
3279    /// for a keyword a key constraint needs for some *other* reason than
3280    /// enforcement — there is no such engine in Razeri's set today.
3281    fn key_constraint_suffix(&self) -> &'static str {
3282        self.constraint_enforcement().keyword()
3283    }
3284
3285    /// **Whether a `PRIMARY KEY` is part of the grammar.**
3286    ///
3287    /// `false` on an engine that has no primary key at all — one that refuses
3288    /// the declaration, not one that accepts it and checks nothing (that is
3289    /// [`Self::constraint_enforcement`]). The key is left out of
3290    /// the `CREATE TABLE` and named in a comment beside it, and the loads still
3291    /// match rows on its columns, as they do everywhere. Default `true`.
3292    fn supports_primary_key_constraint(&self) -> bool {
3293        true
3294    }
3295
3296    /// **Whether a `FOREIGN KEY … REFERENCES` is part of the grammar.**
3297    ///
3298    /// `false` on an engine that refuses the declaration; it is left out and
3299    /// named in a comment beside the table. Default `true`.
3300    fn supports_foreign_key_constraint(&self) -> bool {
3301        true
3302    }
3303
3304    /// Whether a table-level `UNIQUE (…)` constraint is part of the grammar.
3305    ///
3306    /// `false` on an engine that has no such constraint at all, where the
3307    /// declaration is left out of the `CREATE TABLE` and named in a comment
3308    /// beside it rather than emitted and refused.
3309    fn supports_unique_constraint(&self) -> bool {
3310        true
3311    }
3312
3313    /// Whether a table-level `CHECK (…)` constraint is part of the grammar.
3314    ///
3315    /// `false` on an engine that has none, with the same treatment as
3316    /// [`supports_unique_constraint`](Self::supports_unique_constraint): named
3317    /// in a comment, never written as SQL the engine will reject.
3318    fn supports_check_constraint(&self) -> bool {
3319        true
3320    }
3321
3322    /// Whether the platform supports CASCADE/RESTRICT in DROP statements.
3323    ///
3324    /// True for `PostgreSQL`, `CitusDB`, `DuckDB`, Snowflake, Agnostic.
3325    /// False for `SqlServer`, `ClickHouse`, Databricks, `MySQL`, `MariaDB`.
3326    fn supports_cascade_drop(&self) -> bool {
3327        true
3328    }
3329
3330    /// Whether `COMMENT ON PROCEDURE` is part of the grammar.
3331    ///
3332    /// `true` almost everywhere, and **false on `Redshift`**, where
3333    /// `COMMENT ON FUNCTION`, `COMMENT ON VIEW` and `COMMENT ON COLUMN` all
3334    /// exist and the procedure form alone does not: *"syntax error at or near
3335    /// `PROCEDURE`"*, measured on a live workgroup. `CockroachDB` 24.3 refuses
3336    /// it the same way. A description is worth having and is not worth a
3337    /// statement that stops the script, so a declining engine simply carries
3338    /// no description on its procedures. Pass this answer to
3339    /// [`render_procedure_as`](crate::routine_render::render_procedure_as)
3340    /// when you spell a procedure through it, and it leaves the description
3341    /// out too.
3342    fn supports_procedure_comment(&self) -> bool {
3343        true
3344    }
3345
3346    /// Whether the platform supports function argument types in DROP FUNCTION.
3347    ///
3348    /// False for `ClickHouse` (no overloaded functions).
3349    fn supports_drop_function_arg_types(&self) -> bool {
3350        true
3351    }
3352
3353    /// Whether the platform supports SYNC option for DROP (`ClickHouse`).
3354    fn supports_sync_drop(&self) -> bool {
3355        false
3356    }
3357
3358    /// Whether the platform supports FORCE option for DROP (Databricks).
3359    fn supports_force_drop(&self) -> bool {
3360        false
3361    }
3362
3363    /// Whether the platform supports CASCADE in ALTER TABLE DROP.
3364    ///
3365    /// Only `PostgreSQL`, `CitusDB`, `DuckDB` support CASCADE in ALTER TABLE DROP.
3366    fn supports_alter_drop_cascade(&self) -> bool {
3367        false
3368    }
3369}
3370
3371/// **Three questions a load asks of a number written as text**, each a
3372/// condition over the value, for a column declared `decimal(precision,
3373/// scale)` ([`ExpressionRenderer::render_decimal_fit`]).
3374#[derive(Debug, Clone, PartialEq, Eq)]
3375pub struct DecimalFit {
3376    /// True of a value written as a plain number: digits, at most one point,
3377    /// and at most one sign, ahead of them. It may be true of a value with no
3378    /// digits at all, such as the empty text or a lone point.
3379    pub plain: String,
3380    /// True where a digit other than `0` stands more places before the point
3381    /// than the column leaves room for, `precision - scale`, counted from the
3382    /// point (or from the end, where there is none). Asked of any text; false
3383    /// of every plain number that fits.
3384    pub past_room: String,
3385    /// True where a digit other than `0` stands more places after the point
3386    /// than `scale`. Asked of any text; false of every plain number that fits.
3387    pub past_scale: String,
3388}
3389
3390impl DecimalFit {
3391    /// **The three questions as regular expressions**, each pattern handed
3392    /// to `matches` to be written as the engine matches one somewhere in the
3393    /// value (`text ~ 'pattern'`, `regexp_matches(text, 'pattern')`): a plain
3394    /// number is an optional sign, digits and at most one point; a digit
3395    /// other than `0` followed by the column's room in digits, before any
3396    /// point, is too large; one past the scale after the point is a place the
3397    /// column does not keep. The patterns hold no backslash and no quote, so
3398    /// they read the same under every string-literal setting.
3399    pub fn by_regular_expression(
3400        precision: u8,
3401        scale: u8,
3402        matches: impl Fn(&str) -> String,
3403    ) -> Self {
3404        let room = precision.saturating_sub(scale);
3405        Self {
3406            plain: matches("^[+-]?[0-9]*[.]?[0-9]*$"),
3407            past_room: matches(&format!("^[^.]*[1-9][0-9]{{{room}}}")),
3408            past_scale: matches(&format!("[.][0-9]{{{scale}}}[0-9]*[1-9]")),
3409        }
3410    }
3411}
3412
3413/// **A table a procedure writes once and reads by name**
3414/// ([`ProcedureRenderer::render_procedure_table`]).
3415#[derive(Debug, Clone, PartialEq, Eq)]
3416pub struct ProcedureTable {
3417    /// The statements that write it, each ended for a procedure's body.
3418    pub statements: Vec<String>,
3419    /// The name the statements after them read it by.
3420    pub reference: String,
3421}
3422
3423/// **One row, written once** — the pieces of an INSERT that must do nothing
3424/// when a row already carries the same key.
3425///
3426/// The key value is not a field of its own: it is whichever `values` entry sits
3427/// at the same index as the key column in `columns`. Two fields that must agree
3428/// are two fields free to disagree, and the one they would disagree about here
3429/// is the one that decides whether a second write is a duplicate.
3430#[derive(Debug, Clone, Copy)]
3431pub struct InsertIfAbsent<'a> {
3432    /// The target table, already spelled the way the caller wants it written —
3433    /// schema-qualified or bare.
3434    pub table: &'a str,
3435    /// The columns being written, in the order `values` supplies them.
3436    pub columns: &'a [&'a str],
3437    /// One value expression per column.
3438    pub values: &'a [String],
3439    /// The columns whose equality means *this row is already here*.
3440    pub key_columns: &'a [&'a str],
3441}
3442
3443impl InsertIfAbsent<'_> {
3444    /// The value expression written into `column`, if it is being written.
3445    #[must_use]
3446    pub fn value_of(&self, column: &str) -> Option<&str> {
3447        let at = self.columns.iter().position(|name| *name == column)?;
3448        self.values.get(at).map(String::as_str)
3449    }
3450
3451    /// `key = value AND …` — the test for *already here*, in terms of the
3452    /// values this INSERT would have written.
3453    ///
3454    /// `qualifier` prefixes the column side, which the guarded form needs so
3455    /// the probe's own row is named unambiguously.
3456    ///
3457    /// # Panics
3458    ///
3459    /// When a key column is not among the columns being written. A key the
3460    /// INSERT does not supply cannot be tested for, and silently dropping it
3461    /// from the predicate would make the guard match everything.
3462    #[must_use]
3463    pub fn key_predicate(&self, qualifier: &str) -> String {
3464        self.key_columns
3465            .iter()
3466            .map(|column| {
3467                let value = self
3468                    .value_of(column)
3469                    .unwrap_or_else(|| panic!("{column} is a key column and must be written"));
3470                format!("{qualifier}{column} = {value}")
3471            })
3472            .collect::<Vec<_>>()
3473            .join(" AND ")
3474    }
3475
3476    /// **`ON CONFLICT (key) DO NOTHING`** — for the platforms that let the
3477    /// engine decide, which is every platform that has the clause.
3478    ///
3479    /// The engine tests the key as it writes, so two sessions registering one
3480    /// file at the same moment settle on one row rather than on whichever of
3481    /// them looked first.
3482    #[must_use]
3483    pub fn on_conflict_do_nothing(&self) -> String {
3484        format!(
3485            "{}\n{}\nON CONFLICT ({}) DO NOTHING;",
3486            self.target(),
3487            self.values_clause(),
3488            self.key_columns.join(", ")
3489        )
3490    }
3491
3492    /// **`ON DUPLICATE KEY UPDATE key = key`** — the `MySQL` family's no-op.
3493    ///
3494    /// `INSERT IGNORE` would be shorter and it is not the same request: it
3495    /// downgrades *every* error on the statement to a warning — a truncated
3496    /// value, a bad date — so a row that should have been refused arrives
3497    /// mangled and silent. Assigning the key to itself touches only the
3498    /// collision this is about, and leaves everything else to complain
3499    /// normally.
3500    #[must_use]
3501    pub fn on_duplicate_key_no_op(&self) -> String {
3502        let held = self
3503            .key_columns
3504            .iter()
3505            .map(|column| format!("{column} = {column}"))
3506            .collect::<Vec<_>>()
3507            .join(", ");
3508        format!("{}\n{}\nON DUPLICATE KEY UPDATE {held};", self.target(), self.values_clause())
3509    }
3510
3511    /// **The guarded form over an explicit one-row source** — the same
3512    /// `INSERT … SELECT … WHERE NOT EXISTS` the portable default writes, with a
3513    /// `FROM` clause under it.
3514    ///
3515    /// `GoogleSQL` refuses a `WHERE` on a query that selects from nothing —
3516    /// *"Query without FROM clause cannot have a WHERE clause"*, measured on the
3517    /// live service on every generated `register_file` procedure — while
3518    /// `PostgreSQL` and its cousins accept the bare form. `(SELECT 1)` is a
3519    /// one-row table that changes no result: the guard still decides whether
3520    /// the row is written, and the values are still the caller's.
3521    ///
3522    /// It stays a separate form rather than becoming the default because the
3523    /// engines that need no `FROM` read better without one, and a clause every
3524    /// platform carries for one platform's sake is how a rendering stops saying
3525    /// what it means.
3526    #[must_use]
3527    pub fn guarded_over_one_row(&self) -> String {
3528        format!(
3529            "{}\nSELECT {}\nFROM (SELECT 1)\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
3530            self.target(),
3531            self.values.join(", "),
3532            self.table,
3533            self.key_predicate("")
3534        )
3535    }
3536
3537    /// `INSERT INTO t (a, b)` — shared by every form below.
3538    fn target(&self) -> String {
3539        format!("INSERT INTO {} ({})", self.table, self.columns.join(", "))
3540    }
3541
3542    /// `VALUES (…)`.
3543    fn values_clause(&self) -> String {
3544        format!("VALUES ({})", self.values.join(", "))
3545    }
3546}
3547
3548/// Level 4 — DML rendering with reasonable defaults.
3549pub trait DmlRenderer: SqlRenderer {
3550    /// Prefix for INSERT statements.
3551    fn render_insert_prefix(&self) -> &'static str {
3552        "INSERT INTO"
3553    }
3554
3555    /// **Write one row, and do nothing if its key is already there.**
3556    ///
3557    /// Every platform can express this and they do not agree on how, so the
3558    /// spelling belongs to the dialect and not to the caller. The default is
3559    /// the portable one — an `INSERT … SELECT` guarded by `WHERE NOT EXISTS` —
3560    /// which needs no upsert syntax at all and is therefore the right answer
3561    /// for a platform nobody has written an arm for. Platforms with a native
3562    /// idiom override it: `ON CONFLICT … DO NOTHING` where that exists,
3563    /// `ON DUPLICATE KEY UPDATE` on the `MySQL` family.
3564    ///
3565    /// **No dialect is left without an idempotent form.** The guarded form is
3566    /// weaker than the native ones under concurrency — two sessions can both
3567    /// find the row absent and both insert — which is why a platform that can
3568    /// let the engine decide should, and why this one leans on the key's own
3569    /// uniqueness constraint to catch the race rather than pretending it cannot
3570    /// happen. On an engine that enforces no key at all the guard is the whole
3571    /// of what there is, and it is worth saying so rather than implying more.
3572    fn render_insert_if_absent(&self, insert: &InsertIfAbsent<'_>) -> String {
3573        format!(
3574            "{}\nSELECT {}\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
3575            insert.target(),
3576            insert.values.join(", "),
3577            insert.table,
3578            insert.key_predicate("")
3579        )
3580    }
3581
3582    /// Prefix for MERGE statements.
3583    fn render_merge_prefix(&self) -> &'static str {
3584        "MERGE INTO"
3585    }
3586
3587    /// Render the platform's upsert strategy keyword.
3588    ///
3589    /// Returns `None` if platform doesn't support upsert natively.
3590    fn render_upsert_strategy(&self) -> Option<&str> {
3591        None
3592    }
3593
3594    /// Render RETURNING / OUTPUT clause for INSERT/UPDATE.
3595    fn render_returning_clause(&self, _columns: &[&str]) -> Option<String> {
3596        None
3597    }
3598
3599    /// Render a LIMIT clause.
3600    fn render_limit_clause(&self, n: usize) -> String {
3601        format!("LIMIT {n}")
3602    }
3603
3604    /// Render a temporary table prefix or keyword.
3605    fn render_temp_table_prefix(&self) -> &'static str {
3606        "TEMPORARY"
3607    }
3608
3609    /// **One row holding an array becomes one row per element.**
3610    ///
3611    /// Razeri hands over the relation it is reading, the array column, and the
3612    /// element fields the statement needs; the engine answers with the `FROM`
3613    /// item that produces the rows and the expressions that read them. The
3614    /// three parts come back together because on at least one engine they
3615    /// depend on each other: its field expressions name an alias its own
3616    /// `FROM` item introduced.
3617    ///
3618    /// **The ordinal is one for the first element, on every engine.** Engines
3619    /// disagree about where an array starts — some count from one, some from
3620    /// zero, one answers in text — and the element's surrogate key is derived
3621    /// from its position. An engine answering in its own base would give one
3622    /// element two different keys depending on where it was stored, so the
3623    /// normalization belongs here, where the engine that counts from zero pays
3624    /// for it with one addition.
3625    ///
3626    /// `None` — the default — is this engine stating no flatten. Razeri then
3627    /// refuses the declaration and names the engine, rather than guessing an
3628    /// idiom or emitting a statement that does not run.
3629    fn render_flatten(&self, _request: &FlattenRequest<'_>) -> Option<Flatten> {
3630        None
3631    }
3632}
3633
3634/// Level 5 — Stored procedure / function rendering with defaults.
3635pub trait ProcedureRenderer: SqlRenderer {
3636    /// Prefix for CREATE PROCEDURE.
3637    fn render_create_procedure_prefix(&self) -> &'static str {
3638        "CREATE OR REPLACE PROCEDURE"
3639    }
3640
3641    /// Prefix for CREATE FUNCTION.
3642    fn render_create_function_prefix(&self) -> &'static str {
3643        "CREATE OR REPLACE FUNCTION"
3644    }
3645
3646    /// **Rows a procedure writes once and reads by name**: the statements,
3647    /// inside a procedure's body, that keep `query`'s rows in a table only
3648    /// this call sees, and the name the statements after them read it by —
3649    /// or `None`, the default, where the engine has no such table and each
3650    /// statement reads `query` itself.
3651    ///
3652    /// A core table's load converts its staged text into the design's types
3653    /// once, here, and its refusals and its write read the converted rows by
3654    /// name: one pass over the staged rows rather than one for each
3655    /// statement. `name` is a plain identifier, unique within the procedure.
3656    /// The table must not outlive the call, and two calls running at once
3657    /// must not see each other's.
3658    fn render_procedure_table(&self, name: &str, query: &str) -> Option<ProcedureTable> {
3659        let _ = (name, query);
3660        None
3661    }
3662
3663    /// Render a variable declaration inside a procedure body.
3664    fn render_variable_declaration(&self, name: &str, dt: &DataType) -> String {
3665        format!("DECLARE {} {};", name, self.render_data_type(dt))
3666    }
3667
3668    /// Render BEGIN/END block delimiters.
3669    fn render_begin_end(&self, body: &str) -> String {
3670        format!("BEGIN\n{body}\nEND;")
3671    }
3672
3673    /// Whether procedures use a language clause (e.g., Snowflake JavaScript).
3674    fn requires_language_clause(&self) -> bool {
3675        false
3676    }
3677
3678    /// **A statement that calls each of `calls` once for every row of
3679    /// `query`**, or `None` where this engine has none to write, the default.
3680    ///
3681    /// `query` answers one column; each row's value is held in `variable`, of
3682    /// the type `variable_type` spells in this engine, and each call names
3683    /// `variable` where it takes the value. A generated fill asks this to make
3684    /// a staging partition for every day a file holds before it stages a row
3685    /// of any, on an engine that keeps nowhere for a row whose day has no
3686    /// partition. Where the answer is `None`, the fill is refused by name,
3687    /// with the calls to make by hand.
3688    fn render_call_for_each_row(
3689        &self,
3690        variable: &str,
3691        variable_type: &str,
3692        query: &str,
3693        calls: &[String],
3694    ) -> Option<String> {
3695        let _ = (variable, variable_type, query, calls);
3696        None
3697    }
3698}
3699
3700#[cfg(test)]
3701mod tests {
3702    use super::*;
3703    use crate::DialectCapabilities;
3704    use crate::sid_spelling::SidHelperLanguage;
3705
3706    /// A test dialect that implements only the required `SqlRenderer` methods.
3707    /// All other traits use defaults.
3708    struct TestDialect;
3709
3710    impl SqlRenderer for TestDialect {
3711        fn render_data_type(&self, dt: &DataType) -> String {
3712            match dt {
3713                DataType::Boolean(_) => "BOOLEAN".to_string(),
3714                DataType::Integer(_) => "INTEGER".to_string(),
3715                _ => "TEXT".to_string(),
3716            }
3717        }
3718        fn quote_identifier(&self, name: &str) -> String {
3719            format!("\"{name}\"")
3720        }
3721        fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
3722            match schema {
3723                Some(s) => format!("{}.{}", self.quote_identifier(s), self.quote_identifier(name)),
3724                None => self.quote_identifier(name),
3725            }
3726        }
3727        fn render_current_timestamp(&self) -> String {
3728            "CURRENT_TIMESTAMP".to_string()
3729        }
3730    }
3731
3732    impl ExpressionRenderer for TestDialect {}
3733    impl DdlRenderer for TestDialect {}
3734    impl DmlRenderer for TestDialect {}
3735    impl ProcedureRenderer for TestDialect {}
3736    impl DialectCapabilities for TestDialect {}
3737
3738    /// **An alias the engine reserves is quoted, and one it leaves free is
3739    /// not** — by the standard's list until the dialect says otherwise.
3740    #[test]
3741    fn an_alias_is_quoted_only_where_the_engine_reserves_the_word() {
3742        let d = TestDialect;
3743        assert_eq!(d.render_alias("matched"), "matched");
3744        assert_eq!(d.render_alias("standing"), "standing");
3745        assert_eq!(d.render_alias("year"), "\"year\"");
3746        assert_eq!(d.render_alias("VALUE"), "\"VALUE\"");
3747    }
3748
3749    /// **A view nothing reads is made by its own statement, and a view that
3750    /// is read is made after its readers are dropped, the last made first.**
3751    #[test]
3752    fn a_view_that_is_read_is_made_after_its_readers_are_dropped() {
3753        use crate::{ReaderKind, ViewReader, ViewReplacement, WrittenObject};
3754        let d = TestDialect;
3755        let create = "CREATE OR REPLACE VIEW core.\"customers_identity_current\" AS SELECT 1";
3756        let view = WrittenObject::new(
3757            Some("core"),
3758            "\"customers_identity_current\"",
3759            "core.\"customers_identity_current\"",
3760        );
3761        assert_eq!(d.render_view_replacement(&ViewReplacement::new(view, create, &[])), create);
3762        let readers = [
3763            ViewReader::new(
3764                ReaderKind::Procedure,
3765                Some("core".to_owned()),
3766                "\"customers_load\"".to_owned(),
3767                "core.\"customers_load\"".to_owned(),
3768                Vec::new(),
3769            ),
3770            ViewReader::new(
3771                ReaderKind::Function,
3772                Some("core".to_owned()),
3773                "\"customers_as_of\"".to_owned(),
3774                "core.\"customers_as_of\"".to_owned(),
3775                vec!["TIMESTAMP".to_owned()],
3776            ),
3777            ViewReader::new(
3778                ReaderKind::View,
3779                Some("core".to_owned()),
3780                "\"customers_current\"".to_owned(),
3781                "core.\"customers_current\"".to_owned(),
3782                Vec::new(),
3783            ),
3784        ];
3785        assert_eq!(
3786            d.render_view_replacement(&ViewReplacement::new(view, create, &readers)),
3787            format!(
3788                "DROP PROCEDURE IF EXISTS core.\"customers_load\";\n\
3789                 DROP FUNCTION IF EXISTS core.\"customers_as_of\"(TIMESTAMP);\n\
3790                 DROP VIEW IF EXISTS core.\"customers_current\";\n\
3791                 {create}"
3792            )
3793        );
3794        assert!(d.replaces_a_view_that_is_read(), "most engines replace in place");
3795    }
3796
3797    /// **No engine is handed the statement that requires a column until its
3798    /// dialect writes one.**
3799    #[test]
3800    fn requiring_a_column_is_no_statement_until_a_dialect_writes_one() {
3801        let data_type = DataType::boolean();
3802        let change = ColumnEvolution::RequireColumn {
3803            schema: Some("core"),
3804            table: "customers",
3805            column: "is_active",
3806            data_type: &data_type,
3807        };
3808        assert_eq!(change.column(), "is_active");
3809        assert!(TestDialect.render_column_evolution(&change).is_none());
3810    }
3811
3812    /// The same dialect with the two file-and-key facts stated. It exists to
3813    /// prove that a dialect Razeri never compiled against reaches the behaviour
3814    /// by *declaring* it — which is the whole property, and is not visible from
3815    /// a dialect that ships in this tree.
3816    struct StatedDialect;
3817
3818    impl SqlRenderer for StatedDialect {
3819        fn render_data_type(&self, _dt: &DataType) -> String {
3820            "TEXT".to_string()
3821        }
3822        fn quote_identifier(&self, name: &str) -> String {
3823            format!("\"{name}\"")
3824        }
3825        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
3826            self.quote_identifier(name)
3827        }
3828        fn render_current_timestamp(&self) -> String {
3829            "CURRENT_TIMESTAMP".to_string()
3830        }
3831        fn sid_helper_body(&self) -> Option<SidHelperBody> {
3832            Some(SidHelperBody {
3833                language: SidHelperLanguage::Named("ecmascript"),
3834                body: "return 1;",
3835            })
3836        }
3837        fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
3838            Some(format!("SCAN({path_literal})"))
3839        }
3840    }
3841
3842    /// **A dialect that says nothing writes a value by its plain cast**, and
3843    /// renders exactly what it rendered before the question existed.
3844    #[test]
3845    fn a_dialect_that_states_no_value_text_casts_the_value() {
3846        let d: &dyn ExpressionRenderer = &TestDialect;
3847        for value_type in [DataType::date(), DataType::timestamp(), DataType::decimal(12, 2)] {
3848            assert_eq!(
3849                d.render_value_text("x", &value_type, &DataType::varchar(64)),
3850                d.render_cast("x", &DataType::varchar(64)),
3851            );
3852        }
3853        assert!(d.value_text_functions().is_none(), "a plain cast calls no function");
3854    }
3855
3856    /// **A dialect that says nothing refuses by converting the sentence to a
3857    /// number**, which is what every engine that refuses the conversion
3858    /// needs.
3859    #[test]
3860    fn a_dialect_that_states_no_refusal_converts_the_sentence() {
3861        let d: &dyn ExpressionRenderer = &TestDialect;
3862        assert_eq!(d.render_refusal("s"), d.render_cast("s", &DataType::bigint()));
3863    }
3864
3865    /// **A dialect that says nothing counts characters with the standard
3866    /// function.**
3867    #[test]
3868    fn a_dialect_that_states_no_text_length_counts_with_char_length() {
3869        let d: &dyn ExpressionRenderer = &TestDialect;
3870        assert_eq!(d.render_text_length("name"), "CHAR_LENGTH(name)");
3871    }
3872
3873    /// **A dialect that says nothing reads a missing word with the standard
3874    /// `IN`**, each word a standard literal with its quotes doubled.
3875    #[test]
3876    fn a_dialect_that_states_no_missing_value_reading_compares_with_in() {
3877        let d: &dyn ExpressionRenderer = &TestDialect;
3878        assert_eq!(
3879            d.render_missing_value("TRIM(x)", &["", "NULL", "it's"]),
3880            "CASE WHEN TRIM(x) IN ('', 'NULL', 'it''s') THEN NULL ELSE TRIM(x) END"
3881        );
3882    }
3883
3884    /// **Silence is the default, and silence means Razeri composes.**
3885    ///
3886    /// Both facts are opt-in: a dialect that says nothing gets the SQL
3887    /// derivation for its key and no generated staging fill at all. Neither
3888    /// default may become a guess — a composed body on an engine with no hash
3889    /// keys a warehouse to a number nothing reproduces, and an invented file
3890    /// relation fails the load on its first statement.
3891    #[test]
3892    fn a_dialect_that_states_neither_fact_is_asked_for_nothing() {
3893        let d: &dyn SqlRenderer = &TestDialect;
3894        assert_eq!(d.sid_helper_body(), None);
3895        assert_eq!(d.delimited_file_relation("'/data/x.csv'"), None);
3896    }
3897
3898    /// **A dialect that says nothing adds nothing after the column list.** The
3899    /// default is what every engine that takes a bare `CREATE TABLE t (…)`
3900    /// needs, whatever the table is.
3901    #[test]
3902    fn a_dialect_that_spells_no_table_suffix_is_asked_for_none() {
3903        let d: &dyn SqlRenderer = &TestDialect;
3904        let key = ["id".to_owned()];
3905        let cluster = ["region".to_owned()];
3906        for table in [
3907            TableSuffixRequest::new(),
3908            TableSuffixRequest::new().with_temporary(true),
3909            TableSuffixRequest::new()
3910                .with_primary_key(&key)
3911                .with_clustering_columns(&cluster)
3912                .with_version_column(Some("_loaded_at")),
3913        ] {
3914            assert_eq!(d.render_table_suffix(&table), None, "{table:?}");
3915        }
3916    }
3917
3918    /// And a dialect that states them is heard through the trait object, which
3919    /// is the only way Razeri ever holds one.
3920    #[test]
3921    fn a_dialect_that_states_them_is_heard_through_the_trait_object() {
3922        let d: &dyn SqlRenderer = &StatedDialect;
3923        assert_eq!(
3924            d.sid_helper_body(),
3925            Some(SidHelperBody {
3926                language: SidHelperLanguage::Named("ecmascript"),
3927                body: "return 1;",
3928            })
3929        );
3930        assert_eq!(
3931            d.delimited_file_relation("'/data/x.csv'").as_deref(),
3932            Some("SCAN('/data/x.csv')")
3933        );
3934    }
3935
3936    #[test]
3937    fn sql_renderer_core_methods_work() {
3938        let d = TestDialect;
3939        assert_eq!(d.render_data_type(&DataType::boolean()), "BOOLEAN");
3940        assert_eq!(d.quote_identifier("users"), "\"users\"");
3941        assert_eq!(d.qualify_name(Some("public"), "users"), "\"public\".\"users\"");
3942        assert_eq!(d.render_current_timestamp(), "CURRENT_TIMESTAMP");
3943    }
3944
3945    #[test]
3946    fn dialect_name_returns_ansi_by_default() {
3947        let d = TestDialect;
3948        assert_eq!(d.dialect_name(), "ansi");
3949    }
3950
3951    #[test]
3952    fn expression_renderer_defaults_produce_ansi_sql() {
3953        let d = TestDialect;
3954        assert_eq!(d.render_cast("age", &DataType::int()), "CAST(age AS INTEGER)");
3955        assert_eq!(d.render_concat(&["a".into(), "b".into()]), "CONCAT(a, b)");
3956        assert_eq!(d.render_coalesce(&["x".into(), "y".into()]), "COALESCE(x, y)");
3957    }
3958
3959    #[test]
3960    fn ddl_renderer_defaults_produce_ansi_sql() {
3961        let d = TestDialect;
3962        assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
3963        assert_eq!(d.render_create_view_prefix(), "CREATE OR REPLACE VIEW");
3964        assert_eq!(
3965            d.render_column_definition("name", &DataType::boolean(), false),
3966            "\"name\" BOOLEAN NOT NULL"
3967        );
3968        assert_eq!(d.render_column_definition("age", &DataType::int(), true), "\"age\" INTEGER");
3969    }
3970
3971    #[test]
3972    fn dml_renderer_defaults_produce_ansi_sql() {
3973        let d = TestDialect;
3974        assert_eq!(d.render_insert_prefix(), "INSERT INTO");
3975        assert_eq!(d.render_merge_prefix(), "MERGE INTO");
3976        assert_eq!(d.render_limit_clause(10), "LIMIT 10");
3977        assert!(d.render_upsert_strategy().is_none());
3978        assert!(d.render_returning_clause(&["id"]).is_none());
3979    }
3980
3981    #[test]
3982    fn procedure_renderer_defaults_produce_ansi_sql() {
3983        let d = TestDialect;
3984        assert_eq!(d.render_create_procedure_prefix(), "CREATE OR REPLACE PROCEDURE");
3985        assert_eq!(
3986            d.render_variable_declaration("v_count", &DataType::int()),
3987            "DECLARE v_count INTEGER;"
3988        );
3989        assert!(!d.requires_language_clause());
3990    }
3991
3992    #[test]
3993    fn trait_hierarchy_allows_selective_override() {
3994        struct MySqlLike;
3995        impl SqlRenderer for MySqlLike {
3996            fn render_data_type(&self, _: &DataType) -> String {
3997                "INT".into()
3998            }
3999            fn quote_identifier(&self, name: &str) -> String {
4000                format!("`{name}`")
4001            }
4002            fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
4003                match schema {
4004                    Some(s) => format!("`{s}`.`{name}`"),
4005                    None => format!("`{name}`"),
4006                }
4007            }
4008            fn render_current_timestamp(&self) -> String {
4009                "NOW()".into()
4010            }
4011        }
4012        impl ExpressionRenderer for MySqlLike {
4013            fn render_concat(&self, parts: &[String]) -> String {
4014                format!("CONCAT({})", parts.join(", "))
4015            }
4016        }
4017        impl DdlRenderer for MySqlLike {}
4018        impl DmlRenderer for MySqlLike {}
4019        impl ProcedureRenderer for MySqlLike {}
4020        impl DialectCapabilities for MySqlLike {}
4021
4022        let d = MySqlLike;
4023        assert_eq!(d.quote_identifier("users"), "`users`");
4024        assert_eq!(d.render_current_timestamp(), "NOW()");
4025        // DDL defaults still work even though we only overrode expressions
4026        assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
4027    }
4028
4029    #[test]
4030    fn sql_renderer_expression_extensions_produce_ansi_defaults() {
4031        let d = TestDialect;
4032        assert_sql_renderer_literal_defaults(&d);
4033        assert_sql_renderer_parameter_and_merge_defaults(&d);
4034        assert_sql_renderer_update_insert_defaults(&d);
4035        assert_sql_renderer_partition_and_window_defaults(&d);
4036    }
4037
4038    /// Assert ANSI defaults for literal, date/time, and basic expression hooks.
4039    /// Parameters:
4040    /// - dialect: Renderer under test.
4041    fn assert_sql_renderer_literal_defaults(dialect: &TestDialect) {
4042        assert_eq!(dialect.render_boolean_literal(true), "TRUE");
4043        assert_eq!(dialect.render_boolean_literal(false), "FALSE");
4044        assert_eq!(dialect.render_date_literal("2024-01-15"), "DATE '2024-01-15'");
4045        assert_eq!(
4046            dialect.render_timestamp_literal("2024-01-15 12:00:00"),
4047            "TIMESTAMP '2024-01-15 12:00:00'"
4048        );
4049        assert_eq!(dialect.render_interval_literal("1 year"), "INTERVAL '1 year'");
4050        assert_eq!(dialect.render_current_date(), "CURRENT_DATE");
4051        assert_eq!(dialect.concat_operator(), "||");
4052        assert_eq!(dialect.render_nan_literal(&DataType::float()), "NULL");
4053        assert_eq!(dialect.render_infinity_literal(true, &DataType::float()), "NULL");
4054        assert_eq!(dialect.ifnull_function_name(), "COALESCE");
4055        assert_eq!(
4056            dialect.render_iif("x > 0", "pos", "neg"),
4057            "CASE WHEN x > 0 THEN pos ELSE neg END"
4058        );
4059        assert_eq!(
4060            dialect.render_date_trunc("month", "created_at"),
4061            "DATE_TRUNC('month', created_at)"
4062        );
4063        assert_eq!(
4064            dialect.render_date_extract("year", "created_at"),
4065            "EXTRACT(year FROM created_at)"
4066        );
4067        assert_eq!(dialect.render_try_cast("age", &DataType::int()), "TRY_CAST(age AS INTEGER)");
4068    }
4069
4070    /// Assert ANSI defaults for parameter and merge-related extension hooks.
4071    /// Parameters:
4072    /// - dialect: Renderer under test.
4073    fn assert_sql_renderer_parameter_and_merge_defaults(dialect: &TestDialect) {
4074        assert_eq!(dialect.render_named_parameter("user_id"), ":user_id");
4075        assert_eq!(SqlRenderer::merge_not_matched_keyword(dialect), "WHEN NOT MATCHED");
4076        assert!(!SqlRenderer::supports_merge_not_matched_by_source(dialect));
4077        assert!(SqlRenderer::merge_supported(dialect));
4078        assert!(!SqlRenderer::merge_supports_schema_evolution_keyword(dialect));
4079        assert!(!SqlRenderer::merge_supports_table_hints(dialect));
4080        assert!(!SqlRenderer::merge_uses_output_clause(dialect));
4081        assert!(!SqlRenderer::merge_supports_returning_clause(dialect));
4082        assert_eq!(dialect.schema_separator(), ".");
4083        assert_eq!(dialect.statement_separator(), ";\n");
4084    }
4085
4086    /// Assert ANSI defaults for update and insert behavior extension hooks.
4087    /// Parameters:
4088    /// - dialect: Renderer under test.
4089    fn assert_sql_renderer_update_insert_defaults(dialect: &TestDialect) {
4090        assert!(!SqlRenderer::supports_compound_assignment(dialect));
4091        assert!(!SqlRenderer::supports_update_from(dialect));
4092        assert!(!SqlRenderer::uses_alter_table_update(dialect));
4093        // How a mutation is SPELLED and what it may LOOK AT are
4094        // two facts, and the ANSI default is that a mutation may correlate.
4095        assert!(!SqlRenderer::mutation_reads_only_its_own_rows(dialect));
4096        assert!(!dialect.update_supports_top_clause());
4097        assert!(!dialect.update_supports_table_hints());
4098        assert!(!dialect.update_uses_output_clause());
4099        assert!(!dialect.update_supports_returning());
4100        assert!(!dialect.insert_uses_output_clause());
4101        assert!(!dialect.insert_supports_returning());
4102        assert!(!dialect.insert_supports_table_hints());
4103        assert!(!SqlRenderer::supports_insert_overwrite(dialect));
4104        assert!(!SqlRenderer::supports_on_conflict(dialect));
4105        assert!(!dialect.supports_overriding_clause());
4106        assert_eq!(dialect.returning_clause_keyword(), "RETURNING");
4107        assert!(!SqlRenderer::supports_returning_into(dialect));
4108        assert!(!SqlRenderer::supports_multi_table_insert(dialect));
4109    }
4110
4111    /// Assert ANSI defaults for partitioning, generated columns, and window hooks.
4112    /// Parameters:
4113    /// - dialect: Renderer under test.
4114    fn assert_sql_renderer_partition_and_window_defaults(dialect: &TestDialect) {
4115        assert_eq!(
4116            dialect.render_time_partition_expr("event_ts", "monthly"),
4117            "date_trunc('month', event_ts)"
4118        );
4119        assert_eq!(dialect.render_partition_clause("event_ts"), "PARTITION BY (event_ts)");
4120        assert_eq!(
4121            dialect.render_generated_column("event_month", "DATE_TRUNC('month', event_ts)"),
4122            "event_month GENERATED ALWAYS AS (DATE_TRUNC('month', event_ts)) STORED"
4123        );
4124        assert!(!SqlRenderer::supports_window_frame_exclude(dialect));
4125        assert!(!SqlRenderer::supports_window_frame_groups(dialect));
4126        assert!(SqlRenderer::supports_named_windows(dialect));
4127    }
4128
4129    #[test]
4130    fn ddl_renderer_extensions_produce_ansi_defaults() {
4131        let d = TestDialect;
4132        assert_ddl_renderer_transaction_and_view_defaults(&d);
4133        assert_ddl_renderer_drop_defaults(&d);
4134    }
4135
4136    /// Assert ANSI DDL defaults for transaction and view keyword hooks.
4137    /// Parameters:
4138    /// - dialect: Renderer under test.
4139    fn assert_ddl_renderer_transaction_and_view_defaults(dialect: &TestDialect) {
4140        assert_eq!(dialect.render_begin_transaction(), "BEGIN");
4141        assert_eq!(dialect.render_commit(), "COMMIT");
4142        assert!(dialect.supports_ddl_transactions());
4143        assert_eq!(dialect.render_create_view_keyword(false, false), "CREATE OR REPLACE VIEW");
4144        assert_eq!(
4145            dialect.render_create_view_keyword(true, false),
4146            "CREATE OR REPLACE SECURE VIEW"
4147        );
4148        assert!(dialect.supports_alter_drop_if_exists());
4149    }
4150
4151    /// Assert ANSI DDL defaults for drop-related behavior hooks.
4152    /// Parameters:
4153    /// - dialect: Renderer under test.
4154    fn assert_ddl_renderer_drop_defaults(dialect: &TestDialect) {
4155        assert_eq!(dialect.render_drop_object_keyword("table"), "TABLE");
4156        assert_eq!(
4157            dialect.render_drop_function("my_func", &[], true),
4158            "DROP FUNCTION IF EXISTS my_func"
4159        );
4160        assert!(!dialect.drop_index_uses_on_syntax());
4161        assert!(DdlRenderer::supports_cascade_drop(dialect));
4162        assert!(dialect.supports_drop_function_arg_types());
4163        assert!(!DdlRenderer::supports_sync_drop(dialect));
4164        assert!(!DdlRenderer::supports_force_drop(dialect));
4165        assert!(!dialect.supports_alter_drop_cascade());
4166    }
4167
4168    /// **The one statement every engine takes**, written for a dialect that
4169    /// answered nothing. A plugin author gets the commonest evolution there is
4170    /// without writing a line for it.
4171    #[test]
4172    fn a_dialect_that_answers_nothing_still_adds_a_column() {
4173        let data_type = DataType::boolean();
4174        let written = TestDialect.render_column_evolution(&ColumnEvolution::AddColumn {
4175            schema: Some("telemetry_core"),
4176            table: "clients_daily",
4177            column: "is_default_browser",
4178            data_type: &data_type,
4179        });
4180        assert_eq!(
4181            written.as_deref(),
4182            Some(
4183                r#"ALTER TABLE "telemetry_core"."clients_daily" ADD COLUMN "is_default_browser" BOOLEAN"#
4184            )
4185        );
4186    }
4187
4188    /// Everything else waits to be spelled. A default picked from one engine's
4189    /// grammar is a statement the others reject, handed to an operator who
4190    /// finds that out against their own warehouse.
4191    #[test]
4192    fn nothing_else_is_spelled_until_a_dialect_spells_it() {
4193        let data_type = DataType::text();
4194        assert!(
4195            TestDialect
4196                .render_column_evolution(&ColumnEvolution::WidenColumn {
4197                    schema: None,
4198                    table: "t",
4199                    column: "c",
4200                    data_type: &data_type,
4201                })
4202                .is_none()
4203        );
4204        assert!(
4205            TestDialect
4206                .render_column_evolution(&ColumnEvolution::AddNestedField {
4207                    schema: None,
4208                    table: "t",
4209                    column: "c",
4210                    field: "f",
4211                    data_type: &data_type,
4212                })
4213                .is_none()
4214        );
4215    }
4216
4217    /// **The first line break decides how a file's lines end.** A header that
4218    /// ends `\r\n` is a Windows file; one that ends `\n`, or a file with no
4219    /// line break at all, reads with a newline alone.
4220    #[test]
4221    fn the_first_line_break_decides_how_the_lines_end() {
4222        assert_eq!(LineEnding::of(b"id,name\r\n1,Alpha\r\n"), LineEnding::CrLf);
4223        assert_eq!(LineEnding::of(b"id,name\r\n1,Alpha"), LineEnding::CrLf);
4224        assert_eq!(LineEnding::of(b"id,name\n1,Alpha\n"), LineEnding::Lf);
4225        assert_eq!(LineEnding::of(b"id,name"), LineEnding::Lf);
4226        assert_eq!(LineEnding::of(b""), LineEnding::Lf);
4227        assert_eq!(LineEnding::of(b"\n"), LineEnding::Lf);
4228        assert_eq!(LineEnding::default(), LineEnding::Lf);
4229        assert_eq!(LineEnding::CrLf.as_str(), "\r\n");
4230        assert_eq!(LineEnding::CrLf.escaped(), "\\r\\n");
4231        assert_eq!(LineEnding::Lf.escaped(), "\\n");
4232    }
4233
4234    /// **A dialect that states only the path-only read reads only a plain
4235    /// file.** A pipe, a quote other than `"` or a missing header is answered
4236    /// `None`, because the path-only read cannot be told it; a plain file
4237    /// reads byte for byte as before.
4238    #[test]
4239    fn the_default_reads_only_a_plain_file() {
4240        let d: &dyn SqlRenderer = &StatedDialect;
4241        let plain = DelimitedFile::new("'/data/x.csv'", "'/data'", "x.csv");
4242        assert!(plain.is_plain());
4243        assert_eq!(d.delimited_file_relation_for(&plain).as_deref(), Some("SCAN('/data/x.csv')"));
4244        for unplain in [
4245            plain.with_delimiter(FileDelimiter::Pipe),
4246            plain.with_quote('\''),
4247            plain.with_header(false),
4248        ] {
4249            assert!(!unplain.is_plain());
4250            assert_eq!(d.delimited_file_relation_for(&unplain), None, "{unplain:?}");
4251        }
4252        // A named encoding goes where the dialect reads one, and this dialect
4253        // reads none.
4254        assert_eq!(d.delimited_file_relation_for(&plain.with_encoding(Some("windows-1252"))), None);
4255    }
4256
4257    /// **A file is read the default way until a `with_` method says
4258    /// otherwise.**
4259    #[test]
4260    fn a_new_file_is_comma_delimited_quoted_headed_and_utf8() {
4261        let columns = vec!["a".to_owned()];
4262        let file = DelimitedFile::new("'/d/x.csv'", "'/d'", "x.csv");
4263        assert_eq!(file.delimiter, FileDelimiter::Comma);
4264        assert_eq!(file.quote, '"');
4265        assert!(file.header && file.columns.is_empty() && file.encoding.is_none());
4266        assert_eq!(file.line_ending, LineEnding::Lf);
4267        let told = file
4268            .with_columns(&columns)
4269            .with_line_ending(LineEnding::CrLf)
4270            .with_delimiter(FileDelimiter::Fs)
4271            .with_quote('\'')
4272            .with_header(false)
4273            .with_encoding(Some("shift_jis"));
4274        assert_eq!(told.columns, columns.as_slice());
4275        assert_eq!(told.line_ending, LineEnding::CrLf);
4276        assert_eq!(told.delimiter, FileDelimiter::Fs);
4277        assert_eq!((told.quote, told.header, told.encoding), ('\'', false, Some("shift_jis")));
4278    }
4279
4280    /// **Each delimiter is its character, its byte and its word**, and the
4281    /// four ASCII separators are the four control characters.
4282    #[test]
4283    fn each_delimiter_is_its_character_its_byte_and_its_word() {
4284        let all = [
4285            (FileDelimiter::Comma, ',', Some("comma")),
4286            (FileDelimiter::Tab, '\t', Some("tab")),
4287            (FileDelimiter::Pipe, '|', Some("pipe")),
4288            (FileDelimiter::Semicolon, ';', Some("semicolon")),
4289            (FileDelimiter::Fs, '\u{1c}', Some("fs")),
4290            (FileDelimiter::Gs, '\u{1d}', Some("gs")),
4291            (FileDelimiter::Rs, '\u{1e}', Some("rs")),
4292            (FileDelimiter::Us, '\u{1f}', Some("us")),
4293            (FileDelimiter::Literal('~'), '~', None),
4294        ];
4295        for (delimiter, character, word) in all {
4296            assert_eq!(delimiter.as_char(), character);
4297            assert_eq!(char::from(delimiter.as_byte()), character);
4298            assert_eq!(delimiter.word(), word);
4299            assert_eq!(delimiter.is_control(), ('\u{1c}'..='\u{1f}').contains(&character));
4300        }
4301        assert_eq!(FileDelimiter::default(), FileDelimiter::Comma);
4302    }
4303}