1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.
//! Formula-level rendering extensions with ANSI defaults.
use crate::DataTypeRef;
use crate::SqlRenderer;
/// Formula-level function rendering with ANSI-safe defaults.
///
/// These methods replace platform `match` blocks in formula rendering code.
pub trait FormulaRenderer: SqlRenderer {
/// Render `STRING_AGG` / LISTAGG style aggregation.
fn render_string_agg(
&self,
expr: &str,
sep: &str,
distinct: bool,
order: Option<&str>,
) -> String {
let d = if distinct { "DISTINCT " } else { "" };
match order {
Some(o) => format!("STRING_AGG({d}{expr}, '{sep}' ORDER BY {o})"),
None => format!("STRING_AGG({d}{expr}, '{sep}')"),
}
}
/// Render `CONCAT_WS`.
fn render_concat_ws(&self, separator: &str, parts: &[&str]) -> String {
format!("CONCAT_WS('{separator}', {})", parts.join(", "))
}
/// Render `FIRST_VALUE` with optional IGNORE NULLS.
fn render_first_value(&self, expr: &str, ignore_nulls: bool) -> String {
if ignore_nulls {
format!("FIRST_VALUE({expr}) IGNORE NULLS")
} else {
format!("FIRST_VALUE({expr})")
}
}
/// Render `STDDEV_POP` / `STDDEV_SAMP`.
fn render_stddev(&self, expr: &str, population: bool) -> String {
let func = if population { "STDDEV_POP" } else { "STDDEV_SAMP" };
format!("{func}({expr})")
}
/// Render `VAR_POP` / `VAR_SAMP`.
fn render_variance(&self, expr: &str, population: bool) -> String {
let func = if population { "VAR_POP" } else { "VAR_SAMP" };
format!("{func}({expr})")
}
/// Render `PERCENTILE_CONT` / `PERCENTILE_DISC`.
fn render_percentile(&self, expr: &str, percentile: f64, continuous: bool) -> String {
let func = if continuous { "PERCENTILE_CONT" } else { "PERCENTILE_DISC" };
format!("{func}({percentile}) WITHIN GROUP (ORDER BY {expr})")
}
/// Render MEDIAN.
fn render_median(&self, expr: &str) -> String {
format!("PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY {expr})")
}
/// Render COUNT IF semantics.
fn render_count_if(&self, condition: &str) -> String {
format!("COUNT(CASE WHEN {condition} THEN 1 END)")
}
/// Render SUM IF semantics.
fn render_sum_if(&self, expr: &str, condition: &str) -> String {
format!("SUM(CASE WHEN {condition} THEN {expr} END)")
}
/// Render AVG IF semantics.
fn render_avg_if(&self, expr: &str, condition: &str) -> String {
format!("AVG(CASE WHEN {condition} THEN {expr} END)")
}
/// Render SPLIT / `STRING_TO_ARRAY` style expression.
fn render_split(&self, expr: &str, delimiter: &str) -> String {
format!("STRING_TO_ARRAY({expr}, '{delimiter}')")
}
/// Render `REGEXP_LIKE` / RLIKE.
fn render_regexp_like(&self, expr: &str, pattern: &str) -> String {
format!("REGEXP_LIKE({expr}, '{pattern}')")
}
/// Render `REGEXP_REPLACE`.
fn render_regexp_replace(&self, expr: &str, pattern: &str, replacement: &str) -> String {
format!("REGEXP_REPLACE({expr}, '{pattern}', '{replacement}')")
}
/// Render `REGEXP_EXTRACT` / `REGEXP_SUBSTR`.
fn render_regexp_extract(&self, expr: &str, pattern: &str, group: Option<usize>) -> String {
match group {
Some(g) => format!("REGEXP_SUBSTR({expr}, '{pattern}', 1, 1, 'e', {g})"),
None => format!("REGEXP_SUBSTR({expr}, '{pattern}')"),
}
}
/// **Whether this engine splits a text into a list**, the way
/// [`render_split`](Self::render_split) writes it.
///
/// The default is `true`. Answer `false` for an engine with no such
/// function, and a formula that splits is refused by name for it, rather
/// than written with something that returns the text unsplit.
fn supports_split(&self) -> bool {
true
}
/// **Whether this engine tests a text against a regular expression**,
/// the way [`render_regexp_like`](Self::render_regexp_like) writes it.
///
/// The default is `true`. Answer `false` for an engine with no such test,
/// and a formula that asks it is refused by name for it.
fn supports_regexp_like(&self) -> bool {
true
}
/// **Whether this engine takes the part of a text a regular expression
/// matches**, the way [`render_regexp_extract`](Self::render_regexp_extract)
/// writes it.
///
/// The default is `true`. Answer `false` for an engine with no such
/// function, and a formula that asks it is refused by name for it.
fn supports_regexp_extract(&self) -> bool {
true
}
/// **Whether this engine orders the values a string aggregation joins**,
/// the `ORDER BY` inside [`render_string_agg`](Self::render_string_agg).
///
/// The default is `true`. Answer `false` for an engine whose string
/// aggregation takes no order, and a formula that asks for one is
/// refused by name for it, rather than joined in whatever order the
/// engine reads the rows.
fn supports_ordered_string_agg(&self) -> bool {
true
}
// There is deliberately no `render_generate_sid` here, and there never will
// be one. A `GENERATE_SID` formula in a view and a dimension load over the
// same column must key a member the same way, so Razeri composes both from
// one derivation and asks the dialect only for its
// [`SidSpelling`](crate::SidSpelling). Eight dialect crates used to spell
// their own; a second definition that does not exist cannot drift back.
/// Render NVL2 semantics.
fn render_nvl2(&self, expr: &str, not_null: &str, is_null: &str) -> String {
format!("CASE WHEN {expr} IS NOT NULL THEN {not_null} ELSE {is_null} END")
}
/// Render multi-branch IF semantics.
fn render_multi_if(&self, conditions: &[(&str, &str)], else_: &str) -> String {
use std::fmt::Write;
let mut sql = "CASE".to_string();
for (cond, then_expr) in conditions {
let _ = write!(sql, " WHEN {cond} THEN {then_expr}");
}
let _ = write!(sql, " ELSE {else_} END");
sql
}
// ================================================================
// Operator rendering
// ================================================================
//
// An operator your engine does not have is answered `None`, and Razeri
// then refuses a formula that needs it, naming the operator and your
// engine. It never writes the nearest function in the operator's place:
// a function call is not an operator, and a formula that composes one
// would be written wrong.
/// **This engine's exponentiation operator**, or `None` where it has none.
///
/// The default is `^`, which is exponentiation on `PostgreSQL` and
/// `DuckDB` and exclusive-or on several other engines. Answer `None` where
/// your engine raises to a power only through a function such as
/// `POWER(a, b)`.
fn render_power_operator(&self) -> Option<String> {
Some("^".to_string())
}
/// **This engine's case-insensitive `LIKE`**, or `None` where it has none.
fn render_ilike_operator(&self) -> Option<String> {
Some("ILIKE".to_string())
}
/// **This engine's negated case-insensitive `LIKE`**, or `None` where it
/// has none.
fn render_not_ilike_operator(&self) -> Option<String> {
Some("NOT ILIKE".to_string())
}
/// **This engine's string concatenation operator**, or `None` where it
/// joins strings only through a function.
fn render_concat_operator(&self) -> Option<String> {
Some("||".to_string())
}
/// Render the bitwise XOR operator.
#[deprecated(
since = "0.14.0",
note = "answer `render_bitwise_operator(BitwiseOperator::Xor)` instead, which can say \
the engine has none"
)]
fn render_bitwise_xor_operator(&self) -> String {
"^".to_string()
}
/// **This engine's spelling of one bitwise operator**, or `None` where it
/// has no such operator.
///
/// The default is the operator most engines write — `&`, `|`, `~`, `<<`,
/// `>>` — and, for an exclusive or, what
/// [`render_bitwise_xor_operator`](Self::render_bitwise_xor_operator)
/// answers (`^` unless a dialect overrode it). Answer `None` where your
/// engine offers the operation only as a function (`BITAND(a, b)`,
/// `bitAnd(a, b)`): a formula that needs it is then refused by name, never
/// written with a function in the operator's place. Two engines read `^`
/// as something else entirely — a power on one, nothing at all on another
/// — so an exclusive or is worth checking on yours.
fn render_bitwise_operator(&self, operator: BitwiseOperator) -> Option<String> {
Some(match operator {
BitwiseOperator::And => "&".to_owned(),
BitwiseOperator::Or => "|".to_owned(),
#[allow(deprecated)]
BitwiseOperator::Xor => self.render_bitwise_xor_operator(),
BitwiseOperator::Not => "~".to_owned(),
BitwiseOperator::ShiftLeft => "<<".to_owned(),
BitwiseOperator::ShiftRight => ">>".to_owned(),
})
}
// ================================================================
// Conditional / cast rendering
// ================================================================
/// Render `TRY_CAST` expression (takes pre-rendered type string).
fn render_try_cast_str(&self, expr: &str, type_str: &str) -> String {
format!("CAST({expr} AS {type_str})")
}
/// Render CONVERT expression with optional style.
fn render_convert(&self, expr: &str, type_str: &str, style: Option<i32>) -> String {
let _ = style;
format!("CAST({expr} AS {type_str})")
}
/// Render `SAFE_CAST` expression.
fn render_safe_cast(&self, expr: &str, type_str: &str) -> String {
format!("CAST({expr} AS {type_str})")
}
// ================================================================
// Null handling
// ================================================================
/// Render IFNULL / ISNULL / COALESCE expression.
fn render_if_null(&self, expr: &str, replacement: &str) -> String {
format!("COALESCE({expr}, {replacement})")
}
// ================================================================
// Parameter references
// ================================================================
/// Render a named parameter reference.
fn render_named_param(&self, name: &str) -> String {
format!(":{name}")
}
/// Render a positional parameter reference.
fn render_positional_param(&self, pos: usize) -> String {
let _ = pos;
"?".to_string()
}
// ================================================================
// Data type reference rendering (CAST expressions)
// ================================================================
/// Render a [`DataTypeRef`] as a SQL type name string.
///
/// The default implementation produces ANSI-standard type names.
/// Dialects override this for platform-specific names
/// (e.g., `ClickHouse` `Int32` instead of `INT`).
fn render_data_type_ref(&self, dt: &DataTypeRef) -> String {
match dt {
DataTypeRef::Int => "INT".to_string(),
DataTypeRef::BigInt => "BIGINT".to_string(),
DataTypeRef::SmallInt => "SMALLINT".to_string(),
DataTypeRef::TinyInt => "TINYINT".to_string(),
DataTypeRef::Float => "FLOAT".to_string(),
DataTypeRef::Double => "DOUBLE PRECISION".to_string(),
DataTypeRef::Real => "REAL".to_string(),
DataTypeRef::Decimal { precision, scale } => format!("DECIMAL({precision}, {scale})"),
DataTypeRef::Numeric { precision, scale } => format!("NUMERIC({precision}, {scale})"),
DataTypeRef::Varchar { length } => match length {
Some(len) => format!("VARCHAR({len})"),
None => "VARCHAR".to_string(),
},
DataTypeRef::Char { length } => format!("CHAR({length})"),
DataTypeRef::Text | DataTypeRef::Xml => "TEXT".to_string(),
DataTypeRef::NVarchar { length } => match length {
Some(len) => format!("NVARCHAR({len})"),
None => "NVARCHAR(MAX)".to_string(),
},
DataTypeRef::NChar { length } => format!("NCHAR({length})"),
DataTypeRef::Binary { length } => match length {
Some(len) => format!("BINARY({len})"),
None => "BINARY".to_string(),
},
DataTypeRef::VarBinary { length } => match length {
Some(len) => format!("VARBINARY({len})"),
None => "VARBINARY".to_string(),
},
DataTypeRef::Blob => "BLOB".to_string(),
DataTypeRef::Date => "DATE".to_string(),
DataTypeRef::Time { precision } => match precision {
Some(p) => format!("TIME({p})"),
None => "TIME".to_string(),
},
DataTypeRef::DateTime => "DATETIME".to_string(),
DataTypeRef::DateTime2 { precision } => match precision {
Some(p) => format!("DATETIME2({p})"),
None => "DATETIME2".to_string(),
},
DataTypeRef::Timestamp { precision } => match precision {
Some(p) => format!("TIMESTAMP({p})"),
None => "TIMESTAMP".to_string(),
},
DataTypeRef::TimestampTz { precision } => match precision {
Some(p) => format!("TIMESTAMP({p}) WITH TIME ZONE"),
None => "TIMESTAMP WITH TIME ZONE".to_string(),
},
DataTypeRef::Interval => "INTERVAL".to_string(),
DataTypeRef::Boolean => "BOOLEAN".to_string(),
DataTypeRef::Bit => "BIT".to_string(),
DataTypeRef::Json => "VARIANT".to_string(),
DataTypeRef::Jsonb | DataTypeRef::Variant => "JSON".to_string(),
DataTypeRef::Uuid => "UUID".to_string(),
DataTypeRef::Custom(name) => name.clone(),
}
}
}
/// ANSI-standard rendering of [`DataTypeRef`].
///
/// Used as a fallback for dialects that don't override type rendering.
#[must_use]
pub fn render_data_type_ref_ansi(dt: &DataTypeRef) -> String {
match dt {
DataTypeRef::Int => "INT".to_string(),
DataTypeRef::BigInt => "BIGINT".to_string(),
DataTypeRef::SmallInt => "SMALLINT".to_string(),
DataTypeRef::TinyInt => "TINYINT".to_string(),
DataTypeRef::Float => "FLOAT".to_string(),
DataTypeRef::Double => "DOUBLE PRECISION".to_string(),
DataTypeRef::Real => "REAL".to_string(),
DataTypeRef::Decimal { precision, scale } => format!("DECIMAL({precision}, {scale})"),
DataTypeRef::Numeric { precision, scale } => format!("NUMERIC({precision}, {scale})"),
DataTypeRef::Varchar { length } => match length {
Some(len) => format!("VARCHAR({len})"),
None => "VARCHAR".to_string(),
},
DataTypeRef::Char { length } => format!("CHAR({length})"),
DataTypeRef::Text | DataTypeRef::Xml => "TEXT".to_string(),
DataTypeRef::NVarchar { length } => match length {
Some(len) => format!("NVARCHAR({len})"),
None => "NVARCHAR(MAX)".to_string(),
},
DataTypeRef::NChar { length } => format!("NCHAR({length})"),
DataTypeRef::Binary { length } => match length {
Some(len) => format!("BINARY({len})"),
None => "BINARY".to_string(),
},
DataTypeRef::VarBinary { length } => match length {
Some(len) => format!("VARBINARY({len})"),
None => "VARBINARY".to_string(),
},
DataTypeRef::Blob => "BLOB".to_string(),
DataTypeRef::Date => "DATE".to_string(),
DataTypeRef::Time { precision } => match precision {
Some(p) => format!("TIME({p})"),
None => "TIME".to_string(),
},
DataTypeRef::DateTime => "DATETIME".to_string(),
DataTypeRef::DateTime2 { precision } => match precision {
Some(p) => format!("DATETIME2({p})"),
None => "DATETIME2".to_string(),
},
DataTypeRef::Timestamp { precision } => match precision {
Some(p) => format!("TIMESTAMP({p})"),
None => "TIMESTAMP".to_string(),
},
DataTypeRef::TimestampTz { precision } => match precision {
Some(p) => format!("TIMESTAMP({p}) WITH TIME ZONE"),
None => "TIMESTAMP WITH TIME ZONE".to_string(),
},
DataTypeRef::Interval => "INTERVAL".to_string(),
DataTypeRef::Boolean => "BOOLEAN".to_string(),
DataTypeRef::Bit => "BIT".to_string(),
DataTypeRef::Json => "VARIANT".to_string(),
DataTypeRef::Jsonb | DataTypeRef::Variant => "JSON".to_string(),
DataTypeRef::Uuid => "UUID".to_string(),
DataTypeRef::Custom(name) => name.clone(),
}
}
/// **One bitwise operator**, handed to
/// [`FormulaRenderer::render_bitwise_operator`] to spell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BitwiseOperator {
/// Both bits set: `a & b` on most engines.
And,
/// Either bit set: `a | b`.
Or,
/// Exactly one bit set: `a ^ b` on some engines, `a # b` on others.
Xor,
/// Every bit flipped, of one value: `~a`.
Not,
/// The bits moved toward the high end: `a << n`.
ShiftLeft,
/// The bits moved toward the low end: `a >> n`.
ShiftRight,
}
impl BitwiseOperator {
/// Every operator, in the order the formula vocabulary lists them.
pub const ALL: [Self; 6] =
[Self::And, Self::Or, Self::Xor, Self::Not, Self::ShiftLeft, Self::ShiftRight];
/// The operator as most engines write it, which is also how a refusal
/// names it.
#[must_use]
pub const fn standard_spelling(self) -> &'static str {
match self {
Self::And => "&",
Self::Or => "|",
Self::Xor => "^",
Self::Not => "~",
Self::ShiftLeft => "<<",
Self::ShiftRight => ">>",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DataType;
struct TestDialect;
impl SqlRenderer for TestDialect {
fn render_data_type(&self, _dt: &DataType) -> String {
"TEXT".to_string()
}
fn quote_identifier(&self, name: &str) -> String {
format!("\"{name}\"")
}
fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
match schema {
Some(s) => format!("\"{s}\".\"{name}\""),
None => format!("\"{name}\""),
}
}
fn render_current_timestamp(&self) -> String {
"CURRENT_TIMESTAMP".to_string()
}
}
impl FormulaRenderer for TestDialect {}
#[test]
fn formula_renderer_defaults_render_string_agg_with_order() {
let d = TestDialect;
assert_eq!(
d.render_string_agg("name", ",", false, Some("name ASC")),
"STRING_AGG(name, ',' ORDER BY name ASC)"
);
}
#[test]
fn formula_renderer_defaults_render_string_agg_with_distinct() {
let d = TestDialect;
assert_eq!(d.render_string_agg("name", ",", true, None), "STRING_AGG(DISTINCT name, ',')");
}
#[test]
fn formula_renderer_defaults_render_count_if() {
let d = TestDialect;
assert_eq!(d.render_count_if("x > 0"), "COUNT(CASE WHEN x > 0 THEN 1 END)");
}
/// A dialect that has stated no spelling renders the guess, and the guess
/// says so in its name. The value matters — it is what a plugin author sees
/// before they have decided anything — and the name is what lets Razeri's
/// conformance checks tell an undecided dialect from the agnostic renderer,
/// whose identical vocabulary is ANSI on purpose.
#[test]
fn a_dialect_that_states_no_spelling_renders_the_guess_and_is_named_as_one() {
use crate::sid_spelling::UNKNOWN_PLATFORM;
let d = TestDialect;
let spelling = crate::SqlRenderer::sid_spelling(&d);
assert_eq!(spelling.platform, UNKNOWN_PLATFORM);
assert_eq!(spelling.hash, ("xxhash64(", ")"));
}
}