Skip to main content

reddb_rql/
sql_lowering.rs

1use crate::ast::{
2    BinOp, CompareOp, DeleteQuery, Expr, FieldRef, Filter, GraphQuery, InsertQuery, JoinQuery,
3    PathQuery, Projection, SelectItem, Span, TableQuery, UnaryOp, UpdateQuery, VectorQuery,
4};
5use reddb_types::types::{DataType, Value};
6use reddb_types::vector_metadata::MetadataFilter;
7
8pub const PARAMETER_PROJECTION_PREFIX: &str = "__user_param_projection__:";
9
10// A trailing argument carried by the compatibility AST. Keeping the predicate
11// as an Expr retains ordinary parameter binding and column authorization.
12pub const AGGREGATE_FILTER: &str = "__AGG_FILTER";
13const SUM_DISTINCT_INPUT: &str = "__SUM_DISTINCT_INPUT";
14
15pub fn aggregate_filter_expr(args: &[Expr]) -> Option<(&[Expr], &Expr)> {
16    let (Expr::FunctionCall { name, args, .. }, inputs) = args.split_last()? else {
17        return None;
18    };
19    match (name.as_str(), args.as_slice()) {
20        (AGGREGATE_FILTER, [predicate]) => Some((inputs, predicate)),
21        _ => None,
22    }
23}
24
25pub fn aggregate_filter_projection(args: &[Projection]) -> Option<(&[Projection], &Expr)> {
26    let (Projection::Function(name, args), inputs) = args.split_last()? else {
27        return None;
28    };
29    let (AGGREGATE_FILTER, [condition]) = (name.as_str(), args.as_slice()) else {
30        return None;
31    };
32    Some((inputs, condition_projection_expr(condition)?))
33}
34
35/// SUM(DISTINCT) retains its typed input through legacy projection lowering.
36pub fn sum_distinct_input(projection: &Projection) -> Option<&Expr> {
37    let Projection::Function(name, args) = projection else {
38        return None;
39    };
40    let (SUM_DISTINCT_INPUT, [input]) = (name.as_str(), args.as_slice()) else {
41        return None;
42    };
43    condition_projection_expr(input)
44}
45
46pub fn function_args_to_projections(name: &str, args: &[Expr]) -> Option<Vec<Projection>> {
47    args.iter()
48        .enumerate()
49        .map(|(index, arg)| {
50            if index == 0 && name.eq_ignore_ascii_case("SUM_DISTINCT") {
51                Some(Projection::Function(
52                    SUM_DISTINCT_INPUT.to_string(),
53                    vec![case_condition_projection(arg.clone())],
54                ))
55            } else {
56                expr_to_projection(arg)
57            }
58        })
59        .collect()
60}
61
62/// Recursively check whether `expr` contains any `Expr::Parameter` node.
63/// Used by the INSERT parser to know when to defer literal folding to
64/// the user_params binder.
65pub fn expr_contains_parameter(expr: &Expr) -> bool {
66    match expr {
67        Expr::Parameter { .. } => true,
68        Expr::Literal { .. } | Expr::Column { .. } => false,
69        Expr::BinaryOp { lhs, rhs, .. } => {
70            expr_contains_parameter(lhs) || expr_contains_parameter(rhs)
71        }
72        Expr::UnaryOp { operand, .. } => expr_contains_parameter(operand),
73        Expr::Cast { inner, .. } => expr_contains_parameter(inner),
74        Expr::FunctionCall { args, .. } => args.iter().any(expr_contains_parameter),
75        Expr::Case {
76            branches, else_, ..
77        } => {
78            branches
79                .iter()
80                .any(|(c, v)| expr_contains_parameter(c) || expr_contains_parameter(v))
81                || else_.as_deref().is_some_and(expr_contains_parameter)
82        }
83        Expr::IsNull { operand, .. } => expr_contains_parameter(operand),
84        Expr::InList { target, values, .. } => {
85            expr_contains_parameter(target) || values.iter().any(expr_contains_parameter)
86        }
87        Expr::Between {
88            target, low, high, ..
89        } => {
90            expr_contains_parameter(target)
91                || expr_contains_parameter(low)
92                || expr_contains_parameter(high)
93        }
94        Expr::Subquery { .. } => false,
95        Expr::WindowFunctionCall { args, window, .. } => {
96            args.iter().any(expr_contains_parameter)
97                || window.partition_by.iter().any(expr_contains_parameter)
98                || window
99                    .order_by
100                    .iter()
101                    .any(|o| expr_contains_parameter(&o.expr))
102        }
103    }
104}
105
106pub fn expr_to_projection(expr: &Expr) -> Option<Projection> {
107    match expr {
108        Expr::Literal { value, .. } => projection_from_literal(value),
109        Expr::Column { field, .. } => {
110            if matches!(
111                field,
112                FieldRef::TableColumn { table, column } if table.is_empty() && column == "*"
113            ) {
114                Some(Projection::All)
115            } else {
116                Some(Projection::Field(field.clone(), None))
117            }
118        }
119        Expr::Parameter { index, .. } => Some(Projection::Column(format!(
120            "{PARAMETER_PROJECTION_PREFIX}{index}"
121        ))),
122        Expr::BinaryOp { op, lhs, rhs, .. } => match op {
123            BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
124                Some(Projection::Function(
125                    projection_binop_name(*op).to_string(),
126                    vec![expr_to_projection(lhs)?, expr_to_projection(rhs)?],
127                ))
128            }
129            _ => Some(boolean_expr_projection(expr.clone())),
130        },
131        Expr::UnaryOp { op, operand, .. } => match op {
132            UnaryOp::Neg => Some(Projection::Function(
133                "SUB".to_string(),
134                vec![
135                    Projection::Column("LIT:0".to_string()),
136                    expr_to_projection(operand)?,
137                ],
138            )),
139            UnaryOp::Not => Some(boolean_expr_projection(expr.clone())),
140        },
141        Expr::Cast { inner, target, .. } => Some(Projection::Function(
142            "CAST".to_string(),
143            vec![
144                expr_to_projection(inner)?,
145                Projection::Column(format!("TYPE:{target}")),
146            ],
147        )),
148        Expr::FunctionCall { name, args, .. } if name == AGGREGATE_FILTER => {
149            let [predicate] = args.as_slice() else {
150                return None;
151            };
152            Some(Projection::Function(
153                name.clone(),
154                vec![case_condition_projection(predicate.clone())],
155            ))
156        }
157        Expr::FunctionCall { name, args, .. } => Some(Projection::Function(
158            name.to_uppercase(),
159            function_args_to_projections(name, args)?,
160        )),
161        Expr::Case {
162            branches, else_, ..
163        } => {
164            let mut args = Vec::with_capacity(branches.len() * 2 + usize::from(else_.is_some()));
165            for (cond, value) in branches {
166                args.push(case_condition_projection(cond.clone()));
167                args.push(expr_to_projection(value)?);
168            }
169            if let Some(else_expr) = else_ {
170                args.push(expr_to_projection(else_expr)?);
171            }
172            Some(Projection::Function("CASE".to_string(), args))
173        }
174        Expr::IsNull { .. }
175        | Expr::InList { .. }
176        | Expr::Between { .. }
177        | Expr::Subquery { .. } => Some(boolean_expr_projection(expr.clone())),
178        Expr::WindowFunctionCall {
179            name, args, window, ..
180        } => {
181            let lowered_args = args
182                .iter()
183                .map(expr_to_projection)
184                .collect::<Option<Vec<_>>>()?;
185            Some(crate::ast::Projection::Window {
186                name: name.to_uppercase(),
187                args: lowered_args,
188                window: Box::new(window.clone()),
189                alias: None,
190            })
191        }
192    }
193}
194
195pub fn select_item_to_projection(item: &SelectItem) -> Option<Projection> {
196    match item {
197        SelectItem::Wildcard => Some(Projection::All),
198        SelectItem::Expr { expr, alias } => {
199            let projection = expr_to_projection(expr)?;
200            // Attach ONLY an explicit alias here. The previous
201            // `.or_else(|| Some(render_expr_label(expr)))` synthesized an implicit
202            // output label from the expression text and baked it into the legacy
203            // Projection — mangling function names (`CAST` → `CAST:CAST(.. AS ..)`),
204            // wrapping bare columns in a redundant `Alias(name, name)`, and thereby
205            // breaking render→parse→render idempotency. The default output-column
206            // label for an un-aliased projection is derived at render time from the
207            // SelectItem (which keeps `alias: None`), not from this lowering.
208            Some(attach_projection_alias(projection, alias.clone()))
209        }
210    }
211}
212
213pub fn effective_table_projections(query: &TableQuery) -> Vec<Projection> {
214    if !query.select_items.is_empty() {
215        return query
216            .select_items
217            .iter()
218            .filter_map(select_item_to_projection)
219            .collect();
220    }
221    if query.columns.is_empty() {
222        vec![Projection::All]
223    } else {
224        query.columns.clone()
225    }
226}
227
228pub fn effective_table_filter(query: &TableQuery) -> Option<Filter> {
229    query
230        .filter
231        .clone()
232        .or_else(|| query.where_expr.as_ref().map(expr_to_filter))
233        .map(|f| f.optimize()) // OR-of-Eq → In; AND/OR flatten; constant fold
234}
235
236pub fn effective_table_group_by_exprs(query: &TableQuery) -> Vec<Expr> {
237    if !query.group_by_exprs.is_empty() {
238        query.group_by_exprs.clone()
239    } else {
240        query
241            .group_by
242            .iter()
243            .map(|column| Expr::Column {
244                field: FieldRef::TableColumn {
245                    table: String::new(),
246                    column: column.clone(),
247                },
248                span: Span::synthetic(),
249            })
250            .collect()
251    }
252}
253
254pub fn effective_table_having_filter(query: &TableQuery) -> Option<Filter> {
255    query
256        .having
257        .clone()
258        .or_else(|| query.having_expr.as_ref().map(expr_to_filter))
259}
260
261pub fn effective_update_filter(query: &UpdateQuery) -> Option<Filter> {
262    query
263        .filter
264        .clone()
265        .or_else(|| query.where_expr.as_ref().map(expr_to_filter))
266}
267
268pub fn effective_insert_rows(query: &InsertQuery) -> Result<Vec<Vec<Value>>, String> {
269    if !query.value_exprs.is_empty() {
270        return query
271            .value_exprs
272            .iter()
273            .cloned()
274            .map(|row| row.into_iter().map(fold_expr_to_value).collect())
275            .collect();
276    }
277    Ok(query.values.clone())
278}
279
280pub fn effective_delete_filter(query: &DeleteQuery) -> Option<Filter> {
281    query
282        .filter
283        .clone()
284        .or_else(|| query.where_expr.as_ref().map(expr_to_filter))
285}
286
287pub fn effective_join_filter(query: &JoinQuery) -> Option<Filter> {
288    query.filter.clone()
289}
290
291pub fn effective_graph_filter(query: &GraphQuery) -> Option<Filter> {
292    query.filter.clone()
293}
294
295pub fn effective_graph_projections(query: &GraphQuery) -> Vec<Projection> {
296    query.return_.clone()
297}
298
299pub fn effective_path_filter(query: &PathQuery) -> Option<Filter> {
300    query.filter.clone()
301}
302
303pub fn effective_path_projections(query: &PathQuery) -> Vec<Projection> {
304    query.return_.clone()
305}
306
307pub fn effective_vector_filter(query: &VectorQuery) -> Option<MetadataFilter> {
308    query.filter.clone()
309}
310
311pub fn projection_to_expr(projection: &Projection) -> Option<(Expr, Option<String>)> {
312    if let Some(input) = sum_distinct_input(projection) {
313        return Some((input.clone(), None));
314    }
315    match projection {
316        Projection::All => Some((
317            Expr::Column {
318                field: FieldRef::TableColumn {
319                    table: String::new(),
320                    column: "*".to_string(),
321                },
322                span: Span::synthetic(),
323            },
324            None,
325        )),
326        Projection::Column(column) => Some((projection_column_to_expr(column), None)),
327        Projection::Alias(column, alias) => {
328            Some((projection_column_to_expr(column), Some(alias.clone())))
329        }
330        Projection::Function(name, args) => {
331            let (name, alias) = split_projection_function_alias(name);
332            if name == AGGREGATE_FILTER {
333                let [condition] = args.as_slice() else {
334                    return None;
335                };
336                return Some((
337                    Expr::FunctionCall {
338                        name,
339                        args: vec![condition_projection_expr(condition)?.clone()],
340                        span: Span::synthetic(),
341                    },
342                    alias,
343                ));
344            }
345            if name == "CASE" {
346                if args.len() < 2 {
347                    return None;
348                }
349                let mut branches = Vec::with_capacity(args.len() / 2);
350                for pair in args.chunks_exact(2) {
351                    let lhs = condition_projection_expr(&pair[0])?;
352                    branches.push((lhs.clone(), projection_to_expr(&pair[1])?.0));
353                }
354                let else_ = if args.len() % 2 == 1 {
355                    Some(Box::new(projection_to_expr(args.last()?)?.0))
356                } else {
357                    None
358                };
359                return Some((
360                    Expr::Case {
361                        branches,
362                        else_,
363                        span: Span::synthetic(),
364                    },
365                    alias,
366                ));
367            }
368            if name == "CAST" {
369                if let [inner, Projection::Column(target)] = args.as_slice() {
370                    let target = target
371                        .strip_prefix("TYPE:")
372                        .and_then(DataType::from_sql_name);
373                    if let Some(target @ (DataType::Cron | DataType::TimestampMs)) = target {
374                        return Some((
375                            Expr::Cast {
376                                inner: Box::new(projection_to_expr(inner)?.0),
377                                target,
378                                span: Span::synthetic(),
379                            },
380                            alias,
381                        ));
382                    }
383                }
384            }
385            if matches!(name.as_str(), "__SECRET_LITERAL" | "__TYPED_LITERAL") {
386                let [Projection::Expression(filter, None)] = args.as_slice() else {
387                    return None;
388                };
389                let Filter::CompareExpr {
390                    lhs: lhs @ Expr::Literal { value, .. },
391                    op: CompareOp::Eq,
392                    rhs:
393                        Expr::Literal {
394                            value: Value::Boolean(true),
395                            ..
396                        },
397                } = filter.as_ref()
398                else {
399                    return None;
400                };
401                return match (name.as_str(), value) {
402                    ("__SECRET_LITERAL", Value::Secret(_))
403                    | (
404                        "__TYPED_LITERAL",
405                        Value::Timestamp(_) | Value::TimestampMs(_) | Value::Cron(_),
406                    ) => Some((lhs.clone(), alias)),
407                    _ => None,
408                };
409            }
410            if let ("DIV", [lhs, rhs]) = (name.as_str(), args.as_slice()) {
411                return Some((
412                    Expr::binop(
413                        BinOp::Div,
414                        projection_to_expr(lhs)?.0,
415                        projection_to_expr(rhs)?.0,
416                    ),
417                    alias,
418                ));
419            }
420            let args = args
421                .iter()
422                .map(projection_to_expr)
423                .collect::<Option<Vec<_>>>()?
424                .into_iter()
425                .map(|(expr, _)| expr)
426                .collect();
427            Some((
428                Expr::FunctionCall {
429                    name,
430                    args,
431                    span: Span::synthetic(),
432                },
433                alias,
434            ))
435        }
436        Projection::Expression(filter, alias) => Some((filter_to_expr(filter), alias.clone())),
437        Projection::Field(field, alias) => Some((
438            Expr::Column {
439                field: field.clone(),
440                span: Span::synthetic(),
441            },
442            alias.clone(),
443        )),
444        Projection::Window {
445            name,
446            args,
447            window,
448            alias,
449        } => {
450            let args = args
451                .iter()
452                .map(projection_to_expr)
453                .collect::<Option<Vec<_>>>()?
454                .into_iter()
455                .map(|(expr, _)| expr)
456                .collect();
457            Some((
458                Expr::WindowFunctionCall {
459                    name: name.clone(),
460                    args,
461                    window: (**window).clone(),
462                    span: Span::synthetic(),
463                },
464                alias.clone(),
465            ))
466        }
467    }
468}
469
470fn projection_column_to_expr(column: &str) -> Expr {
471    if let Some(value) = projection_literal_value(column) {
472        return Expr::Literal {
473            value,
474            span: Span::synthetic(),
475        };
476    }
477
478    Expr::Column {
479        field: FieldRef::TableColumn {
480            table: String::new(),
481            column: column.to_string(),
482        },
483        span: Span::synthetic(),
484    }
485}
486
487fn projection_literal_value(column: &str) -> Option<Value> {
488    let literal = column.strip_prefix("LIT:")?;
489    if literal.is_empty() {
490        return Some(Value::Null);
491    }
492    if let Ok(value) = literal.parse::<i64>() {
493        return Some(Value::Integer(value));
494    }
495    if let Ok(value) = literal.parse::<f64>() {
496        return Some(Value::Float(value));
497    }
498    Some(Value::text(literal.to_string()))
499}
500
501pub fn projection_to_select_item(projection: &Projection) -> Option<SelectItem> {
502    match projection {
503        Projection::All => Some(SelectItem::Wildcard),
504        other => {
505            let (expr, alias) = projection_to_expr(other)?;
506            Some(SelectItem::Expr { expr, alias })
507        }
508    }
509}
510
511pub fn effective_join_projections(query: &JoinQuery) -> Vec<Projection> {
512    if !query.return_items.is_empty() {
513        return query
514            .return_items
515            .iter()
516            .filter_map(select_item_to_projection)
517            .collect();
518    }
519    query.return_.clone()
520}
521
522pub fn expr_to_filter(expr: &Expr) -> Filter {
523    match expr {
524        Expr::BinaryOp { op, lhs, rhs, .. } => match op {
525            BinOp::And => Filter::And(Box::new(expr_to_filter(lhs)), Box::new(expr_to_filter(rhs))),
526            BinOp::Or => Filter::Or(Box::new(expr_to_filter(lhs)), Box::new(expr_to_filter(rhs))),
527            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => {
528                try_specialized_compare_filter(lhs, *op, rhs).unwrap_or_else(|| {
529                    Filter::CompareExpr {
530                        lhs: lhs.as_ref().clone(),
531                        op: binop_to_compare_op(*op),
532                        rhs: rhs.as_ref().clone(),
533                    }
534                })
535            }
536            BinOp::Add
537            | BinOp::Sub
538            | BinOp::Mul
539            | BinOp::Div
540            | BinOp::Mod
541            | BinOp::Concat
542            | BinOp::IsDistinctFrom
543            | BinOp::IsNotDistinctFrom => Filter::CompareExpr {
544                lhs: expr.clone(),
545                op: CompareOp::Eq,
546                rhs: Expr::lit(Value::Boolean(true)),
547            },
548        },
549        Expr::UnaryOp {
550            op: UnaryOp::Not,
551            operand,
552            ..
553        } => Filter::Not(Box::new(expr_to_filter(operand))),
554        Expr::IsNull {
555            operand, negated, ..
556        } => match operand.as_ref() {
557            Expr::Column { field, .. } => {
558                if *negated {
559                    Filter::IsNotNull(field.clone())
560                } else {
561                    Filter::IsNull(field.clone())
562                }
563            }
564            _ => Filter::CompareExpr {
565                lhs: expr.clone(),
566                op: CompareOp::Eq,
567                rhs: Expr::lit(Value::Boolean(true)),
568            },
569        },
570        Expr::InList {
571            target,
572            values,
573            negated,
574            ..
575        } => match (target.as_ref(), all_literal_values(values)) {
576            (Expr::Column { field, .. }, Some(values)) if !negated => Filter::In {
577                field: field.clone(),
578                values,
579            },
580            _ => Filter::CompareExpr {
581                lhs: expr.clone(),
582                op: CompareOp::Eq,
583                rhs: Expr::lit(Value::Boolean(true)),
584            },
585        },
586        Expr::Between {
587            target,
588            low,
589            high,
590            negated,
591            ..
592        } => match (
593            target.as_ref(),
594            literal_expr_value(low),
595            literal_expr_value(high),
596        ) {
597            (Expr::Column { field, .. }, Some(low), Some(high)) if !negated => Filter::Between {
598                field: field.clone(),
599                low,
600                high,
601            },
602            _ => Filter::CompareExpr {
603                lhs: expr.clone(),
604                op: CompareOp::Eq,
605                rhs: Expr::lit(Value::Boolean(true)),
606            },
607        },
608        Expr::Subquery { .. } => Filter::CompareExpr {
609            lhs: expr.clone(),
610            op: CompareOp::Eq,
611            rhs: Expr::lit(Value::Boolean(true)),
612        },
613        // Reverse-lower the string-predicate FunctionCall forms emitted by
614        // `filter_to_expr` (`LIKE`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`)
615        // back to the typed `Filter` variants. The runtime filter
616        // evaluators (`runtime::join_filter`, virtual `red.*` reads) only
617        // understand the typed variants; without this round-trip step a
618        // `WHERE path STARTS WITH 'infra'` clause survives the parser as
619        // `Filter::StartsWith` but is reduced to a `where_expr`-only
620        // `FunctionCall` after subquery resolution clears `table.filter`,
621        // and `effective_table_filter` would then fall through to a
622        // generic `CompareExpr(FunctionCall, =, true)` that no virtual
623        // table can evaluate. Refs #785.
624        Expr::FunctionCall { name, args, .. } => string_predicate_from_function_call(name, args)
625            .unwrap_or_else(|| Filter::CompareExpr {
626                lhs: expr.clone(),
627                op: CompareOp::Eq,
628                rhs: Expr::lit(Value::Boolean(true)),
629            }),
630        _ => Filter::CompareExpr {
631            lhs: expr.clone(),
632            op: CompareOp::Eq,
633            rhs: Expr::lit(Value::Boolean(true)),
634        },
635    }
636}
637
638fn string_predicate_from_function_call(name: &str, args: &[Expr]) -> Option<Filter> {
639    if args.len() != 2 {
640        return None;
641    }
642    let field = match &args[0] {
643        Expr::Column { field, .. } => field.clone(),
644        _ => return None,
645    };
646    let text = match &args[1] {
647        Expr::Literal {
648            value: Value::Text(value),
649            ..
650        } => value.as_ref().to_string(),
651        _ => return None,
652    };
653    if name.eq_ignore_ascii_case("LIKE") {
654        Some(Filter::Like {
655            field,
656            pattern: text,
657        })
658    } else if name.eq_ignore_ascii_case("STARTS_WITH") {
659        Some(Filter::StartsWith {
660            field,
661            prefix: text,
662        })
663    } else if name.eq_ignore_ascii_case("ENDS_WITH") {
664        Some(Filter::EndsWith {
665            field,
666            suffix: text,
667        })
668    } else if name.eq_ignore_ascii_case("CONTAINS") {
669        Some(Filter::Contains {
670            field,
671            substring: text,
672        })
673    } else {
674        None
675    }
676}
677
678pub fn boolean_expr_projection(expr: Expr) -> Projection {
679    Projection::Expression(
680        Box::new(Filter::CompareExpr {
681            lhs: expr,
682            op: CompareOp::Eq,
683            rhs: Expr::Literal {
684                value: Value::Boolean(true),
685                span: Span::synthetic(),
686            },
687        }),
688        None,
689    )
690}
691
692pub fn filter_to_expr(filter: &Filter) -> Expr {
693    match filter {
694        Filter::Compare { field, op, value } => Expr::BinaryOp {
695            op: compare_op_to_binop(*op),
696            lhs: Box::new(Expr::Column {
697                field: field.clone(),
698                span: Span::synthetic(),
699            }),
700            rhs: Box::new(Expr::Literal {
701                value: value.clone(),
702                span: Span::synthetic(),
703            }),
704            span: Span::synthetic(),
705        },
706        Filter::CompareFields { left, op, right } => Expr::BinaryOp {
707            op: compare_op_to_binop(*op),
708            lhs: Box::new(Expr::Column {
709                field: left.clone(),
710                span: Span::synthetic(),
711            }),
712            rhs: Box::new(Expr::Column {
713                field: right.clone(),
714                span: Span::synthetic(),
715            }),
716            span: Span::synthetic(),
717        },
718        Filter::CompareExpr { lhs, op, rhs } => Expr::BinaryOp {
719            op: compare_op_to_binop(*op),
720            lhs: Box::new(lhs.clone()),
721            rhs: Box::new(rhs.clone()),
722            span: Span::synthetic(),
723        },
724        Filter::And(left, right) => Expr::BinaryOp {
725            op: BinOp::And,
726            lhs: Box::new(filter_to_expr(left)),
727            rhs: Box::new(filter_to_expr(right)),
728            span: Span::synthetic(),
729        },
730        Filter::Or(left, right) => Expr::BinaryOp {
731            op: BinOp::Or,
732            lhs: Box::new(filter_to_expr(left)),
733            rhs: Box::new(filter_to_expr(right)),
734            span: Span::synthetic(),
735        },
736        Filter::Not(inner) => Expr::UnaryOp {
737            op: UnaryOp::Not,
738            operand: Box::new(filter_to_expr(inner)),
739            span: Span::synthetic(),
740        },
741        Filter::IsNull(field) => Expr::IsNull {
742            operand: Box::new(Expr::Column {
743                field: field.clone(),
744                span: Span::synthetic(),
745            }),
746            negated: false,
747            span: Span::synthetic(),
748        },
749        Filter::IsNotNull(field) => Expr::IsNull {
750            operand: Box::new(Expr::Column {
751                field: field.clone(),
752                span: Span::synthetic(),
753            }),
754            negated: true,
755            span: Span::synthetic(),
756        },
757        Filter::In { field, values } => Expr::InList {
758            target: Box::new(Expr::Column {
759                field: field.clone(),
760                span: Span::synthetic(),
761            }),
762            values: values
763                .iter()
764                .cloned()
765                .map(|value| Expr::Literal {
766                    value,
767                    span: Span::synthetic(),
768                })
769                .collect(),
770            negated: false,
771            span: Span::synthetic(),
772        },
773        Filter::Between { field, low, high } => Expr::Between {
774            target: Box::new(Expr::Column {
775                field: field.clone(),
776                span: Span::synthetic(),
777            }),
778            low: Box::new(Expr::Literal {
779                value: low.clone(),
780                span: Span::synthetic(),
781            }),
782            high: Box::new(Expr::Literal {
783                value: high.clone(),
784                span: Span::synthetic(),
785            }),
786            negated: false,
787            span: Span::synthetic(),
788        },
789        Filter::Like { field, pattern } => Expr::FunctionCall {
790            name: "LIKE".to_string(),
791            args: vec![
792                Expr::Column {
793                    field: field.clone(),
794                    span: Span::synthetic(),
795                },
796                Expr::Literal {
797                    value: Value::text(pattern.clone()),
798                    span: Span::synthetic(),
799                },
800            ],
801            span: Span::synthetic(),
802        },
803        Filter::StartsWith { field, prefix } => Expr::FunctionCall {
804            name: "STARTS_WITH".to_string(),
805            args: vec![
806                Expr::Column {
807                    field: field.clone(),
808                    span: Span::synthetic(),
809                },
810                Expr::Literal {
811                    value: Value::text(prefix.clone()),
812                    span: Span::synthetic(),
813                },
814            ],
815            span: Span::synthetic(),
816        },
817        Filter::EndsWith { field, suffix } => Expr::FunctionCall {
818            name: "ENDS_WITH".to_string(),
819            args: vec![
820                Expr::Column {
821                    field: field.clone(),
822                    span: Span::synthetic(),
823                },
824                Expr::Literal {
825                    value: Value::text(suffix.clone()),
826                    span: Span::synthetic(),
827                },
828            ],
829            span: Span::synthetic(),
830        },
831        Filter::Contains { field, substring } => Expr::FunctionCall {
832            name: "CONTAINS".to_string(),
833            args: vec![
834                Expr::Column {
835                    field: field.clone(),
836                    span: Span::synthetic(),
837                },
838                Expr::Literal {
839                    value: Value::text(substring.clone()),
840                    span: Span::synthetic(),
841                },
842            ],
843            span: Span::synthetic(),
844        },
845    }
846}
847
848pub fn projection_from_literal(value: &Value) -> Option<Projection> {
849    match value {
850        // Scalar subqueries return typed encrypted values. Carry the literal
851        // in the existing expression payload instead of rendering it as text.
852        Value::Secret(_) => Some(Projection::Function(
853            "__SECRET_LITERAL".into(),
854            vec![case_condition_projection(Expr::lit(value.clone()))],
855        )),
856        Value::Timestamp(_) | Value::TimestampMs(_) | Value::Cron(_) => Some(Projection::Function(
857            "__TYPED_LITERAL".into(),
858            vec![case_condition_projection(Expr::lit(value.clone()))],
859        )),
860        Value::Boolean(_) => Some(boolean_expr_projection(Expr::Literal {
861            value: value.clone(),
862            span: Span::synthetic(),
863        })),
864        _ => Some(Projection::Column(format!(
865            "LIT:{}",
866            render_projection_literal(value)
867        ))),
868    }
869}
870
871pub fn case_condition_projection(condition: Expr) -> Projection {
872    Projection::Expression(
873        Box::new(Filter::CompareExpr {
874            lhs: condition,
875            op: CompareOp::Eq,
876            rhs: Expr::Literal {
877                value: Value::Boolean(true),
878                span: Span::synthetic(),
879            },
880        }),
881        None,
882    )
883}
884
885fn condition_projection_expr(projection: &Projection) -> Option<&Expr> {
886    let Projection::Expression(filter, None) = projection else {
887        return None;
888    };
889    match filter.as_ref() {
890        Filter::CompareExpr {
891            lhs,
892            op: CompareOp::Eq,
893            rhs:
894                Expr::Literal {
895                    value: Value::Boolean(true),
896                    ..
897                },
898        } => Some(lhs),
899        _ => None,
900    }
901}
902
903pub fn fold_expr_to_value(expr: Expr) -> Result<Value, String> {
904    match expr {
905        Expr::Literal { value, .. } => Ok(value),
906        Expr::FunctionCall { name, args, .. } => {
907            if (name.eq_ignore_ascii_case("PASSWORD") || name.eq_ignore_ascii_case("SECRET"))
908                && args.len() == 1
909            {
910                let plaintext = match fold_expr_to_value(args.into_iter().next().unwrap())? {
911                    Value::Text(text) => text,
912                    other => {
913                        return Err(format!(
914                            "{name}() expects a string literal argument, got {other:?}"
915                        ))
916                    }
917                };
918                return Ok(if name.eq_ignore_ascii_case("PASSWORD") {
919                    Value::Password(format!("@@plain@@{plaintext}"))
920                } else {
921                    Value::Secret(format!("@@plain@@{plaintext}").into_bytes())
922                });
923            }
924            if name.eq_ignore_ascii_case("CRON") {
925                let arguments = args
926                    .into_iter()
927                    .map(fold_expr_to_value)
928                    .collect::<Result<Vec<_>, _>>()?;
929                return reddb_types::cron::construct(&arguments);
930            }
931            // ADR 0067 (#1721): `JSON_PARSE('{…}')` is the sanctioned escape
932            // hatch for writing JSON from a runtime string. Fold a literal
933            // string argument to a `Value::Json` here so it is accepted in
934            // INSERT VALUES positions, using the same parse+canonicalize
935            // pipeline as an inline JSON literal.
936            if name.eq_ignore_ascii_case("JSON_PARSE") && args.len() == 1 {
937                let raw = match fold_expr_to_value(args.into_iter().next().unwrap())? {
938                    Value::Text(text) => text,
939                    other => {
940                        return Err(format!(
941                            "JSON_PARSE() expects a string literal argument, got {other:?}"
942                        ))
943                    }
944                };
945                let parsed = reddb_types::utils::json::parse_json(raw.as_ref())
946                    .map_err(|err| format!("JSON_PARSE failed to parse JSON: {err}"))?;
947                let canonical = reddb_types::serde_json::Value::from(parsed);
948                let bytes = reddb_types::json::to_vec(&canonical)
949                    .map_err(|err| format!("JSON_PARSE failed to encode JSON: {err}"))?;
950                return Ok(Value::Json(bytes));
951            }
952            Err(format!(
953                "expression is not a foldable literal: FunctionCall({name})"
954            ))
955        }
956        Expr::UnaryOp { op, operand, .. } => {
957            let inner = fold_expr_to_value(*operand)?;
958            match (op, inner) {
959                (UnaryOp::Neg, Value::Integer(n)) => Ok(Value::Integer(-n)),
960                (UnaryOp::Neg, Value::UnsignedInteger(n)) => Ok(Value::Integer(-(n as i64))),
961                (UnaryOp::Neg, Value::Float(f)) => Ok(Value::Float(-f)),
962                (UnaryOp::Not, Value::Boolean(b)) => Ok(Value::Boolean(!b)),
963                (other_op, other) => Err(format!(
964                    "unary `{other_op:?}` cannot fold to literal Value (operand: {other:?})"
965                )),
966            }
967        }
968        Expr::Cast {
969            inner,
970            target: DataType::Cron,
971            ..
972        } => match fold_expr_to_value(*inner)? {
973            value @ Value::Cron(_) => Ok(value),
974            value => reddb_types::cron::construct(&[value]),
975        },
976        Expr::Cast { inner, .. } => fold_expr_to_value(*inner),
977        other => Err(format!("expression is not a foldable literal: {other:?}")),
978    }
979}
980
981fn projection_binop_name(op: BinOp) -> &'static str {
982    match op {
983        BinOp::Add => "ADD",
984        BinOp::Sub => "SUB",
985        BinOp::Mul => "MUL",
986        BinOp::Div => "DIV",
987        BinOp::Mod => "MOD",
988        BinOp::Concat => "CONCAT",
989        BinOp::Eq
990        | BinOp::Ne
991        | BinOp::Lt
992        | BinOp::Le
993        | BinOp::Gt
994        | BinOp::Ge
995        | BinOp::IsDistinctFrom
996        | BinOp::IsNotDistinctFrom
997        | BinOp::And
998        | BinOp::Or => {
999            unreachable!("boolean operators are lowered through Projection::Expression")
1000        }
1001    }
1002}
1003
1004// SQL-text label rendering for projection expressions. Retained verbatim from
1005// the pre-move module (no live caller today); kept for the upcoming Fase 2
1006// projection-aliasing work rather than dropped during the byte-faithful move.
1007#[allow(dead_code)]
1008pub fn render_expr_label(expr: &Expr) -> String {
1009    render_expr_label_prec(expr, 0)
1010}
1011
1012#[allow(dead_code)]
1013fn render_expr_label_prec(expr: &Expr, parent_prec: u8) -> String {
1014    match expr {
1015        Expr::Literal { value, .. } => render_sql_literal_label(value),
1016        Expr::Column { field, .. } => render_field_label(field),
1017        Expr::Parameter { index, .. } => format!("${index}"),
1018        Expr::BinaryOp { op, lhs, rhs, .. } => {
1019            let prec = op.precedence();
1020            let rendered = format!(
1021                "{} {} {}",
1022                render_expr_label_prec(lhs, prec),
1023                render_binop_label(*op),
1024                render_expr_label_prec(rhs, prec + 1)
1025            );
1026            if prec < parent_prec {
1027                format!("({rendered})")
1028            } else {
1029                rendered
1030            }
1031        }
1032        Expr::UnaryOp { op, operand, .. } => match op {
1033            UnaryOp::Neg => format!("-{}", render_expr_label_prec(operand, u8::MAX)),
1034            UnaryOp::Not => format!("NOT {}", render_expr_label_prec(operand, u8::MAX)),
1035        },
1036        Expr::Cast { inner, target, .. } => {
1037            format!("CAST({} AS {target})", render_expr_label(inner))
1038        }
1039        Expr::FunctionCall { name, args, .. } => {
1040            let format_call = |inputs: &[Expr]| {
1041                let inputs = inputs
1042                    .iter()
1043                    .map(render_expr_label)
1044                    .collect::<Vec<_>>()
1045                    .join(", ");
1046                if name.eq_ignore_ascii_case("SUM_DISTINCT") {
1047                    format!("SUM(DISTINCT {inputs})")
1048                } else {
1049                    format!("{name}({inputs})")
1050                }
1051            };
1052            if let Some((inputs, predicate)) = aggregate_filter_expr(args) {
1053                return format!(
1054                    "{} FILTER (WHERE {})",
1055                    format_call(inputs),
1056                    render_expr_label(predicate)
1057                );
1058            }
1059            format_call(args)
1060        }
1061        Expr::Case {
1062            branches, else_, ..
1063        } => {
1064            let mut out = String::from("CASE");
1065            for (condition, value) in branches {
1066                out.push_str(" WHEN ");
1067                out.push_str(&render_expr_label(condition));
1068                out.push_str(" THEN ");
1069                out.push_str(&render_expr_label(value));
1070            }
1071            if let Some(else_expr) = else_ {
1072                out.push_str(" ELSE ");
1073                out.push_str(&render_expr_label(else_expr));
1074            }
1075            out.push_str(" END");
1076            out
1077        }
1078        Expr::IsNull {
1079            operand, negated, ..
1080        } => {
1081            let op = if *negated { "IS NOT NULL" } else { "IS NULL" };
1082            format!("{} {op}", render_expr_label_prec(operand, u8::MAX))
1083        }
1084        Expr::InList {
1085            target,
1086            values,
1087            negated,
1088            ..
1089        } => {
1090            let op = if *negated { "NOT IN" } else { "IN" };
1091            let values = values
1092                .iter()
1093                .map(render_expr_label)
1094                .collect::<Vec<_>>()
1095                .join(", ");
1096            format!("{} {op} ({values})", render_expr_label(target))
1097        }
1098        Expr::Between {
1099            target,
1100            low,
1101            high,
1102            negated,
1103            ..
1104        } => {
1105            let op = if *negated { "NOT BETWEEN" } else { "BETWEEN" };
1106            format!(
1107                "{} {op} {} AND {}",
1108                render_expr_label(target),
1109                render_expr_label(low),
1110                render_expr_label(high)
1111            )
1112        }
1113        Expr::Subquery { .. } => "subquery".to_string(),
1114        Expr::WindowFunctionCall { name, args, .. } => {
1115            let args = args
1116                .iter()
1117                .map(render_expr_label)
1118                .collect::<Vec<_>>()
1119                .join(", ");
1120            format!("{name}({args}) OVER (...)")
1121        }
1122    }
1123}
1124
1125#[allow(dead_code)]
1126fn render_binop_label(op: BinOp) -> &'static str {
1127    match op {
1128        BinOp::Add => "+",
1129        BinOp::Sub => "-",
1130        BinOp::Mul => "*",
1131        BinOp::Div => "/",
1132        BinOp::Mod => "%",
1133        BinOp::Concat => "||",
1134        BinOp::Eq => "=",
1135        BinOp::Ne => "!=",
1136        BinOp::Lt => "<",
1137        BinOp::Le => "<=",
1138        BinOp::Gt => ">",
1139        BinOp::Ge => ">=",
1140        BinOp::IsDistinctFrom => "IS DISTINCT FROM",
1141        BinOp::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
1142        BinOp::And => "AND",
1143        BinOp::Or => "OR",
1144    }
1145}
1146
1147#[allow(dead_code)]
1148fn render_field_label(field: &FieldRef) -> String {
1149    match field {
1150        FieldRef::TableColumn { table, column } => {
1151            if table.is_empty() {
1152                column.clone()
1153            } else {
1154                format!("{table}.{column}")
1155            }
1156        }
1157        FieldRef::NodeProperty { alias, property } => format!("{alias}.{property}"),
1158        FieldRef::EdgeProperty { alias, property } => format!("{alias}.{property}"),
1159        FieldRef::NodeId { alias } => format!("{alias}.id"),
1160    }
1161}
1162
1163#[allow(dead_code)]
1164fn render_sql_literal_label(value: &Value) -> String {
1165    match value {
1166        Value::Null => "NULL".to_string(),
1167        Value::Text(value) => format!("'{}'", value.replace('\'', "''")),
1168        Value::Boolean(value) => value.to_string(),
1169        Value::Integer(value) => value.to_string(),
1170        Value::UnsignedInteger(value) => value.to_string(),
1171        Value::Float(value) => {
1172            if value.fract().abs() < f64::EPSILON {
1173                (*value as i64).to_string()
1174            } else {
1175                value.to_string()
1176            }
1177        }
1178        other => other.to_string(),
1179    }
1180}
1181
1182fn binop_to_compare_op(op: BinOp) -> CompareOp {
1183    match op {
1184        BinOp::Eq => CompareOp::Eq,
1185        BinOp::Ne => CompareOp::Ne,
1186        BinOp::Lt => CompareOp::Lt,
1187        BinOp::Le => CompareOp::Le,
1188        BinOp::Gt => CompareOp::Gt,
1189        BinOp::Ge => CompareOp::Ge,
1190        other => unreachable!("non-compare binop cannot lower to CompareOp: {other:?}"),
1191    }
1192}
1193
1194fn compare_op_to_binop(op: CompareOp) -> BinOp {
1195    match op {
1196        CompareOp::Eq => BinOp::Eq,
1197        CompareOp::Ne => BinOp::Ne,
1198        CompareOp::Lt => BinOp::Lt,
1199        CompareOp::Le => BinOp::Le,
1200        CompareOp::Gt => BinOp::Gt,
1201        CompareOp::Ge => BinOp::Ge,
1202    }
1203}
1204
1205fn attach_projection_alias(proj: Projection, alias: Option<String>) -> Projection {
1206    let Some(alias) = alias else { return proj };
1207    match proj {
1208        Projection::Field(f, _) => Projection::Field(f, Some(alias)),
1209        Projection::Expression(filter, _) => Projection::Expression(filter, Some(alias)),
1210        Projection::Function(name, args) => {
1211            if name.contains(':') {
1212                Projection::Function(name, args)
1213            } else {
1214                Projection::Function(format!("{name}:{alias}"), args)
1215            }
1216        }
1217        Projection::Column(c) => Projection::Alias(c, alias),
1218        Projection::Window {
1219            name, args, window, ..
1220        } => Projection::Window {
1221            name,
1222            args,
1223            window,
1224            alias: Some(alias),
1225        },
1226        other => other,
1227    }
1228}
1229
1230fn split_projection_function_alias(name: &str) -> (String, Option<String>) {
1231    match name.split_once(':') {
1232        Some((function, alias)) if !function.is_empty() && !alias.is_empty() => {
1233            (function.to_string(), Some(alias.to_string()))
1234        }
1235        _ => (name.to_string(), None),
1236    }
1237}
1238
1239fn render_projection_literal(value: &Value) -> String {
1240    match value {
1241        Value::Null => String::new(),
1242        Value::Integer(v) => v.to_string(),
1243        Value::UnsignedInteger(v) => v.to_string(),
1244        Value::Float(v) => {
1245            if v.fract().abs() < f64::EPSILON {
1246                (*v as i64).to_string()
1247            } else {
1248                v.to_string()
1249            }
1250        }
1251        Value::Text(v) => v.to_string(),
1252        Value::Boolean(true) => "true".to_string(),
1253        Value::Boolean(false) => "false".to_string(),
1254        // Composite values (arrays, vectors, blobs) would lose fidelity
1255        // going through `Display` — `Vec<Value>` turns into
1256        // "<vector dim=N>". Use a JSON sentinel so the reader in
1257        // `eval_projection_value` can round-trip the exact Value.
1258        Value::Array(_) | Value::Vector(_) | Value::Json(_) | Value::Blob(_) => {
1259            format!("@RL:{}", serialize_value_json(value))
1260        }
1261        other => other.to_string(),
1262    }
1263}
1264
1265fn serialize_value_json(value: &Value) -> String {
1266    // Uses `crate::serde_json` which is already a workspace dep.
1267    match value {
1268        Value::Array(items) => {
1269            let mut out = String::from("[");
1270            for (i, item) in items.iter().enumerate() {
1271                if i > 0 {
1272                    out.push(',');
1273                }
1274                out.push_str(&serialize_value_json(item));
1275            }
1276            out.push(']');
1277            out
1278        }
1279        Value::Vector(items) => {
1280            let mut out = String::from("V[");
1281            for (i, f) in items.iter().enumerate() {
1282                if i > 0 {
1283                    out.push(',');
1284                }
1285                out.push_str(&f.to_string());
1286            }
1287            out.push(']');
1288            out
1289        }
1290        Value::Integer(n) | Value::BigInt(n) => n.to_string(),
1291        Value::UnsignedInteger(n) => n.to_string(),
1292        Value::Float(f) => f.to_string(),
1293        Value::Text(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1294        Value::Boolean(b) => b.to_string(),
1295        Value::Null => "null".to_string(),
1296        other => format!("\"{}\"", other.to_string().replace('"', "\\\"")),
1297    }
1298}
1299
1300fn try_specialized_compare_filter(lhs: &Expr, op: BinOp, rhs: &Expr) -> Option<Filter> {
1301    let op = binop_to_compare_op(op);
1302    match (lhs, rhs) {
1303        (Expr::Column { field, .. }, Expr::Literal { value, .. }) => Some(Filter::Compare {
1304            field: field.clone(),
1305            op,
1306            value: value.clone(),
1307        }),
1308        (Expr::Literal { value, .. }, Expr::Column { field, .. }) => Some(Filter::Compare {
1309            field: field.clone(),
1310            op: flipped_compare_op(op),
1311            value: value.clone(),
1312        }),
1313        (Expr::Column { field: left, .. }, Expr::Column { field: right, .. }) => {
1314            Some(Filter::CompareFields {
1315                left: left.clone(),
1316                op,
1317                right: right.clone(),
1318            })
1319        }
1320        _ => None,
1321    }
1322}
1323
1324fn flipped_compare_op(op: CompareOp) -> CompareOp {
1325    match op {
1326        CompareOp::Eq => CompareOp::Eq,
1327        CompareOp::Ne => CompareOp::Ne,
1328        CompareOp::Lt => CompareOp::Gt,
1329        CompareOp::Le => CompareOp::Ge,
1330        CompareOp::Gt => CompareOp::Lt,
1331        CompareOp::Ge => CompareOp::Le,
1332    }
1333}
1334
1335fn literal_expr_value(expr: &Expr) -> Option<Value> {
1336    match expr {
1337        Expr::Literal { value, .. } => Some(value.clone()),
1338        _ => None,
1339    }
1340}
1341
1342fn all_literal_values(values: &[Expr]) -> Option<Vec<Value>> {
1343    values.iter().map(literal_expr_value).collect()
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348    use super::*;
1349    use crate::ast::{
1350        GraphPattern, GraphQuery, JoinCondition, JoinQuery, NodeSelector, OrderByClause, PathQuery,
1351        QueryExpr, VectorQuery, VectorSource, WindowOrderItem, WindowSpec,
1352    };
1353
1354    fn field(name: &str) -> FieldRef {
1355        FieldRef::column("", name)
1356    }
1357
1358    fn col(name: &str) -> Expr {
1359        Expr::Column {
1360            field: field(name),
1361            span: Span::synthetic(),
1362        }
1363    }
1364
1365    fn lit(value: Value) -> Expr {
1366        Expr::Literal {
1367            value,
1368            span: Span::synthetic(),
1369        }
1370    }
1371
1372    fn parameter(index: usize) -> Expr {
1373        Expr::Parameter {
1374            index,
1375            span: Span::synthetic(),
1376        }
1377    }
1378
1379    fn bin(op: BinOp, lhs: Expr, rhs: Expr) -> Expr {
1380        Expr::BinaryOp {
1381            op,
1382            lhs: Box::new(lhs),
1383            rhs: Box::new(rhs),
1384            span: Span::synthetic(),
1385        }
1386    }
1387
1388    #[test]
1389    fn expr_contains_parameter_walks_nested_expression_shapes() {
1390        assert!(expr_contains_parameter(&bin(
1391            BinOp::Add,
1392            col("age"),
1393            parameter(1)
1394        )));
1395
1396        let case = Expr::Case {
1397            branches: vec![(col("active"), lit(Value::Integer(1)))],
1398            else_: Some(Box::new(parameter(2))),
1399            span: Span::synthetic(),
1400        };
1401        assert!(expr_contains_parameter(&case));
1402
1403        let window = Expr::WindowFunctionCall {
1404            name: "row_number".to_string(),
1405            args: Vec::new(),
1406            window: WindowSpec {
1407                partition_by: vec![col("tenant_id")],
1408                order_by: vec![WindowOrderItem {
1409                    expr: parameter(3),
1410                    ascending: true,
1411                    nulls_first: false,
1412                }],
1413                frame: None,
1414            },
1415            span: Span::synthetic(),
1416        };
1417        assert!(expr_contains_parameter(&window));
1418
1419        let no_parameter = Expr::FunctionCall {
1420            name: "lower".to_string(),
1421            args: vec![col("name")],
1422            span: Span::synthetic(),
1423        };
1424        assert!(!expr_contains_parameter(&no_parameter));
1425    }
1426
1427    #[test]
1428    fn expressions_lower_to_legacy_projections_with_aliases_preserved() {
1429        assert!(matches!(
1430            expr_to_projection(&col("*")),
1431            Some(Projection::All)
1432        ));
1433
1434        let param_projection = expr_to_projection(&parameter(7)).unwrap();
1435        assert!(matches!(
1436            param_projection,
1437            Projection::Column(value) if value == format!("{PARAMETER_PROJECTION_PREFIX}7")
1438        ));
1439
1440        let arithmetic = bin(BinOp::Add, col("age"), lit(Value::Integer(1)));
1441        let projection = select_item_to_projection(&SelectItem::Expr {
1442            expr: arithmetic,
1443            alias: Some("age_plus_one".to_string()),
1444        })
1445        .unwrap();
1446        assert!(matches!(
1447            projection,
1448            Projection::Function(ref name, ref args)
1449                if name == "ADD:age_plus_one" && args.len() == 2
1450        ));
1451
1452        let negated = Expr::UnaryOp {
1453            op: UnaryOp::Neg,
1454            operand: Box::new(col("age")),
1455            span: Span::synthetic(),
1456        };
1457        assert!(matches!(
1458            expr_to_projection(&negated),
1459            Some(Projection::Function(name, args)) if name == "SUB" && args.len() == 2
1460        ));
1461
1462        let cast = Expr::Cast {
1463            inner: Box::new(col("age")),
1464            target: reddb_types::types::DataType::Text,
1465            span: Span::synthetic(),
1466        };
1467        assert!(matches!(
1468            expr_to_projection(&cast),
1469            Some(Projection::Function(name, args)) if name == "CAST" && args.len() == 2
1470        ));
1471
1472        let window = Expr::WindowFunctionCall {
1473            name: "sum".to_string(),
1474            args: vec![col("amount")],
1475            window: WindowSpec::default(),
1476            span: Span::synthetic(),
1477        };
1478        assert!(matches!(
1479            select_item_to_projection(&SelectItem::Expr {
1480                expr: window,
1481                alias: Some("running_sum".to_string()),
1482            }),
1483            Some(Projection::Window { name, alias, .. })
1484                if name == "SUM" && alias.as_deref() == Some("running_sum")
1485        ));
1486    }
1487
1488    #[test]
1489    fn projections_raise_back_to_select_items_and_expression_nodes() {
1490        assert!(matches!(
1491            projection_to_select_item(&Projection::All),
1492            Some(SelectItem::Wildcard)
1493        ));
1494
1495        let literal = projection_to_expr(&Projection::Column("LIT:42".to_string())).unwrap();
1496        assert!(matches!(
1497            literal,
1498            (
1499                Expr::Literal {
1500                    value: Value::Integer(42),
1501                    ..
1502                },
1503                None
1504            )
1505        ));
1506
1507        let float_literal = projection_to_expr(&Projection::Column("LIT:3.5".to_string())).unwrap();
1508        assert!(matches!(
1509            float_literal,
1510            (Expr::Literal { value: Value::Float(v), .. }, None) if (v - 3.5).abs() < f64::EPSILON
1511        ));
1512
1513        let null_literal = projection_to_expr(&Projection::Column("LIT:".to_string())).unwrap();
1514        assert!(matches!(
1515            null_literal,
1516            (
1517                Expr::Literal {
1518                    value: Value::Null,
1519                    ..
1520                },
1521                None
1522            )
1523        ));
1524
1525        let function = Projection::Function(
1526            "LOWER:lower_name".to_string(),
1527            vec![Projection::Field(field("name"), None)],
1528        );
1529        let (expr, alias) = projection_to_expr(&function).unwrap();
1530        assert_eq!(alias.as_deref(), Some("lower_name"));
1531        assert!(
1532            matches!(expr, Expr::FunctionCall { name, args, .. } if name == "LOWER" && args.len() == 1)
1533        );
1534
1535        let window = Projection::Window {
1536            name: "ROW_NUMBER".to_string(),
1537            args: Vec::new(),
1538            window: Box::new(WindowSpec::default()),
1539            alias: Some("rn".to_string()),
1540        };
1541        let (expr, alias) = projection_to_expr(&window).unwrap();
1542        assert_eq!(alias.as_deref(), Some("rn"));
1543        assert!(matches!(expr, Expr::WindowFunctionCall { name, .. } if name == "ROW_NUMBER"));
1544    }
1545
1546    #[test]
1547    fn filters_round_trip_through_expression_forms() {
1548        let filters = vec![
1549            Filter::Compare {
1550                field: field("age"),
1551                op: CompareOp::Ge,
1552                value: Value::Integer(18),
1553            },
1554            Filter::CompareFields {
1555                left: field("updated_at"),
1556                op: CompareOp::Gt,
1557                right: field("created_at"),
1558            },
1559            Filter::And(
1560                Box::new(Filter::IsNotNull(field("email"))),
1561                Box::new(Filter::Like {
1562                    field: field("email"),
1563                    pattern: "%@example.com".to_string(),
1564                }),
1565            ),
1566            Filter::Or(
1567                Box::new(Filter::StartsWith {
1568                    field: field("path"),
1569                    prefix: "infra/".to_string(),
1570                }),
1571                Box::new(Filter::EndsWith {
1572                    field: field("path"),
1573                    suffix: ".log".to_string(),
1574                }),
1575            ),
1576            Filter::Not(Box::new(Filter::Contains {
1577                field: field("body"),
1578                substring: "secret".to_string(),
1579            })),
1580            Filter::IsNull(field("deleted_at")),
1581            Filter::In {
1582                field: field("status"),
1583                values: vec![Value::text("open"), Value::text("pending")],
1584            },
1585            Filter::Between {
1586                field: field("score"),
1587                low: Value::Integer(10),
1588                high: Value::Integer(20),
1589            },
1590        ];
1591
1592        for filter in filters {
1593            let expr = filter_to_expr(&filter);
1594            assert_eq!(expr_to_filter(&expr), filter);
1595        }
1596    }
1597
1598    #[test]
1599    fn expression_filters_specialize_common_predicates_and_fallbacks() {
1600        let flipped = expr_to_filter(&bin(BinOp::Lt, lit(Value::Integer(10)), col("age")));
1601        assert_eq!(
1602            flipped,
1603            Filter::Compare {
1604                field: field("age"),
1605                op: CompareOp::Gt,
1606                value: Value::Integer(10),
1607            }
1608        );
1609
1610        let field_to_field = expr_to_filter(&bin(BinOp::Eq, col("lhs"), col("rhs")));
1611        assert_eq!(
1612            field_to_field,
1613            Filter::CompareFields {
1614                left: field("lhs"),
1615                op: CompareOp::Eq,
1616                right: field("rhs"),
1617            }
1618        );
1619
1620        let arithmetic = expr_to_filter(&bin(BinOp::Add, col("age"), lit(Value::Integer(1))));
1621        assert!(matches!(
1622            arithmetic,
1623            Filter::CompareExpr {
1624                op: CompareOp::Eq,
1625                rhs: Expr::Literal {
1626                    value: Value::Boolean(true),
1627                    ..
1628                },
1629                ..
1630            }
1631        ));
1632
1633        let negated_in = Expr::InList {
1634            target: Box::new(col("status")),
1635            values: vec![lit(Value::text("closed"))],
1636            negated: true,
1637            span: Span::synthetic(),
1638        };
1639        assert!(matches!(
1640            expr_to_filter(&negated_in),
1641            Filter::CompareExpr {
1642                op: CompareOp::Eq,
1643                ..
1644            }
1645        ));
1646    }
1647
1648    #[test]
1649    fn table_effective_helpers_prefer_canonical_expr_fields() {
1650        let mut query = TableQuery::new("users");
1651        query.select_items = vec![
1652            SelectItem::Expr {
1653                expr: col("name"),
1654                alias: Some("display_name".to_string()),
1655            },
1656            SelectItem::Expr {
1657                expr: bin(BinOp::Add, col("age"), lit(Value::Integer(1))),
1658                alias: Some("next_age".to_string()),
1659            },
1660        ];
1661        query.where_expr = Some(bin(BinOp::Eq, col("active"), lit(Value::Boolean(true))));
1662        query.group_by_exprs = vec![col("name")];
1663        query.group_by = vec!["legacy_group".to_string()];
1664        query.having_expr = Some(bin(BinOp::Gt, col("age"), lit(Value::Integer(18))));
1665
1666        let projections = effective_table_projections(&query);
1667        assert_eq!(projections.len(), 2);
1668        assert!(matches!(
1669            &projections[0],
1670            Projection::Field(FieldRef::TableColumn { column, .. }, Some(alias))
1671                if column == "name" && alias == "display_name"
1672        ));
1673
1674        assert!(matches!(
1675            effective_table_filter(&query),
1676            Some(Filter::Compare {
1677                field: FieldRef::TableColumn { column, .. },
1678                op: CompareOp::Eq,
1679                value: Value::Boolean(true)
1680            }) if column == "active"
1681        ));
1682        assert_eq!(effective_table_group_by_exprs(&query), vec![col("name")]);
1683        assert!(matches!(
1684            effective_table_having_filter(&query),
1685            Some(Filter::Compare {
1686                field: FieldRef::TableColumn { column, .. },
1687                op: CompareOp::Gt,
1688                value: Value::Integer(18)
1689            }) if column == "age"
1690        ));
1691
1692        let mut legacy = TableQuery::new("users");
1693        legacy.columns = vec![Projection::column("id")];
1694        legacy.group_by = vec!["tenant_id".to_string()];
1695        assert!(matches!(
1696            effective_table_projections(&legacy).as_slice(),
1697            [Projection::Column(column)] if column == "id"
1698        ));
1699        assert_eq!(
1700            effective_table_group_by_exprs(&legacy),
1701            vec![Expr::Column {
1702                field: field("tenant_id"),
1703                span: Span::synthetic(),
1704            }]
1705        );
1706
1707        let default_projection = TableQuery::new("users");
1708        assert!(matches!(
1709            effective_table_projections(&default_projection).as_slice(),
1710            [Projection::All]
1711        ));
1712    }
1713
1714    #[test]
1715    fn non_table_effective_helpers_preserve_existing_query_fields() {
1716        let mut join = JoinQuery::new(
1717            QueryExpr::Table(TableQuery::new("users")),
1718            QueryExpr::Graph(GraphQuery::new(GraphPattern::new())),
1719            JoinCondition::new(field("id"), FieldRef::node_id("n")),
1720        );
1721        join.filter = Some(Filter::IsNotNull(field("id")));
1722        join.return_items = vec![SelectItem::Expr {
1723            expr: col("name"),
1724            alias: Some("display_name".to_string()),
1725        }];
1726        join.return_ = vec![Projection::Column("legacy_name".to_string())];
1727
1728        assert_eq!(
1729            effective_join_filter(&join),
1730            Some(Filter::IsNotNull(field("id")))
1731        );
1732        assert!(matches!(
1733            effective_join_projections(&join).as_slice(),
1734            [Projection::Field(FieldRef::TableColumn { column, .. }, Some(alias))]
1735                if column == "name" && alias == "display_name"
1736        ));
1737
1738        join.return_items.clear();
1739        assert_eq!(
1740            effective_join_projections(&join),
1741            vec![Projection::Column("legacy_name".to_string())]
1742        );
1743
1744        let graph_filter = Filter::StartsWith {
1745            field: FieldRef::node_prop("n", "path"),
1746            prefix: "infra/".to_string(),
1747        };
1748        let graph_return = vec![Projection::Field(FieldRef::node_prop("n", "name"), None)];
1749        let mut graph = GraphQuery::new(GraphPattern::new());
1750        graph.filter = Some(graph_filter.clone());
1751        graph.return_ = graph_return.clone();
1752        assert_eq!(effective_graph_filter(&graph), Some(graph_filter));
1753        assert_eq!(effective_graph_projections(&graph), graph_return);
1754
1755        let path_filter = Filter::Contains {
1756            field: FieldRef::edge_prop("e", "label"),
1757            substring: "depends".to_string(),
1758        };
1759        let path_return = vec![Projection::Column("path".to_string())];
1760        let mut path = PathQuery::new(NodeSelector::by_id("start"), NodeSelector::by_id("end"));
1761        path.filter = Some(path_filter.clone());
1762        path.return_ = path_return.clone();
1763        assert_eq!(effective_path_filter(&path), Some(path_filter));
1764        assert_eq!(effective_path_projections(&path), path_return);
1765
1766        let mut vector = VectorQuery::new("embeddings", VectorSource::literal(vec![0.1, 0.2]));
1767        assert!(effective_vector_filter(&vector).is_none());
1768        vector.filter = Some(MetadataFilter::eq("source", "nmap"));
1769        assert!(matches!(
1770            effective_vector_filter(&vector),
1771            Some(MetadataFilter::Eq(key, reddb_types::vector_metadata::MetadataValue::String(value)))
1772                if key == "source" && value == "nmap"
1773        ));
1774    }
1775
1776    #[test]
1777    fn insert_update_delete_helpers_fold_canonical_expressions() {
1778        let insert = InsertQuery {
1779            table: "users".to_string(),
1780            entity_type: crate::ast::InsertEntityType::Row,
1781            columns: vec!["name".to_string(), "password".to_string()],
1782            value_exprs: vec![vec![
1783                lit(Value::text("ada")),
1784                Expr::FunctionCall {
1785                    name: "PASSWORD".to_string(),
1786                    args: vec![lit(Value::text("pw"))],
1787                    span: Span::synthetic(),
1788                },
1789            ]],
1790            values: Vec::new(),
1791            on_conflict: None,
1792            returning: None,
1793            ttl_ms: None,
1794            expires_at_ms: None,
1795            with_metadata: Vec::new(),
1796            auto_embed: None,
1797            suppress_events: false,
1798        };
1799        let rows = effective_insert_rows(&insert).unwrap();
1800        assert!(matches!(
1801            rows.as_slice(),
1802            [row] if row[0] == Value::text("ada")
1803                && matches!(&row[1], Value::Password(value) if value == "@@plain@@pw")
1804        ));
1805
1806        let update = UpdateQuery {
1807            table: "users".to_string(),
1808            target: crate::ast::UpdateTarget::Rows,
1809            assignment_exprs: Vec::new(),
1810            compound_assignment_ops: Vec::new(),
1811            assignments: Vec::new(),
1812            where_expr: Some(bin(BinOp::Eq, col("id"), lit(Value::Integer(1)))),
1813            filter: None,
1814            ttl_ms: None,
1815            expires_at_ms: None,
1816            with_metadata: Vec::new(),
1817            returning: None,
1818            order_by: vec![OrderByClause::asc(field("id"))],
1819            limit: Some(1),
1820            claim_limit: None,
1821            claim_exact: false,
1822            suppress_events: false,
1823        };
1824        assert!(matches!(
1825            effective_update_filter(&update),
1826            Some(Filter::Compare {
1827                field: FieldRef::TableColumn { column, .. },
1828                value: Value::Integer(1),
1829                ..
1830            }) if column == "id"
1831        ));
1832
1833        let delete = DeleteQuery {
1834            table: "users".to_string(),
1835            where_expr: Some(Expr::IsNull {
1836                operand: Box::new(col("deleted_at")),
1837                negated: false,
1838                span: Span::synthetic(),
1839            }),
1840            filter: None,
1841            returning: None,
1842            suppress_events: false,
1843        };
1844        assert!(matches!(
1845            effective_delete_filter(&delete),
1846            Some(Filter::IsNull(FieldRef::TableColumn { column, .. })) if column == "deleted_at"
1847        ));
1848    }
1849
1850    #[test]
1851    fn fold_expr_to_value_handles_secret_constructors_unary_and_errors() {
1852        assert_eq!(
1853            fold_expr_to_value(Expr::UnaryOp {
1854                op: UnaryOp::Neg,
1855                operand: Box::new(lit(Value::UnsignedInteger(7))),
1856                span: Span::synthetic(),
1857            })
1858            .unwrap(),
1859            Value::Integer(-7)
1860        );
1861        assert_eq!(
1862            fold_expr_to_value(Expr::UnaryOp {
1863                op: UnaryOp::Not,
1864                operand: Box::new(lit(Value::Boolean(false))),
1865                span: Span::synthetic(),
1866            })
1867            .unwrap(),
1868            Value::Boolean(true)
1869        );
1870
1871        let secret = fold_expr_to_value(Expr::FunctionCall {
1872            name: "SECRET".to_string(),
1873            args: vec![lit(Value::text("token"))],
1874            span: Span::synthetic(),
1875        })
1876        .unwrap();
1877        assert!(matches!(secret, Value::Secret(bytes) if bytes == b"@@plain@@token"));
1878
1879        let casted = fold_expr_to_value(Expr::Cast {
1880            inner: Box::new(lit(Value::Integer(5))),
1881            target: reddb_types::types::DataType::Text,
1882            span: Span::synthetic(),
1883        })
1884        .unwrap();
1885        assert_eq!(casted, Value::Integer(5));
1886
1887        assert!(fold_expr_to_value(bin(BinOp::Add, col("age"), lit(Value::Integer(1)))).is_err());
1888        assert!(fold_expr_to_value(Expr::FunctionCall {
1889            name: "PASSWORD".to_string(),
1890            args: vec![lit(Value::Integer(1))],
1891            span: Span::synthetic(),
1892        })
1893        .is_err());
1894    }
1895
1896    #[test]
1897    fn render_label_and_literal_helpers_cover_private_round_trip_paths() {
1898        assert_eq!(
1899            render_expr_label(&lit(Value::text("O'Reilly"))),
1900            "'O''Reilly'"
1901        );
1902        assert_eq!(render_expr_label(&parameter(4)), "$4");
1903        assert_eq!(
1904            render_expr_label(&bin(
1905                BinOp::Mul,
1906                bin(BinOp::Add, col("a"), col("b")),
1907                col("c")
1908            )),
1909            "(a + b) * c"
1910        );
1911        assert_eq!(
1912            render_expr_label(&Expr::UnaryOp {
1913                op: UnaryOp::Not,
1914                operand: Box::new(col("active")),
1915                span: Span::synthetic(),
1916            }),
1917            "NOT active"
1918        );
1919        assert_eq!(
1920            render_expr_label(&Expr::Cast {
1921                inner: Box::new(col("age")),
1922                target: reddb_types::types::DataType::Text,
1923                span: Span::synthetic(),
1924            }),
1925            "CAST(age AS TEXT)"
1926        );
1927        assert_eq!(
1928            render_expr_label(&Expr::FunctionCall {
1929                name: "lower".to_string(),
1930                args: vec![col("name")],
1931                span: Span::synthetic(),
1932            }),
1933            "lower(name)"
1934        );
1935        assert_eq!(
1936            render_expr_label(&Expr::Case {
1937                branches: vec![(col("active"), lit(Value::text("yes")))],
1938                else_: Some(Box::new(lit(Value::text("no")))),
1939                span: Span::synthetic(),
1940            }),
1941            "CASE WHEN active THEN 'yes' ELSE 'no' END"
1942        );
1943        assert_eq!(
1944            render_expr_label(&Expr::IsNull {
1945                operand: Box::new(col("deleted_at")),
1946                negated: true,
1947                span: Span::synthetic(),
1948            }),
1949            "deleted_at IS NOT NULL"
1950        );
1951        assert_eq!(
1952            render_expr_label(&Expr::InList {
1953                target: Box::new(col("status")),
1954                values: vec![lit(Value::text("closed"))],
1955                negated: true,
1956                span: Span::synthetic(),
1957            }),
1958            "status NOT IN ('closed')"
1959        );
1960        assert_eq!(
1961            render_expr_label(&Expr::Between {
1962                target: Box::new(col("age")),
1963                low: Box::new(lit(Value::Integer(18))),
1964                high: Box::new(lit(Value::Integer(65))),
1965                negated: false,
1966                span: Span::synthetic(),
1967            }),
1968            "age BETWEEN 18 AND 65"
1969        );
1970        assert_eq!(
1971            render_expr_label(&Expr::Subquery {
1972                query: crate::ast::ExprSubquery {
1973                    query: Box::new(QueryExpr::Table(TableQuery::new("users"))),
1974                },
1975                span: Span::synthetic(),
1976            }),
1977            "subquery"
1978        );
1979        assert_eq!(
1980            render_expr_label(&Expr::WindowFunctionCall {
1981                name: "sum".to_string(),
1982                args: vec![col("amount")],
1983                window: WindowSpec::default(),
1984                span: Span::synthetic(),
1985            }),
1986            "sum(amount) OVER (...)"
1987        );
1988
1989        assert_eq!(render_field_label(&FieldRef::node_id("n")), "n.id");
1990        assert_eq!(
1991            render_field_label(&FieldRef::edge_prop("e", "weight")),
1992            "e.weight"
1993        );
1994        assert_eq!(render_binop_label(BinOp::Concat), "||");
1995        assert_eq!(render_sql_literal_label(&Value::Float(3.0)), "3");
1996        assert_eq!(
1997            render_projection_literal(&Value::Array(vec![Value::Integer(1), Value::text("x"),])),
1998            "@RL:[1,\"x\"]"
1999        );
2000        assert_eq!(
2001            render_projection_literal(&Value::Vector(vec![1.0, 2.5])),
2002            "@RL:V[1,2.5]"
2003        );
2004        assert_eq!(
2005            render_projection_literal(&Value::Json(br#"{"a":1}"#.to_vec())),
2006            "@RL:\"<json 7 bytes>\""
2007        );
2008        assert!(matches!(
2009            projection_from_literal(&Value::Boolean(true)),
2010            Some(Projection::Expression(_, None))
2011        ));
2012        assert_eq!(
2013            split_projection_function_alias("LOWER:name").1.as_deref(),
2014            Some("name")
2015        );
2016        assert_eq!(split_projection_function_alias(":bad").1, None);
2017    }
2018
2019    #[test]
2020    fn lowering_fallbacks_cover_alias_legacy_and_non_specialized_paths() {
2021        for (op, name) in [
2022            (BinOp::Sub, "SUB"),
2023            (BinOp::Div, "DIV"),
2024            (BinOp::Mod, "MOD"),
2025            (BinOp::Concat, "CONCAT"),
2026        ] {
2027            assert!(matches!(
2028                expr_to_projection(&bin(op, col("lhs"), col("rhs"))),
2029                Some(Projection::Function(function, args))
2030                    if function == name && args.len() == 2
2031            ));
2032        }
2033
2034        assert!(matches!(
2035            select_item_to_projection(&SelectItem::Expr {
2036                expr: lit(Value::Integer(1)),
2037                alias: Some("one".to_string()),
2038            }),
2039            Some(Projection::Alias(column, alias)) if column == "LIT:1" && alias == "one"
2040        ));
2041        assert!(matches!(
2042            select_item_to_projection(&SelectItem::Expr {
2043                expr: Expr::UnaryOp {
2044                    op: UnaryOp::Not,
2045                    operand: Box::new(col("active")),
2046                    span: Span::synthetic(),
2047                },
2048                alias: Some("inactive".to_string()),
2049            }),
2050            Some(Projection::Expression(_, Some(alias))) if alias == "inactive"
2051        ));
2052
2053        let legacy_insert = InsertQuery {
2054            table: "users".to_string(),
2055            entity_type: crate::ast::InsertEntityType::Row,
2056            columns: vec!["id".to_string()],
2057            value_exprs: Vec::new(),
2058            values: vec![vec![Value::Integer(1)]],
2059            on_conflict: None,
2060            returning: None,
2061            ttl_ms: None,
2062            expires_at_ms: None,
2063            with_metadata: Vec::new(),
2064            auto_embed: None,
2065            suppress_events: false,
2066        };
2067        assert_eq!(
2068            effective_insert_rows(&legacy_insert).unwrap(),
2069            vec![vec![Value::Integer(1)]]
2070        );
2071
2072        assert!(matches!(
2073            expr_to_filter(&Expr::IsNull {
2074                operand: Box::new(lit(Value::Null)),
2075                negated: false,
2076                span: Span::synthetic(),
2077            }),
2078            Filter::CompareExpr { .. }
2079        ));
2080        assert!(matches!(
2081            expr_to_filter(&Expr::InList {
2082                target: Box::new(col("status")),
2083                values: vec![col("other_status")],
2084                negated: false,
2085                span: Span::synthetic(),
2086            }),
2087            Filter::CompareExpr { .. }
2088        ));
2089        assert!(matches!(
2090            expr_to_filter(&Expr::Between {
2091                target: Box::new(col("age")),
2092                low: Box::new(lit(Value::Integer(18))),
2093                high: Box::new(lit(Value::Integer(65))),
2094                negated: true,
2095                span: Span::synthetic(),
2096            }),
2097            Filter::CompareExpr { .. }
2098        ));
2099        assert!(matches!(
2100            expr_to_filter(&Expr::FunctionCall {
2101                name: "UNKNOWN".to_string(),
2102                args: vec![col("name"), lit(Value::text("a"))],
2103                span: Span::synthetic(),
2104            }),
2105            Filter::CompareExpr { .. }
2106        ));
2107        assert!(matches!(
2108            expr_to_filter(&Expr::FunctionCall {
2109                name: "LIKE".to_string(),
2110                args: vec![lit(Value::text("not_field")), lit(Value::text("a"))],
2111                span: Span::synthetic(),
2112            }),
2113            Filter::CompareExpr { .. }
2114        ));
2115
2116        assert_eq!(
2117            fold_expr_to_value(Expr::UnaryOp {
2118                op: UnaryOp::Neg,
2119                operand: Box::new(lit(Value::Float(1.5))),
2120                span: Span::synthetic(),
2121            })
2122            .unwrap(),
2123            Value::Float(-1.5)
2124        );
2125        assert!(fold_expr_to_value(Expr::UnaryOp {
2126            op: UnaryOp::Not,
2127            operand: Box::new(lit(Value::Integer(1))),
2128            span: Span::synthetic(),
2129        })
2130        .is_err());
2131        assert!(fold_expr_to_value(Expr::FunctionCall {
2132            name: "LOWER".to_string(),
2133            args: vec![lit(Value::text("Ada"))],
2134            span: Span::synthetic(),
2135        })
2136        .is_err());
2137
2138        assert_eq!(render_projection_literal(&Value::Null), "");
2139        assert_eq!(render_projection_literal(&Value::UnsignedInteger(7)), "7");
2140        assert_eq!(render_projection_literal(&Value::Boolean(false)), "false");
2141        assert_eq!(
2142            render_projection_literal(&Value::Blob(vec![1, 2, 3])),
2143            "@RL:\"<blob 3 bytes>\""
2144        );
2145        assert_eq!(serialize_value_json(&Value::Null), "null");
2146    }
2147    #[test]
2148    fn secret_projection_literals_preserve_ciphertext_and_type() {
2149        let secret = Value::Secret(vec![1, 2, 3, 4]);
2150        let projection = projection_from_literal(&secret).expect("projection");
2151        let (expression, alias) = projection_to_expr(&projection).expect("typed literal");
2152        assert_eq!(expression, Expr::lit(secret));
2153        assert_eq!(alias, None);
2154        assert!(projection_to_expr(&Projection::Function(
2155            "__SECRET_LITERAL".into(),
2156            vec![Projection::Column("LIT:plaintext".into())],
2157        ))
2158        .is_none());
2159
2160        for (value, expected) in [
2161            (Value::Integer(8), "LIT:8"),
2162            (Value::text("ordinary"), "LIT:ordinary"),
2163            (Value::Null, "LIT:"),
2164        ] {
2165            assert_eq!(
2166                projection_from_literal(&value),
2167                Some(Projection::Column(expected.into()))
2168            );
2169        }
2170    }
2171    #[test]
2172    fn case_projection_roundtrip_preserves_nested_case_secret_literals_and_aliases() {
2173        let nested = Expr::Case {
2174            branches: vec![(col("flag"), lit(Value::Secret(vec![1, 2, 3])))],
2175            else_: Some(Box::new(lit(Value::text("fallback")))),
2176            span: Span::synthetic(),
2177        };
2178        for else_ in [None, Some(Box::new(lit(Value::Null)))] {
2179            let expression = Expr::Case {
2180                branches: vec![
2181                    (
2182                        bin(BinOp::Eq, col("id"), lit(Value::Integer(1))),
2183                        nested.clone(),
2184                    ),
2185                    (lit(Value::Boolean(false)), lit(Value::Integer(42))),
2186                ],
2187                else_,
2188                span: Span::synthetic(),
2189            };
2190            let mut projection = expr_to_projection(&expression).expect("CASE projection");
2191            let Projection::Function(name, _) = &mut projection else {
2192                panic!("CASE projection must have its legacy function carrier");
2193            };
2194            name.push_str(":result");
2195            let (actual, alias) = projection_to_expr(&projection).expect("CASE expression");
2196            assert_eq!(actual, expression);
2197            assert_eq!(alias.as_deref(), Some("result"));
2198        }
2199        assert!(projection_to_expr(&Projection::Function(
2200            "CASE".into(),
2201            vec![Projection::Column("LIT:invalid".into())],
2202        ))
2203        .is_none());
2204    }
2205}