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