Skip to main content

reddb_engine/query/planning/
shape.rs

1use reddb_rql::ast::{
2    Expr, FusionStrategy, GraphPattern, GraphQuery, HybridQuery, JoinQuery, NodePattern,
3    NodeSelector, OrderByClause, PathQuery, Projection, PropertyFilter, QueryExpr, SelectItem,
4    TableQuery, TableSource, VectorQuery, VectorSource,
5};
6use reddb_rql::sql_lowering::{
7    expr_to_filter, filter_to_expr, projection_from_literal, PARAMETER_PROJECTION_PREFIX,
8};
9use reddb_types::vector_metadata::{MetadataFilter, MetadataValue};
10use reddb_types::Value;
11
12const PROJECTION_PARAM_PREFIX: &str = "__shape_projection_param__:";
13const STRING_PARAM_PREFIX: &str = "__shape_string_param__:";
14const VALUE_PARAM_PREFIX: &str = "__shape_value_param__:";
15const ROW_SELECTOR_TABLE_PREFIX: &str = "__shape_row_selector__:";
16const METADATA_VALUE_PARAM_PREFIX: &str = "__shape_metadata_value_param__:";
17const VECTOR_TEXT_PARAM_PREFIX: &str = "__shape_vector_text_param__:";
18const VECTOR_REF_ID_PREFIX: &str = "__shape_vector_ref_id__:";
19const FLOAT32_PARAM_BITS_BASE: u32 = 0x7fc0_0000;
20const FLOAT64_PARAM_BITS_BASE: u64 = 0x7ff8_0000_0000_0000;
21const U32_PARAM_BASE: u32 = 0xfff0_0000;
22
23#[derive(Debug, Clone)]
24pub struct ParameterizedQuery {
25    pub shape: QueryExpr,
26    pub parameter_count: usize,
27}
28
29pub fn parameterize_query_expr(expr: &QueryExpr) -> Option<ParameterizedQuery> {
30    let mut next_index = 0usize;
31    let shape = parameterize_query_expr_inner(expr, &mut next_index)?;
32    Some(ParameterizedQuery {
33        shape,
34        parameter_count: next_index,
35    })
36}
37
38/// Bind user-supplied positional `$N` parameters into a freshly-parsed
39/// query expression. Unlike [`bind_parameterized_query`] — which is the
40/// other half of the auto-parameterized prepared-statement shape cache —
41/// this entry point assumes the parser already emitted `Expr::Parameter`
42/// nodes (one per `$N` reference) and just substitutes them in place.
43///
44/// Validation (arity, gaps) is performed by `user_params::validate`
45/// before this call; here we trust the slice indexes match the parser's
46/// 0-based slot numbering.
47pub fn bind_user_param_query(expr: &QueryExpr, params: &[Value]) -> Option<QueryExpr> {
48    bind_query_expr_inner(expr, params)
49}
50
51pub fn bind_parameterized_query(
52    expr: &QueryExpr,
53    binds: &[Value],
54    parameter_count: usize,
55) -> Option<QueryExpr> {
56    if binds.len() != parameter_count {
57        return None;
58    }
59    bind_query_expr_inner(expr, binds)
60}
61
62fn parameterize_query_expr_inner(expr: &QueryExpr, next_index: &mut usize) -> Option<QueryExpr> {
63    match expr {
64        QueryExpr::Table(query) => Some(QueryExpr::Table(parameterize_table_query(
65            query, next_index,
66        )?)),
67        QueryExpr::Join(query) => {
68            Some(QueryExpr::Join(parameterize_join_query(query, next_index)?))
69        }
70        QueryExpr::Graph(query) => Some(QueryExpr::Graph(parameterize_graph_query(
71            query, next_index,
72        )?)),
73        QueryExpr::Path(query) => {
74            Some(QueryExpr::Path(parameterize_path_query(query, next_index)?))
75        }
76        QueryExpr::Vector(query) => Some(QueryExpr::Vector(parameterize_vector_query(
77            query, next_index,
78        )?)),
79        QueryExpr::Hybrid(query) => Some(QueryExpr::Hybrid(parameterize_hybrid_query(
80            query, next_index,
81        )?)),
82        _ => None,
83    }
84}
85
86fn parameterize_table_query(query: &TableQuery, next_index: &mut usize) -> Option<TableQuery> {
87    // DESCRIBE/SHOW CREATE carry the identifier as a synthetic filter literal.
88    // It has no matching SQL literal for the cache hit's lexer to rebind, and
89    // their catalog readers require that filter, not a parameterized WHERE.
90    if [
91        "red.describe",
92        "__red_schema_describe",
93        "red.show_create",
94        "__red_schema_show_create",
95    ]
96    .iter()
97    .any(|name| query.table.eq_ignore_ascii_case(name))
98    {
99        return None;
100    }
101    let source = match &query.source {
102        Some(TableSource::Name(name)) => Some(TableSource::Name(name.clone())),
103        Some(TableSource::Subquery(inner)) => Some(TableSource::Subquery(Box::new(
104            parameterize_query_expr_inner(inner, next_index)?,
105        ))),
106        // Table-valued functions have no parameterizable subexpressions
107        // (identifier args only); preserve them verbatim (issue #795). The
108        // inline-graph form (issue #799) is likewise preserved verbatim — its
109        // subquery literals are not lifted into plan parameters.
110        Some(other @ (TableSource::Function { .. } | TableSource::InlineGraphFunction { .. })) => {
111            Some(other.clone())
112        }
113        None => None,
114    };
115
116    let select_items = query
117        .select_items
118        .iter()
119        .map(|item| parameterize_select_item(item, next_index))
120        .collect::<Option<Vec<_>>>()?;
121
122    let where_expr = query
123        .where_expr
124        .as_ref()
125        .map(|expr| parameterize_expr(expr, next_index))
126        .or_else(|| {
127            query
128                .filter
129                .as_ref()
130                .map(|filter| parameterize_expr(&filter_to_expr(filter), next_index))
131        });
132
133    let group_by_exprs = if !query.group_by_exprs.is_empty() {
134        query
135            .group_by_exprs
136            .iter()
137            .map(|expr| parameterize_expr(expr, next_index))
138            .collect()
139    } else {
140        Vec::new()
141    };
142
143    let having_expr = query
144        .having_expr
145        .as_ref()
146        .map(|expr| parameterize_expr(expr, next_index))
147        .or_else(|| {
148            query
149                .having
150                .as_ref()
151                .map(|filter| parameterize_expr(&filter_to_expr(filter), next_index))
152        });
153
154    let order_by = query
155        .order_by
156        .iter()
157        .map(|clause| parameterize_order_by(clause, next_index))
158        .collect::<Option<Vec<_>>>()?;
159
160    Some(TableQuery {
161        table: query.table.clone(),
162        source,
163        alias: query.alias.clone(),
164        select_items,
165        columns: Vec::new(),
166        where_expr,
167        filter: None,
168        group_by_exprs,
169        group_by: Vec::new(),
170        having_expr,
171        having: None,
172        order_by,
173        limit: query.limit,
174        limit_param: query.limit_param,
175        offset: query.offset,
176        offset_param: query.offset_param,
177        expand: query.expand.clone(),
178        as_of: query.as_of.clone(),
179        sessionize: query.sessionize.clone(),
180        distinct: query.distinct,
181    })
182}
183
184fn parameterize_select_item(item: &SelectItem, next_index: &mut usize) -> Option<SelectItem> {
185    match item {
186        SelectItem::Wildcard => Some(SelectItem::Wildcard),
187        SelectItem::Expr { expr, alias } => Some(SelectItem::Expr {
188            expr: parameterize_expr(expr, next_index),
189            alias: alias.clone(),
190        }),
191    }
192}
193
194fn parameterize_order_by(clause: &OrderByClause, next_index: &mut usize) -> Option<OrderByClause> {
195    Some(OrderByClause {
196        field: clause.field.clone(),
197        expr: clause
198            .expr
199            .as_ref()
200            .map(|expr| parameterize_expr(expr, next_index)),
201        ascending: clause.ascending,
202        nulls_first: clause.nulls_first,
203    })
204}
205
206fn parameterize_expr(expr: &Expr, next_index: &mut usize) -> Expr {
207    match expr {
208        Expr::Literal { value, span } => {
209            let index = *next_index;
210            *next_index += 1;
211            let _ = value;
212            Expr::Parameter { index, span: *span }
213        }
214        Expr::Column { .. } | Expr::Parameter { .. } => expr.clone(),
215        Expr::BinaryOp { op, lhs, rhs, span } => Expr::BinaryOp {
216            op: *op,
217            lhs: Box::new(parameterize_expr(lhs, next_index)),
218            rhs: Box::new(parameterize_expr(rhs, next_index)),
219            span: *span,
220        },
221        Expr::UnaryOp { op, operand, span } => Expr::UnaryOp {
222            op: *op,
223            operand: Box::new(parameterize_expr(operand, next_index)),
224            span: *span,
225        },
226        Expr::Cast {
227            inner,
228            target,
229            span,
230        } => Expr::Cast {
231            inner: Box::new(parameterize_expr(inner, next_index)),
232            target: *target,
233            span: *span,
234        },
235        Expr::FunctionCall { name, args, span } => Expr::FunctionCall {
236            name: name.clone(),
237            args: args
238                .iter()
239                .map(|arg| parameterize_expr(arg, next_index))
240                .collect(),
241            span: *span,
242        },
243        Expr::Case {
244            branches,
245            else_,
246            span,
247        } => Expr::Case {
248            branches: branches
249                .iter()
250                .map(|(cond, value)| {
251                    (
252                        parameterize_expr(cond, next_index),
253                        parameterize_expr(value, next_index),
254                    )
255                })
256                .collect(),
257            else_: else_
258                .as_ref()
259                .map(|expr| Box::new(parameterize_expr(expr, next_index))),
260            span: *span,
261        },
262        Expr::IsNull {
263            operand,
264            negated,
265            span,
266        } => Expr::IsNull {
267            operand: Box::new(parameterize_expr(operand, next_index)),
268            negated: *negated,
269            span: *span,
270        },
271        Expr::InList {
272            target,
273            values,
274            negated,
275            span,
276        } => Expr::InList {
277            target: Box::new(parameterize_expr(target, next_index)),
278            values: values
279                .iter()
280                .map(|value| parameterize_expr(value, next_index))
281                .collect(),
282            negated: *negated,
283            span: *span,
284        },
285        Expr::Between {
286            target,
287            low,
288            high,
289            negated,
290            span,
291        } => Expr::Between {
292            target: Box::new(parameterize_expr(target, next_index)),
293            low: Box::new(parameterize_expr(low, next_index)),
294            high: Box::new(parameterize_expr(high, next_index)),
295            negated: *negated,
296            span: *span,
297        },
298        Expr::Subquery { .. } => expr.clone(),
299        // Slice 7a (#589): preserve WindowFunctionCall shape unchanged
300        // for parameterization. The slice only ships parser/AST, so
301        // there are no parameter substitutions to thread through yet.
302        Expr::WindowFunctionCall { .. } => expr.clone(),
303    }
304}
305
306fn bind_query_expr_inner(expr: &QueryExpr, binds: &[Value]) -> Option<QueryExpr> {
307    match expr {
308        QueryExpr::Table(query) => Some(QueryExpr::Table(bind_table_query(query, binds)?)),
309        QueryExpr::Join(query) => Some(QueryExpr::Join(bind_join_query(query, binds)?)),
310        QueryExpr::Graph(query) => Some(QueryExpr::Graph(bind_graph_query(query, binds)?)),
311        QueryExpr::Path(query) => Some(QueryExpr::Path(bind_path_query(query, binds)?)),
312        QueryExpr::Vector(query) => Some(QueryExpr::Vector(bind_vector_query(query, binds)?)),
313        QueryExpr::Hybrid(query) => Some(QueryExpr::Hybrid(bind_hybrid_query(query, binds)?)),
314        _ => None,
315    }
316}
317
318fn parameterize_vector_query(query: &VectorQuery, next_index: &mut usize) -> Option<VectorQuery> {
319    Some(VectorQuery {
320        mode: query.mode,
321        alias: query.alias.clone(),
322        collection: query.collection.clone(),
323        query_vector: parameterize_vector_source(&query.query_vector, next_index)?,
324        k: query.k,
325        filter: query
326            .filter
327            .as_ref()
328            .map(|filter| parameterize_metadata_filter(filter, next_index)),
329        metric: query.metric,
330        include_vectors: query.include_vectors,
331        include_metadata: query.include_metadata,
332        threshold: query
333            .threshold
334            .map(|_| encode_f32_placeholder(allocate_param_index(next_index))),
335    })
336}
337
338fn bind_vector_query(query: &VectorQuery, binds: &[Value]) -> Option<VectorQuery> {
339    Some(VectorQuery {
340        mode: query.mode,
341        alias: query.alias.clone(),
342        collection: query.collection.clone(),
343        query_vector: bind_vector_source(&query.query_vector, binds)?,
344        k: query.k,
345        filter: query
346            .filter
347            .as_ref()
348            .and_then(|filter| bind_metadata_filter(filter, binds)),
349        metric: query.metric,
350        include_vectors: query.include_vectors,
351        include_metadata: query.include_metadata,
352        threshold: query
353            .threshold
354            .and_then(|value| bind_placeholder_f32(value, binds)),
355    })
356}
357
358fn parameterize_hybrid_query(query: &HybridQuery, next_index: &mut usize) -> Option<HybridQuery> {
359    Some(HybridQuery {
360        alias: query.alias.clone(),
361        structured: Box::new(parameterize_query_expr_inner(
362            &query.structured,
363            next_index,
364        )?),
365        vector: parameterize_vector_query(&query.vector, next_index)?,
366        fusion: parameterize_fusion_strategy(&query.fusion, next_index),
367        limit: query.limit,
368    })
369}
370
371fn bind_hybrid_query(query: &HybridQuery, binds: &[Value]) -> Option<HybridQuery> {
372    Some(HybridQuery {
373        alias: query.alias.clone(),
374        structured: Box::new(bind_query_expr_inner(&query.structured, binds)?),
375        vector: bind_vector_query(&query.vector, binds)?,
376        fusion: bind_fusion_strategy(&query.fusion, binds)?,
377        limit: query.limit,
378    })
379}
380
381fn parameterize_vector_source(
382    source: &VectorSource,
383    next_index: &mut usize,
384) -> Option<VectorSource> {
385    match source {
386        VectorSource::Literal(values) => Some(VectorSource::Literal(
387            values
388                .iter()
389                .map(|_| encode_f32_placeholder(allocate_param_index(next_index)))
390                .collect(),
391        )),
392        VectorSource::Text(_) => Some(VectorSource::Text(format!(
393            "{VECTOR_TEXT_PARAM_PREFIX}{}",
394            allocate_param_index(next_index)
395        ))),
396        VectorSource::Reference { collection, .. } => Some(VectorSource::Reference {
397            collection: format!(
398                "{VECTOR_REF_ID_PREFIX}{}:{collection}",
399                allocate_param_index(next_index)
400            ),
401            vector_id: 0,
402        }),
403        VectorSource::Subquery(expr) => Some(VectorSource::Subquery(Box::new(
404            parameterize_query_expr_inner(expr, next_index)?,
405        ))),
406    }
407}
408
409fn bind_vector_source(source: &VectorSource, binds: &[Value]) -> Option<VectorSource> {
410    match source {
411        VectorSource::Literal(values) => Some(VectorSource::Literal(
412            values
413                .iter()
414                .map(|value| bind_placeholder_f32(*value, binds))
415                .collect::<Option<Vec<_>>>()?,
416        )),
417        VectorSource::Text(text) => {
418            if let Some(index) = parse_placeholder_index(text, VECTOR_TEXT_PARAM_PREFIX) {
419                Some(VectorSource::Text(bind_value_to_string(binds.get(index)?)?))
420            } else {
421                Some(VectorSource::Text(text.clone()))
422            }
423        }
424        VectorSource::Reference {
425            collection,
426            vector_id,
427        } => {
428            if let Some((index, original_collection)) =
429                parse_prefixed_index_with_suffix(collection, VECTOR_REF_ID_PREFIX)
430            {
431                Some(VectorSource::Reference {
432                    collection: original_collection.to_string(),
433                    vector_id: bind_value_to_u64(binds.get(index)?)?,
434                })
435            } else {
436                Some(VectorSource::Reference {
437                    collection: collection.clone(),
438                    vector_id: *vector_id,
439                })
440            }
441        }
442        VectorSource::Subquery(expr) => Some(VectorSource::Subquery(Box::new(
443            bind_query_expr_inner(expr, binds)?,
444        ))),
445    }
446}
447
448fn parameterize_fusion_strategy(fusion: &FusionStrategy, next_index: &mut usize) -> FusionStrategy {
449    match fusion {
450        FusionStrategy::Rerank { .. } => FusionStrategy::Rerank {
451            weight: encode_f32_placeholder(allocate_param_index(next_index)),
452        },
453        FusionStrategy::FilterThenSearch => FusionStrategy::FilterThenSearch,
454        FusionStrategy::SearchThenFilter => FusionStrategy::SearchThenFilter,
455        FusionStrategy::RRF { .. } => FusionStrategy::RRF {
456            k: encode_u32_placeholder(allocate_param_index(next_index)),
457        },
458        FusionStrategy::Intersection => FusionStrategy::Intersection,
459        FusionStrategy::Union { .. } => FusionStrategy::Union {
460            structured_weight: encode_f32_placeholder(allocate_param_index(next_index)),
461            vector_weight: encode_f32_placeholder(allocate_param_index(next_index)),
462        },
463    }
464}
465
466fn bind_fusion_strategy(fusion: &FusionStrategy, binds: &[Value]) -> Option<FusionStrategy> {
467    match fusion {
468        FusionStrategy::Rerank { weight } => Some(FusionStrategy::Rerank {
469            weight: bind_placeholder_f32(*weight, binds)?,
470        }),
471        FusionStrategy::FilterThenSearch => Some(FusionStrategy::FilterThenSearch),
472        FusionStrategy::SearchThenFilter => Some(FusionStrategy::SearchThenFilter),
473        FusionStrategy::RRF { k } => Some(FusionStrategy::RRF {
474            k: bind_placeholder_u32(*k, binds)?,
475        }),
476        FusionStrategy::Intersection => Some(FusionStrategy::Intersection),
477        FusionStrategy::Union {
478            structured_weight,
479            vector_weight,
480        } => Some(FusionStrategy::Union {
481            structured_weight: bind_placeholder_f32(*structured_weight, binds)?,
482            vector_weight: bind_placeholder_f32(*vector_weight, binds)?,
483        }),
484    }
485}
486
487fn parameterize_metadata_filter(filter: &MetadataFilter, next_index: &mut usize) -> MetadataFilter {
488    match filter {
489        MetadataFilter::Eq(key, value) => {
490            MetadataFilter::Eq(key.clone(), parameterize_metadata_value(value, next_index))
491        }
492        MetadataFilter::Ne(key, value) => {
493            MetadataFilter::Ne(key.clone(), parameterize_metadata_value(value, next_index))
494        }
495        MetadataFilter::Gt(key, value) => {
496            MetadataFilter::Gt(key.clone(), parameterize_metadata_value(value, next_index))
497        }
498        MetadataFilter::Gte(key, value) => {
499            MetadataFilter::Gte(key.clone(), parameterize_metadata_value(value, next_index))
500        }
501        MetadataFilter::Lt(key, value) => {
502            MetadataFilter::Lt(key.clone(), parameterize_metadata_value(value, next_index))
503        }
504        MetadataFilter::Lte(key, value) => {
505            MetadataFilter::Lte(key.clone(), parameterize_metadata_value(value, next_index))
506        }
507        MetadataFilter::In(key, values) => MetadataFilter::In(
508            key.clone(),
509            values
510                .iter()
511                .map(|value| parameterize_metadata_value(value, next_index))
512                .collect(),
513        ),
514        MetadataFilter::NotIn(key, values) => MetadataFilter::NotIn(
515            key.clone(),
516            values
517                .iter()
518                .map(|value| parameterize_metadata_value(value, next_index))
519                .collect(),
520        ),
521        MetadataFilter::Contains(_, _) => MetadataFilter::Contains(
522            match filter {
523                MetadataFilter::Contains(key, _) => key.clone(),
524                _ => unreachable!(),
525            },
526            format!("{STRING_PARAM_PREFIX}{}", allocate_param_index(next_index)),
527        ),
528        MetadataFilter::StartsWith(_, _) => MetadataFilter::StartsWith(
529            match filter {
530                MetadataFilter::StartsWith(key, _) => key.clone(),
531                _ => unreachable!(),
532            },
533            format!("{STRING_PARAM_PREFIX}{}", allocate_param_index(next_index)),
534        ),
535        MetadataFilter::EndsWith(_, _) => MetadataFilter::EndsWith(
536            match filter {
537                MetadataFilter::EndsWith(key, _) => key.clone(),
538                _ => unreachable!(),
539            },
540            format!("{STRING_PARAM_PREFIX}{}", allocate_param_index(next_index)),
541        ),
542        MetadataFilter::GeoRadius {
543            key,
544            center_lat,
545            center_lon,
546            radius_km,
547        } => MetadataFilter::GeoRadius {
548            key: key.clone(),
549            center_lat: parameterize_f64(*center_lat, next_index),
550            center_lon: parameterize_f64(*center_lon, next_index),
551            radius_km: parameterize_f64(*radius_km, next_index),
552        },
553        MetadataFilter::Exists(key) => MetadataFilter::Exists(key.clone()),
554        MetadataFilter::NotExists(key) => MetadataFilter::NotExists(key.clone()),
555        MetadataFilter::And(filters) => MetadataFilter::And(
556            filters
557                .iter()
558                .map(|filter| parameterize_metadata_filter(filter, next_index))
559                .collect(),
560        ),
561        MetadataFilter::Or(filters) => MetadataFilter::Or(
562            filters
563                .iter()
564                .map(|filter| parameterize_metadata_filter(filter, next_index))
565                .collect(),
566        ),
567        MetadataFilter::Not(inner) => {
568            MetadataFilter::Not(Box::new(parameterize_metadata_filter(inner, next_index)))
569        }
570    }
571}
572
573fn bind_metadata_filter(filter: &MetadataFilter, binds: &[Value]) -> Option<MetadataFilter> {
574    match filter {
575        MetadataFilter::Eq(key, value) => Some(MetadataFilter::Eq(
576            key.clone(),
577            bind_metadata_value(value, binds)?,
578        )),
579        MetadataFilter::Ne(key, value) => Some(MetadataFilter::Ne(
580            key.clone(),
581            bind_metadata_value(value, binds)?,
582        )),
583        MetadataFilter::Gt(key, value) => Some(MetadataFilter::Gt(
584            key.clone(),
585            bind_metadata_value(value, binds)?,
586        )),
587        MetadataFilter::Gte(key, value) => Some(MetadataFilter::Gte(
588            key.clone(),
589            bind_metadata_value(value, binds)?,
590        )),
591        MetadataFilter::Lt(key, value) => Some(MetadataFilter::Lt(
592            key.clone(),
593            bind_metadata_value(value, binds)?,
594        )),
595        MetadataFilter::Lte(key, value) => Some(MetadataFilter::Lte(
596            key.clone(),
597            bind_metadata_value(value, binds)?,
598        )),
599        MetadataFilter::In(key, values) => Some(MetadataFilter::In(
600            key.clone(),
601            values
602                .iter()
603                .map(|value| bind_metadata_value(value, binds))
604                .collect::<Option<Vec<_>>>()?,
605        )),
606        MetadataFilter::NotIn(key, values) => Some(MetadataFilter::NotIn(
607            key.clone(),
608            values
609                .iter()
610                .map(|value| bind_metadata_value(value, binds))
611                .collect::<Option<Vec<_>>>()?,
612        )),
613        MetadataFilter::Contains(key, value) => Some(MetadataFilter::Contains(
614            key.clone(),
615            bind_placeholder_string(value, binds)?.unwrap_or_default(),
616        )),
617        MetadataFilter::StartsWith(key, value) => Some(MetadataFilter::StartsWith(
618            key.clone(),
619            bind_placeholder_string(value, binds)?.unwrap_or_default(),
620        )),
621        MetadataFilter::EndsWith(key, value) => Some(MetadataFilter::EndsWith(
622            key.clone(),
623            bind_placeholder_string(value, binds)?.unwrap_or_default(),
624        )),
625        MetadataFilter::GeoRadius {
626            key,
627            center_lat,
628            center_lon,
629            radius_km,
630        } => Some(MetadataFilter::GeoRadius {
631            key: key.clone(),
632            center_lat: bind_placeholder_f64(*center_lat, binds)?,
633            center_lon: bind_placeholder_f64(*center_lon, binds)?,
634            radius_km: bind_placeholder_f64(*radius_km, binds)?,
635        }),
636        MetadataFilter::Exists(key) => Some(MetadataFilter::Exists(key.clone())),
637        MetadataFilter::NotExists(key) => Some(MetadataFilter::NotExists(key.clone())),
638        MetadataFilter::And(filters) => Some(MetadataFilter::And(
639            filters
640                .iter()
641                .map(|filter| bind_metadata_filter(filter, binds))
642                .collect::<Option<Vec<_>>>()?,
643        )),
644        MetadataFilter::Or(filters) => Some(MetadataFilter::Or(
645            filters
646                .iter()
647                .map(|filter| bind_metadata_filter(filter, binds))
648                .collect::<Option<Vec<_>>>()?,
649        )),
650        MetadataFilter::Not(inner) => Some(MetadataFilter::Not(Box::new(bind_metadata_filter(
651            inner, binds,
652        )?))),
653    }
654}
655
656fn parameterize_metadata_value(_value: &MetadataValue, next_index: &mut usize) -> MetadataValue {
657    MetadataValue::String(format!(
658        "{METADATA_VALUE_PARAM_PREFIX}{}",
659        allocate_param_index(next_index)
660    ))
661}
662
663fn bind_metadata_value(value: &MetadataValue, binds: &[Value]) -> Option<MetadataValue> {
664    match value {
665        MetadataValue::String(text) => {
666            if let Some(index) = parse_placeholder_index(text, METADATA_VALUE_PARAM_PREFIX) {
667                Some(bind_value_to_metadata_value(binds.get(index)?)?)
668            } else {
669                Some(MetadataValue::String(text.clone()))
670            }
671        }
672        other => Some(other.clone()),
673    }
674}
675
676fn parameterize_join_query(query: &JoinQuery, next_index: &mut usize) -> Option<JoinQuery> {
677    Some(JoinQuery {
678        left: Box::new(parameterize_query_expr_inner(&query.left, next_index)?),
679        right: Box::new(parameterize_query_expr_inner(&query.right, next_index)?),
680        join_type: query.join_type,
681        on: query.on.clone(),
682        group_by: query.group_by.clone(),
683        having: query
684            .having
685            .as_ref()
686            .map(|expr| parameterize_expr(expr, next_index)),
687        filter: query
688            .filter
689            .as_ref()
690            .map(|filter| parameterize_filter(filter, next_index)),
691        order_by: query
692            .order_by
693            .iter()
694            .map(|clause| parameterize_order_by(clause, next_index))
695            .collect::<Option<Vec<_>>>()?,
696        limit: query.limit,
697        offset: query.offset,
698        return_items: query
699            .return_items
700            .iter()
701            .map(|item| parameterize_select_item(item, next_index))
702            .collect::<Option<Vec<_>>>()?,
703        return_: query
704            .return_
705            .iter()
706            .map(|projection| parameterize_projection(projection, next_index))
707            .collect::<Option<Vec<_>>>()?,
708    })
709}
710
711fn bind_join_query(query: &JoinQuery, binds: &[Value]) -> Option<JoinQuery> {
712    Some(JoinQuery {
713        left: Box::new(bind_query_expr_inner(&query.left, binds)?),
714        right: Box::new(bind_query_expr_inner(&query.right, binds)?),
715        join_type: query.join_type,
716        on: query.on.clone(),
717        group_by: query.group_by.clone(),
718        having: match &query.having {
719            Some(expr) => Some(bind_expr(expr, binds)?),
720            None => None,
721        },
722        filter: query
723            .filter
724            .as_ref()
725            .and_then(|filter| bind_filter(filter, binds)),
726        order_by: query
727            .order_by
728            .iter()
729            .map(|clause| bind_order_by(clause, binds))
730            .collect::<Option<Vec<_>>>()?,
731        limit: query.limit,
732        offset: query.offset,
733        return_items: query
734            .return_items
735            .iter()
736            .map(|item| bind_select_item(item, binds))
737            .collect::<Option<Vec<_>>>()?,
738        return_: query
739            .return_
740            .iter()
741            .map(|projection| bind_projection(projection, binds))
742            .collect::<Option<Vec<_>>>()?,
743    })
744}
745
746fn parameterize_graph_query(query: &GraphQuery, next_index: &mut usize) -> Option<GraphQuery> {
747    Some(GraphQuery {
748        alias: query.alias.clone(),
749        pattern: parameterize_graph_pattern(&query.pattern, next_index),
750        filter: query
751            .filter
752            .as_ref()
753            .map(|filter| parameterize_filter(filter, next_index)),
754        return_: query
755            .return_
756            .iter()
757            .map(|projection| parameterize_projection(projection, next_index))
758            .collect::<Option<Vec<_>>>()?,
759        limit: query.limit,
760    })
761}
762
763fn bind_graph_query(query: &GraphQuery, binds: &[Value]) -> Option<GraphQuery> {
764    Some(GraphQuery {
765        alias: query.alias.clone(),
766        pattern: bind_graph_pattern(&query.pattern, binds)?,
767        filter: query
768            .filter
769            .as_ref()
770            .and_then(|filter| bind_filter(filter, binds)),
771        return_: query
772            .return_
773            .iter()
774            .map(|projection| bind_projection(projection, binds))
775            .collect::<Option<Vec<_>>>()?,
776        limit: query.limit,
777    })
778}
779
780fn parameterize_path_query(query: &PathQuery, next_index: &mut usize) -> Option<PathQuery> {
781    Some(PathQuery {
782        alias: query.alias.clone(),
783        from: parameterize_node_selector(&query.from, next_index),
784        to: parameterize_node_selector(&query.to, next_index),
785        via: query.via.clone(),
786        max_length: query.max_length,
787        filter: query
788            .filter
789            .as_ref()
790            .map(|filter| parameterize_filter(filter, next_index)),
791        return_: query
792            .return_
793            .iter()
794            .map(|projection| parameterize_projection(projection, next_index))
795            .collect::<Option<Vec<_>>>()?,
796    })
797}
798
799fn bind_path_query(query: &PathQuery, binds: &[Value]) -> Option<PathQuery> {
800    Some(PathQuery {
801        alias: query.alias.clone(),
802        from: bind_node_selector(&query.from, binds)?,
803        to: bind_node_selector(&query.to, binds)?,
804        via: query.via.clone(),
805        max_length: query.max_length,
806        filter: query
807            .filter
808            .as_ref()
809            .and_then(|filter| bind_filter(filter, binds)),
810        return_: query
811            .return_
812            .iter()
813            .map(|projection| bind_projection(projection, binds))
814            .collect::<Option<Vec<_>>>()?,
815    })
816}
817
818fn parameterize_filter(
819    filter: &reddb_rql::ast::Filter,
820    next_index: &mut usize,
821) -> reddb_rql::ast::Filter {
822    expr_to_filter(&parameterize_expr(&filter_to_expr(filter), next_index))
823}
824
825fn bind_filter(filter: &reddb_rql::ast::Filter, binds: &[Value]) -> Option<reddb_rql::ast::Filter> {
826    Some(expr_to_filter(&bind_expr(&filter_to_expr(filter), binds)?))
827}
828
829fn parameterize_projection(projection: &Projection, next_index: &mut usize) -> Option<Projection> {
830    match projection {
831        Projection::All => Some(Projection::All),
832        Projection::Column(column) => {
833            Some(parameterize_projection_column(column, None, next_index))
834        }
835        Projection::Alias(column, alias) => Some(parameterize_projection_column(
836            column,
837            Some(alias.as_str()),
838            next_index,
839        )),
840        Projection::Function(name, args) => Some(Projection::Function(
841            name.clone(),
842            args.iter()
843                .map(|arg| parameterize_projection(arg, next_index))
844                .collect::<Option<Vec<_>>>()?,
845        )),
846        Projection::Expression(filter, alias) => Some(Projection::Expression(
847            Box::new(parameterize_filter(filter, next_index)),
848            alias.clone(),
849        )),
850        Projection::Field(field, alias) => Some(Projection::Field(field.clone(), alias.clone())),
851        // Slice 7a (#589): window projections are preserved verbatim;
852        // they don't carry parameter slots yet.
853        Projection::Window { .. } => Some(projection.clone()),
854    }
855}
856
857fn bind_projection(projection: &Projection, binds: &[Value]) -> Option<Projection> {
858    match projection {
859        Projection::All => Some(Projection::All),
860        Projection::Column(column) => bind_projection_column(column, None, binds),
861        Projection::Alias(column, alias) => {
862            bind_projection_column(column, Some(alias.as_str()), binds)
863        }
864        Projection::Function(name, args) => Some(Projection::Function(
865            name.clone(),
866            args.iter()
867                .map(|arg| bind_projection(arg, binds))
868                .collect::<Option<Vec<_>>>()?,
869        )),
870        Projection::Expression(filter, alias) => Some(Projection::Expression(
871            Box::new(bind_filter(filter, binds)?),
872            alias.clone(),
873        )),
874        Projection::Field(field, alias) => Some(Projection::Field(field.clone(), alias.clone())),
875        Projection::Window { .. } => Some(projection.clone()),
876    }
877}
878
879fn parameterize_projection_column(
880    column: &str,
881    alias: Option<&str>,
882    next_index: &mut usize,
883) -> Projection {
884    if column.starts_with("LIT:") {
885        let index = *next_index;
886        *next_index += 1;
887        let placeholder = format!("{PROJECTION_PARAM_PREFIX}{index}");
888        if let Some(alias) = alias {
889            Projection::Alias(placeholder, alias.to_string())
890        } else {
891            Projection::Column(placeholder)
892        }
893    } else if let Some(alias) = alias {
894        Projection::Alias(column.to_string(), alias.to_string())
895    } else {
896        Projection::Column(column.to_string())
897    }
898}
899
900fn bind_projection_column(
901    column: &str,
902    alias: Option<&str>,
903    binds: &[Value],
904) -> Option<Projection> {
905    if let Some(index) = parse_placeholder_index(column, PROJECTION_PARAM_PREFIX) {
906        let projection = projection_from_literal(binds.get(index)?)?;
907        Some(attach_projection_alias(projection, alias))
908    } else if let Some(index) = parse_placeholder_index(column, PARAMETER_PROJECTION_PREFIX) {
909        let projection = projection_from_literal(binds.get(index)?)?;
910        Some(attach_projection_alias(projection, alias))
911    } else if let Some(alias) = alias {
912        Some(Projection::Alias(column.to_string(), alias.to_string()))
913    } else {
914        Some(Projection::Column(column.to_string()))
915    }
916}
917
918fn parameterize_graph_pattern(pattern: &GraphPattern, next_index: &mut usize) -> GraphPattern {
919    GraphPattern {
920        nodes: pattern
921            .nodes
922            .iter()
923            .map(|node| parameterize_node_pattern(node, next_index))
924            .collect(),
925        edges: pattern.edges.clone(),
926    }
927}
928
929fn bind_graph_pattern(pattern: &GraphPattern, binds: &[Value]) -> Option<GraphPattern> {
930    Some(GraphPattern {
931        nodes: pattern
932            .nodes
933            .iter()
934            .map(|node| bind_node_pattern(node, binds))
935            .collect::<Option<Vec<_>>>()?,
936        edges: pattern.edges.clone(),
937    })
938}
939
940fn parameterize_node_pattern(node: &NodePattern, next_index: &mut usize) -> NodePattern {
941    NodePattern {
942        alias: node.alias.clone(),
943        node_label: node.node_label.clone(),
944        properties: node
945            .properties
946            .iter()
947            .map(|property| parameterize_property_filter(property, next_index))
948            .collect(),
949    }
950}
951
952fn bind_node_pattern(node: &NodePattern, binds: &[Value]) -> Option<NodePattern> {
953    Some(NodePattern {
954        alias: node.alias.clone(),
955        node_label: node.node_label.clone(),
956        properties: node
957            .properties
958            .iter()
959            .map(|property| bind_property_filter(property, binds))
960            .collect::<Option<Vec<_>>>()?,
961    })
962}
963
964fn parameterize_property_filter(filter: &PropertyFilter, next_index: &mut usize) -> PropertyFilter {
965    PropertyFilter {
966        name: filter.name.clone(),
967        op: filter.op,
968        value: parameterize_value_placeholder(next_index),
969    }
970}
971
972fn bind_property_filter(filter: &PropertyFilter, binds: &[Value]) -> Option<PropertyFilter> {
973    Some(PropertyFilter {
974        name: filter.name.clone(),
975        op: filter.op,
976        value: bind_value_placeholder(&filter.value, binds)?,
977    })
978}
979
980fn parameterize_node_selector(selector: &NodeSelector, next_index: &mut usize) -> NodeSelector {
981    match selector {
982        NodeSelector::ById(_) => {
983            let index = *next_index;
984            *next_index += 1;
985            NodeSelector::ById(format!("{STRING_PARAM_PREFIX}{index}"))
986        }
987        NodeSelector::ByType { node_label, filter } => NodeSelector::ByType {
988            node_label: node_label.clone(),
989            filter: filter
990                .as_ref()
991                .map(|filter| parameterize_property_filter(filter, next_index)),
992        },
993        NodeSelector::ByRow { table, .. } => {
994            let index = *next_index;
995            *next_index += 1;
996            NodeSelector::ByRow {
997                table: format!("{ROW_SELECTOR_TABLE_PREFIX}{index}:{table}"),
998                row_id: 0,
999            }
1000        }
1001    }
1002}
1003
1004fn bind_node_selector(selector: &NodeSelector, binds: &[Value]) -> Option<NodeSelector> {
1005    match selector {
1006        NodeSelector::ById(id) => {
1007            if let Some(index) = parse_placeholder_index(id, STRING_PARAM_PREFIX) {
1008                Some(NodeSelector::ById(bind_value_to_string(binds.get(index)?)?))
1009            } else {
1010                Some(NodeSelector::ById(id.clone()))
1011            }
1012        }
1013        NodeSelector::ByType { node_label, filter } => Some(NodeSelector::ByType {
1014            node_label: node_label.clone(),
1015            filter: filter
1016                .as_ref()
1017                .and_then(|filter| bind_property_filter(filter, binds)),
1018        }),
1019        NodeSelector::ByRow { table, row_id } => {
1020            if let Some((index, original_table)) = parse_row_selector_placeholder(table) {
1021                Some(NodeSelector::ByRow {
1022                    table: original_table.to_string(),
1023                    row_id: bind_value_to_u64(binds.get(index)?)?,
1024                })
1025            } else {
1026                Some(NodeSelector::ByRow {
1027                    table: table.clone(),
1028                    row_id: *row_id,
1029                })
1030            }
1031        }
1032    }
1033}
1034
1035fn parameterize_value_placeholder(next_index: &mut usize) -> Value {
1036    let index = *next_index;
1037    *next_index += 1;
1038    Value::text(format!("{VALUE_PARAM_PREFIX}{index}"))
1039}
1040
1041fn bind_value_placeholder(value: &Value, binds: &[Value]) -> Option<Value> {
1042    match value {
1043        Value::Text(text) => {
1044            if let Some(index) = parse_placeholder_index(text, VALUE_PARAM_PREFIX) {
1045                binds.get(index).cloned()
1046            } else {
1047                Some(value.clone())
1048            }
1049        }
1050        _ => Some(value.clone()),
1051    }
1052}
1053
1054fn attach_projection_alias(projection: Projection, alias: Option<&str>) -> Projection {
1055    let Some(alias) = alias else {
1056        return projection;
1057    };
1058    match projection {
1059        Projection::Field(field, _) => Projection::Field(field, Some(alias.to_string())),
1060        Projection::Expression(filter, _) => {
1061            Projection::Expression(filter, Some(alias.to_string()))
1062        }
1063        Projection::Function(name, args) => {
1064            if name.contains(':') {
1065                Projection::Function(name, args)
1066            } else {
1067                Projection::Function(format!("{name}:{alias}"), args)
1068            }
1069        }
1070        Projection::Column(column) => Projection::Alias(column, alias.to_string()),
1071        Projection::Alias(column, _) => Projection::Alias(column, alias.to_string()),
1072        Projection::All => Projection::All,
1073        Projection::Window {
1074            name, args, window, ..
1075        } => Projection::Window {
1076            name,
1077            args,
1078            window,
1079            alias: Some(alias.to_string()),
1080        },
1081    }
1082}
1083
1084fn bind_value_to_string(value: &Value) -> Option<String> {
1085    match value {
1086        Value::Null => None,
1087        _ => Some(value.to_string()),
1088    }
1089}
1090
1091fn bind_placeholder_string(value: &str, binds: &[Value]) -> Option<Option<String>> {
1092    if let Some(index) = parse_placeholder_index(value, STRING_PARAM_PREFIX) {
1093        Some(bind_value_to_string(binds.get(index)?))
1094    } else {
1095        Some(Some(value.to_string()))
1096    }
1097}
1098
1099fn bind_value_to_u64(value: &Value) -> Option<u64> {
1100    match value {
1101        Value::UnsignedInteger(value) => Some(*value),
1102        Value::Integer(value) if *value >= 0 => Some(*value as u64),
1103        Value::BigInt(value) if *value >= 0 => Some(*value as u64),
1104        Value::Text(value) => value.parse().ok(),
1105        _ => None,
1106    }
1107}
1108
1109fn parse_placeholder_index(value: &str, prefix: &str) -> Option<usize> {
1110    value.strip_prefix(prefix)?.parse().ok()
1111}
1112
1113fn parse_prefixed_index_with_suffix<'a>(value: &'a str, prefix: &str) -> Option<(usize, &'a str)> {
1114    let rest = value.strip_prefix(prefix)?;
1115    let (index, suffix) = rest.split_once(':')?;
1116    Some((index.parse().ok()?, suffix))
1117}
1118
1119fn parse_row_selector_placeholder(value: &str) -> Option<(usize, &str)> {
1120    let rest = value.strip_prefix(ROW_SELECTOR_TABLE_PREFIX)?;
1121    let (index, table) = rest.split_once(':')?;
1122    Some((index.parse().ok()?, table))
1123}
1124
1125fn allocate_param_index(next_index: &mut usize) -> usize {
1126    let index = *next_index;
1127    *next_index += 1;
1128    index
1129}
1130
1131fn encode_f32_placeholder(index: usize) -> f32 {
1132    f32::from_bits(FLOAT32_PARAM_BITS_BASE | (index as u32 & 0x003f_ffff))
1133}
1134
1135fn decode_f32_placeholder(value: f32) -> Option<usize> {
1136    let bits = value.to_bits();
1137    if bits & FLOAT32_PARAM_BITS_BASE == FLOAT32_PARAM_BITS_BASE {
1138        Some((bits & 0x003f_ffff) as usize)
1139    } else {
1140        None
1141    }
1142}
1143
1144fn bind_placeholder_f32(value: f32, binds: &[Value]) -> Option<f32> {
1145    if let Some(index) = decode_f32_placeholder(value) {
1146        bind_value_to_f32(binds.get(index)?)
1147    } else {
1148        Some(value)
1149    }
1150}
1151
1152fn parameterize_f64(value: f64, next_index: &mut usize) -> f64 {
1153    if value.is_finite() {
1154        encode_f64_placeholder(allocate_param_index(next_index))
1155    } else {
1156        value
1157    }
1158}
1159
1160fn encode_f64_placeholder(index: usize) -> f64 {
1161    f64::from_bits(FLOAT64_PARAM_BITS_BASE | (index as u64 & 0x0007_ffff_ffff_ffff))
1162}
1163
1164fn decode_f64_placeholder(value: f64) -> Option<usize> {
1165    let bits = value.to_bits();
1166    if bits & FLOAT64_PARAM_BITS_BASE == FLOAT64_PARAM_BITS_BASE {
1167        Some((bits & 0x0007_ffff_ffff_ffff) as usize)
1168    } else {
1169        None
1170    }
1171}
1172
1173fn bind_placeholder_f64(value: f64, binds: &[Value]) -> Option<f64> {
1174    if let Some(index) = decode_f64_placeholder(value) {
1175        bind_value_to_f64(binds.get(index)?)
1176    } else {
1177        Some(value)
1178    }
1179}
1180
1181fn encode_u32_placeholder(index: usize) -> u32 {
1182    U32_PARAM_BASE | (index as u32 & 0x000f_ffff)
1183}
1184
1185fn decode_u32_placeholder(value: u32) -> Option<usize> {
1186    if value & 0xfff0_0000 == U32_PARAM_BASE {
1187        Some((value & 0x000f_ffff) as usize)
1188    } else {
1189        None
1190    }
1191}
1192
1193fn bind_placeholder_u32(value: u32, binds: &[Value]) -> Option<u32> {
1194    if let Some(index) = decode_u32_placeholder(value) {
1195        bind_value_to_u64(binds.get(index)?).and_then(|value| u32::try_from(value).ok())
1196    } else {
1197        Some(value)
1198    }
1199}
1200
1201fn bind_value_to_f32(value: &Value) -> Option<f32> {
1202    match value {
1203        Value::Float(value) => Some(*value as f32),
1204        Value::Integer(value) => Some(*value as f32),
1205        Value::UnsignedInteger(value) => Some(*value as f32),
1206        Value::BigInt(value) => Some(*value as f32),
1207        Value::Text(value) => value.parse().ok(),
1208        _ => None,
1209    }
1210}
1211
1212fn bind_value_to_f64(value: &Value) -> Option<f64> {
1213    match value {
1214        Value::Float(value) => Some(*value),
1215        Value::Integer(value) => Some(*value as f64),
1216        Value::UnsignedInteger(value) => Some(*value as f64),
1217        Value::BigInt(value) => Some(*value as f64),
1218        Value::Text(value) => value.parse().ok(),
1219        _ => None,
1220    }
1221}
1222
1223fn bind_value_to_metadata_value(value: &Value) -> Option<MetadataValue> {
1224    match value {
1225        Value::Text(value) => Some(MetadataValue::String(value.to_string())),
1226        Value::Integer(value) => Some(MetadataValue::Integer(*value)),
1227        Value::UnsignedInteger(value) => i64::try_from(*value).ok().map(MetadataValue::Integer),
1228        Value::BigInt(value) => Some(MetadataValue::Integer(*value)),
1229        Value::Float(value) => Some(MetadataValue::Float(*value)),
1230        Value::Boolean(value) => Some(MetadataValue::Bool(*value)),
1231        Value::Null => Some(MetadataValue::Null),
1232        _ => None,
1233    }
1234}
1235
1236fn bind_table_query(query: &TableQuery, binds: &[Value]) -> Option<TableQuery> {
1237    let source = match &query.source {
1238        Some(TableSource::Name(name)) => Some(TableSource::Name(name.clone())),
1239        Some(TableSource::Subquery(inner)) => Some(TableSource::Subquery(Box::new(
1240            bind_query_expr_inner(inner, binds)?,
1241        ))),
1242        // Table-valued functions take identifier args only — nothing to bind;
1243        // preserve them verbatim (issue #795). The inline-graph form (issue
1244        // #799) is preserved verbatim for the same reason (no plan params).
1245        Some(other @ (TableSource::Function { .. } | TableSource::InlineGraphFunction { .. })) => {
1246            Some(other.clone())
1247        }
1248        None => None,
1249    };
1250
1251    Some(TableQuery {
1252        table: query.table.clone(),
1253        source,
1254        alias: query.alias.clone(),
1255        select_items: query
1256            .select_items
1257            .iter()
1258            .map(|item| bind_select_item(item, binds))
1259            .collect::<Option<Vec<_>>>()?,
1260        columns: query
1261            .columns
1262            .iter()
1263            .map(|projection| bind_projection(projection, binds))
1264            .collect::<Option<Vec<_>>>()?,
1265        where_expr: query
1266            .where_expr
1267            .as_ref()
1268            .and_then(|expr| bind_expr(expr, binds)),
1269        filter: None,
1270        group_by_exprs: query
1271            .group_by_exprs
1272            .iter()
1273            .map(|expr| bind_expr(expr, binds))
1274            .collect::<Option<Vec<_>>>()?,
1275        group_by: Vec::new(),
1276        having_expr: query
1277            .having_expr
1278            .as_ref()
1279            .and_then(|expr| bind_expr(expr, binds)),
1280        having: None,
1281        order_by: query
1282            .order_by
1283            .iter()
1284            .map(|clause| bind_order_by(clause, binds))
1285            .collect::<Option<Vec<_>>>()?,
1286        limit: query.limit,
1287        limit_param: query.limit_param,
1288        offset: query.offset,
1289        offset_param: query.offset_param,
1290        expand: query.expand.clone(),
1291        as_of: query.as_of.clone(),
1292        sessionize: query.sessionize.clone(),
1293        distinct: query.distinct,
1294    })
1295}
1296
1297fn bind_select_item(item: &SelectItem, binds: &[Value]) -> Option<SelectItem> {
1298    match item {
1299        SelectItem::Wildcard => Some(SelectItem::Wildcard),
1300        SelectItem::Expr { expr, alias } => Some(SelectItem::Expr {
1301            expr: bind_expr(expr, binds)?,
1302            alias: alias.clone(),
1303        }),
1304    }
1305}
1306
1307fn bind_order_by(clause: &OrderByClause, binds: &[Value]) -> Option<OrderByClause> {
1308    Some(OrderByClause {
1309        field: clause.field.clone(),
1310        expr: clause.expr.as_ref().and_then(|expr| bind_expr(expr, binds)),
1311        ascending: clause.ascending,
1312        nulls_first: clause.nulls_first,
1313    })
1314}
1315
1316fn bind_expr(expr: &Expr, binds: &[Value]) -> Option<Expr> {
1317    match expr {
1318        Expr::Literal { .. } | Expr::Column { .. } => Some(expr.clone()),
1319        Expr::Parameter { index, span } => Some(Expr::Literal {
1320            value: binds.get(*index)?.clone(),
1321            span: *span,
1322        }),
1323        Expr::BinaryOp { op, lhs, rhs, span } => Some(Expr::BinaryOp {
1324            op: *op,
1325            lhs: Box::new(bind_expr(lhs, binds)?),
1326            rhs: Box::new(bind_expr(rhs, binds)?),
1327            span: *span,
1328        }),
1329        Expr::UnaryOp { op, operand, span } => Some(Expr::UnaryOp {
1330            op: *op,
1331            operand: Box::new(bind_expr(operand, binds)?),
1332            span: *span,
1333        }),
1334        Expr::Cast {
1335            inner,
1336            target,
1337            span,
1338        } => Some(Expr::Cast {
1339            inner: Box::new(bind_expr(inner, binds)?),
1340            target: *target,
1341            span: *span,
1342        }),
1343        Expr::FunctionCall { name, args, span } => Some(Expr::FunctionCall {
1344            name: name.clone(),
1345            args: args
1346                .iter()
1347                .map(|arg| bind_expr(arg, binds))
1348                .collect::<Option<Vec<_>>>()?,
1349            span: *span,
1350        }),
1351        Expr::Case {
1352            branches,
1353            else_,
1354            span,
1355        } => Some(Expr::Case {
1356            branches: branches
1357                .iter()
1358                .map(|(cond, value)| Some((bind_expr(cond, binds)?, bind_expr(value, binds)?)))
1359                .collect::<Option<Vec<_>>>()?,
1360            else_: else_
1361                .as_ref()
1362                .and_then(|expr| bind_expr(expr, binds).map(Box::new)),
1363            span: *span,
1364        }),
1365        Expr::IsNull {
1366            operand,
1367            negated,
1368            span,
1369        } => Some(Expr::IsNull {
1370            operand: Box::new(bind_expr(operand, binds)?),
1371            negated: *negated,
1372            span: *span,
1373        }),
1374        Expr::InList {
1375            target,
1376            values,
1377            negated,
1378            span,
1379        } => Some(Expr::InList {
1380            target: Box::new(bind_expr(target, binds)?),
1381            values: values
1382                .iter()
1383                .map(|value| bind_expr(value, binds))
1384                .collect::<Option<Vec<_>>>()?,
1385            negated: *negated,
1386            span: *span,
1387        }),
1388        Expr::Between {
1389            target,
1390            low,
1391            high,
1392            negated,
1393            span,
1394        } => Some(Expr::Between {
1395            target: Box::new(bind_expr(target, binds)?),
1396            low: Box::new(bind_expr(low, binds)?),
1397            high: Box::new(bind_expr(high, binds)?),
1398            negated: *negated,
1399            span: *span,
1400        }),
1401        Expr::Subquery { .. } => Some(expr.clone()),
1402        Expr::WindowFunctionCall { .. } => Some(expr.clone()),
1403    }
1404}
1405
1406#[cfg(test)]
1407mod tests {
1408    use super::*;
1409    use reddb_rql::ast::{BinOp, FieldRef, SelectItem, TableQuery};
1410    use reddb_rql::modes::parse_multi;
1411
1412    #[test]
1413    fn table_shape_round_trips_with_new_binds() {
1414        let query = QueryExpr::Table(TableQuery {
1415            table: "users".to_string(),
1416            source: None,
1417            alias: None,
1418            select_items: vec![SelectItem::Expr {
1419                expr: Expr::Column {
1420                    field: FieldRef::TableColumn {
1421                        table: String::new(),
1422                        column: "name".to_string(),
1423                    },
1424                    span: reddb_rql::ast::Span::synthetic(),
1425                },
1426                alias: None,
1427            }],
1428            columns: Vec::new(),
1429            where_expr: Some(Expr::BinaryOp {
1430                op: BinOp::Eq,
1431                lhs: Box::new(Expr::Column {
1432                    field: FieldRef::TableColumn {
1433                        table: String::new(),
1434                        column: "age".to_string(),
1435                    },
1436                    span: reddb_rql::ast::Span::synthetic(),
1437                }),
1438                rhs: Box::new(Expr::Literal {
1439                    value: Value::Integer(18),
1440                    span: reddb_rql::ast::Span::synthetic(),
1441                }),
1442                span: reddb_rql::ast::Span::synthetic(),
1443            }),
1444            filter: None,
1445            group_by_exprs: Vec::new(),
1446            group_by: Vec::new(),
1447            having_expr: None,
1448            having: None,
1449            order_by: Vec::new(),
1450            limit: None,
1451            limit_param: None,
1452            offset: None,
1453            offset_param: None,
1454            expand: None,
1455            as_of: None,
1456            sessionize: None,
1457            distinct: false,
1458        });
1459
1460        let prepared = parameterize_query_expr(&query).unwrap();
1461        assert_eq!(prepared.parameter_count, 1);
1462
1463        let rebound = bind_parameterized_query(
1464            &prepared.shape,
1465            &[Value::Integer(42)],
1466            prepared.parameter_count,
1467        )
1468        .unwrap();
1469
1470        let QueryExpr::Table(bound_table) = rebound else {
1471            panic!("expected table query");
1472        };
1473        match bound_table.where_expr.unwrap() {
1474            Expr::BinaryOp { rhs, .. } => match *rhs {
1475                Expr::Literal { value, .. } => assert_eq!(value, Value::Integer(42)),
1476                other => panic!("expected rebound literal, got {other:?}"),
1477            },
1478            other => panic!("expected binary op, got {other:?}"),
1479        }
1480    }
1481
1482    #[test]
1483    fn user_param_binding_preserves_literal_projection_columns() {
1484        let query = parse_multi("SELECT $1").unwrap();
1485        let rebound = bind_user_param_query(&query, &[Value::Integer(42)]).unwrap();
1486        let QueryExpr::Table(bound_table) = rebound else {
1487            panic!("expected table query");
1488        };
1489        assert_eq!(
1490            bound_table.columns,
1491            vec![Projection::Column("LIT:42".into())]
1492        );
1493    }
1494}