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