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::constraint_enforcement::ConstraintEnforcement;
12use crate::date_format::DateFormat;
13use crate::evolution::ColumnEvolution;
14use crate::flatten::{Flatten, FlattenRequest};
15use crate::number_format::NumberFormat;
16use crate::procedure_log_level::ProcedureLogLevel;
17use crate::routine_form::{ProcedureForm, ScalarFunctionForm, TableFunctionForm};
18use crate::routine_spec::RoutineSpec;
19use crate::sid_spelling::{SidHelperBody, SidSpelling, UNSPELLED_SID};
20
21/// **Where the aggregated expression goes** in a form returned by
22/// [`SqlRenderer::median_aggregate_form`].
23///
24/// The form is a template rather than finished SQL so that *which function*
25/// and *how a column is written* stay in different hands — the dialect answers
26/// the first, the query renderer the second. A form must carry this token
27/// exactly once.
28pub const AGGREGATE_ARGUMENT: &str = "{argument}";
29
30/// **What kind of value an aggregate would have to collapse** — the axis
31/// [`SqlRenderer::render_single_row_aggregate`] varies on, held to three arms
32/// because three is what the measurements distinguish.
33///
34/// Not the full type lattice: `MAX` behaves identically across every numeric,
35/// textual and temporal type on every platform razeri reaches, and splitting
36/// them would invite per-type arms nothing has measured.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum AggregableKind {
39 /// Numeric, textual and temporal — every platform orders these and every
40 /// platform has `MAX` for them.
41 Orderable,
42 /// A truth value. `PostgreSQL` and SQL Server have no `MAX` for it and each
43 /// spells the collapse differently.
44 Boolean,
45 /// `uuid`, JSON, binary, interval, array, map — the families with no
46 /// ordering to borrow. Availability is per platform and is measured, never
47 /// assumed.
48 Opaque,
49}
50
51/// **A clock bound once for a whole load script** — what
52/// [`SqlRenderer::render_inline_clock_binding`] answers on an engine whose
53/// loads ship as flat statement lists rather than procedure bodies.
54///
55/// The `statements` run first and capture the engine's current moment under
56/// one name; `reference` is the expression every later statement of the same
57/// run reads it back by. One binding, many readers, is what makes a version's
58/// close and its successor's open the same instant by construction.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct InlineClockBinding {
61 /// The statement(s) that bind the moment, in run order, each terminated.
62 pub statements: Vec<String>,
63 /// The expression that reads the bound moment back.
64 pub reference: String,
65}
66
67/// Level 1 — Core SQL rendering. REQUIRED: every dialect must implement these 4 methods.
68///
69/// These methods define the absolute minimum surface for rendering SQL:
70/// data types, identifier quoting, qualified names, and timestamps.
71pub trait SqlRenderer: Send + Sync {
72 /// Render a [`DataType`] as platform-specific SQL.
73 fn render_data_type(&self, dt: &DataType) -> String;
74
75 /// **The type text for a routine's PARAMETER**, which is not always the text
76 /// a column carries.
77 ///
78 /// Most engines spell a type one way wherever it appears, and for those this
79 /// hook is [`Self::render_data_type`] under another name — which is the
80 /// default, so a dialect with nothing to say says nothing.
81 ///
82 /// **Oracle is the reason it exists.** A column there takes
83 /// `NUMBER(19, 0)` and `VARCHAR2(100)`; the same types in a parameter list
84 /// are a compile error (`PLS-00103`, reported at the opening parenthesis),
85 /// and the bare `NUMBER` and `VARCHAR2` are what a parameter clause takes.
86 /// The length and the precision belong on the local declaration instead,
87 /// which keeps them. A dialect there answers:
88 ///
89 /// ```ignore
90 /// fn render_parameter_data_type(&self, dt: &DataType) -> String {
91 /// let column = self.render_data_type(dt);
92 /// match column.find('(') {
93 /// Some(at) => column[..at].trim_end().to_owned(),
94 /// None => column,
95 /// }
96 /// }
97 /// ```
98 ///
99 /// It is what fills
100 /// [`RoutineParameter::data_type`](crate::routine_spec::RoutineParameter::data_type),
101 /// so a dialect that answers it does not also post-process the string
102 /// Razeri handed it.
103 ///
104 /// Parameters:
105 /// - `dt`: the type the design declared.
106 fn render_parameter_data_type(&self, dt: &DataType) -> String {
107 self.render_data_type(dt)
108 }
109
110 /// **The type text for a column that ADMITS NULL** — the whole type, not a
111 /// modifier appended to one.
112 ///
113 /// Nine of razeri's ten platforms spell nullability by SILENCE: a column
114 /// declared without `NOT NULL` admits one, and its type text is the same
115 /// text a required column carries. That is the default here, and for those
116 /// nine this hook is [`SqlRenderer::render_data_type`] under another name.
117 ///
118 /// **`ClickHouse` is the exception, and it is the reason this hook exists.**
119 /// There a bare type is NOT NULL — nullability is a property OF the type,
120 /// spelled `Nullable(T)` — so a renderer that expresses *nullable* by
121 /// omitting a keyword expresses nothing at all. `render_field` used to carry
122 /// a comment saying the wrapper was *"handled in data type"*; it was handled
123 /// nowhere, and every `nullable:` a design declared was discarded on that
124 /// one engine (`Nullable(` appeared ZERO times in any rendered
125 /// `schema.sql`).
126 ///
127 /// # What the discard actually cost, measured rather than assumed
128 ///
129 /// Not a loud refusal. `insert_null_as_default` **defaults to `1`** on
130 /// `ClickHouse` (24.10.2, server default, `changed = 0`), so
131 /// `INSERT … SELECT NULL` into a bare column does not raise — it writes the
132 /// TYPE'S DEFAULT, silently: `''` for `String`, `0` for `Int64`,
133 /// `1900-01-01` for `Date32` (which is razeri's own unknown-member date, so
134 /// an unknown attribute came back indistinguishable from a deliberately
135 /// seeded one). Only with `insert_null_as_default = 0` does the engine
136 /// answer `Code: 70 … Cannot convert NULL to a non-nullable type`. **A
137 /// design's own data was being fabricated on one engine and honest on the
138 /// other nine**, and the DDL is where that is fixed.
139 ///
140 /// # A dialect overriding this owes a measurement
141 ///
142 /// Not every type can be wrapped. `ClickHouse` refuses
143 /// `Nullable(Array(…))`, `Nullable(Map(…))` and `Nullable(JSON)` outright,
144 /// so its override declines those and says so in its own rustdoc. A
145 /// wrapper that cannot be applied must be DECLINED by name, never applied
146 /// and hoped for: an unwrappable type rendered `Nullable(…)` turns a silent
147 /// wrong value into a `CREATE TABLE` that does not run.
148 fn render_nullable_data_type(&self, dt: &DataType) -> String {
149 self.render_data_type(dt)
150 }
151
152 /// Quote an identifier using platform conventions.
153 ///
154 /// `PostgreSQL`: `"name"`, `MySQL`: `` `name` ``, SQL Server: `[name]`
155 fn quote_identifier(&self, name: &str) -> String;
156
157 /// Render a fully qualified name (optional schema + name).
158 fn qualify_name(&self, schema: Option<&str>, name: &str) -> String;
159
160 /// Whether this dialect uses schemas in qualified names.
161 ///
162 /// `ClickHouse` uses only `database.object` (no schema level).
163 /// Default: `true` (most platforms use `catalog.schema.object`).
164 fn uses_schema_in_qualified_names(&self) -> bool {
165 true
166 }
167
168 /// Whether this dialect is the "agnostic" pseudo-dialect.
169 ///
170 /// Agnostic rendering produces unquoted, platform-neutral DDL.
171 /// Real dialect implementations should not override this.
172 fn is_agnostic_dialect(&self) -> bool {
173 false
174 }
175
176 /// Whether this dialect supports `SECURE VIEW` (Snowflake).
177 fn supports_secure_view(&self) -> bool {
178 false
179 }
180
181 /// Whether this dialect supports `GLOBAL TEMPORARY VIEW` (Databricks).
182 fn supports_global_temporary_view(&self) -> bool {
183 false
184 }
185
186 /// Render the platform's `CURRENT_TIMESTAMP` expression.
187 fn render_current_timestamp(&self) -> String;
188
189 /// **The schemas a catalog scan passes over** — the engine's own
190 /// bookkeeping, never a warehouse's contents.
191 ///
192 /// Read by [`Self::render_catalog_columns_query`] and
193 /// [`Self::render_catalog_object_times_query`] when no single schema was
194 /// named, so a scan of a whole warehouse sees the tables somebody created
195 /// and not the catalog describing them. The default names the one schema
196 /// the SQL standard puts the catalog in; an engine that keeps more of its
197 /// own next to it adds them.
198 fn catalog_system_schemas(&self) -> &'static [&'static str] {
199 &["information_schema"]
200 }
201
202 /// **The query that lists what the warehouse holds** — one row per column,
203 /// as `(schema, object, column)`.
204 ///
205 /// Razeri asks it to answer a question it cannot answer from a design: how
206 /// much of this warehouse razeri itself rendered. Columns rather than
207 /// object names alone, because the answer is read off both — a name carries
208 /// the tier razeri mints (`…_staging`, `…_current`), and a column carries
209 /// the bookkeeping only razeri writes (`…_sid`, `_loaded_at`). A scan that
210 /// saw names alone would either miss an entity whose target table is a
211 /// plain noun or count a table razeri never touched.
212 ///
213 /// The three columns are positional and in that order: every caller reads
214 /// row `0`, `1`, `2` and nothing reads a column by name, so an engine whose
215 /// catalog spells the headings differently needs no special case.
216 ///
217 /// `None` means **this engine states no catalog razeri can scan**, which is
218 /// an answer rather than an omission: the caller says so by name instead of
219 /// reporting an empty warehouse.
220 ///
221 /// Parameters:
222 /// - `schema`: the one schema to look in. `None` means the whole warehouse,
223 /// minus [`Self::catalog_system_schemas`].
224 fn render_catalog_columns_query(&self, schema: Option<&str>) -> Option<String> {
225 Some(format!(
226 "SELECT table_schema, table_name, column_name\nFROM \
227 information_schema.columns\n{}\nORDER BY table_schema, table_name, column_name",
228 self.catalog_scope_predicate("table_schema", schema)
229 ))
230 }
231
232 /// **The query that says when each object was created**, as
233 /// `(schema, object, created_at)` — where the engine records it at all.
234 ///
235 /// A second, independent reading of the same question
236 /// [`Self::render_catalog_columns_query`] opens: the earliest moment razeri
237 /// can prove it was here. It is a `None` on most engines, and deliberately
238 /// so — `PostgreSQL` and `DuckDB` keep no creation time for a relation, and
239 /// inventing one would be worse than having none.
240 ///
241 /// Parameters:
242 /// - `schema`: the one schema to look in, or `None` for the whole
243 /// warehouse.
244 fn render_catalog_object_times_query(&self, schema: Option<&str>) -> Option<String> {
245 let _ = schema;
246 None
247 }
248
249 /// The `WHERE` clause both catalog queries share: one named schema, or
250 /// every schema that is not the engine's own.
251 ///
252 /// Parameters:
253 /// - `column`: the catalog's own name for the schema column.
254 /// - `schema`: the one schema to look in, or `None` for the whole
255 /// warehouse.
256 fn catalog_scope_predicate(&self, column: &str, schema: Option<&str>) -> String {
257 if let Some(one) = schema {
258 return format!("WHERE {column} = '{}'", one.replace('\'', "''"));
259 }
260 let excluded: Vec<String> = self
261 .catalog_system_schemas()
262 .iter()
263 .map(|name| format!("'{}'", name.replace('\'', "''")))
264 .collect();
265 format!("WHERE {column} NOT IN ({})", excluded.join(", "))
266 }
267
268 /// Return a stable string identifier for this dialect.
269 ///
270 /// Used for dispatch when trait-based rendering is not yet available for
271 /// a domain concept, and as a human-readable label in diagnostics and
272 /// error messages. This method works for **all dialects** registered
273 /// in the `PlatformRegistry` (e.g. `"postgresql"`, `"sqlite"`,
274 /// `"cockroachdb"`).
275 ///
276 /// Convention: lowercase, hyphen-separated (e.g. `"postgresql"`,
277 /// `"sql-server"`, `"snowflake"`, `"sqlite"`).
278 ///
279 /// The default returns `"ansi"`.
280 fn dialect_name(&self) -> &'static str {
281 "ansi"
282 }
283
284 /// **How this engine spells a surrogate key.**
285 ///
286 /// Razeri derives every key one way — normalize each part, join them, hash
287 /// the result, guard NULLs with a sentinel — and composes that derivation
288 /// in exactly one place. What a dialect decides is the *vocabulary*: what
289 /// this engine calls `LOWER` and `TRIM`, how it joins strings, how it casts
290 /// a value to text, and how it spells a 64-bit hash.
291 ///
292 /// The default is [`UNSPELLED_SID`] — ANSI's vocabulary under a name that
293 /// says it is a guess. **A dialect that leaves it there is telling Razeri it
294 /// has not decided**, and the emitted SQL will call an `xxhash64` its engine
295 /// very likely does not have. Override it.
296 ///
297 /// If your engine has no portable 64-bit hash, say so rather than reaching
298 /// for the nearest-looking function: a hash that is deterministic within one
299 /// warehouse and equal to nothing outside it is the lock-in a portable key
300 /// exists to end. Name an artifact your dialect's prerequisites install, or
301 /// refuse the key and orient the reader.
302 fn sid_spelling(&self) -> SidSpelling {
303 UNSPELLED_SID
304 }
305
306 /// **The body of the surrogate-key helper, where SQL cannot spell it.**
307 ///
308 /// Razeri emits one function per warehouse — `generate_sid` — and normally
309 /// builds its body itself, from the vocabulary
310 /// [`sid_spelling`](Self::sid_spelling) states. The default here is `None`,
311 /// which says exactly that: *compose the derivation in my own SQL*.
312 ///
313 /// Answer with [`SidHelperBody`] only when there is no SQL that could hold
314 /// the derivation — the engine has no 64-bit hash under any name, so the
315 /// vocabulary has nothing to spell the hash with and the definition has to
316 /// be written in another language. `BigQuery` is the case Razeri ships:
317 /// `GoogleSQL` has no XXH64, and the function that looks like the answer
318 /// (`FARM_FINGERPRINT`) is a different number, so the body is JavaScript.
319 ///
320 /// **Do not use this to change the key.** The body computes the same number
321 /// every other engine computes — XXH64, seed 0, over the UTF-8 bytes of the
322 /// one already-normalized argument — and [`SidHelperBody`] says what it owes
323 /// in full. Reaching for a native hash that is merely deterministic keys a
324 /// warehouse to numbers nothing outside it can reproduce.
325 ///
326 /// A dialect that answers here should also state a
327 /// [`SidSpelling::hash`](crate::SidSpelling::hash) that no engine has, so
328 /// that any path which fell back to composing SQL fails loudly at deploy
329 /// time rather than hashing nothing and handing back the value.
330 fn sid_helper_body(&self) -> Option<SidHelperBody> {
331 None
332 }
333
334 /// **How this engine reads a delimited text file as a relation**, or `None`
335 /// where it cannot.
336 ///
337 /// A design can bind an entity to a source file, and Razeri then generates
338 /// the staging fill: an `INSERT … SELECT … FROM <this>`. That only works on
339 /// an engine that can open a file from inside a query. `DuckDB` can
340 /// (`read_csv_auto`); most cannot — `PostgreSQL` wants `COPY`, Snowflake a
341 /// stage, `SQLite` has nothing at all. Each of those is a bulk-load design
342 /// decision rather than a rendering detail, so the default is `None` and
343 /// the generated bundle says which platform declined and why instead of
344 /// emitting SQL the engine would refuse.
345 ///
346 /// `path_literal` arrives as a finished single-quoted SQL string literal,
347 /// already escaped — put it where the relation takes a path and do not
348 /// quote it again.
349 ///
350 /// **What the returned relation owes**, because the fill is written against
351 /// it and nothing checks these at render time:
352 ///
353 /// - the file's first row is its header, and the column names come from it,
354 /// spelled exactly as the file spells them;
355 /// - every column reads as **text**, unparsed. The fill casts nothing: a
356 /// date's layout and a currency's prefix are the source's business, and a
357 /// reader that guessed a type would fail the load on its first row;
358 /// - it is a relation usable in a `FROM` clause, not a statement.
359 ///
360 /// The path is embedded in the generated file as it was spelled when the
361 /// bundle was built, so it must be one the engine resolves at run time.
362 fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
363 let _ = path_literal;
364 None
365 }
366
367 /// **How this engine reads a delimited text file whose bytes are not
368 /// UTF-8**, or `None` where it states no way to.
369 ///
370 /// UTF-8 is the canonical form and every engine reads it, so
371 /// [`delimited_file_relation`](Self::delimited_file_relation) answers for
372 /// it and this is asked only about the other days. A design can name the
373 /// encoding to fall back to when a file's bytes are not UTF-8, and razeri
374 /// resolves that name once, to the one name the encoding standard files it
375 /// under — `windows-1252`, `shift_jis`, `koi8-r`. That name arrives here,
376 /// and an engine that has its own word for the same encoding translates it
377 /// the way an engine translates every other name razeri hands it.
378 ///
379 /// Everything the returned relation owes, it owes for the same reasons
380 /// [`delimited_file_relation`](Self::delimited_file_relation) says: header
381 /// from the first row, every column as text, usable in a `FROM` clause.
382 ///
383 /// **`None` is a complete answer, and the common one.** An engine that
384 /// reads no file at all says nothing here; so does an engine that reads
385 /// files but has no word for this particular encoding. Razeri then declines
386 /// that source by name and says what to do instead — convert the file to
387 /// UTF-8, or write the load by hand — rather than pointing the engine at
388 /// bytes it will read as some other language.
389 ///
390 /// **Answer only for encodings you have run.** An engine that accepts the
391 /// name and reads the bytes as something else is worse than one that
392 /// refuses the name: the first is a warehouse of plausible nonsense and the
393 /// second is a sentence on a terminal.
394 ///
395 /// `path_literal` arrives as a finished single-quoted SQL string literal,
396 /// already escaped — put it where the relation takes a path and do not
397 /// quote it again. `encoding` does not: it is a bare name, and an engine
398 /// that puts it in a string literal writes the quotes itself.
399 fn delimited_file_relation_in_encoding(
400 &self,
401 path_literal: &str,
402 encoding: &str,
403 ) -> Option<String> {
404 let _ = (path_literal, encoding);
405 None
406 }
407
408 /// **The `CAST` target spelling for a [`DataType`] on this engine.**
409 ///
410 /// A column declaration and a `CAST` target are two grammars on most
411 /// engines, so this is a separate answer from
412 /// [`render_data_type`](Self::render_data_type) and not a synonym for it.
413 /// `MySQL` takes `SIGNED` where it declares `BIGINT`; T-SQL takes
414 /// `NVARCHAR(MAX)` where ANSI says `TEXT`.
415 ///
416 /// Where the two *are* the same on your engine — which is the common case
417 /// on engines with one type vocabulary — say so by delegating:
418 ///
419 /// ```ignore
420 /// fn render_cast_type(&self, dt: &DataType) -> String {
421 /// self.render_data_type(dt)
422 /// }
423 /// ```
424 ///
425 /// The default is ANSI's cast vocabulary. Razeri's generated load opens
426 /// with a CTE that casts every source column to its declared type, so a
427 /// wrong name here fails the load on its first statement.
428 fn render_cast_type(&self, dt: &DataType) -> String {
429 crate::agnostic::render_cast_type_ansi(dt)
430 }
431
432 /// **Which stored-procedure grammar this engine speaks.**
433 ///
434 /// Razeri composes the procedure — its parameters, its steps, its comment —
435 /// and spells it in the form this returns. The default is
436 /// [`ProcedureForm::Agnostic`], which parses on no engine: it is the honest
437 /// answer for a dialect that has not said, and it is what an unlisted
438 /// platform has always been handed.
439 ///
440 /// It lives on `SqlRenderer` rather than on
441 /// [`ProcedureRenderer`] because the composer
442 /// holds the renderer as a [`DdlRenderer`], and a decision reachable only
443 /// through a trait the caller does not hold is a decision the caller makes
444 /// instead.
445 fn procedure_form(&self) -> ProcedureForm {
446 ProcedureForm::Agnostic
447 }
448
449 /// **Which scalar-function grammar this engine speaks.**
450 ///
451 /// The default is [`ScalarFunctionForm::PostgreSql`] — what an unlisted
452 /// dialect has always been handed, and a dangerous inheritance on a near
453 /// neighbour: `LANGUAGE SQL IMMUTABLE PARALLEL SAFE` is a *"syntax error at
454 /// or near `PARALLEL`"* on an engine that descends from `PostgreSQL` and
455 /// reports itself as one.
456 fn scalar_function_form(&self) -> ScalarFunctionForm {
457 ScalarFunctionForm::PostgreSql
458 }
459
460 /// **Which table-valued-function grammar this engine speaks, and — where it
461 /// has none — the words it refuses in.**
462 ///
463 /// The default is [`TableFunctionForm::PostgreSql`], what an unlisted
464 /// dialect has always been handed. If your engine has no routine a query
465 /// selects `FROM`, answer [`TableFunctionForm::Unsupported`] with your own
466 /// sentence: Razeri then declines to build the routine at all and prints
467 /// **your** words rather than another engine's. A refusal written once per
468 /// artifact kind tells every author about whichever engine happened to need
469 /// it first, and the near form an author will otherwise find on their own
470 /// is exactly what costs them a day.
471 fn table_function_form(&self) -> TableFunctionForm {
472 TableFunctionForm::PostgreSql
473 }
474
475 // ═══════════════════════════════════════════════════════════════
476 // Routines this dialect spells itself
477 // ═══════════════════════════════════════════════════════════════
478
479 /// **Spell a whole stored procedure in this engine's own grammar** — the
480 /// method [`ProcedureForm::Custom`] promises.
481 ///
482 /// Razeri composes the routine and hands it over as a [`RoutineSpec`]: the
483 /// name, the parameters with their types already in your spelling, the
484 /// declarations, the body's statements, the comment. What comes back is the
485 /// complete `CREATE`, punctuation and all, and Razeri emits it unchanged.
486 ///
487 /// The default is `None`, which means *"I did not write one"*. It is only
488 /// ever reached by a dialect that answered
489 /// [`ProcedureForm::Custom`] and then did not override this — the
490 /// conformance kit reports that as blocking, and the emitted SQL carries a
491 /// comment saying the same thing where the procedure would have been.
492 ///
493 /// It lives on `SqlRenderer` rather than on [`ProcedureRenderer`] for the
494 /// reason [`Self::procedure_form`] does: the composer holds the renderer as
495 /// a [`DdlRenderer`], and an answer reachable only through a trait the
496 /// caller does not hold is an answer the caller makes up instead.
497 ///
498 /// Parameters:
499 /// - `routine`: the procedure Razeri composed.
500 fn render_procedure(&self, routine: &RoutineSpec) -> Option<String> {
501 let _ = routine;
502 None
503 }
504
505 /// **Spell a whole scalar function in this engine's own grammar** — the
506 /// method [`ScalarFunctionForm::Custom`] promises.
507 ///
508 /// The same contract as [`Self::render_procedure`]: a composed
509 /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
510 /// dialect claimed a custom grammar and did not write the method.
511 ///
512 /// Parameters:
513 /// - `routine`: the function Razeri composed.
514 fn render_scalar_function(&self, routine: &RoutineSpec) -> Option<String> {
515 let _ = routine;
516 None
517 }
518
519 /// **Spell a whole table-valued function in this engine's own grammar** —
520 /// the method [`TableFunctionForm::Custom`] promises.
521 ///
522 /// The same contract as [`Self::render_procedure`]: a composed
523 /// [`RoutineSpec`] in, the complete `CREATE` out, and `None` only where a
524 /// dialect claimed a custom grammar and did not write the method.
525 ///
526 /// Parameters:
527 /// - `routine`: the function Razeri composed.
528 fn render_table_function(&self, routine: &RoutineSpec) -> Option<String> {
529 let _ = routine;
530 None
531 }
532
533 // ═══════════════════════════════════════════════════════════════
534 // Expression rendering extensions
535 // ═══════════════════════════════════════════════════════════════
536
537 /// Platform's `CURRENT_DATE` expression.
538 ///
539 /// `SqlServer`: `CAST(GETDATE() AS DATE)`, `ClickHouse`: `today()`, others: `CURRENT_DATE`
540 fn render_current_date(&self) -> String {
541 "CURRENT_DATE".to_string()
542 }
543
544 /// Render a boolean literal.
545 ///
546 /// SqlServer/ClickHouse: `1`/`0`, others: `TRUE`/`FALSE`
547 fn render_boolean_literal(&self, value: bool) -> String {
548 if value { "TRUE".to_string() } else { "FALSE".to_string() }
549 }
550
551 /// **Collapse a subquery that selects AT MOST ONE ROW into an aggregate**,
552 /// for the engines that will not accept an unaggregated correlated scalar.
553 ///
554 /// Razeri's SCD-2 and SCD-1 re-opens assign `col = (SELECT … WHERE
555 /// {correlation})`. Databricks refuses that shape by name
556 /// (`MUST_AGGREGATE_CORRELATED_SCALAR_SUBQUERY`) and Snowflake stopped
557 /// unnesting it the day the guard beside it became uncorrelated, so the
558 /// emission wraps the projection in an aggregate. **Which** aggregate is a
559 /// dialect fact and **whether one exists at all** is a dialect × type fact,
560 /// which is why this hook takes the kind and may answer `None`:
561 ///
562 /// - `MAX` is the obvious choice and is wrong for a BOOLEAN on two of the
563 /// platforms razeri reaches. Measured on the running
564 /// containers: `PostgreSQL` and Citus raise
565 /// *"function max(boolean) does not exist"*, SQL Server raises
566 /// *"Msg 8117: Operand data type bit is invalid for max operator"*, while
567 /// `MariaDB` (`MAX(TRUE)` → `1`) and `ClickHouse` (`max(true)` → `true`)
568 /// answer it happily;
569 /// - `PostgreSQL` has no `max()` for `uuid`, `jsonb` or `bytea` either
570 /// (measured, same run), and SQL Server has one for both
571 /// `uniqueidentifier` and `varbinary` (measured).
572 ///
573 /// **`None` means *this dialect cannot aggregate this kind* and is not a
574 /// failure.** The caller then emits the bare correlated scalar — the
575 /// prior shape, measured green on the whole
576 /// `PostgreSQL` family — and says so on the output, because that shape is
577 /// the one Databricks refuses.
578 ///
579 /// **Correctness does not come from the aggregate's meaning.** The subquery
580 /// is under a guard that is false for the entire load if any member
581 /// disagrees with itself, so it selects one row; `MAX`, `BOOL_OR` and
582 /// `BOOLOR_AGG` of one value are all that value. The choice between them is
583 /// availability, not semantics.
584 fn render_single_row_aggregate(
585 &self,
586 expression: &str,
587 kind: AggregableKind,
588 ) -> Option<String> {
589 let _ = kind;
590 Some(format!("MAX({expression})"))
591 }
592
593 /// **Take any one value of `expression` from a group**, for the engines
594 /// that cannot group on the column itself.
595 ///
596 /// A load collapses staged rows that repeat. Where the engine will not
597 /// group on a nested column
598 /// ([`crate::DialectCapabilities::groups_nested_values`]) the collapse
599 /// groups on the remaining columns and takes one value of that one, which
600 /// is what this renders.
601 ///
602 /// `ANY_VALUE` is the spelling `BigQuery`, Snowflake, Redshift, Databricks
603 /// and `MySQL` all use, so it is the default; an engine that spells it
604 /// differently, or reaches it through `FIRST`, says so here.
605 ///
606 /// Unlike [`Self::render_single_row_aggregate`] this one cannot decline:
607 /// it is asked only where the dialect has already said it cannot group on
608 /// the column, so there is no second shape to fall back to.
609 ///
610 /// Parameters:
611 /// - `expression`: the column reference, already spelled by the renderer
612 /// that lays out the query.
613 fn render_any_value(&self, expression: &str) -> String {
614 format!("ANY_VALUE({expression})")
615 }
616
617 /// **The AGGREGATE median this engine has for `expression`, or `None` when
618 /// it has none.**
619 ///
620 /// Aggregate is the load-bearing word, and it is why this cannot be
621 /// answered from a function-name table. Four spellings are in the wild:
622 ///
623 /// - a plain `median(x)` aggregate — `duckdb`, `clickhouse`, `snowflake`;
624 /// - the SQL ordered-set aggregate
625 /// `PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)` — `postgres` and its
626 /// family (measured on a running instance: it groups);
627 /// - a two-argument `PERCENTILE(x, 0.5)` — `databricks`;
628 /// - and a WINDOW function wearing one of those names, which is **not**
629 /// this. `mariadb` has `MEDIAN(x) OVER (…)` and `sqlserver` has
630 /// `PERCENTILE_CONT(…) OVER (…)`, and both are a syntax error in a
631 /// `GROUP BY` select list (measured: `MariaDB` raises `ERROR 1064` and
632 /// SQL Server raises *"Msg 10753: The function `PERCENTILE_CONT` must
633 /// have an OVER clause"*). A window function returns one value per ROW,
634 /// not one per group, so it is a different answer and not a fallback.
635 ///
636 /// **The default declines**, so a dialect that has never been asked the
637 /// question is never assumed to have the answer, and a dialect added
638 /// tomorrow opts in deliberately with a form somebody measured. The caller
639 /// turns `None` into a build-time refusal naming the column and the target
640 /// — razeri does not emit SQL its target cannot run.
641 ///
642 /// # Why a TEMPLATE rather than finished SQL
643 ///
644 /// The aggregated expression is a column reference, and how a column
645 /// reference is spelled — quoted, bracketed, upper-cased — belongs to the
646 /// renderer that lays out the query, not to this answer. Handing back a
647 /// form with [`AGGREGATE_ARGUMENT`] where the expression goes keeps the
648 /// two apart: this trait owns *which function*, the query renderer owns
649 /// *how the column is written*, and neither has to reimplement the other.
650 fn median_aggregate_form(&self) -> Option<&'static str> {
651 None
652 }
653
654 /// Render a date literal.
655 ///
656 /// `ClickHouse`: `toDate('2024-01-15')`, others: `DATE '2024-01-15'`
657 fn render_date_literal(&self, date: &str) -> String {
658 format!("DATE '{date}'")
659 }
660
661 /// Render a timestamp literal.
662 ///
663 /// `ClickHouse`: `toDateTime('...')`, others: `TIMESTAMP '...'`
664 fn render_timestamp_literal(&self, ts: &str) -> String {
665 format!("TIMESTAMP '{ts}'")
666 }
667
668 /// Render an interval literal.
669 ///
670 /// `SqlServer`: `'P1Y2M3D'`, `ClickHouse`: `INTERVAL 1 YEAR`, others: `INTERVAL '1 year'`
671 fn render_interval_literal(&self, interval: &str) -> String {
672 format!("INTERVAL '{interval}'")
673 }
674
675 /// Render the string concatenation operator.
676 ///
677 /// `SqlServer`: `+`, others: `||`
678 fn concat_operator(&self) -> &'static str {
679 "||"
680 }
681
682 /// Render a NaN literal for a floating-point type.
683 ///
684 /// `PostgreSQL`: `'NaN'::float`, others: `NULL`
685 fn render_nan_literal(&self, _dt: &DataType) -> String {
686 "NULL".to_string()
687 }
688
689 /// Render an infinity literal for a floating-point type.
690 ///
691 /// `PostgreSQL`: `'Infinity'::float` / `'-Infinity'::float`, others: `NULL`
692 fn render_infinity_literal(&self, _positive: bool, _dt: &DataType) -> String {
693 "NULL".to_string()
694 }
695
696 /// Render the NULL-coalescing function name.
697 ///
698 /// `SqlServer`: `ISNULL`, `ClickHouse`: `ifNull`, others: `COALESCE`
699 fn ifnull_function_name(&self) -> &'static str {
700 "COALESCE"
701 }
702
703 /// Render an IIF expression (or CASE WHEN equivalent).
704 ///
705 /// `SqlServer`: `IIF(cond, then, else)`, others: `CASE WHEN cond THEN then ELSE else END`
706 fn render_iif(&self, cond: &str, then_val: &str, else_val: &str) -> String {
707 format!("CASE WHEN {cond} THEN {then_val} ELSE {else_val} END")
708 }
709
710 /// Render a `DATE_TRUNC` expression.
711 ///
712 /// `SqlServer`: `DATETRUNC(field, expr)`, `ClickHouse`: `toStartOfMonth(expr)`, others: `DATE_TRUNC('field', expr)`
713 fn render_date_trunc(&self, field: &str, expr: &str) -> String {
714 format!("DATE_TRUNC('{field}', {expr})")
715 }
716
717 /// Render a date field extraction expression.
718 ///
719 /// `SqlServer`: `DATEPART(field, column)`, `ClickHouse`: `toYear(col)/toMonth(col)`, others: `EXTRACT(field FROM column)`
720 fn render_date_extract(&self, field: &str, column: &str) -> String {
721 format!("EXTRACT({field} FROM {column})")
722 }
723
724 /// Render a `TRY_CAST` expression.
725 ///
726 /// `ClickHouse`: `accurateCastOrNull(expr, 'Type')`, others: `TRY_CAST(expr AS Type)`
727 fn render_try_cast(&self, expr: &str, target: &DataType) -> String {
728 format!("TRY_CAST({} AS {})", expr, self.render_data_type(target))
729 }
730
731 /// Render a positional parameter placeholder.
732 ///
733 /// `PostgreSQL`: `$1`, `SqlServer`: `@p1`, Databricks: `{param1}`, others: `?`
734 fn render_parameter_placeholder(&self, index: usize) -> String {
735 format!("${index}")
736 }
737
738 /// Render a named parameter placeholder.
739 ///
740 /// `SqlServer`: `@name`, `PostgreSQL`: `:name`, Databricks: `{name}`
741 fn render_named_parameter(&self, name: &str) -> String {
742 format!(":{name}")
743 }
744
745 /// Keyword emitted for MERGE NOT MATCHED branch.
746 ///
747 /// SqlServer/Databricks: `WHEN NOT MATCHED BY TARGET`, others: `WHEN NOT MATCHED`.
748 fn merge_not_matched_keyword(&self) -> &'static str {
749 "WHEN NOT MATCHED"
750 }
751
752 /// Whether MERGE supports `WHEN NOT MATCHED BY SOURCE`.
753 fn supports_merge_not_matched_by_source(&self) -> bool {
754 false
755 }
756
757 /// Whether this platform takes a `MERGE` statement.
758 ///
759 /// **This is `DialectCapabilities::merge_shape().merges()`, restated where
760 /// only a `SqlRenderer` is in hand** — the standalone `MergeStatement`
761 /// builder takes this trait alone and cannot ask the capability surface.
762 /// The two must answer identically; the capability/renderer consistency
763 /// gate holds them to equality with no exceptions, so a dialect that
764 /// overrides one and not the other is refused before it ships. An engine
765 /// whose shape is an upsert statement, an engine-deduplicated insert, or a
766 /// refusal answers `false` here.
767 fn merge_supported(&self) -> bool {
768 true
769 }
770
771 /// Whether `WITH SCHEMA EVOLUTION` is supported for MERGE.
772 fn merge_supports_schema_evolution_keyword(&self) -> bool {
773 false
774 }
775
776 /// Whether table hints are supported in MERGE target.
777 fn merge_supports_table_hints(&self) -> bool {
778 false
779 }
780
781 /// Whether OUTPUT clause should be used for MERGE result projection.
782 fn merge_uses_output_clause(&self) -> bool {
783 false
784 }
785
786 /// Whether RETURNING clause is supported for MERGE.
787 fn merge_supports_returning_clause(&self) -> bool {
788 false
789 }
790
791 /// **Whether this engine lets a `MERGE` target carry an alias.**
792 ///
793 /// Most do, and the composed load addresses the target through a short
794 /// `tgt`. An engine that answers `false` gets the target's own qualified
795 /// name in every position the alias would have stood — dropping the
796 /// qualifier instead makes the shared column names ambiguous.
797 fn merge_target_accepts_alias(&self) -> bool {
798 true
799 }
800
801 /// **Whether this engine refuses a `WITH` clause in front of `MERGE`.**
802 ///
803 /// The composed load types its staging rows in one common table expression
804 /// and hashes them in a second. Where a leading `WITH` parses, the two sit
805 /// in front of the statement and the source is the second one by name.
806 /// Where it does not, the same two move inside the `USING` subquery, which
807 /// is the same query in a position the grammar accepts.
808 ///
809 /// Answer `true` if `WITH … MERGE INTO …` is a syntax error on your engine.
810 fn merge_source_requires_inlined_ctes(&self) -> bool {
811 false
812 }
813
814 /// **Whether a `WITH` clause parses in front of this engine's `INSERT`.**
815 ///
816 /// A load that writes rows without matching them — one slice replaced, or
817 /// rows appended — types its staging rows in one common table expression
818 /// and hashes them in a second, exactly as the matching load does. Most
819 /// engines take those two inside the statement, after the column list and
820 /// in front of the `SELECT`, which is where Razeri puts them by default.
821 ///
822 /// Answer `true` where the same two have to lead instead, because the
823 /// engine reads a `WITH` after a table name as something else entirely:
824 /// T-SQL parses it as a table hint and rejects the statement. Nothing here
825 /// changes the query — only where the engine will accept it written down.
826 fn insert_accepts_leading_ctes(&self) -> bool {
827 false
828 }
829
830 /// **Whether this engine can be given a function by `CREATE FUNCTION`.**
831 ///
832 /// Razeri derives a surrogate key through a small emitted function, and an
833 /// engine whose SQL surface has no `CREATE FUNCTION` at all can never
834 /// receive it — the definition has to come from application code instead.
835 /// Such an engine gets no emitted helper and no per-entity key function,
836 /// and its dialect states the substitute in its own words.
837 ///
838 /// This is about the **grammar**, not about who owns the name: an engine
839 /// that can define functions but takes its key function from an installed
840 /// artifact still answers `true` here.
841 fn supports_sql_function_ddl(&self) -> bool {
842 true
843 }
844
845 /// **Whether a scalar function's body is a bare expression.**
846 ///
847 /// Most engines want a full `SELECT` in front of the value a function
848 /// returns. Some take the expression alone and reject the `SELECT`.
849 fn scalar_function_body_is_expression(&self) -> bool {
850 false
851 }
852
853 /// **Whether a scalar function belongs to a schema.**
854 ///
855 /// On most engines a function lives in a schema and both its definition and
856 /// its call sites name it. On an engine that answers `false`, functions are
857 /// server-global: `CREATE FUNCTION` takes no qualifier, and a qualified
858 /// call names a function that does not exist.
859 fn scalar_function_names_are_schema_qualified(&self) -> bool {
860 true
861 }
862
863 /// **Whether an unqualified scalar-function call resolves.**
864 ///
865 /// Most engines resolve a bare function name through a search path. An
866 /// engine that answers `true` resolves none, so a call with no schema in
867 /// front of it has to be given one — [`DialectCapabilities::default_schema`]
868 /// is the
869 /// schema the function was created in when the caller named none.
870 ///
871 /// [`DialectCapabilities::default_schema`]: crate::DialectCapabilities::default_schema
872 fn scalar_function_call_requires_schema(&self) -> bool {
873 false
874 }
875
876 /// **How this engine invokes a stored procedure**, as a whole statement.
877 ///
878 /// The composed load calls its own identity step, and a deploy script that
879 /// has no procedures at all has to recognise these calls in order to inline
880 /// what they would have run — so the call is spelled once, here.
881 fn render_procedure_call(&self, qualified_name: &str) -> String {
882 format!("CALL {qualified_name}();")
883 }
884
885 /// The schema separator for qualified names.
886 ///
887 /// Almost always `.`, but could differ for some platforms.
888 fn schema_separator(&self) -> &'static str {
889 "."
890 }
891
892 /// The statement separator for scripts.
893 ///
894 /// Almost all platforms: `;\n`, `SqlServer`: `;\nGO\n`
895 fn statement_separator(&self) -> &'static str {
896 ";\n"
897 }
898
899 // ═══════════════════════════════════════════════════════════════
900 // UPDATE behavior hooks
901 // ═══════════════════════════════════════════════════════════════
902
903 /// Whether the platform supports compound assignment operators (e.g., `col += value`).
904 ///
905 /// `SqlServer`: `true`, others: `false`.
906 fn supports_compound_assignment(&self) -> bool {
907 false
908 }
909
910 /// Whether UPDATE supports FROM clause for join-based updates.
911 ///
912 /// `PostgreSQL`, `SqlServer`, Snowflake, `CitusDB`: `true`, others: `false`.
913 fn supports_update_from(&self) -> bool {
914 false
915 }
916
917 /// Whether the platform uses ALTER TABLE ... UPDATE syntax (`ClickHouse` mutations).
918 fn uses_alter_table_update(&self) -> bool {
919 false
920 }
921
922 /// **Whether a mutation on this platform can read only the row it is
923 /// mutating.**
924 ///
925 /// `uses_alter_table_update` above says how the mutation is SPELLED; this
926 /// says what the mutation may LOOK AT, and the two are independent facts
927 /// that happen to be true of the same engine today. A platform answering
928 /// `true` here cannot express *assign this column from another relation*
929 /// at all: neither the `SET` list nor the `WHERE` may correlate out to a
930 /// second table, so no re-spelling of a correlated `UPDATE` compiles —
931 /// what is available instead is `INSERT … SELECT` over a join and a
932 /// mutation whose predicate is an uncorrelated `IN`.
933 ///
934 /// **Measured, and it is the reason the seam exists.** `ClickHouse`
935 /// 24.10.2 (2026-08-23) answered razeri's emitted re-open with
936 /// `Code: 47 … UNKNOWN_IDENTIFIER` while resolving the assignment's own
937 /// subquery — after the statement PARSED, which is what made the
938 /// distinction visible: the syntax was right and the reach was not.
939 ///
940 /// It sits here on [`SqlRenderer`] and **only** here, deliberately not
941 /// duplicated onto `DialectCapabilities`: `SqlRenderer` is the trait
942 /// razeri's generators call, so this is the definition that decides, and a
943 /// second declaration of the same fact is one that can drift.
944 ///
945 /// Default `false`: every engine razeri reaches except `ClickHouse` lets a
946 /// mutation correlate, and the ANSI correlated `UPDATE` those nine compile
947 /// is unchanged by this flag existing.
948 fn mutation_reads_only_its_own_rows(&self) -> bool {
949 false
950 }
951
952 /// **The spelling a SQL statement inside a generated procedure body reads
953 /// a declared local variable by.**
954 ///
955 /// A versioning load binds its clock ONCE — a `Declare` step at the top of
956 /// the procedure — and every close and every open reads the variable
957 /// instead of the engine's clock, so there is no daylight between the
958 /// close of one version and the open of the next. The DECLARATION is the
959 /// procedure renderer's business; what the load generators need is the
960 /// reference spelling to embed in the raw statements they compose, and
961 /// that differs by procedure language:
962 ///
963 /// - bare `name` — PL/pgSQL, MySQL/MariaDB, and the default;
964 /// - `@name` — T-SQL;
965 /// - `:name` — Snowflake Scripting's bind syntax inside SQL statements;
966 /// - `$name` — the agnostic format's marker.
967 ///
968 /// It mirrors the variable-reference spelling of Razeri's own procedure
969 /// renderers — the two must agree, and each override says so beside the
970 /// spelling.
971 fn render_procedure_variable_reference(&self, name: &str) -> String {
972 name.to_owned()
973 }
974
975 /// **The statement that binds one query's answer to a declared local.**
976 ///
977 /// A procedure body asks a question — how many rows arrived, what the
978 /// latest timestamp is — and keeps the answer in a variable the rest of the
979 /// body reads. Every procedural language has that statement and no two
980 /// spell it alike:
981 ///
982 /// - `SELECT COUNT(*) FROM stage INTO v_seen;` — PL/pgSQL;
983 /// - `SELECT @v_seen = (SELECT COUNT(*) FROM stage);` — T-SQL;
984 /// - `v_seen := (SELECT COUNT(*) FROM stage);` — Snowflake Scripting;
985 /// - `EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM stage' INTO v_seen;` —
986 /// Oracle's PL/SQL.
987 ///
988 /// `query` is the question, already carrying this dialect's variable
989 /// spelling and with no trailing terminator; `variable` is the bare name of
990 /// the local, so a grammar that wants the reference spelling asks
991 /// [`Self::render_procedure_variable_reference`] for it and one that wants
992 /// the bare name has it already. The answer is a whole statement,
993 /// terminator included.
994 ///
995 /// The default names the query and the target in a form that belongs to no
996 /// engine, because there is no spelling every engine shares. A dialect
997 /// rendering its own routine grammar answers this and the body arrives
998 /// ready to compile.
999 fn render_procedure_query_into_variable(&self, variable: &str, query: &str) -> String {
1000 format!("EXECUTE {query} INTO {};", self.render_procedure_variable_reference(variable))
1001 }
1002
1003 /// **The statement that stops a procedure body with an error of its own.**
1004 ///
1005 /// A generated load checks what it was given and refuses to go on when the
1006 /// answer is wrong. Every procedural language can stop that way and no two
1007 /// write it alike:
1008 ///
1009 /// - `RAISE EXCEPTION '%', 'the run brought no rows';` — PL/pgSQL;
1010 /// - `THROW 50000, 'the run brought no rows', 1;` — T-SQL;
1011 /// - `SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'the run brought no rows';`
1012 /// — `MySQL` and `MariaDB`;
1013 /// - `RAISE_APPLICATION_ERROR(-20001, 'the run brought no rows');` —
1014 /// Oracle's PL/SQL.
1015 ///
1016 /// `message` is the message **already rendered as a SQL expression in this
1017 /// dialect's spelling**: a literal arrives quoted and escaped, and a
1018 /// variable arrives named the way
1019 /// [`Self::render_procedure_variable_reference`] names one, because a body
1020 /// may raise what it read rather than what it was written with. Put it
1021 /// where the statement wants it and do not quote it again. `error_code` is
1022 /// the number the design gave, if it gave one; an engine whose statement
1023 /// takes a number supplies its own when this is `None`. The answer is a
1024 /// whole statement, terminator included.
1025 ///
1026 /// The default names the raise in a form that belongs to no engine. A
1027 /// dialect rendering its own routine grammar answers this and the body
1028 /// arrives ready to compile.
1029 fn render_procedure_raise(&self, message: &str, error_code: Option<i32>) -> String {
1030 match error_code {
1031 Some(code) => format!("RAISE EXCEPTION [{code}] {message};"),
1032 None => format!("RAISE EXCEPTION {message};"),
1033 }
1034 }
1035
1036 /// **The statement that writes a message where an operator can read it.**
1037 ///
1038 /// A load says how it is going, and where that message goes is an engine's
1039 /// own business — a client notice, a print stream, an event table, a
1040 /// result set nobody reads:
1041 ///
1042 /// - `RAISE NOTICE '%', 'loaded';` — PL/pgSQL;
1043 /// - `PRINT 'loaded';` — T-SQL;
1044 /// - `SYSTEM$LOG('INFO', 'loaded');` — Snowflake Scripting;
1045 /// - `DBMS_OUTPUT.PUT_LINE('loaded');` — Oracle's PL/SQL, which has no
1046 /// levels and ignores the one it is given.
1047 ///
1048 /// `message` arrives the same way [`Self::render_procedure_raise`] takes
1049 /// it: already a SQL expression in this dialect's spelling, quoted where it
1050 /// is a literal. `level` is the severity the design wrote; an engine whose
1051 /// statement carries one reads
1052 /// [`ProcedureLogLevel::as_str`] and spells it the way that statement
1053 /// wants. The answer is a whole statement, terminator included.
1054 ///
1055 /// The default names the level and the message in a form that belongs to no
1056 /// engine. A dialect rendering its own routine grammar answers this and the
1057 /// body arrives ready to compile.
1058 fn render_procedure_log(&self, level: ProcedureLogLevel, message: &str) -> String {
1059 let word = match level {
1060 ProcedureLogLevel::Debug => "DEBUG",
1061 ProcedureLogLevel::Info => "NOTICE",
1062 ProcedureLogLevel::Warning => "WARNING",
1063 ProcedureLogLevel::Error => "EXCEPTION",
1064 };
1065 format!("LOG {word} {message};")
1066 }
1067
1068 /// **The statement a generated load asks a scalar question with and throws
1069 /// the answer away.**
1070 ///
1071 /// A load's guard evaluates one scalar and reads nothing back: it either
1072 /// passes silently or stops the load on the engine's own error. What
1073 /// differs between engines is not the question but the STATEMENT that may
1074 /// carry it, and the difference is a procedure-language rule rather than a
1075 /// SQL one:
1076 ///
1077 /// - a bare `SELECT` is a legal script statement everywhere, and is legal
1078 /// inside the procedure bodies `MySQL`, `MariaDB` and T-SQL accept, where it
1079 /// simply hands the caller a result set nobody reads — so that is the
1080 /// default;
1081 /// - **PL/pgSQL refuses it.** A `SELECT` with no destination inside a
1082 /// procedure body is `query has no destination for result data`, raised
1083 /// the moment the procedure is called. PL/pgSQL's own discard form is
1084 /// `PERFORM`, and the Postgres family overrides this to spell it.
1085 ///
1086 /// The engines that ship no stored procedure inline the same statement into
1087 /// a script, where the default is the only form that runs — and every such
1088 /// engine takes the default, so one answer per dialect is unambiguous.
1089 ///
1090 /// `alias` names the answered column for the forms that answer one; a
1091 /// discard form that answers nothing ignores it.
1092 fn render_discarded_scalar(&self, expression: &str, alias: &str) -> String {
1093 format!("SELECT {expression} AS {alias};")
1094 }
1095
1096 /// **How a script with no stored procedures binds the load's clock once**
1097 /// — same rule as [`Self::render_procedure_variable_reference`], on the
1098 /// engines where a load ships as a flat statement list rather than a
1099 /// procedure body.
1100 ///
1101 /// The statements run FIRST and bind the engine's current moment to
1102 /// `name`; the reference is the expression every close and open in the
1103 /// same run then reads, so a version's `record_end_timestamp` and its
1104 /// successor's `record_start_timestamp` are one value by construction.
1105 /// Every spelling must be RE-RUNNABLE in one session — a second load in
1106 /// the same session rebinds rather than failing — because a load script is
1107 /// run whole and run again.
1108 ///
1109 /// The default is the one shape every engine can carry: a one-row
1110 /// temporary table capturing [`Self::render_current_timestamp`], read back
1111 /// through a scalar subquery. Engines with a native variable idiom
1112 /// override it (`DuckDB`'s `SET VARIABLE`, Databricks' session variables);
1113 /// `ClickHouse` overrides only the temporary-table spelling its own DDL
1114 /// requires.
1115 fn render_inline_clock_binding(&self, name: &str, moment: &str) -> InlineClockBinding {
1116 InlineClockBinding {
1117 statements: vec![
1118 format!("DROP TABLE IF EXISTS {name};"),
1119 format!("CREATE TEMPORARY TABLE {name} AS SELECT {moment} AS load_clock;"),
1120 ],
1121 reference: format!("(SELECT load_clock FROM {name})"),
1122 }
1123 }
1124
1125 /// Whether UPDATE supports TOP(n) clause (`SqlServer`).
1126 fn update_supports_top_clause(&self) -> bool {
1127 false
1128 }
1129
1130 /// Whether UPDATE supports table hints (e.g., `WITH (NOLOCK)`) (`SqlServer`).
1131 fn update_supports_table_hints(&self) -> bool {
1132 false
1133 }
1134
1135 /// Whether UPDATE uses OUTPUT clause positioned before FROM (`SqlServer`).
1136 ///
1137 /// When `true`, RETURNING/OUTPUT is rendered between SET and FROM.
1138 /// When `false`, RETURNING is rendered at the end of the statement.
1139 fn update_uses_output_clause(&self) -> bool {
1140 false
1141 }
1142
1143 /// Whether UPDATE supports a RETURNING clause at the end of the statement.
1144 ///
1145 /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
1146 fn update_supports_returning(&self) -> bool {
1147 false
1148 }
1149
1150 // ========================================================================
1151 // INSERT behavior hooks
1152 // ========================================================================
1153
1154 /// Whether INSERT uses OUTPUT clause positioned before VALUES/SELECT (`SqlServer`).
1155 ///
1156 /// When `true`, RETURNING/OUTPUT is rendered between column list and source.
1157 /// When `false`, RETURNING is rendered at the end of the statement.
1158 fn insert_uses_output_clause(&self) -> bool {
1159 false
1160 }
1161
1162 /// Whether INSERT supports RETURNING at the end (`PostgreSQL`, `CitusDB`).
1163 fn insert_supports_returning(&self) -> bool {
1164 false
1165 }
1166
1167 /// Whether INSERT supports table hints (e.g., `WITH (TABLOCK)`) (`SqlServer`).
1168 fn insert_supports_table_hints(&self) -> bool {
1169 false
1170 }
1171
1172 /// Whether INSERT OVERWRITE is supported (Snowflake, Databricks).
1173 fn supports_insert_overwrite(&self) -> bool {
1174 false
1175 }
1176
1177 /// Whether INSERT ... ON CONFLICT is supported (`PostgreSQL`, `CitusDB`).
1178 fn supports_on_conflict(&self) -> bool {
1179 false
1180 }
1181
1182 /// Whether OVERRIDING SYSTEM/USER VALUE clause is supported (`PostgreSQL`).
1183 fn supports_overriding_clause(&self) -> bool {
1184 false
1185 }
1186
1187 /// The keyword for returning data from DML: "OUTPUT" (`SqlServer`) or "RETURNING" (others).
1188 fn returning_clause_keyword(&self) -> &'static str {
1189 "RETURNING"
1190 }
1191
1192 /// Whether OUTPUT ... INTO is supported (`SqlServer`).
1193 fn supports_returning_into(&self) -> bool {
1194 false
1195 }
1196
1197 /// Whether multi-table INSERT (INSERT ALL) is supported (Snowflake).
1198 fn supports_multi_table_insert(&self) -> bool {
1199 false
1200 }
1201
1202 // ========================================================================
1203 // Function/procedure parameter behavior hooks
1204 // ========================================================================
1205
1206 /// Render the security mode clause for function/procedure definitions.
1207 ///
1208 /// Standard SQL: `SECURITY INVOKER`/`SECURITY DEFINER`.
1209 /// T-SQL: `EXECUTE AS CALLER`/`EXECUTE AS OWNER`.
1210 fn render_security_mode(&self, is_definer: bool) -> &'static str {
1211 if is_definer { "SECURITY DEFINER" } else { "SECURITY INVOKER" }
1212 }
1213
1214 /// Render a function parameter name.
1215 ///
1216 /// Standard SQL uses the bare name. T-SQL prefixes with `@`.
1217 fn render_function_parameter_name(&self, name: &str) -> String {
1218 name.to_string()
1219 }
1220
1221 /// Render explicit nullability for a function parameter, if the platform requires it.
1222 ///
1223 /// Most platforms omit nullability in parameter lists. T-SQL native
1224 /// compilation requires explicit `NULL`/`NOT NULL`.
1225 fn render_function_parameter_nullable(&self, _nullable: bool) -> Option<&'static str> {
1226 None
1227 }
1228
1229 /// Render the default-value clause for a function parameter.
1230 ///
1231 /// Standard SQL: `DEFAULT value`. T-SQL: `= value`.
1232 fn render_function_parameter_default(&self, value: &str) -> String {
1233 format!("DEFAULT {value}")
1234 }
1235
1236 /// Render a column name inside a table-valued function definition.
1237 ///
1238 /// Standard SQL uses the bare name. T-SQL uses bracket quoting `[name]`.
1239 fn render_function_column_name(&self, name: &str) -> String {
1240 name.to_string()
1241 }
1242
1243 // ========================================================================
1244 // Partition & generated column rendering hooks
1245 // ========================================================================
1246
1247 /// Render a time partition expression for a column and granularity.
1248 ///
1249 /// Granularity values: `"hourly"`, `"daily"`, `"weekly"`, `"monthly"`,
1250 /// `"quarterly"`, `"yearly"`.
1251 ///
1252 /// Default: `date_trunc('unit', column)` (ANSI / `PostgreSQL` style),
1253 /// mapping granularity names to `date_trunc` units.
1254 fn render_time_partition_expr(&self, column: &str, granularity: &str) -> String {
1255 let unit = match granularity {
1256 "hourly" => "hour",
1257 "daily" => "day",
1258 "weekly" => "week",
1259 "monthly" => "month",
1260 "quarterly" => "quarter",
1261 "yearly" => "year",
1262 other => other,
1263 };
1264 format!("date_trunc('{unit}', {column})")
1265 }
1266
1267 /// Render a DDL partition clause wrapping the expression list.
1268 ///
1269 /// Default: `PARTITION BY (expr)`. Snowflake: `CLUSTER BY (expr)`,
1270 /// Databricks: `PARTITIONED BY (expr)`, `ClickHouse`: `PARTITION BY expr` (no parens).
1271 fn render_partition_clause(&self, expr: &str) -> String {
1272 format!("PARTITION BY ({expr})")
1273 }
1274
1275 /// Render a generated column declaration.
1276 ///
1277 /// Default: `name GENERATED ALWAYS AS (expr) STORED` (`PostgreSQL` style).
1278 fn render_generated_column(&self, name: &str, expr: &str) -> String {
1279 format!("{name} GENERATED ALWAYS AS ({expr}) STORED")
1280 }
1281
1282 // ========================================================================
1283 // Window function capability hooks
1284 // ========================================================================
1285
1286 /// Whether the platform supports the EXCLUDE clause in window frame specifications.
1287 ///
1288 /// `PostgreSQL`, Snowflake, Databricks: `true`. Others: `false`.
1289 fn supports_window_frame_exclude(&self) -> bool {
1290 false
1291 }
1292
1293 /// Whether the platform supports the GROUPS frame mode in window functions.
1294 ///
1295 /// `PostgreSQL`, Databricks: `true`. Others: `false`.
1296 fn supports_window_frame_groups(&self) -> bool {
1297 false
1298 }
1299
1300 /// Whether the platform supports named windows (WINDOW clause).
1301 ///
1302 /// Most platforms: `true`. `ClickHouse`, `DuckDB`, `MariaDB`: `false`.
1303 fn supports_named_windows(&self) -> bool {
1304 true
1305 }
1306
1307 // ========================================================================
1308 // DDL table-scope capability hooks
1309 // ========================================================================
1310
1311 /// Whether the platform uses a `#` prefix for session-scoped temporary table names.
1312 ///
1313 /// SQL Server: `true`. Others: `false`.
1314 fn uses_hash_temp_table_prefix(&self) -> bool {
1315 false
1316 }
1317
1318 /// Whether the platform supports `DECLARE @name TABLE (...)` table variables.
1319 ///
1320 /// SQL Server: `true`. Others: `false`.
1321 fn supports_table_variables(&self) -> bool {
1322 false
1323 }
1324
1325 /// The full CREATE keyword for session-scoped temporary tables.
1326 ///
1327 /// Default: `"CREATE TEMPORARY"`.
1328 /// SQL Server: `"CREATE"` (uses `#name` instead of TEMPORARY keyword).
1329 /// Databricks: `"CREATE OR REPLACE TEMPORARY"`.
1330 fn render_create_temp_table_keyword(&self) -> &'static str {
1331 "CREATE TEMPORARY"
1332 }
1333
1334 /// Whether the platform supports transient tables (e.g. `CREATE TRANSIENT TABLE`).
1335 ///
1336 /// Snowflake: `true`. Others: `false`.
1337 fn supports_transient_tables(&self) -> bool {
1338 false
1339 }
1340
1341 /// Whether the platform supports `ON COMMIT DROP` for transaction-scoped temp tables.
1342 ///
1343 /// `PostgreSQL`, `CitusDB`: `true`. Others: `false`.
1344 fn supports_on_commit_drop(&self) -> bool {
1345 false
1346 }
1347
1348 /// Whether the platform requires an `ENGINE = ...` clause on CREATE TABLE.
1349 ///
1350 /// `ClickHouse`: `true`. Others: `false`.
1351 ///
1352 /// A platform that answers `true` owns its whole engine suffix in ONE place:
1353 /// the `CREATE TABLE` composer emits the engine, then the sorting key, then
1354 /// whatever the resolved storage plan contributes. A storage renderer for
1355 /// such a platform must therefore contribute NEITHER an engine clause nor a
1356 /// sorting key — two engine clauses is `Code: 62 … Syntax error`, and a
1357 /// sorting key that disagrees with the inline `PRIMARY KEY` is
1358 /// `Code: 36 … Primary key must be a prefix of the sorting key` (both
1359 /// measured on `ClickHouse` 24.10.2).
1360 fn requires_table_engine(&self) -> bool {
1361 false
1362 }
1363
1364 /// Whether this platform's table sorting key refuses nullable columns.
1365 ///
1366 /// `ClickHouse`: `true` — a `MergeTree` sorting key containing a
1367 /// `Nullable(…)` column answers `Code: 44 … Sorting key contains nullable
1368 /// columns, but merge tree setting allow_nullable_key is disabled`, measured
1369 /// on 24.10.2 against the control (the same key over a non-nullable column
1370 /// of the same type is accepted). Others: `false`.
1371 ///
1372 /// The materializer asks this before it lets a design's clustering columns
1373 /// into a sorting key, so the answer is a refusal the author can act on
1374 /// rather than a deployment failure they cannot.
1375 fn sorting_key_refuses_nullable_columns(&self) -> bool {
1376 false
1377 }
1378
1379 /// Whether the platform requires a primary key on every table.
1380 ///
1381 /// `ClickHouse` (MergeTree): `true`. Others: `false`.
1382 fn requires_primary_key_in_create_table(&self) -> bool {
1383 false
1384 }
1385
1386 /// Create a boxed [`FormulaRenderer`](crate::FormulaRenderer) for this dialect.
1387 ///
1388 /// Real dialect implementations override this to return `Box::new(Self)`.
1389 /// The default returns an ANSI dialect with standard function names.
1390 fn to_formula_renderer(&self) -> Box<dyn crate::FormulaRenderer> {
1391 Box::new(crate::AnsiDialect)
1392 }
1393}
1394
1395/// Level 2 — Expression rendering with ANSI SQL defaults.
1396pub trait ExpressionRenderer: SqlRenderer {
1397 /// **Render a conversion of `expr` to `target`** — the expression the
1398 /// generated load's typed projection writes for every column.
1399 ///
1400 /// The default is `CAST(expr AS …)` over
1401 /// [`render_cast_type`](SqlRenderer::render_cast_type), the cast vocabulary
1402 /// rather than the column vocabulary: a column may be declared `STRING(36)`
1403 /// where a cast may name only `STRING`, and `TINYINT` where a cast must say
1404 /// `SMALLINT`. Override it where a conversion is not a `CAST` at all —
1405 /// `GoogleSQL` has no cast from `STRING` to `JSON` ("Invalid cast from
1406 /// STRING to JSON") and converts with `PARSE_JSON(expr)` instead.
1407 fn render_cast(&self, expr: &str, target: &DataType) -> String {
1408 format!("CAST({} AS {})", expr, self.render_cast_type(target))
1409 }
1410
1411 /// **Read a value the source spells its own way** into `target`, which is
1412 /// a date or a timestamp.
1413 ///
1414 /// An import arrives with `1/1/2015` in one column and
1415 /// `2015-01-01T00:00:00Z` in the next, and no engine reads either of them
1416 /// the same way as the engine beside it. So the design states the
1417 /// spelling, razeri reads it once into a [`DateFormat`], and this
1418 /// translates that list into whatever this engine's own pattern language
1419 /// is — `MM/DD/YYYY`, `MM/dd/yyyy`, a style number, or a format string
1420 /// this engine calls its own.
1421 ///
1422 /// **A value that is not spelled that way has to come back as NULL.**
1423 /// razeri reads the NULL as *this row did not parse* and writes the row
1424 /// into the table it sets rows aside in, naming the column and the format
1425 /// it was told to expect. An expression that stops the load instead leaves
1426 /// a warehouse half-loaded over one bad row, and one that answers a
1427 /// different day than the value says is worse than either. An engine whose
1428 /// parse reads a value it cannot read — rolling the forty-fifth of a month
1429 /// forward rather than answering nothing — writes its own guard beside the
1430 /// parse; [`DateFormat::shape_pattern`] and
1431 /// [`DateFormat::capture_pattern`] come from the same directive list, so
1432 /// the guard and the parse cannot hold two opinions about one spelling.
1433 ///
1434 /// **A directive this engine cannot say is a refusal, not a guess.**
1435 /// [`DateFormat::translate`] hands back the first directive this engine
1436 /// answered nothing for, and answering `None` here is how that reaches
1437 /// the author — by name, at the door, rather than as a wrong day in the
1438 /// warehouse.
1439 ///
1440 /// `None` — the default — is this engine stating nothing about how it
1441 /// reads a spelled value. razeri then refuses the column and names the
1442 /// engine.
1443 fn render_parse_datetime(
1444 &self,
1445 _expr: &str,
1446 _format: &DateFormat,
1447 _target: &DataType,
1448 ) -> Option<String> {
1449 None
1450 }
1451
1452 /// **Read a value the source writes its own way** into `target`, which is
1453 /// a number.
1454 ///
1455 /// A file writes a price `$2,899.99 `. The symbol, the thousands mark and
1456 /// the space around it are not part of the number, and no two engines
1457 /// agree about what to do with them — one converts the text to nothing,
1458 /// one to `2`, one raises. So the design states the picture, razeri reads
1459 /// it once into a [`NumberFormat`], and this renders the reading in
1460 /// whatever this engine's own words for *take this out* and *convert this*
1461 /// are.
1462 ///
1463 /// **A value that is not written that way has to come back as NULL.**
1464 /// razeri reads the NULL as *this row did not parse* and writes the row
1465 /// into the table it sets rows aside in, naming the column and the picture
1466 /// it was told to expect. An expression that stops the load instead leaves
1467 /// a warehouse half-loaded over one bad row, and one that answers `0` for
1468 /// text that was never a number is worse than either. An engine whose
1469 /// conversion raises, or answers a number for text that is not one, writes
1470 /// a guard in front of it; [`NumberFormat::shape_pattern`] is built from
1471 /// the same picture the marks come from, so the guard and the reading
1472 /// cannot hold two opinions about one spelling.
1473 ///
1474 /// `None` — the default — is this engine stating nothing about how it
1475 /// reads a written amount. razeri then refuses the column and names the
1476 /// engine. `None` is also the right answer for a target that is not a
1477 /// number: a picture says how an amount is written, and there is nothing
1478 /// else for it to be about.
1479 ///
1480 /// [`NumberFormat`]: crate::number_format::NumberFormat
1481 /// [`NumberFormat::shape_pattern`]: crate::number_format::NumberFormat::shape_pattern
1482 fn render_parse_number(
1483 &self,
1484 _expr: &str,
1485 _format: &NumberFormat,
1486 _target: &DataType,
1487 ) -> Option<String> {
1488 None
1489 }
1490
1491 /// Render string concatenation.
1492 fn render_concat(&self, parts: &[String]) -> String {
1493 format!("CONCAT({})", parts.join(", "))
1494 }
1495
1496 /// Render a COALESCE expression.
1497 fn render_coalesce(&self, parts: &[String]) -> String {
1498 format!("COALESCE({})", parts.join(", "))
1499 }
1500
1501 /// Render a string aggregation function.
1502 fn render_string_agg(&self, expr: &str, separator: &str) -> String {
1503 format!("STRING_AGG({expr}, '{separator}')")
1504 }
1505}
1506
1507/// A foreign key's referential action — SQL's own five words, no synonyms.
1508///
1509/// Lives here (rather than in the table model) so a dialect can answer
1510/// [`DdlRenderer::supports_foreign_key_action`] about a specific action
1511/// without depending on the modeling crate.
1512#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1513pub enum ReferentialAction {
1514 /// Also delete or update the referencing rows
1515 Cascade,
1516 /// Set the referencing columns to NULL
1517 SetNull,
1518 /// Reject the delete or update; some engines defer the check
1519 Restrict,
1520 /// Reject the delete or update (the SQL default)
1521 NoAction,
1522 /// Set the referencing columns to their default values
1523 SetDefault,
1524}
1525
1526impl ReferentialAction {
1527 /// Parses the SQL words, case-insensitively; underscores read as spaces
1528 /// so `set_null` and `SET NULL` both land.
1529 ///
1530 /// # Errors
1531 /// Returns a plain message listing the valid words when the input is not
1532 /// one of them.
1533 pub fn from_sql_word(word: &str) -> Result<Self, String> {
1534 match word.trim().replace('_', " ").to_uppercase().as_str() {
1535 "CASCADE" => Ok(Self::Cascade),
1536 "SET NULL" => Ok(Self::SetNull),
1537 "RESTRICT" => Ok(Self::Restrict),
1538 "NO ACTION" => Ok(Self::NoAction),
1539 "SET DEFAULT" => Ok(Self::SetDefault),
1540 _ => Err(format!(
1541 "'{word}' is not a referential action. Use one of: CASCADE, SET NULL, \
1542 RESTRICT, NO ACTION, SET DEFAULT."
1543 )),
1544 }
1545 }
1546}
1547
1548impl std::fmt::Display for ReferentialAction {
1549 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1550 match self {
1551 Self::Cascade => write!(f, "CASCADE"),
1552 Self::SetNull => write!(f, "SET NULL"),
1553 Self::Restrict => write!(f, "RESTRICT"),
1554 Self::NoAction => write!(f, "NO ACTION"),
1555 Self::SetDefault => write!(f, "SET DEFAULT"),
1556 }
1557 }
1558}
1559
1560/// Level 3 — DDL rendering with reasonable defaults.
1561pub trait DdlRenderer: SqlRenderer {
1562 /// Prefix for CREATE TABLE statements.
1563 fn render_create_table_prefix(&self) -> &'static str {
1564 "CREATE TABLE"
1565 }
1566
1567 /// Whether this engine carries the given foreign-key referential action
1568 /// (`ON DELETE …` / `ON UPDATE …`) in `CREATE TABLE` DDL.
1569 ///
1570 /// The ANSI default says yes to all five words. A dialect answers `false`
1571 /// for an action its engine rejects or silently never enforces; the
1572 /// renderer then keeps the author's declaration visible as a plain
1573 /// comment instead of emitting a clause the engine would refuse — a
1574 /// declared action never vanishes without a trace.
1575 fn supports_foreign_key_action(&self, action: ReferentialAction) -> bool {
1576 let _ = action;
1577 true
1578 }
1579
1580 /// Prefix for CREATE VIEW statements.
1581 fn render_create_view_prefix(&self) -> &'static str {
1582 "CREATE OR REPLACE VIEW"
1583 }
1584
1585 /// Render a column definition (name, type, nullability).
1586 fn render_column_definition(&self, name: &str, dt: &DataType, nullable: bool) -> String {
1587 let quoted = self.quote_identifier(name);
1588 let (type_str, null_str) = if nullable {
1589 (self.render_nullable_data_type(dt), "")
1590 } else {
1591 (self.render_data_type(dt), " NOT NULL")
1592 };
1593 format!("{quoted} {type_str}{null_str}")
1594 }
1595
1596 /// **The statement this engine takes for one change to a table that
1597 /// already holds rows**, or `None` where it has none.
1598 ///
1599 /// Razeri classifies every difference between two deploys and hands the
1600 /// ones that lose nothing to this method, one at a time. What comes back
1601 /// goes into the file an operator runs; `None` means the change is named in
1602 /// the plan with this engine's name beside it, so the reader learns which
1603 /// engine has no statement rather than that no engine does.
1604 ///
1605 /// # The default, and why it is the only one
1606 ///
1607 /// `ALTER TABLE … ADD COLUMN … <type>` is the one spelling every engine
1608 /// Razeri targets accepts, so a dialect that answers nothing still writes
1609 /// the commonest evolution there is: a column that was not there yesterday.
1610 /// The column is declared without `NOT NULL`, which is the only form that
1611 /// can be added to a table that already holds rows.
1612 ///
1613 /// Every other change answers `None` by default. A widening and a record
1614 /// that gained a field are each spelled three or four ways across the
1615 /// engines Razeri reaches, and a default picked from one of them writes SQL
1616 /// the others reject — a statement handed to an operator who then finds out
1617 /// their engine will not take it. A dialect that has measured its engine
1618 /// says so here, and the ones that have not say nothing.
1619 ///
1620 /// The statement comes back without a terminator; the caller separates
1621 /// statements the way this engine separates them.
1622 fn render_column_evolution(&self, change: &ColumnEvolution<'_>) -> Option<String> {
1623 match change {
1624 ColumnEvolution::AddColumn { schema, table, column, data_type } => {
1625 let target = self.qualify_name(*schema, table);
1626 let name = self.quote_identifier(column);
1627 let rendered = self.render_nullable_data_type(data_type);
1628 Some(format!("ALTER TABLE {target} ADD COLUMN {name} {rendered}"))
1629 }
1630 ColumnEvolution::WidenColumn { .. } | ColumnEvolution::AddNestedField { .. } => None,
1631 }
1632 }
1633
1634 /// Render the surrogate identity column — a plain, ungenerated `BIGINT NOT
1635 /// NULL` on **every** dialect.
1636 ///
1637 /// **razeri's surrogate keys are logical and DETERMINATE, never
1638 /// engine-generated.** The identity value is a hash
1639 /// derived from the entity's identity grain, WRITTEN BY THE LOAD
1640 /// (`materialize_core`, `sid_expression`), so the same design loaded with the
1641 /// same data converges to the same key on `Postgres`, `Snowflake`, `MariaDB`,
1642 /// `ClickHouse` — every target. A database-assigned `AUTO_INCREMENT` /
1643 /// `IDENTITY(1,1)` / `GENERATED ALWAYS AS IDENTITY` would be sequential,
1644 /// load-order-dependent and **non-portable** — a different key per database
1645 /// for the same row — which is the one thing a portable key may not be. So no
1646 /// dialect emits a generator here; every one renders a plain column and the
1647 /// load fills it.
1648 ///
1649 /// `SQLite` narrows the type to `INTEGER` and `ClickHouse`/`DuckDB` carry
1650 /// their own overrides only to document the same plain shape; no override
1651 /// re-introduces a generator.
1652 ///
1653 /// The `_data_type` argument is reserved for future use (e.g., dialect-aware
1654 /// width selection); current dialects always emit `BIGINT` / `INTEGER`.
1655 fn render_identity_column(&self, name: &str, _data_type: &DataType) -> String {
1656 let quoted = self.quote_identifier(name);
1657 format!("{quoted} BIGINT NOT NULL")
1658 }
1659
1660 /// Whether this platform's engine actually **assigns** an identity column's
1661 /// value, rather than merely tolerating the declaration.
1662 ///
1663 /// **This is a dialect fact, not a field fact, and the difference is a
1664 /// deploy-time failure.** `Field::identity` says razeri intends the engine
1665 /// to generate the value; whether it does depends entirely on the target.
1666 /// `render_identity_column`'s own table above records that `DuckDB`,
1667 /// `SQLite` and `ClickHouse` have **no native identity** — there the column
1668 /// comes out as a plain `NOT NULL` and **the writer must supply it.**
1669 ///
1670 /// The default is `false` because the default `render_identity_column`
1671 /// emits no generation clause: a dialect that overrides the rendering to
1672 /// generate values must override this too, and
1673 /// `the_identity_capability_matches_what_each_dialect_renders` holds the two
1674 /// in step so they cannot drift.
1675 ///
1676 /// Read by the deploy bundle's write contract: a column
1677 /// the engine does not generate is a column a hand-written `INSERT` owes.
1678 fn generates_identity_values(&self) -> bool {
1679 false
1680 }
1681
1682 /// **The latest instant this platform can hold EXACTLY in the column it
1683 /// renders for `data_type`** — the ceiling the refuse-by-name rule compares
1684 /// against, or `None` for *no declared ceiling*.
1685 ///
1686 /// Spelled `YYYY-MM-DD HH:MM:SS`, which is how razeri writes a timestamp
1687 /// literal (`razeri_materialize::convert::OPEN_INTERVAL_SENTINEL`), so the
1688 /// comparison is a string comparison over a format that sorts
1689 /// chronologically. A ceiling and a value in the same spelling cannot be
1690 /// compared wrongly by a parser neither of them goes through.
1691 ///
1692 /// # What the refusal contract asks of this
1693 ///
1694 /// > A value razeri cannot store exactly on a target platform is a
1695 /// > deploy-time refusal naming the value, the column, the platform and the
1696 /// > ceiling — never a truncation, never a saturated write.
1697 ///
1698 /// The *refusal* lives in `razeri_materialize::bundle`, which is the one
1699 /// place it is built — the function is `refuse_unrepresentable_values`, and
1700 /// it is reached from `generate_bundle` before a single file is rendered.
1701 /// This is only where a platform declares the number.
1702 ///
1703 /// # A stated variance from the decision's original wording
1704 ///
1705 /// The refusal was decided as a *deploy-time* act, homed in the
1706 /// prerequisites step. Razeri refuses **earlier**: at bundle
1707 /// generation, by declining to emit the bundle at all. That is strictly
1708 /// ahead of deploy time and cannot be skipped by an operator who never runs
1709 /// the script — a deliberate strengthening, recorded rather
1710 /// than glossed. The consequence worth knowing: a *hand-assembled* bundle,
1711 /// or one from an older razeri, is not re-checked at deploy time by
1712 /// anything. **The default is `None`, which
1713 /// means "razeri has no measured ceiling for this platform and type" and not
1714 /// "this platform holds everything"** — an unmeasured platform gets no
1715 /// refusal rather than an invented one.
1716 ///
1717 /// # The ceiling is a property of the TYPE, not of the platform
1718 ///
1719 /// That is the half a platform-flat capability would get wrong, and it is
1720 /// measured rather than assumed (reading the renderers):
1721 ///
1722 /// | platform | `Timestamp(p)` renders | ceiling | `TimestampTz(p)` renders | ceiling |
1723 /// |---|---|---|---|---|
1724 /// | `MySQL`, `MariaDB` | `DATETIME(p)` | `None` — the end of the four-digit calendar is not a constraint | `TIMESTAMP(p)` | **`2038-01-19 03:14:07`** |
1725 /// | `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 |
1726 /// | everything else | — | not measured → `None` | — | `None` |
1727 ///
1728 /// On `MySQL` the two razeri type variants land on *different engine types*
1729 /// and get different answers: `Timestamp` renders as the
1730 /// non-converting `DATETIME` — the type whose semantics match the declared
1731 /// non-tz timestamp — which runs to the end of the calendar and so
1732 /// declares no ceiling at all, while `TimestampTz` keeps `TIMESTAMP` and its
1733 /// 32-bit epoch boundary. A check keyed on the platform alone would either
1734 /// miss the real ceiling or refuse a column that is fine. On `ClickHouse`
1735 /// the ceiling moves with the **declared precision** of one type:
1736 /// `DateTime64(9)` is int64 nanoseconds from the epoch and stops at
1737 /// 2262-04-11, while `DateTime64(6)` reaches 2299.
1738 ///
1739 /// Parameters:
1740 /// - `data_type`: the column's declared type, as the design carries it —
1741 /// not the rendered string, because the precision is what moves the answer
1742 /// and re-parsing it back out of `DateTime64(9)` would be a second reading
1743 /// of what the dialect already knows.
1744 fn representable_timestamp_ceiling(&self, data_type: &DataType) -> Option<&'static str> {
1745 let _ = data_type;
1746 None
1747 }
1748
1749 /// Whether the platform requires every auto-increment / identity column to
1750 /// be the leading column of an index (PK or KEY).
1751 ///
1752 /// `MySQL` / `MariaDB`: `true` (otherwise error 1075). Others: `false`.
1753 ///
1754 /// When this is `true` and an identity column is not already the leading
1755 /// column of the primary key, the DDL renderer must emit an additional
1756 /// `KEY (identity_col)` clause on the table.
1757 fn auto_increment_requires_key(&self) -> bool {
1758 false
1759 }
1760
1761 /// Prefix for DROP TABLE statements.
1762 fn render_drop_table_prefix(&self, if_exists: bool) -> String {
1763 if if_exists { "DROP TABLE IF EXISTS".to_string() } else { "DROP TABLE".to_string() }
1764 }
1765
1766 /// Prefix for DROP VIEW statements.
1767 fn render_drop_view_prefix(&self, if_exists: bool) -> String {
1768 if if_exists { "DROP VIEW IF EXISTS".to_string() } else { "DROP VIEW".to_string() }
1769 }
1770
1771 /// Prefix for CREATE SCHEMA / CREATE NAMESPACE.
1772 fn render_create_schema_prefix(&self, if_not_exists: bool) -> String {
1773 if if_not_exists {
1774 "CREATE SCHEMA IF NOT EXISTS".to_string()
1775 } else {
1776 "CREATE SCHEMA".to_string()
1777 }
1778 }
1779
1780 /// Render a complete CREATE SCHEMA statement.
1781 ///
1782 /// Dialects that need fundamentally different syntax (e.g. T-SQL wrapping
1783 /// in `IF SCHEMA_ID(...) IS NULL EXEC(...)`) should override this method.
1784 /// The default concatenates [`Self::render_create_schema_prefix`] with the name.
1785 fn render_create_schema_statement(&self, name: &str, if_not_exists: bool) -> String {
1786 let prefix = self.render_create_schema_prefix(if_not_exists);
1787 format!("{prefix} {name}")
1788 }
1789
1790 /// Render a table comment (platform-specific syntax).
1791 ///
1792 /// Like [`Self::render_column_comment`], nothing in the tree calls this and
1793 /// no dialect overrides it — **and unlike its sibling it has not been
1794 /// measured.** Read that method's table before wiring either: the ANSI
1795 /// spelling is a hard syntax error on five of the ten platforms razeri
1796 /// renders for at the column level, and this form was not probed.
1797 fn render_table_comment(&self, table: &str, comment: &str) -> Option<String> {
1798 Some(format!("COMMENT ON TABLE {table} IS '{comment}'"))
1799 }
1800
1801 /// Render a column comment — **not wired to anything, and measured**.
1802 ///
1803 /// # Nothing calls this
1804 ///
1805 /// No caller in the tree, no dialect override, and, until measured, no
1806 /// execution against a live engine — the exact state the column `DEFAULT`
1807 /// clause was in when it turned out to be refused outright on four platforms
1808 /// of ten and silently wrong on a fifth. Moving the open
1809 /// interval's meaning here was proposed **on the condition that it be measured first**,
1810 /// because *"a comment that fails to compile is a worse outcome than the
1811 /// clause it replaced"*.
1812 ///
1813 /// # It was measured, on ten platforms, and this ANSI form is right on five
1814 ///
1815 /// Executed against six containers, in-process `DuckDB` and
1816 /// `SQLite`, and both live cloud accounts:
1817 ///
1818 /// | platform | this `COMMENT ON COLUMN` | inline `COMMENT` in `CREATE TABLE` | what it does take |
1819 /// |---|---|---|---|
1820 /// | `PostgreSQL`, Citus | ✅ | ❌ syntax error | this, as a separate statement |
1821 /// | `DuckDB` | ✅ | ❌ syntax error | this, as a separate statement |
1822 /// | Snowflake, Databricks | ✅ | ✅ | either |
1823 /// | `ClickHouse` | ❌ `SYNTAX_ERROR` (code 62) | ✅ | inline, or `ALTER TABLE … COMMENT COLUMN c '…'` |
1824 /// | `MySQL`, `MariaDB` | ❌ `ERROR 1064` | ✅ | inline, or `ALTER TABLE … MODIFY <whole column definition> COMMENT '…'` |
1825 /// | SQL Server | ❌ `Msg 156, Incorrect syntax near the keyword 'ON'` | ❌ `Msg 102` | `EXEC sp_addextendedproperty …` — a stored procedure, not DDL |
1826 /// | `SQLite` | ❌ syntax error | ❌ syntax error | **nothing at all** |
1827 ///
1828 /// Four mechanisms for ten platforms, and two of them carry a hazard the
1829 /// `DEFAULT` clause never had:
1830 ///
1831 /// - `MySQL`'s and `MariaDB`'s only `ALTER` route **redefines the column**.
1832 /// Measured: a `MODIFY` that did not restate `NOT NULL` left
1833 /// `is_nullable = YES` behind it. A documentation mechanism that can
1834 /// silently de-constrain a column is strictly worse than the clause it
1835 /// replaces.
1836 /// - SQL Server's `sp_addextendedproperty` **is not idempotent**:
1837 /// `Msg 15233 — Property 'MS_Description' already exists`. Razeri emits
1838 /// `CREATE TABLE IF NOT EXISTS` so a deploy bundle can be re-applied; a
1839 /// comment mechanism that fails on the second run takes that away.
1840 ///
1841 /// # So the escape hatch was taken
1842 ///
1843 /// Q1's answer included its own fall-back — *"if the measurement comes back
1844 /// ugly, take the simpler answer: no comment, and the bundle README carries
1845 /// the contract"* — and the measurement is ugly. **Razeri emits no column
1846 /// comment.** The open interval's meaning ships instead in the deploy
1847 /// bundle's generated *write contract*
1848 /// (`razeri_materialize::bundle::write_contract`, Q5), which is prose an
1849 /// operator reads, is right on all ten platforms because no engine parses
1850 /// it, and is owed regardless of how this measurement came out.
1851 ///
1852 /// The hook stays, unchanged and unwired, for the same reason
1853 /// `render_column_default` stays: a dialect that genuinely wants to emit one
1854 /// has somewhere to say so. **A dialect that overrides this owes a
1855 /// measurement first** — the ANSI spelling below is a hard syntax error on
1856 /// five of the ten platforms razeri renders for.
1857 fn render_column_comment(&self, table: &str, column: &str, comment: &str) -> Option<String> {
1858 Some(format!("COMMENT ON COLUMN {table}.{column} IS '{comment}'"))
1859 }
1860
1861 /// Whether to render IF NOT EXISTS on CREATE TABLE.
1862 fn supports_if_not_exists(&self) -> bool {
1863 true
1864 }
1865
1866 /// Render a column's `DEFAULT` clause — **keyword included** — or decline it.
1867 ///
1868 /// `None` means *this dialect renders no default clause for this value*,
1869 /// and Razeri's column renderer omits the whole clause. The ANSI default
1870 /// returns `None` for every value, which
1871 /// is the write-contract rule expressed where the renderer can see it:
1872 /// **razeri emits no
1873 /// column `DEFAULT` clause in rendered DDL, on any platform, for any value —
1874 /// a value the generated load owns is written by the load, never by the
1875 /// schema.**
1876 ///
1877 /// *Read that qualifier deliberately.* The sentence is about the DDL an engine
1878 /// executes. The `.raz.sql` **agnostic interchange** form —
1879 /// `Table::to_ddl()`, which `Table::from_ddl()` parses back — still
1880 /// serializes `Field::default_value` as `DEFAULT <value>`, because that is
1881 /// where a design's declared default survives a save and a load.
1882 ///
1883 /// **That exception is a serializer, not a platform, and the word "agnostic"
1884 /// names both.** `to_ddl()` renders through a free function and consults no
1885 /// dialect; you reach it by calling it, never by choosing a target.
1886 /// `SchemaObject::render_ddl` short-circuits to it only for a renderer whose
1887 /// [`SqlRenderer::is_agnostic_dialect`] answers `true` — which defaults to
1888 /// `false` here and is overridden by exactly one type in the tree,
1889 /// `AnsiDialect`, which no registration hands out. The platform the registry
1890 /// publishes under the name `agnostic` is `AgnosticDialect`; it does **not**
1891 /// override the method, so it declines the clause like every other target.
1892 /// The rule therefore holds on all eleven registered platforms, `agnostic`
1893 /// included, on every rendering path, and a regression test pins it.
1894 ///
1895 /// # Why the keyword lives in here
1896 ///
1897 /// It used to be concatenated by the caller — `parts.push(format!("DEFAULT
1898 /// {rendered}"))` — so the hook could rewrite a value and **could not decline
1899 /// a clause**: a dialect returning `""` emitted a bare dangling `DEFAULT`.
1900 /// This is the same correction made for
1901 /// statement boundaries: *the emission declares the boundary; a consumer
1902 /// never infers it.*
1903 ///
1904 /// # Why the hook survives the decision
1905 ///
1906 /// `Field::default_value` stays on the struct, so the design
1907 /// still knows what a column's intended default is, and a future dialect that
1908 /// genuinely wants to emit one has somewhere to say so. The distinction being
1909 /// bought is between **what razeri knows** and **what razeri emits**.
1910 ///
1911 /// A dialect that overrides this owes the whole clause, keyword and all —
1912 /// `Some(format!("DEFAULT {value}"))` — because there is nowhere else it is
1913 /// added.
1914 fn render_column_default(&self, value: &str) -> Option<String> {
1915 let _ = value;
1916 None
1917 }
1918
1919 /// **Spell an author's OWN declared default in this engine's words.**
1920 ///
1921 /// This is the other sense of "default", and the seam a dialect had no way
1922 /// to reach. [`render_column_default`](Self::render_column_default) governs
1923 /// the tables Razeri's generated load owns, and it declines everywhere by
1924 /// design. A `tile: base` table is the ruled exception: the author owns
1925 /// every column, no generated statement writes into it, and the declared
1926 /// default is an engine constraint they asked for — so it is rendered, on
1927 /// every platform, and it used to be rendered **verbatim**.
1928 ///
1929 /// Verbatim is a portability hole with the design's own words in it. A
1930 /// design declaring `default: CURRENT_TIMESTAMP` is asking for *the current
1931 /// moment*, not for those eighteen characters; on `BigQuery` those
1932 /// characters name the zone-aware type, the column Razeri builds is
1933 /// `DATETIME`, and the `CREATE TABLE` is refused outright — *"Column
1934 /// default expression has type TIMESTAMP which cannot be assigned to column
1935 /// type DATETIME"*. The design was right and had nowhere to be translated.
1936 ///
1937 /// The default returns the value unchanged, which is exactly today's
1938 /// behaviour on every platform, so a dialect that says nothing renders what
1939 /// it always did.
1940 ///
1941 /// # A dialect overriding this owes a measurement, and owes restraint
1942 ///
1943 /// Translate an expression whose *meaning* your engine spells differently.
1944 /// Do not rewrite an author's literal, do not widen a type, and do not
1945 /// silently drop a default you cannot express — an author who declared one
1946 /// and got none has a column that fills with NULL and a document that says
1947 /// otherwise. Where the engine has no equivalent at all, leave the value
1948 /// alone and let the engine refuse it: a loud failure belongs to the value
1949 /// the author wrote, and a quiet substitution belongs to nobody.
1950 ///
1951 /// Parameters:
1952 /// - `value`: the default exactly as the design declares it.
1953 /// - `column_type`: the type of the column it is being assigned to —
1954 /// load-bearing, because the same expression is legal against one type
1955 /// and refused against another on the same engine.
1956 fn render_declared_column_default(&self, value: &str, column_type: &DataType) -> String {
1957 let _ = column_type;
1958 value.to_owned()
1959 }
1960
1961 // ═══════════════════════════════════════════════════════════════
1962 // DDL Extensions
1963 // ═══════════════════════════════════════════════════════════════
1964
1965 /// Render a BEGIN transaction statement.
1966 ///
1967 /// `PostgreSQL`: `BEGIN`, `SqlServer`: `BEGIN TRANSACTION`, `ClickHouse`: empty (no DDL transactions)
1968 fn render_begin_transaction(&self) -> &'static str {
1969 "BEGIN"
1970 }
1971
1972 /// Render a COMMIT transaction statement.
1973 fn render_commit(&self) -> &'static str {
1974 "COMMIT"
1975 }
1976
1977 /// Whether the platform supports DDL transactions.
1978 fn supports_ddl_transactions(&self) -> bool {
1979 true
1980 }
1981
1982 /// Render a DROP FUNCTION statement with optional parameter types for overloaded functions.
1983 fn render_drop_function(&self, name: &str, param_types: &[&str], if_exists: bool) -> String {
1984 let exists = if if_exists { " IF EXISTS" } else { "" };
1985 if param_types.is_empty() {
1986 format!("DROP FUNCTION{exists} {name}")
1987 } else {
1988 format!("DROP FUNCTION{exists} {name}({})", param_types.join(", "))
1989 }
1990 }
1991
1992 /// Render the drop keyword for a SQL object type.
1993 fn render_drop_object_keyword(&self, obj_type: &str) -> String {
1994 obj_type.to_uppercase()
1995 }
1996
1997 /// Render the CREATE VIEW keyword/prefix with `secure/global_temp` modifiers.
1998 fn render_create_view_keyword(&self, secure: bool, global_temp: bool) -> String {
1999 let mut parts = vec!["CREATE OR REPLACE"];
2000 if secure {
2001 parts.push("SECURE");
2002 }
2003 if global_temp {
2004 parts.push("GLOBAL TEMPORARY");
2005 }
2006 parts.push("VIEW");
2007 parts.join(" ")
2008 }
2009
2010 /// Render an IF EXISTS clause for ALTER TABLE DROP COLUMN/CONSTRAINT.
2011 ///
2012 /// Some platforms (`SqlServer`, Databricks, `MariaDB`) don't support IF EXISTS in ALTER DROP.
2013 fn supports_alter_drop_if_exists(&self) -> bool {
2014 true
2015 }
2016
2017 // ═══════════════════════════════════════════════════════════════
2018 // Drop Behavior Hooks
2019 // ═══════════════════════════════════════════════════════════════
2020
2021 /// Whether DROP INDEX uses ON syntax: `DROP INDEX idx ON table` (`SqlServer`).
2022 fn drop_index_uses_on_syntax(&self) -> bool {
2023 false
2024 }
2025
2026 /// **Whether this engine checks the constraints it accepts.**
2027 ///
2028 /// The default is [`ConstraintEnforcement::Enforced`] — eight of Razeri's
2029 /// registered platforms, and the safe assumption for a dialect that has not
2030 /// said, because *"this engine guarantees nothing"* is the unusual claim.
2031 ///
2032 /// Answer [`ConstraintEnforcement::DeclaredOnly`] where a `PRIMARY KEY`,
2033 /// `FOREIGN KEY` or `UNIQUE` is accepted and never checked. Two engines are
2034 /// that, in two different ways, and the type carries both:
2035 ///
2036 /// - `BigQuery` has the words. `NOT ENFORCED` is the only legal spelling,
2037 /// so the keyword goes on the constraint line and the engine makes the
2038 /// declaration honest by itself.
2039 /// - `Redshift` has no words. It takes all three constraints, checks none,
2040 /// and renders DDL a reader cannot tell from `PostgreSQL`'s — so the note
2041 /// is written above the constraint list instead, and it is the only place
2042 /// that DDL says what it means.
2043 ///
2044 /// [`key_constraint_suffix`](Self::key_constraint_suffix) reads this, so
2045 /// stating enforcement states the suffix too.
2046 fn constraint_enforcement(&self) -> ConstraintEnforcement {
2047 ConstraintEnforcement::Enforced
2048 }
2049
2050 /// **The words a key constraint must carry to be accepted at all.**
2051 ///
2052 /// Appended to a table-level `PRIMARY KEY (…)` and to a
2053 /// `FOREIGN KEY (…) REFERENCES …`. Empty on every engine that enforces its
2054 /// keys, and empty on a declaring engine that has no keyword for it.
2055 ///
2056 /// The default reads
2057 /// [`constraint_enforcement`](Self::constraint_enforcement), so the two are
2058 /// one fact rather than two that must be kept in step. Override this only
2059 /// for a keyword a key constraint needs for some *other* reason than
2060 /// enforcement — there is no such engine in Razeri's set today.
2061 fn key_constraint_suffix(&self) -> &'static str {
2062 self.constraint_enforcement().keyword()
2063 }
2064
2065 /// Whether a table-level `UNIQUE (…)` constraint is part of the grammar.
2066 ///
2067 /// `false` on an engine that has no such constraint at all, where the
2068 /// declaration is left out of the `CREATE TABLE` and named in a comment
2069 /// beside it rather than emitted and refused.
2070 fn supports_unique_constraint(&self) -> bool {
2071 true
2072 }
2073
2074 /// Whether a table-level `CHECK (…)` constraint is part of the grammar.
2075 ///
2076 /// `false` on an engine that has none, with the same treatment as
2077 /// [`supports_unique_constraint`](Self::supports_unique_constraint): named
2078 /// in a comment, never written as SQL the engine will reject.
2079 fn supports_check_constraint(&self) -> bool {
2080 true
2081 }
2082
2083 /// Whether the platform supports CASCADE/RESTRICT in DROP statements.
2084 ///
2085 /// True for `PostgreSQL`, `CitusDB`, `DuckDB`, Snowflake, Agnostic.
2086 /// False for `SqlServer`, `ClickHouse`, Databricks, `MySQL`, `MariaDB`.
2087 fn supports_cascade_drop(&self) -> bool {
2088 true
2089 }
2090
2091 /// Whether `COMMENT ON PROCEDURE` is part of the grammar.
2092 ///
2093 /// `true` almost everywhere, and **false on `Redshift`**, where
2094 /// `COMMENT ON FUNCTION`, `COMMENT ON VIEW` and `COMMENT ON COLUMN` all
2095 /// exist and the procedure form alone does not: *"syntax error at or near
2096 /// `PROCEDURE`"*, measured on a live workgroup. A description is worth
2097 /// having and is not worth a statement that stops the script, so a
2098 /// declining engine simply carries no description on its procedures.
2099 fn supports_procedure_comment(&self) -> bool {
2100 true
2101 }
2102
2103 /// Whether the platform supports function argument types in DROP FUNCTION.
2104 ///
2105 /// False for `ClickHouse` (no overloaded functions).
2106 fn supports_drop_function_arg_types(&self) -> bool {
2107 true
2108 }
2109
2110 /// Whether the platform supports SYNC option for DROP (`ClickHouse`).
2111 fn supports_sync_drop(&self) -> bool {
2112 false
2113 }
2114
2115 /// Whether the platform supports FORCE option for DROP (Databricks).
2116 fn supports_force_drop(&self) -> bool {
2117 false
2118 }
2119
2120 /// Whether the platform supports CASCADE in ALTER TABLE DROP.
2121 ///
2122 /// Only `PostgreSQL`, `CitusDB`, `DuckDB` support CASCADE in ALTER TABLE DROP.
2123 fn supports_alter_drop_cascade(&self) -> bool {
2124 false
2125 }
2126}
2127
2128/// **One row, written once** — the pieces of an INSERT that must do nothing
2129/// when a row already carries the same key.
2130///
2131/// The key value is not a field of its own: it is whichever `values` entry sits
2132/// at the same index as the key column in `columns`. Two fields that must agree
2133/// are two fields free to disagree, and the one they would disagree about here
2134/// is the one that decides whether a second write is a duplicate.
2135#[derive(Debug, Clone, Copy)]
2136pub struct InsertIfAbsent<'a> {
2137 /// The target table, already spelled the way the caller wants it written —
2138 /// schema-qualified or bare.
2139 pub table: &'a str,
2140 /// The columns being written, in the order `values` supplies them.
2141 pub columns: &'a [&'a str],
2142 /// One value expression per column.
2143 pub values: &'a [String],
2144 /// The columns whose equality means *this row is already here*.
2145 pub key_columns: &'a [&'a str],
2146}
2147
2148impl InsertIfAbsent<'_> {
2149 /// The value expression written into `column`, if it is being written.
2150 #[must_use]
2151 pub fn value_of(&self, column: &str) -> Option<&str> {
2152 let at = self.columns.iter().position(|name| *name == column)?;
2153 self.values.get(at).map(String::as_str)
2154 }
2155
2156 /// `key = value AND …` — the test for *already here*, in terms of the
2157 /// values this INSERT would have written.
2158 ///
2159 /// `qualifier` prefixes the column side, which the guarded form needs so
2160 /// the probe's own row is named unambiguously.
2161 ///
2162 /// # Panics
2163 ///
2164 /// When a key column is not among the columns being written. A key the
2165 /// INSERT does not supply cannot be tested for, and silently dropping it
2166 /// from the predicate would make the guard match everything.
2167 #[must_use]
2168 pub fn key_predicate(&self, qualifier: &str) -> String {
2169 self.key_columns
2170 .iter()
2171 .map(|column| {
2172 let value = self
2173 .value_of(column)
2174 .unwrap_or_else(|| panic!("{column} is a key column and must be written"));
2175 format!("{qualifier}{column} = {value}")
2176 })
2177 .collect::<Vec<_>>()
2178 .join(" AND ")
2179 }
2180
2181 /// **`ON CONFLICT (key) DO NOTHING`** — for the platforms that let the
2182 /// engine decide, which is every platform that has the clause.
2183 ///
2184 /// The engine tests the key as it writes, so two sessions registering one
2185 /// file at the same moment settle on one row rather than on whichever of
2186 /// them looked first.
2187 #[must_use]
2188 pub fn on_conflict_do_nothing(&self) -> String {
2189 format!(
2190 "{}\n{}\nON CONFLICT ({}) DO NOTHING;",
2191 self.target(),
2192 self.values_clause(),
2193 self.key_columns.join(", ")
2194 )
2195 }
2196
2197 /// **`ON DUPLICATE KEY UPDATE key = key`** — the `MySQL` family's no-op.
2198 ///
2199 /// `INSERT IGNORE` would be shorter and it is not the same request: it
2200 /// downgrades *every* error on the statement to a warning — a truncated
2201 /// value, a bad date — so a row that should have been refused arrives
2202 /// mangled and silent. Assigning the key to itself touches only the
2203 /// collision this is about, and leaves everything else to complain
2204 /// normally.
2205 #[must_use]
2206 pub fn on_duplicate_key_no_op(&self) -> String {
2207 let held = self
2208 .key_columns
2209 .iter()
2210 .map(|column| format!("{column} = {column}"))
2211 .collect::<Vec<_>>()
2212 .join(", ");
2213 format!("{}\n{}\nON DUPLICATE KEY UPDATE {held};", self.target(), self.values_clause())
2214 }
2215
2216 /// **The guarded form over an explicit one-row source** — the same
2217 /// `INSERT … SELECT … WHERE NOT EXISTS` the portable default writes, with a
2218 /// `FROM` clause under it.
2219 ///
2220 /// `GoogleSQL` refuses a `WHERE` on a query that selects from nothing —
2221 /// *"Query without FROM clause cannot have a WHERE clause"*, measured on the
2222 /// live service on every generated `register_file` procedure — while
2223 /// `PostgreSQL` and its cousins accept the bare form. `(SELECT 1)` is a
2224 /// one-row table that changes no result: the guard still decides whether
2225 /// the row is written, and the values are still the caller's.
2226 ///
2227 /// It stays a separate form rather than becoming the default because the
2228 /// engines that need no `FROM` read better without one, and a clause every
2229 /// platform carries for one platform's sake is how a rendering stops saying
2230 /// what it means.
2231 #[must_use]
2232 pub fn guarded_over_one_row(&self) -> String {
2233 format!(
2234 "{}\nSELECT {}\nFROM (SELECT 1)\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
2235 self.target(),
2236 self.values.join(", "),
2237 self.table,
2238 self.key_predicate("")
2239 )
2240 }
2241
2242 /// `INSERT INTO t (a, b)` — shared by every form below.
2243 fn target(&self) -> String {
2244 format!("INSERT INTO {} ({})", self.table, self.columns.join(", "))
2245 }
2246
2247 /// `VALUES (…)`.
2248 fn values_clause(&self) -> String {
2249 format!("VALUES ({})", self.values.join(", "))
2250 }
2251}
2252
2253/// Level 4 — DML rendering with reasonable defaults.
2254pub trait DmlRenderer: SqlRenderer {
2255 /// Prefix for INSERT statements.
2256 fn render_insert_prefix(&self) -> &'static str {
2257 "INSERT INTO"
2258 }
2259
2260 /// **Write one row, and do nothing if its key is already there.**
2261 ///
2262 /// Every platform can express this and they do not agree on how, so the
2263 /// spelling belongs to the dialect and not to the caller. The default is
2264 /// the portable one — an `INSERT … SELECT` guarded by `WHERE NOT EXISTS` —
2265 /// which needs no upsert syntax at all and is therefore the right answer
2266 /// for a platform nobody has written an arm for. Platforms with a native
2267 /// idiom override it: `ON CONFLICT … DO NOTHING` where that exists,
2268 /// `ON DUPLICATE KEY UPDATE` on the `MySQL` family.
2269 ///
2270 /// **No dialect is left without an idempotent form.** The guarded form is
2271 /// weaker than the native ones under concurrency — two sessions can both
2272 /// find the row absent and both insert — which is why a platform that can
2273 /// let the engine decide should, and why this one leans on the key's own
2274 /// uniqueness constraint to catch the race rather than pretending it cannot
2275 /// happen. On an engine that enforces no key at all the guard is the whole
2276 /// of what there is, and it is worth saying so rather than implying more.
2277 fn render_insert_if_absent(&self, insert: &InsertIfAbsent<'_>) -> String {
2278 format!(
2279 "{}\nSELECT {}\nWHERE NOT EXISTS (SELECT 1 FROM {} WHERE {});",
2280 insert.target(),
2281 insert.values.join(", "),
2282 insert.table,
2283 insert.key_predicate("")
2284 )
2285 }
2286
2287 /// Prefix for MERGE statements.
2288 fn render_merge_prefix(&self) -> &'static str {
2289 "MERGE INTO"
2290 }
2291
2292 /// Render the platform's upsert strategy keyword.
2293 ///
2294 /// Returns `None` if platform doesn't support upsert natively.
2295 fn render_upsert_strategy(&self) -> Option<&str> {
2296 None
2297 }
2298
2299 /// Render RETURNING / OUTPUT clause for INSERT/UPDATE.
2300 fn render_returning_clause(&self, _columns: &[&str]) -> Option<String> {
2301 None
2302 }
2303
2304 /// Render a LIMIT clause.
2305 fn render_limit_clause(&self, n: usize) -> String {
2306 format!("LIMIT {n}")
2307 }
2308
2309 /// Render a temporary table prefix or keyword.
2310 fn render_temp_table_prefix(&self) -> &'static str {
2311 "TEMPORARY"
2312 }
2313
2314 /// **One row holding an array becomes one row per element.**
2315 ///
2316 /// Razeri hands over the relation it is reading, the array column, and the
2317 /// element fields the statement needs; the engine answers with the `FROM`
2318 /// item that produces the rows and the expressions that read them. The
2319 /// three parts come back together because on at least one engine they
2320 /// depend on each other: its field expressions name an alias its own
2321 /// `FROM` item introduced.
2322 ///
2323 /// **The ordinal is one for the first element, on every engine.** Engines
2324 /// disagree about where an array starts — some count from one, some from
2325 /// zero, one answers in text — and the element's surrogate key is derived
2326 /// from its position. An engine answering in its own base would give one
2327 /// element two different keys depending on where it was stored, so the
2328 /// normalization belongs here, where the engine that counts from zero pays
2329 /// for it with one addition.
2330 ///
2331 /// `None` — the default — is this engine stating no flatten. Razeri then
2332 /// refuses the declaration and names the engine, rather than guessing an
2333 /// idiom or emitting a statement that does not run.
2334 fn render_flatten(&self, _request: &FlattenRequest<'_>) -> Option<Flatten> {
2335 None
2336 }
2337}
2338
2339/// Level 5 — Stored procedure / function rendering with defaults.
2340pub trait ProcedureRenderer: SqlRenderer {
2341 /// Prefix for CREATE PROCEDURE.
2342 fn render_create_procedure_prefix(&self) -> &'static str {
2343 "CREATE OR REPLACE PROCEDURE"
2344 }
2345
2346 /// Prefix for CREATE FUNCTION.
2347 fn render_create_function_prefix(&self) -> &'static str {
2348 "CREATE OR REPLACE FUNCTION"
2349 }
2350
2351 /// Render a variable declaration inside a procedure body.
2352 fn render_variable_declaration(&self, name: &str, dt: &DataType) -> String {
2353 format!("DECLARE {} {};", name, self.render_data_type(dt))
2354 }
2355
2356 /// Render BEGIN/END block delimiters.
2357 fn render_begin_end(&self, body: &str) -> String {
2358 format!("BEGIN\n{body}\nEND;")
2359 }
2360
2361 /// Whether procedures use a language clause (e.g., Snowflake JavaScript).
2362 fn requires_language_clause(&self) -> bool {
2363 false
2364 }
2365}
2366
2367#[cfg(test)]
2368mod tests {
2369 use super::*;
2370 use crate::DialectCapabilities;
2371 use crate::sid_spelling::SidHelperLanguage;
2372
2373 /// A test dialect that implements only the required `SqlRenderer` methods.
2374 /// All other traits use defaults.
2375 struct TestDialect;
2376
2377 impl SqlRenderer for TestDialect {
2378 fn render_data_type(&self, dt: &DataType) -> String {
2379 match dt {
2380 DataType::Boolean(_) => "BOOLEAN".to_string(),
2381 DataType::Integer(_) => "INTEGER".to_string(),
2382 _ => "TEXT".to_string(),
2383 }
2384 }
2385 fn quote_identifier(&self, name: &str) -> String {
2386 format!("\"{name}\"")
2387 }
2388 fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
2389 match schema {
2390 Some(s) => format!("{}.{}", self.quote_identifier(s), self.quote_identifier(name)),
2391 None => self.quote_identifier(name),
2392 }
2393 }
2394 fn render_current_timestamp(&self) -> String {
2395 "CURRENT_TIMESTAMP".to_string()
2396 }
2397 }
2398
2399 impl ExpressionRenderer for TestDialect {}
2400 impl DdlRenderer for TestDialect {}
2401 impl DmlRenderer for TestDialect {}
2402 impl ProcedureRenderer for TestDialect {}
2403 impl DialectCapabilities for TestDialect {}
2404
2405 /// The same dialect with the two file-and-key facts stated. It exists to
2406 /// prove that a dialect Razeri never compiled against reaches the behaviour
2407 /// by *declaring* it — which is the whole property, and is not visible from
2408 /// a dialect that ships in this tree.
2409 struct StatedDialect;
2410
2411 impl SqlRenderer for StatedDialect {
2412 fn render_data_type(&self, _dt: &DataType) -> String {
2413 "TEXT".to_string()
2414 }
2415 fn quote_identifier(&self, name: &str) -> String {
2416 format!("\"{name}\"")
2417 }
2418 fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
2419 self.quote_identifier(name)
2420 }
2421 fn render_current_timestamp(&self) -> String {
2422 "CURRENT_TIMESTAMP".to_string()
2423 }
2424 fn sid_helper_body(&self) -> Option<SidHelperBody> {
2425 Some(SidHelperBody {
2426 language: SidHelperLanguage::Named("ecmascript"),
2427 body: "return 1;",
2428 })
2429 }
2430 fn delimited_file_relation(&self, path_literal: &str) -> Option<String> {
2431 Some(format!("SCAN({path_literal})"))
2432 }
2433 }
2434
2435 /// **Silence is the default, and silence means Razeri composes.**
2436 ///
2437 /// Both facts are opt-in: a dialect that says nothing gets the SQL
2438 /// derivation for its key and no generated staging fill at all. Neither
2439 /// default may become a guess — a composed body on an engine with no hash
2440 /// keys a warehouse to a number nothing reproduces, and an invented file
2441 /// relation fails the load on its first statement.
2442 #[test]
2443 fn a_dialect_that_states_neither_fact_is_asked_for_nothing() {
2444 let d: &dyn SqlRenderer = &TestDialect;
2445 assert_eq!(d.sid_helper_body(), None);
2446 assert_eq!(d.delimited_file_relation("'/data/x.csv'"), None);
2447 }
2448
2449 /// And a dialect that states them is heard through the trait object, which
2450 /// is the only way Razeri ever holds one.
2451 #[test]
2452 fn a_dialect_that_states_them_is_heard_through_the_trait_object() {
2453 let d: &dyn SqlRenderer = &StatedDialect;
2454 assert_eq!(
2455 d.sid_helper_body(),
2456 Some(SidHelperBody {
2457 language: SidHelperLanguage::Named("ecmascript"),
2458 body: "return 1;",
2459 })
2460 );
2461 assert_eq!(
2462 d.delimited_file_relation("'/data/x.csv'").as_deref(),
2463 Some("SCAN('/data/x.csv')")
2464 );
2465 }
2466
2467 #[test]
2468 fn sql_renderer_core_methods_work() {
2469 let d = TestDialect;
2470 assert_eq!(d.render_data_type(&DataType::boolean()), "BOOLEAN");
2471 assert_eq!(d.quote_identifier("users"), "\"users\"");
2472 assert_eq!(d.qualify_name(Some("public"), "users"), "\"public\".\"users\"");
2473 assert_eq!(d.render_current_timestamp(), "CURRENT_TIMESTAMP");
2474 }
2475
2476 #[test]
2477 fn dialect_name_returns_ansi_by_default() {
2478 let d = TestDialect;
2479 assert_eq!(d.dialect_name(), "ansi");
2480 }
2481
2482 #[test]
2483 fn expression_renderer_defaults_produce_ansi_sql() {
2484 let d = TestDialect;
2485 assert_eq!(d.render_cast("age", &DataType::int()), "CAST(age AS INTEGER)");
2486 assert_eq!(d.render_concat(&["a".into(), "b".into()]), "CONCAT(a, b)");
2487 assert_eq!(d.render_coalesce(&["x".into(), "y".into()]), "COALESCE(x, y)");
2488 }
2489
2490 #[test]
2491 fn ddl_renderer_defaults_produce_ansi_sql() {
2492 let d = TestDialect;
2493 assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
2494 assert_eq!(d.render_create_view_prefix(), "CREATE OR REPLACE VIEW");
2495 assert_eq!(
2496 d.render_column_definition("name", &DataType::boolean(), false),
2497 "\"name\" BOOLEAN NOT NULL"
2498 );
2499 assert_eq!(d.render_column_definition("age", &DataType::int(), true), "\"age\" INTEGER");
2500 }
2501
2502 #[test]
2503 fn dml_renderer_defaults_produce_ansi_sql() {
2504 let d = TestDialect;
2505 assert_eq!(d.render_insert_prefix(), "INSERT INTO");
2506 assert_eq!(d.render_merge_prefix(), "MERGE INTO");
2507 assert_eq!(d.render_limit_clause(10), "LIMIT 10");
2508 assert!(d.render_upsert_strategy().is_none());
2509 assert!(d.render_returning_clause(&["id"]).is_none());
2510 }
2511
2512 #[test]
2513 fn procedure_renderer_defaults_produce_ansi_sql() {
2514 let d = TestDialect;
2515 assert_eq!(d.render_create_procedure_prefix(), "CREATE OR REPLACE PROCEDURE");
2516 assert_eq!(
2517 d.render_variable_declaration("v_count", &DataType::int()),
2518 "DECLARE v_count INTEGER;"
2519 );
2520 assert!(!d.requires_language_clause());
2521 }
2522
2523 #[test]
2524 fn trait_hierarchy_allows_selective_override() {
2525 struct MySqlLike;
2526 impl SqlRenderer for MySqlLike {
2527 fn render_data_type(&self, _: &DataType) -> String {
2528 "INT".into()
2529 }
2530 fn quote_identifier(&self, name: &str) -> String {
2531 format!("`{name}`")
2532 }
2533 fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
2534 match schema {
2535 Some(s) => format!("`{s}`.`{name}`"),
2536 None => format!("`{name}`"),
2537 }
2538 }
2539 fn render_current_timestamp(&self) -> String {
2540 "NOW()".into()
2541 }
2542 }
2543 impl ExpressionRenderer for MySqlLike {
2544 fn render_concat(&self, parts: &[String]) -> String {
2545 format!("CONCAT({})", parts.join(", "))
2546 }
2547 }
2548 impl DdlRenderer for MySqlLike {}
2549 impl DmlRenderer for MySqlLike {}
2550 impl ProcedureRenderer for MySqlLike {}
2551 impl DialectCapabilities for MySqlLike {}
2552
2553 let d = MySqlLike;
2554 assert_eq!(d.quote_identifier("users"), "`users`");
2555 assert_eq!(d.render_current_timestamp(), "NOW()");
2556 // DDL defaults still work even though we only overrode expressions
2557 assert_eq!(d.render_create_table_prefix(), "CREATE TABLE");
2558 }
2559
2560 #[test]
2561 fn sql_renderer_expression_extensions_produce_ansi_defaults() {
2562 let d = TestDialect;
2563 assert_sql_renderer_literal_defaults(&d);
2564 assert_sql_renderer_parameter_and_merge_defaults(&d);
2565 assert_sql_renderer_update_insert_defaults(&d);
2566 assert_sql_renderer_partition_and_window_defaults(&d);
2567 }
2568
2569 /// Assert ANSI defaults for literal, date/time, and basic expression hooks.
2570 /// Parameters:
2571 /// - dialect: Renderer under test.
2572 fn assert_sql_renderer_literal_defaults(dialect: &TestDialect) {
2573 assert_eq!(dialect.render_boolean_literal(true), "TRUE");
2574 assert_eq!(dialect.render_boolean_literal(false), "FALSE");
2575 assert_eq!(dialect.render_date_literal("2024-01-15"), "DATE '2024-01-15'");
2576 assert_eq!(
2577 dialect.render_timestamp_literal("2024-01-15 12:00:00"),
2578 "TIMESTAMP '2024-01-15 12:00:00'"
2579 );
2580 assert_eq!(dialect.render_interval_literal("1 year"), "INTERVAL '1 year'");
2581 assert_eq!(dialect.render_current_date(), "CURRENT_DATE");
2582 assert_eq!(dialect.concat_operator(), "||");
2583 assert_eq!(dialect.render_nan_literal(&DataType::float()), "NULL");
2584 assert_eq!(dialect.render_infinity_literal(true, &DataType::float()), "NULL");
2585 assert_eq!(dialect.ifnull_function_name(), "COALESCE");
2586 assert_eq!(
2587 dialect.render_iif("x > 0", "pos", "neg"),
2588 "CASE WHEN x > 0 THEN pos ELSE neg END"
2589 );
2590 assert_eq!(
2591 dialect.render_date_trunc("month", "created_at"),
2592 "DATE_TRUNC('month', created_at)"
2593 );
2594 assert_eq!(
2595 dialect.render_date_extract("year", "created_at"),
2596 "EXTRACT(year FROM created_at)"
2597 );
2598 assert_eq!(dialect.render_try_cast("age", &DataType::int()), "TRY_CAST(age AS INTEGER)");
2599 }
2600
2601 /// Assert ANSI defaults for parameter and merge-related extension hooks.
2602 /// Parameters:
2603 /// - dialect: Renderer under test.
2604 fn assert_sql_renderer_parameter_and_merge_defaults(dialect: &TestDialect) {
2605 assert_eq!(dialect.render_parameter_placeholder(1), "$1");
2606 assert_eq!(dialect.render_named_parameter("user_id"), ":user_id");
2607 assert_eq!(SqlRenderer::merge_not_matched_keyword(dialect), "WHEN NOT MATCHED");
2608 assert!(!SqlRenderer::supports_merge_not_matched_by_source(dialect));
2609 assert!(SqlRenderer::merge_supported(dialect));
2610 assert!(!SqlRenderer::merge_supports_schema_evolution_keyword(dialect));
2611 assert!(!SqlRenderer::merge_supports_table_hints(dialect));
2612 assert!(!SqlRenderer::merge_uses_output_clause(dialect));
2613 assert!(!SqlRenderer::merge_supports_returning_clause(dialect));
2614 assert_eq!(dialect.schema_separator(), ".");
2615 assert_eq!(dialect.statement_separator(), ";\n");
2616 }
2617
2618 /// Assert ANSI defaults for update and insert behavior extension hooks.
2619 /// Parameters:
2620 /// - dialect: Renderer under test.
2621 fn assert_sql_renderer_update_insert_defaults(dialect: &TestDialect) {
2622 assert!(!SqlRenderer::supports_compound_assignment(dialect));
2623 assert!(!SqlRenderer::supports_update_from(dialect));
2624 assert!(!SqlRenderer::uses_alter_table_update(dialect));
2625 // How a mutation is SPELLED and what it may LOOK AT are
2626 // two facts, and the ANSI default is that a mutation may correlate.
2627 assert!(!SqlRenderer::mutation_reads_only_its_own_rows(dialect));
2628 assert!(!dialect.update_supports_top_clause());
2629 assert!(!dialect.update_supports_table_hints());
2630 assert!(!dialect.update_uses_output_clause());
2631 assert!(!dialect.update_supports_returning());
2632 assert!(!dialect.insert_uses_output_clause());
2633 assert!(!dialect.insert_supports_returning());
2634 assert!(!dialect.insert_supports_table_hints());
2635 assert!(!SqlRenderer::supports_insert_overwrite(dialect));
2636 assert!(!SqlRenderer::supports_on_conflict(dialect));
2637 assert!(!dialect.supports_overriding_clause());
2638 assert_eq!(dialect.returning_clause_keyword(), "RETURNING");
2639 assert!(!SqlRenderer::supports_returning_into(dialect));
2640 assert!(!SqlRenderer::supports_multi_table_insert(dialect));
2641 }
2642
2643 /// Assert ANSI defaults for partitioning, generated columns, and window hooks.
2644 /// Parameters:
2645 /// - dialect: Renderer under test.
2646 fn assert_sql_renderer_partition_and_window_defaults(dialect: &TestDialect) {
2647 assert_eq!(
2648 dialect.render_time_partition_expr("event_ts", "monthly"),
2649 "date_trunc('month', event_ts)"
2650 );
2651 assert_eq!(dialect.render_partition_clause("event_ts"), "PARTITION BY (event_ts)");
2652 assert_eq!(
2653 dialect.render_generated_column("event_month", "DATE_TRUNC('month', event_ts)"),
2654 "event_month GENERATED ALWAYS AS (DATE_TRUNC('month', event_ts)) STORED"
2655 );
2656 assert!(!SqlRenderer::supports_window_frame_exclude(dialect));
2657 assert!(!SqlRenderer::supports_window_frame_groups(dialect));
2658 assert!(SqlRenderer::supports_named_windows(dialect));
2659 }
2660
2661 #[test]
2662 fn ddl_renderer_extensions_produce_ansi_defaults() {
2663 let d = TestDialect;
2664 assert_ddl_renderer_transaction_and_view_defaults(&d);
2665 assert_ddl_renderer_drop_defaults(&d);
2666 }
2667
2668 /// Assert ANSI DDL defaults for transaction and view keyword hooks.
2669 /// Parameters:
2670 /// - dialect: Renderer under test.
2671 fn assert_ddl_renderer_transaction_and_view_defaults(dialect: &TestDialect) {
2672 assert_eq!(dialect.render_begin_transaction(), "BEGIN");
2673 assert_eq!(dialect.render_commit(), "COMMIT");
2674 assert!(dialect.supports_ddl_transactions());
2675 assert_eq!(dialect.render_create_view_keyword(false, false), "CREATE OR REPLACE VIEW");
2676 assert_eq!(
2677 dialect.render_create_view_keyword(true, false),
2678 "CREATE OR REPLACE SECURE VIEW"
2679 );
2680 assert!(dialect.supports_alter_drop_if_exists());
2681 }
2682
2683 /// Assert ANSI DDL defaults for drop-related behavior hooks.
2684 /// Parameters:
2685 /// - dialect: Renderer under test.
2686 fn assert_ddl_renderer_drop_defaults(dialect: &TestDialect) {
2687 assert_eq!(dialect.render_drop_object_keyword("table"), "TABLE");
2688 assert_eq!(
2689 dialect.render_drop_function("my_func", &[], true),
2690 "DROP FUNCTION IF EXISTS my_func"
2691 );
2692 assert!(!dialect.drop_index_uses_on_syntax());
2693 assert!(DdlRenderer::supports_cascade_drop(dialect));
2694 assert!(dialect.supports_drop_function_arg_types());
2695 assert!(!DdlRenderer::supports_sync_drop(dialect));
2696 assert!(!DdlRenderer::supports_force_drop(dialect));
2697 assert!(!dialect.supports_alter_drop_cascade());
2698 }
2699
2700 /// **The one statement every engine takes**, written for a dialect that
2701 /// answered nothing. A plugin author gets the commonest evolution there is
2702 /// without writing a line for it.
2703 #[test]
2704 fn a_dialect_that_answers_nothing_still_adds_a_column() {
2705 let data_type = DataType::boolean();
2706 let written = TestDialect.render_column_evolution(&ColumnEvolution::AddColumn {
2707 schema: Some("telemetry_core"),
2708 table: "clients_daily",
2709 column: "is_default_browser",
2710 data_type: &data_type,
2711 });
2712 assert_eq!(
2713 written.as_deref(),
2714 Some(
2715 r#"ALTER TABLE "telemetry_core"."clients_daily" ADD COLUMN "is_default_browser" BOOLEAN"#
2716 )
2717 );
2718 }
2719
2720 /// Everything else waits to be spelled. A default picked from one engine's
2721 /// grammar is a statement the others reject, handed to an operator who
2722 /// finds that out against their own warehouse.
2723 #[test]
2724 fn nothing_else_is_spelled_until_a_dialect_spells_it() {
2725 let data_type = DataType::text();
2726 assert!(
2727 TestDialect
2728 .render_column_evolution(&ColumnEvolution::WidenColumn {
2729 schema: None,
2730 table: "t",
2731 column: "c",
2732 data_type: &data_type,
2733 })
2734 .is_none()
2735 );
2736 assert!(
2737 TestDialect
2738 .render_column_evolution(&ColumnEvolution::AddNestedField {
2739 schema: None,
2740 table: "t",
2741 column: "c",
2742 field: "f",
2743 data_type: &data_type,
2744 })
2745 .is_none()
2746 );
2747 }
2748}