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