icydb-core 0.114.1

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use crate::db::sql::lowering::{SqlLoweringError, aggregate::lower_aggregate_call};
use crate::{
    db::{
        query::{
            builder::NumericProjectionExpr,
            plan::expr::{BinaryOp, CaseWhenArm, Expr, FieldId, Function, UnaryOp},
        },
        sql::parser::{SqlExpr, SqlExprBinaryOp, SqlExprUnaryOp, SqlScalarFunction},
    },
    value::Value,
};

///
/// SqlExprPhase
///
/// Lowering-time SQL expression phase boundary.
/// Clause owners pass this to the shared SQL-expression lowering seam so
/// aggregate admission stays explicit instead of leaking through wrappers.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::sql::lowering) enum SqlExprPhase {
    Scalar,
    PreAggregate,
    PostAggregate,
}

// Lower one SQL expression tree into the canonical planner expression tree
// while enforcing the aggregate-admission rule for the owning clause phase.
pub(in crate::db::sql::lowering) fn lower_sql_expr(
    expr: &SqlExpr,
    phase: SqlExprPhase,
) -> Result<Expr, SqlLoweringError> {
    match expr {
        SqlExpr::Field(field) => Ok(Expr::Field(FieldId::new(field.clone()))),
        SqlExpr::Aggregate(aggregate) => {
            if !phase_allows_aggregate(phase) {
                return Err(phase_aggregate_error(phase));
            }

            Ok(Expr::Aggregate(lower_aggregate_call(aggregate.clone())?))
        }
        SqlExpr::Literal(literal) => Ok(Expr::Literal(literal.clone())),
        SqlExpr::Param { index } => Err(SqlLoweringError::unsupported_parameter_placement(
            Some(*index),
            "unbound SQL parameter reached expression lowering without prepare-time binding",
        )),
        SqlExpr::Membership {
            expr,
            values,
            negated,
        } => lower_sql_membership_expr(expr.as_ref(), values.as_slice(), *negated, phase),
        SqlExpr::NullTest { expr, negated } => Ok(Expr::FunctionCall {
            function: if *negated {
                Function::IsNotNull
            } else {
                Function::IsNull
            },
            args: vec![lower_sql_expr(expr.as_ref(), phase)?],
        }),
        SqlExpr::FunctionCall { function, args } => lower_sql_function_call(*function, args, phase),
        SqlExpr::Unary { op, expr } => Ok(Expr::Unary {
            op: lower_sql_unary_op(*op),
            expr: Box::new(lower_sql_expr(expr.as_ref(), phase)?),
        }),
        SqlExpr::Binary { op, left, right } => {
            lower_sql_binary_expr(*op, left.as_ref(), right.as_ref(), phase)
        }
        SqlExpr::Case { arms, else_expr } => Ok(Expr::Case {
            when_then_arms: arms
                .iter()
                .map(|arm| {
                    Ok(CaseWhenArm::new(
                        lower_sql_expr(&arm.condition, phase)?,
                        lower_sql_expr(&arm.result, phase)?,
                    ))
                })
                .collect::<Result<Vec<_>, SqlLoweringError>>()?,
            else_expr: Box::new(match else_expr.as_ref() {
                Some(else_expr) => lower_sql_expr(else_expr.as_ref(), phase)?,
                None => Expr::Literal(Value::Null),
            }),
        }),
    }
}

// Lower one parser-owned membership surface onto the existing boolean compare
// expression family so later WHERE compilation can still reuse the shipped
// normalized predicate path.
fn lower_sql_membership_expr(
    expr: &SqlExpr,
    values: &[Value],
    negated: bool,
    phase: SqlExprPhase,
) -> Result<Expr, SqlLoweringError> {
    let Some((first, rest)) = values.split_first() else {
        unreachable!("parsed membership expression must keep at least one literal");
    };

    let compare_op = if negated {
        SqlExprBinaryOp::Ne
    } else {
        SqlExprBinaryOp::Eq
    };
    let join_op = if negated {
        SqlExprBinaryOp::And
    } else {
        SqlExprBinaryOp::Or
    };

    let mut lowered =
        lower_sql_binary_expr(compare_op, expr, &SqlExpr::Literal(first.clone()), phase)?;
    for value in rest {
        lowered = Expr::Binary {
            op: lower_sql_binary_op(join_op),
            left: Box::new(lowered),
            right: Box::new(lower_sql_binary_expr(
                compare_op,
                expr,
                &SqlExpr::Literal(value.clone()),
                phase,
            )?),
        };
    }

    Ok(lowered)
}

fn lower_sql_binary_expr(
    op: SqlExprBinaryOp,
    left: &SqlExpr,
    right: &SqlExpr,
    phase: SqlExprPhase,
) -> Result<Expr, SqlLoweringError> {
    if let (SqlExpr::Field(field), SqlExpr::Literal(literal)) = (left, right)
        && let Some(expr) = lower_field_literal_numeric_expr(op, field.as_str(), literal)?
    {
        return Ok(expr);
    }

    Ok(Expr::Binary {
        op: lower_sql_binary_op(op),
        left: Box::new(lower_sql_expr(left, phase)?),
        right: Box::new(lower_sql_expr(right, phase)?),
    })
}

fn lower_field_literal_numeric_expr(
    op: SqlExprBinaryOp,
    field: &str,
    literal: &Value,
) -> Result<Option<Expr>, SqlLoweringError> {
    let builder = match op {
        SqlExprBinaryOp::Add => Some(NumericProjectionExpr::add_value(
            field.to_string(),
            literal.clone(),
        )),
        SqlExprBinaryOp::Sub => Some(NumericProjectionExpr::sub_value(
            field.to_string(),
            literal.clone(),
        )),
        SqlExprBinaryOp::Mul => Some(NumericProjectionExpr::mul_value(
            field.to_string(),
            literal.clone(),
        )),
        SqlExprBinaryOp::Div => Some(NumericProjectionExpr::div_value(
            field.to_string(),
            literal.clone(),
        )),
        SqlExprBinaryOp::Or
        | SqlExprBinaryOp::And
        | SqlExprBinaryOp::Eq
        | SqlExprBinaryOp::Ne
        | SqlExprBinaryOp::Lt
        | SqlExprBinaryOp::Lte
        | SqlExprBinaryOp::Gt
        | SqlExprBinaryOp::Gte => None,
    };

    builder
        .transpose()
        .map(|projection| projection.map(|projection| projection.expr().clone()))
        .map_err(SqlLoweringError::from)
}

const fn phase_allows_aggregate(phase: SqlExprPhase) -> bool {
    matches!(phase, SqlExprPhase::PostAggregate)
}

fn phase_aggregate_error(phase: SqlExprPhase) -> SqlLoweringError {
    match phase {
        SqlExprPhase::Scalar => SqlLoweringError::unsupported_select_projection(),
        SqlExprPhase::PreAggregate => SqlLoweringError::unsupported_aggregate_input_expressions(),
        SqlExprPhase::PostAggregate => {
            unreachable!("post-aggregate lowering allows aggregate leaves")
        }
    }
}

const fn lower_sql_unary_op(op: SqlExprUnaryOp) -> UnaryOp {
    match op {
        SqlExprUnaryOp::Not => UnaryOp::Not,
    }
}

pub(in crate::db::sql::lowering) const fn lower_sql_binary_op(op: SqlExprBinaryOp) -> BinaryOp {
    match op {
        SqlExprBinaryOp::Or => BinaryOp::Or,
        SqlExprBinaryOp::And => BinaryOp::And,
        SqlExprBinaryOp::Eq => BinaryOp::Eq,
        SqlExprBinaryOp::Ne => BinaryOp::Ne,
        SqlExprBinaryOp::Lt => BinaryOp::Lt,
        SqlExprBinaryOp::Lte => BinaryOp::Lte,
        SqlExprBinaryOp::Gt => BinaryOp::Gt,
        SqlExprBinaryOp::Gte => BinaryOp::Gte,
        SqlExprBinaryOp::Add => BinaryOp::Add,
        SqlExprBinaryOp::Sub => BinaryOp::Sub,
        SqlExprBinaryOp::Mul => BinaryOp::Mul,
        SqlExprBinaryOp::Div => BinaryOp::Div,
    }
}

// Report whether one parsed SQL expression shape is admitted as a boolean
// result surface by SQL lowering before unbound parameters are substituted.
// This stays parser/lowering-owned because it classifies SQL expression
// structure, not planner-owned semantic type results.
pub(in crate::db::sql::lowering) const fn sql_expr_is_boolean_shape(expr: &SqlExpr) -> bool {
    match expr {
        SqlExpr::Membership { .. }
        | SqlExpr::NullTest { .. }
        | SqlExpr::Unary { .. }
        | SqlExpr::FunctionCall { .. }
        | SqlExpr::Case { .. } => true,
        SqlExpr::Binary { op, .. } => matches!(
            op,
            SqlExprBinaryOp::Or
                | SqlExprBinaryOp::And
                | SqlExprBinaryOp::Eq
                | SqlExprBinaryOp::Ne
                | SqlExprBinaryOp::Lt
                | SqlExprBinaryOp::Lte
                | SqlExprBinaryOp::Gt
                | SqlExprBinaryOp::Gte
        ),
        SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } | SqlExpr::Aggregate(_) => {
            false
        }
    }
}

///
/// PreparedSqlPredicateTemplateShape
///
/// Parser-owned shape classification for the bounded symbolic scalar prepared
/// predicate lane. Session binding consumes this to pair parsed SQL predicate
/// structure with planner-owned compare metadata without re-deriving the SQL
/// tree shape locally.
///

pub(in crate::db) enum PreparedSqlPredicateTemplateShape<'a> {
    And {
        left: &'a SqlExpr,
        right: &'a SqlExpr,
    },
    Or {
        left: &'a SqlExpr,
        right: &'a SqlExpr,
    },
    Not {
        expr: &'a SqlExpr,
    },
    CompareWithParamRhs {
        slot_index: usize,
    },
}

// Classify one parsed SQL predicate subtree for the bounded symbolic scalar
// prepared lane. This stays lowering-owned because it is only interpreting
// parser structure, not planner predicate meaning.
pub(in crate::db) fn sql_expr_prepared_predicate_template_shape(
    expr: &SqlExpr,
) -> Option<PreparedSqlPredicateTemplateShape<'_>> {
    match expr {
        SqlExpr::Binary {
            op: SqlExprBinaryOp::And,
            left,
            right,
        } => Some(PreparedSqlPredicateTemplateShape::And { left, right }),
        SqlExpr::Binary {
            op: SqlExprBinaryOp::Or,
            left,
            right,
        } => Some(PreparedSqlPredicateTemplateShape::Or { left, right }),
        SqlExpr::Unary { expr, .. } => Some(PreparedSqlPredicateTemplateShape::Not { expr }),
        SqlExpr::Binary {
            op:
                SqlExprBinaryOp::Eq
                | SqlExprBinaryOp::Ne
                | SqlExprBinaryOp::Lt
                | SqlExprBinaryOp::Lte
                | SqlExprBinaryOp::Gt
                | SqlExprBinaryOp::Gte,
            left,
            right,
        } => match (&**left, &**right) {
            (SqlExpr::Field(_), SqlExpr::Param { index }) => {
                Some(PreparedSqlPredicateTemplateShape::CompareWithParamRhs { slot_index: *index })
            }
            _ => None,
        },
        _ => None,
    }
}

///
/// PreparedSqlTemplateExprScope
///
/// Scoped template-admission classifier for prepared SQL expression lanes.
/// Lowering owns this parser-shape decision so prepared statement assembly can
/// consume one shared expression classifier instead of keeping a local ladder
/// inside the prepared lowering owner.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db::sql::lowering) enum PreparedSqlTemplateExprScope {
    Filter,
    Having,
}

// Return whether one parsed SQL expression uses parameter slots inside one
// general expression-owned shape that must stay off template lanes for the
// selected scope.
pub(in crate::db) fn sql_expr_uses_general_template_expr_parameters(
    scope: PreparedSqlTemplateExprScope,
    expr: &SqlExpr,
) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } | SqlExpr::Aggregate(_) => {
            false
        }
        SqlExpr::Membership { expr, .. } => sql_expr_contains_param(expr.as_ref()),
        SqlExpr::NullTest { expr, .. } => !sql_null_test_target_is_template_shape(scope, expr),
        SqlExpr::Unary { expr, .. } => sql_expr_uses_general_template_expr_parameters(scope, expr),
        SqlExpr::Binary { op, left, right } => match op {
            SqlExprBinaryOp::And | SqlExprBinaryOp::Or => {
                sql_expr_uses_general_template_expr_parameters(scope, left)
                    || sql_expr_uses_general_template_expr_parameters(scope, right)
            }
            SqlExprBinaryOp::Eq
            | SqlExprBinaryOp::Ne
            | SqlExprBinaryOp::Lt
            | SqlExprBinaryOp::Lte
            | SqlExprBinaryOp::Gt
            | SqlExprBinaryOp::Gte => {
                !(sql_compare_target_is_template_shape(scope, left)
                    && sql_compare_target_is_template_shape(scope, right))
                    && (sql_expr_contains_param(left) || sql_expr_contains_param(right))
            }
            SqlExprBinaryOp::Add
            | SqlExprBinaryOp::Sub
            | SqlExprBinaryOp::Mul
            | SqlExprBinaryOp::Div => {
                sql_expr_contains_param(left) || sql_expr_contains_param(right)
            }
        },
        SqlExpr::FunctionCall { function, args } => {
            !sql_function_is_template_shape(scope, *function, args.as_slice())
                && args.iter().any(sql_expr_contains_param)
        }
        SqlExpr::Case { arms, else_expr } => {
            arms.iter().any(|arm| {
                sql_expr_contains_param(&arm.condition) || sql_expr_contains_param(&arm.result)
            }) || else_expr
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_param(expr))
        }
    }
}

// Return whether one parsed SQL expression is a direct compare/text-predicate
// operand shape that prepared predicate/access templates are still allowed to
// own.
fn sql_compare_target_is_template_shape(
    scope: PreparedSqlTemplateExprScope,
    expr: &SqlExpr,
) -> bool {
    match scope {
        PreparedSqlTemplateExprScope::Filter => match expr {
            SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } => true,
            SqlExpr::FunctionCall { function, args }
                if matches!(
                    function,
                    SqlScalarFunction::Lower | SqlScalarFunction::Upper
                ) && matches!(args.as_slice(), [SqlExpr::Field(_)]) =>
            {
                true
            }
            _ => false,
        },
        PreparedSqlTemplateExprScope::Having => matches!(
            expr,
            SqlExpr::Field(_) | SqlExpr::Literal(_) | SqlExpr::Param { .. } | SqlExpr::Aggregate(_)
        ),
    }
}

// Return whether one parsed SQL null-test target still matches the predicate
// lane that prepared templates are allowed to rebuild.
fn sql_null_test_target_is_template_shape(
    scope: PreparedSqlTemplateExprScope,
    expr: &SqlExpr,
) -> bool {
    match scope {
        PreparedSqlTemplateExprScope::Filter => matches!(expr, SqlExpr::Field(_)),
        PreparedSqlTemplateExprScope::Having => !sql_expr_contains_param(expr),
    }
}

// Return whether one parsed SQL function call is one direct text predicate
// shape still owned by prepared predicate templates.
fn sql_function_is_template_shape(
    scope: PreparedSqlTemplateExprScope,
    function: SqlScalarFunction,
    args: &[SqlExpr],
) -> bool {
    match scope {
        PreparedSqlTemplateExprScope::Filter => {
            matches!(
                function,
                SqlScalarFunction::StartsWith
                    | SqlScalarFunction::EndsWith
                    | SqlScalarFunction::Contains
            ) && matches!(
                args,
                [left, right]
                    if sql_compare_target_is_template_shape(
                        PreparedSqlTemplateExprScope::Filter,
                        left
                    ) && sql_compare_target_is_template_shape(
                        PreparedSqlTemplateExprScope::Filter,
                        right
                    )
            )
        }
        PreparedSqlTemplateExprScope::Having => false,
    }
}

// Return whether one parsed SQL boolean expression is compound enough that
// grouped symbolic template ownership must keep failing closed instead of
// claiming a combined access-plus-residual route. This remains lowering-owned
// because it classifies parser structure, not session binding policy.
pub(in crate::db) const fn sql_expr_is_compound_boolean_shape(expr: &SqlExpr) -> bool {
    matches!(
        expr,
        SqlExpr::Binary {
            op: SqlExprBinaryOp::And | SqlExprBinaryOp::Or,
            ..
        } | SqlExpr::Unary { .. }
    )
}

// Walk one parsed SQL expression and report whether it references any runtime
// parameter slot. Lowering owns this parser-tree traversal so prepared
// lowering and session binding do not each keep their own local walker.
pub(in crate::db) fn sql_expr_contains_param(expr: &SqlExpr) -> bool {
    sql_expr_first_param_index(expr).is_some()
}

// Walk one parsed SQL expression tree and report whether it already contains
// any literal equal to one of the supplied values. Lowering owns this parser
// traversal so session binding can reuse one shared SQL-expression walk for
// template-sentinel collision checks instead of keeping its own copy.
pub(in crate::db) fn sql_expr_contains_any_literal(expr: &SqlExpr, values: &[Value]) -> bool {
    match expr {
        SqlExpr::Field(_) | SqlExpr::Param { .. } => false,
        SqlExpr::Aggregate(aggregate) => {
            aggregate
                .input
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_any_literal(expr, values))
                || aggregate
                    .filter_expr
                    .as_ref()
                    .is_some_and(|expr| sql_expr_contains_any_literal(expr, values))
        }
        SqlExpr::Literal(value) => values.contains(value),
        SqlExpr::Membership {
            expr,
            values: members,
            ..
        } => {
            sql_expr_contains_any_literal(expr, values)
                || members.iter().any(|value| values.contains(value))
        }
        SqlExpr::NullTest { expr, .. } | SqlExpr::Unary { expr, .. } => {
            sql_expr_contains_any_literal(expr, values)
        }
        SqlExpr::FunctionCall { args, .. } => args
            .iter()
            .any(|arg| sql_expr_contains_any_literal(arg, values)),
        SqlExpr::Binary { left, right, .. } => {
            sql_expr_contains_any_literal(left, values)
                || sql_expr_contains_any_literal(right, values)
        }
        SqlExpr::Case { arms, else_expr } => {
            arms.iter().any(|arm| {
                sql_expr_contains_any_literal(&arm.condition, values)
                    || sql_expr_contains_any_literal(&arm.result, values)
            }) || else_expr
                .as_ref()
                .is_some_and(|expr| sql_expr_contains_any_literal(expr, values))
        }
    }
}

// Return the first runtime parameter slot referenced by one parsed SQL
// expression. This stays lowering-owned because it classifies parser-owned
// SQL structure rather than prepared-lane semantics.
pub(in crate::db) fn sql_expr_first_param_index(expr: &SqlExpr) -> Option<usize> {
    match expr {
        SqlExpr::Param { index } => Some(*index),
        SqlExpr::Field(_) | SqlExpr::Literal(_) => None,
        SqlExpr::Aggregate(aggregate) => aggregate
            .input
            .as_deref()
            .and_then(sql_expr_first_param_index)
            .or_else(|| {
                aggregate
                    .filter_expr
                    .as_deref()
                    .and_then(sql_expr_first_param_index)
            }),
        SqlExpr::Membership { expr, .. }
        | SqlExpr::NullTest { expr, .. }
        | SqlExpr::Unary { expr, .. } => sql_expr_first_param_index(expr),
        SqlExpr::FunctionCall { args, .. } => sql_expr_first_param_index_from_args(args.as_slice()),
        SqlExpr::Binary { left, right, .. } => {
            sql_expr_first_param_index(left).or_else(|| sql_expr_first_param_index(right))
        }
        SqlExpr::Case { arms, else_expr } => arms
            .iter()
            .find_map(|arm| {
                sql_expr_first_param_index(&arm.condition)
                    .or_else(|| sql_expr_first_param_index(&arm.result))
            })
            .or_else(|| else_expr.as_deref().and_then(sql_expr_first_param_index)),
    }
}

// Return the first runtime parameter slot referenced by one parsed SQL
// argument list.
pub(in crate::db) fn sql_expr_first_param_index_from_args(args: &[SqlExpr]) -> Option<usize> {
    args.iter().find_map(sql_expr_first_param_index)
}

// Return the first runtime parameter slot referenced across one parsed SQL
// left/right pair.
pub(in crate::db) fn sql_expr_first_param_index_from_pair(
    left: &SqlExpr,
    right: &SqlExpr,
) -> Option<usize> {
    sql_expr_first_param_index(left).or_else(|| sql_expr_first_param_index(right))
}

pub(in crate::db::sql::lowering) const fn lower_sql_scalar_function(
    function: SqlScalarFunction,
) -> Function {
    match function {
        SqlScalarFunction::Trim => Function::Trim,
        SqlScalarFunction::Ltrim => Function::Ltrim,
        SqlScalarFunction::Rtrim => Function::Rtrim,
        SqlScalarFunction::Round => Function::Round,
        SqlScalarFunction::Coalesce => Function::Coalesce,
        SqlScalarFunction::NullIf => Function::NullIf,
        SqlScalarFunction::Abs => Function::Abs,
        SqlScalarFunction::Ceil => Function::Ceil,
        SqlScalarFunction::Ceiling => Function::Ceiling,
        SqlScalarFunction::Floor => Function::Floor,
        SqlScalarFunction::Lower => Function::Lower,
        SqlScalarFunction::Upper => Function::Upper,
        SqlScalarFunction::Length => Function::Length,
        SqlScalarFunction::Left => Function::Left,
        SqlScalarFunction::Right => Function::Right,
        SqlScalarFunction::StartsWith => Function::StartsWith,
        SqlScalarFunction::EndsWith => Function::EndsWith,
        SqlScalarFunction::Contains => Function::Contains,
        SqlScalarFunction::Position => Function::Position,
        SqlScalarFunction::Replace => Function::Replace,
        SqlScalarFunction::Substring => Function::Substring,
    }
}

fn lower_sql_function_call(
    function: SqlScalarFunction,
    args: &[SqlExpr],
    phase: SqlExprPhase,
) -> Result<Expr, SqlLoweringError> {
    if matches!(function, SqlScalarFunction::Round) {
        return lower_sql_round_function_call(args, phase);
    }

    Ok(Expr::FunctionCall {
        function: lower_sql_scalar_function(function),
        args: args
            .iter()
            .map(|arg| lower_sql_expr(arg, phase))
            .collect::<Result<Vec<_>, SqlLoweringError>>()?,
    })
}

fn lower_sql_round_function_call(
    args: &[SqlExpr],
    phase: SqlExprPhase,
) -> Result<Expr, SqlLoweringError> {
    if !(1..=2).contains(&args.len()) {
        return Err(crate::db::QueryError::unsupported_query(format!(
            "ROUND(...) expects 1 or 2 args, found {}",
            args.len()
        ))
        .into());
    }

    let input = lower_sql_expr(&args[0], phase)?;
    let scale = match args.get(1) {
        Some(SqlExpr::Literal(scale)) => Expr::Literal(Value::Uint(u64::from(
            validate_round_projection_scale(scale.clone())?,
        ))),
        Some(other) => lower_sql_expr(other, phase)?,
        None => Expr::Literal(Value::Uint(0)),
    };

    Ok(Expr::FunctionCall {
        function: Function::Round,
        args: vec![input, scale],
    })
}

fn validate_round_projection_scale(scale: Value) -> Result<u32, SqlLoweringError> {
    match scale {
        Value::Int(value) => u32::try_from(value).map_err(|_| {
            crate::db::QueryError::unsupported_query(format!(
                "ROUND(...) requires non-negative integer scale, found {value}",
            ))
            .into()
        }),
        Value::Uint(value) => u32::try_from(value).map_err(|_| {
            crate::db::QueryError::unsupported_query(format!(
                "ROUND(...) scale exceeds supported integer range, found {value}",
            ))
            .into()
        }),
        other => Err(crate::db::QueryError::unsupported_query(format!(
            "ROUND(...) requires integer scale, found {other:?}",
        ))
        .into()),
    }
}