Skip to main content

reddb_engine/query/
parameters.rs

1//! User-supplied positional parameter binding for `$N` placeholders.
2//!
3//! Tracer-bullet half of issue #353. The parser emits `Expr::Parameter`
4//! nodes when it sees `$N`; this module validates that the indices form
5//! a contiguous 0-based range and substitutes the user-provided values
6//! into the AST. Type validation is delegated to the existing engine
7//! type checker, which runs on the substituted literals downstream.
8
9use crate::query::planning::shape::bind_user_param_query;
10use reddb_rql::ast::{Expr, QueryExpr, SearchCommand, Span};
11use reddb_rql::sql_lowering::{expr_to_filter, fold_expr_to_value};
12use reddb_types::Value;
13
14/// One parameter placeholder found in the parsed query AST.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct ParameterRef {
17    /// Zero-based index into the caller-supplied parameter slice.
18    pub index: usize,
19    /// Source span of the placeholder token.
20    pub span: Span,
21}
22
23/// Recursively check whether `expr` contains any `Expr::Parameter` node.
24/// Used by the INSERT parser to know when to defer literal folding to
25/// the user_params binder.
26///
27/// The implementation moved with the parser family into `reddb-io-rql`
28/// (#1103, ADR 0053) — it is pure `Expr`-tree walking and depends only on
29/// the AST that already lives in the crate. This re-export keeps the
30/// historical `storage::query::user_params::expr_contains_parameter` path
31/// resolving for the binder's call-sites.
32pub use reddb_rql::sql_lowering::expr_contains_parameter;
33
34/// Substitute every `Expr::Parameter { index }` in `expr` with
35/// `Expr::Literal { value: params[index] }`. Used by INSERT binding,
36/// which must hand a fully literal AST to `fold_expr_to_value`.
37fn substitute_params_in_expr(expr: Expr, params: &[Value]) -> Result<Expr, UserParamError> {
38    match expr {
39        Expr::Parameter { index, span } => {
40            let value = params.get(index).ok_or(UserParamError::Arity {
41                expected: index + 1,
42                got: params.len(),
43            })?;
44            Ok(Expr::Literal {
45                value: value.clone(),
46                span,
47            })
48        }
49        Expr::Literal { .. } | Expr::Column { .. } => Ok(expr),
50        Expr::BinaryOp { op, lhs, rhs, span } => Ok(Expr::BinaryOp {
51            op,
52            lhs: Box::new(substitute_params_in_expr(*lhs, params)?),
53            rhs: Box::new(substitute_params_in_expr(*rhs, params)?),
54            span,
55        }),
56        Expr::UnaryOp { op, operand, span } => Ok(Expr::UnaryOp {
57            op,
58            operand: Box::new(substitute_params_in_expr(*operand, params)?),
59            span,
60        }),
61        Expr::Cast {
62            inner,
63            target,
64            span,
65        } => Ok(Expr::Cast {
66            inner: Box::new(substitute_params_in_expr(*inner, params)?),
67            target,
68            span,
69        }),
70        Expr::FunctionCall { name, args, span } => {
71            let new_args = args
72                .into_iter()
73                .map(|a| substitute_params_in_expr(a, params))
74                .collect::<Result<Vec<_>, _>>()?;
75            Ok(Expr::FunctionCall {
76                name,
77                args: new_args,
78                span,
79            })
80        }
81        Expr::Case {
82            branches,
83            else_,
84            span,
85        } => {
86            let new_branches = branches
87                .into_iter()
88                .map(|(c, v)| {
89                    Ok::<_, UserParamError>((
90                        substitute_params_in_expr(c, params)?,
91                        substitute_params_in_expr(v, params)?,
92                    ))
93                })
94                .collect::<Result<Vec<_>, _>>()?;
95            let new_else = match else_ {
96                Some(e) => Some(Box::new(substitute_params_in_expr(*e, params)?)),
97                None => None,
98            };
99            Ok(Expr::Case {
100                branches: new_branches,
101                else_: new_else,
102                span,
103            })
104        }
105        Expr::IsNull {
106            operand,
107            negated,
108            span,
109        } => Ok(Expr::IsNull {
110            operand: Box::new(substitute_params_in_expr(*operand, params)?),
111            negated,
112            span,
113        }),
114        Expr::InList {
115            target,
116            values,
117            negated,
118            span,
119        } => Ok(Expr::InList {
120            target: Box::new(substitute_params_in_expr(*target, params)?),
121            values: values
122                .into_iter()
123                .map(|v| substitute_params_in_expr(v, params))
124                .collect::<Result<Vec<_>, _>>()?,
125            negated,
126            span,
127        }),
128        Expr::Between {
129            target,
130            low,
131            high,
132            negated,
133            span,
134        } => Ok(Expr::Between {
135            target: Box::new(substitute_params_in_expr(*target, params)?),
136            low: Box::new(substitute_params_in_expr(*low, params)?),
137            high: Box::new(substitute_params_in_expr(*high, params)?),
138            negated,
139            span,
140        }),
141        Expr::Subquery { .. } => Ok(expr),
142        // Window function calls don't appear in INSERT VALUES contexts
143        // (the only path that drives substitute_params_in_expr), but
144        // forward parameter substitution into the args / partition /
145        // order keys so this stays correct if a future caller routes
146        // window-bearing expressions through here.
147        Expr::WindowFunctionCall {
148            name,
149            args,
150            window,
151            span,
152        } => {
153            let new_args = args
154                .into_iter()
155                .map(|a| substitute_params_in_expr(a, params))
156                .collect::<Result<Vec<_>, _>>()?;
157            let new_partition = window
158                .partition_by
159                .into_iter()
160                .map(|e| substitute_params_in_expr(e, params))
161                .collect::<Result<Vec<_>, _>>()?;
162            let new_order = window
163                .order_by
164                .into_iter()
165                .map(|o| {
166                    Ok::<_, UserParamError>(reddb_rql::ast::WindowOrderItem {
167                        expr: substitute_params_in_expr(o.expr, params)?,
168                        ascending: o.ascending,
169                        nulls_first: o.nulls_first,
170                    })
171                })
172                .collect::<Result<Vec<_>, _>>()?;
173            Ok(Expr::WindowFunctionCall {
174                name,
175                args: new_args,
176                window: reddb_rql::ast::WindowSpec {
177                    partition_by: new_partition,
178                    order_by: new_order,
179                    frame: window.frame,
180                },
181                span,
182            })
183        }
184    }
185}
186
187/// Errors surfaced when binding fails. The wire layer turns these into
188/// `QUERY_ERROR` / `INVALID_PARAMS` responses.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum UserParamError {
191    /// Caller supplied fewer or more values than the SQL references.
192    /// `expected` is the highest `$N` index in the SQL (so a SQL using
193    /// `$1` and `$3` reports `expected = 3`).
194    Arity { expected: usize, got: usize },
195    /// SQL uses `$1` and `$3` but not `$2` — placeholder indices must
196    /// be a contiguous run starting from 1.
197    Gap { missing: usize, max: usize },
198    /// The runtime accepts only `QueryExpr` variants supported by the
199    /// shape binder (Table / Join / Graph / Path / Vector / Hybrid).
200    /// Other shapes (DDL, KV ops, etc.) cannot carry placeholders in
201    /// the tracer-bullet scope.
202    UnsupportedShape,
203    /// A parameter was supplied in a slot that requires a specific type
204    /// (e.g. a vector slot received a string). `slot` describes the
205    /// context, `got` describes the user-supplied value's variant.
206    TypeMismatch {
207        slot: &'static str,
208        got: &'static str,
209    },
210}
211
212impl std::fmt::Display for UserParamError {
213    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214        match self {
215            UserParamError::Arity { expected, got } => write!(
216                f,
217                "wrong number of parameters: SQL expects {expected}, got {got}"
218            ),
219            UserParamError::Gap { missing, max } => write!(
220                f,
221                "parameter $`{missing}` is missing (max index used is ${max}) — `$N` indices must be contiguous starting at $1"
222            ),
223            UserParamError::UnsupportedShape => f.write_str(
224                "this query shape does not support `$N` parameters in the tracer-bullet slice",
225            ),
226            UserParamError::TypeMismatch { slot, got } => write!(
227                f,
228                "parameter type mismatch: {slot} (got {got})"
229            ),
230        }
231    }
232}
233
234impl std::error::Error for UserParamError {}
235
236/// Public bind error alias matching the parameter-contract ADR wording.
237pub type BindError = UserParamError;
238
239/// Walk `expr`, collecting parameter placeholders that carry source spans.
240pub fn scan_parameters(expr: &QueryExpr) -> Vec<ParameterRef> {
241    let mut out = Vec::new();
242    visit_query_expr(expr, &mut |e| {
243        if let Expr::Parameter { index, span } = e {
244            out.push(ParameterRef {
245                index: *index,
246                span: *span,
247            });
248        }
249    });
250    out
251}
252
253/// Walk `expr`, collect every `Expr::Parameter { index }` encountered.
254/// Also picks up parameter slots that live outside the `Expr` tree —
255/// today only the vector slot of `SEARCH SIMILAR $N` (see #355).
256pub fn collect_indices(expr: &QueryExpr) -> Vec<usize> {
257    let mut out: Vec<usize> = scan_parameters(expr)
258        .into_iter()
259        .map(|param| param.index)
260        .collect();
261    collect_non_expr_indices(expr, &mut out);
262    out
263}
264
265/// Parameter slots that live on AST nodes outside the `Expr` tree
266/// (e.g. `SearchCommand::Similar { vector_param }`).
267//
268// `clippy::collapsible_match` would have us fold each `if let Some(idx) =
269// limit_param` into the outer pattern. With 10+ near-identical SearchCommand
270// variants, the collapsed form doubles the match arm count and obscures the
271// shared shape. Keep the two-level form for symmetry.
272#[allow(clippy::collapsible_match)]
273fn collect_non_expr_indices(expr: &QueryExpr, out: &mut Vec<usize>) {
274    match expr {
275        QueryExpr::SearchCommand(SearchCommand::Similar {
276            vector_param,
277            limit_param,
278            min_score_param,
279            text_param,
280            ..
281        }) => {
282            if let Some(idx) = vector_param {
283                out.push(*idx);
284            }
285            if let Some(idx) = limit_param {
286                out.push(*idx);
287            }
288            if let Some(idx) = min_score_param {
289                out.push(*idx);
290            }
291            if let Some(idx) = text_param {
292                out.push(*idx);
293            }
294        }
295        QueryExpr::SearchCommand(SearchCommand::Hybrid { limit_param, .. }) => {
296            if let Some(idx) = limit_param {
297                out.push(*idx);
298            }
299        }
300        QueryExpr::SearchCommand(SearchCommand::SpatialNearest { k_param, .. }) => {
301            if let Some(idx) = k_param {
302                out.push(*idx);
303            }
304        }
305        QueryExpr::SearchCommand(SearchCommand::SpatialRadius { limit_param, .. }) => {
306            if let Some(idx) = limit_param {
307                out.push(*idx);
308            }
309        }
310        QueryExpr::SearchCommand(SearchCommand::SpatialBbox { limit_param, .. }) => {
311            if let Some(idx) = limit_param {
312                out.push(*idx);
313            }
314        }
315        QueryExpr::SearchCommand(SearchCommand::SpatialWithinPolygon { limit_param, .. }) => {
316            if let Some(idx) = limit_param {
317                out.push(*idx);
318            }
319        }
320        QueryExpr::SearchCommand(SearchCommand::Text { limit_param, .. }) => {
321            if let Some(idx) = limit_param {
322                out.push(*idx);
323            }
324        }
325        QueryExpr::SearchCommand(SearchCommand::Multimodal { limit_param, .. }) => {
326            if let Some(idx) = limit_param {
327                out.push(*idx);
328            }
329        }
330        QueryExpr::SearchCommand(SearchCommand::Index { limit_param, .. }) => {
331            if let Some(idx) = limit_param {
332                out.push(*idx);
333            }
334        }
335        QueryExpr::SearchCommand(SearchCommand::Context { limit_param, .. }) => {
336            if let Some(idx) = limit_param {
337                out.push(*idx);
338            }
339        }
340        QueryExpr::Table(q) => {
341            if let Some(idx) = q.limit_param {
342                out.push(idx);
343            }
344            if let Some(idx) = q.offset_param {
345                out.push(idx);
346            }
347        }
348        QueryExpr::Ask(q) => {
349            if let Some(idx) = q.question_param {
350                out.push(idx);
351            }
352        }
353        _ => {}
354    }
355}
356
357/// Validate that the indices used by the SQL match the caller's
358/// supplied params (contiguous from 0, length match).
359pub fn validate(indices: &[usize], param_count: usize) -> Result<(), UserParamError> {
360    let max_used = indices.iter().copied().max();
361
362    let expected = match max_used {
363        Some(m) => m + 1,
364        None => 0,
365    };
366
367    if expected != param_count {
368        return Err(UserParamError::Arity {
369            expected,
370            got: param_count,
371        });
372    }
373
374    if let Some(max) = max_used {
375        let mut seen = vec![false; max + 1];
376        for &i in indices {
377            seen[i] = true;
378        }
379        for (i, used) in seen.iter().enumerate() {
380            if !used {
381                return Err(UserParamError::Gap {
382                    missing: i + 1,
383                    max: max + 1,
384                });
385            }
386        }
387    }
388
389    Ok(())
390}
391
392/// One-shot helper: validate arity/gaps then substitute the values.
393pub fn bind(expr: &QueryExpr, params: &[Value]) -> Result<QueryExpr, UserParamError> {
394    let indices = collect_indices(expr);
395    validate(&indices, params.len())?;
396    bind_validated_parameters(expr, params, !indices.is_empty())
397}
398
399/// A stored-function statement may use only a subset of its function's arguments.
400/// The function signature owns arity; individual references still need bounds checks.
401#[doc(hidden)]
402pub fn bind_available_parameters(
403    expr: &QueryExpr,
404    params: &[Value],
405) -> Result<QueryExpr, UserParamError> {
406    let indices = collect_indices(expr);
407    if let Some(index) = indices.iter().find(|index| **index >= params.len()) {
408        return Err(UserParamError::Arity {
409            expected: index + 1,
410            got: params.len(),
411        });
412    }
413
414    bind_validated_parameters(expr, params, !indices.is_empty())
415}
416
417fn bind_validated_parameters(
418    expr: &QueryExpr,
419    params: &[Value],
420    has_parameters: bool,
421) -> Result<QueryExpr, UserParamError> {
422    if !has_parameters {
423        return Ok(expr.clone());
424    }
425
426    if let QueryExpr::Function(command) = expr {
427        if let reddb_rql::stored_function::FunctionCommand::Call { name, arguments } =
428            command.as_ref()
429        {
430            return Ok(QueryExpr::Function(Box::new(
431                reddb_rql::stored_function::FunctionCommand::Call {
432                    name: name.clone(),
433                    arguments: arguments
434                        .iter()
435                        .cloned()
436                        .map(|argument| substitute_params_in_expr(argument, params))
437                        .collect::<Result<_, _>>()?,
438                },
439            )));
440        }
441    }
442
443    // SEARCH SIMILAR $N has its parameter slot outside the `Expr`
444    // tree — handle it here rather than threading the binds through
445    // the planner's shape binder, which only knows about `Expr` slots.
446    if let QueryExpr::SearchCommand(SearchCommand::Similar {
447        vector,
448        text,
449        provider,
450        collection,
451        limit,
452        min_score,
453        vector_param,
454        limit_param,
455        min_score_param,
456        text_param,
457    }) = expr
458    {
459        let mut bound_vector = vector.clone();
460        if let Some(idx) = vector_param {
461            let value = params.get(*idx).ok_or(UserParamError::Arity {
462                expected: idx + 1,
463                got: params.len(),
464            })?;
465            bound_vector = match value {
466                Value::Vector(v) => v.clone(),
467                other => {
468                    return Err(UserParamError::TypeMismatch {
469                        slot: "SEARCH SIMILAR vector parameter",
470                        got: value_variant_name(other),
471                    });
472                }
473            };
474        }
475        let bound_limit = if let Some(idx) = limit_param {
476            let value = params.get(*idx).ok_or(UserParamError::Arity {
477                expected: idx + 1,
478                got: params.len(),
479            })?;
480            match value {
481                Value::Integer(n) if *n > 0 => *n as usize,
482                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
483                Value::BigInt(n) if *n > 0 => *n as usize,
484                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
485                    return Err(UserParamError::TypeMismatch {
486                        slot: "SEARCH SIMILAR LIMIT parameter (must be > 0)",
487                        got: value_variant_name(value),
488                    });
489                }
490                other => {
491                    return Err(UserParamError::TypeMismatch {
492                        slot: "SEARCH SIMILAR LIMIT parameter",
493                        got: value_variant_name(other),
494                    });
495                }
496            }
497        } else {
498            *limit
499        };
500        let bound_min_score = if let Some(idx) = min_score_param {
501            let value = params.get(*idx).ok_or(UserParamError::Arity {
502                expected: idx + 1,
503                got: params.len(),
504            })?;
505            match value {
506                Value::Float(f) => *f as f32,
507                Value::Integer(n) => *n as f32,
508                Value::UnsignedInteger(n) => *n as f32,
509                Value::BigInt(n) => *n as f32,
510                other => {
511                    return Err(UserParamError::TypeMismatch {
512                        slot: "SEARCH SIMILAR MIN_SCORE parameter",
513                        got: value_variant_name(other),
514                    });
515                }
516            }
517        } else {
518            *min_score
519        };
520        let bound_text = if let Some(idx) = text_param {
521            let value = params.get(*idx).ok_or(UserParamError::Arity {
522                expected: idx + 1,
523                got: params.len(),
524            })?;
525            match value {
526                Value::Text(s) => Some(s.to_string()),
527                other => {
528                    return Err(UserParamError::TypeMismatch {
529                        slot: "SEARCH SIMILAR TEXT parameter",
530                        got: value_variant_name(other),
531                    });
532                }
533            }
534        } else {
535            text.clone()
536        };
537        return Ok(QueryExpr::SearchCommand(SearchCommand::Similar {
538            vector: bound_vector,
539            text: bound_text,
540            provider: provider.clone(),
541            collection: collection.clone(),
542            limit: bound_limit,
543            min_score: bound_min_score,
544            vector_param: None,
545            limit_param: None,
546            min_score_param: None,
547            text_param: None,
548        }));
549    }
550
551    if let QueryExpr::SearchCommand(SearchCommand::Hybrid {
552        vector,
553        query,
554        collection,
555        limit,
556        limit_param,
557    }) = expr
558    {
559        let bound_limit = if let Some(idx) = limit_param {
560            let value = params.get(*idx).ok_or(UserParamError::Arity {
561                expected: idx + 1,
562                got: params.len(),
563            })?;
564            match value {
565                Value::Integer(n) if *n > 0 => *n as usize,
566                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
567                Value::BigInt(n) if *n > 0 => *n as usize,
568                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
569                    return Err(UserParamError::TypeMismatch {
570                        slot: "SEARCH HYBRID LIMIT parameter (must be > 0)",
571                        got: value_variant_name(value),
572                    });
573                }
574                other => {
575                    return Err(UserParamError::TypeMismatch {
576                        slot: "SEARCH HYBRID LIMIT parameter",
577                        got: value_variant_name(other),
578                    });
579                }
580            }
581        } else {
582            *limit
583        };
584        return Ok(QueryExpr::SearchCommand(SearchCommand::Hybrid {
585            vector: vector.clone(),
586            query: query.clone(),
587            collection: collection.clone(),
588            limit: bound_limit,
589            limit_param: None,
590        }));
591    }
592
593    if let QueryExpr::SearchCommand(SearchCommand::SpatialNearest {
594        lat,
595        lon,
596        k,
597        collection,
598        column,
599        k_param,
600    }) = expr
601    {
602        let bound_k = if let Some(idx) = k_param {
603            let value = params.get(*idx).ok_or(UserParamError::Arity {
604                expected: idx + 1,
605                got: params.len(),
606            })?;
607            match value {
608                Value::Integer(n) if *n > 0 => *n as usize,
609                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
610                Value::BigInt(n) if *n > 0 => *n as usize,
611                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
612                    return Err(UserParamError::TypeMismatch {
613                        slot: "SEARCH SPATIAL NEAREST K parameter (must be > 0)",
614                        got: value_variant_name(value),
615                    });
616                }
617                other => {
618                    return Err(UserParamError::TypeMismatch {
619                        slot: "SEARCH SPATIAL NEAREST K parameter",
620                        got: value_variant_name(other),
621                    });
622                }
623            }
624        } else {
625            *k
626        };
627        return Ok(QueryExpr::SearchCommand(SearchCommand::SpatialNearest {
628            lat: *lat,
629            lon: *lon,
630            k: bound_k,
631            collection: collection.clone(),
632            column: column.clone(),
633            k_param: None,
634        }));
635    }
636
637    if let QueryExpr::SearchCommand(SearchCommand::SpatialRadius {
638        center_lat,
639        center_lon,
640        radius_km,
641        collection,
642        column,
643        limit,
644        limit_param,
645    }) = expr
646    {
647        let bound_limit = if let Some(idx) = limit_param {
648            let value = params.get(*idx).ok_or(UserParamError::Arity {
649                expected: idx + 1,
650                got: params.len(),
651            })?;
652            match value {
653                Value::Integer(n) if *n > 0 => *n as usize,
654                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
655                Value::BigInt(n) if *n > 0 => *n as usize,
656                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
657                    return Err(UserParamError::TypeMismatch {
658                        slot: "SEARCH SPATIAL RADIUS LIMIT parameter (must be > 0)",
659                        got: value_variant_name(value),
660                    });
661                }
662                other => {
663                    return Err(UserParamError::TypeMismatch {
664                        slot: "SEARCH SPATIAL RADIUS LIMIT parameter",
665                        got: value_variant_name(other),
666                    });
667                }
668            }
669        } else {
670            *limit
671        };
672        return Ok(QueryExpr::SearchCommand(SearchCommand::SpatialRadius {
673            center_lat: *center_lat,
674            center_lon: *center_lon,
675            radius_km: *radius_km,
676            collection: collection.clone(),
677            column: column.clone(),
678            limit: bound_limit,
679            limit_param: None,
680        }));
681    }
682
683    if let QueryExpr::SearchCommand(SearchCommand::SpatialBbox {
684        min_lat,
685        min_lon,
686        max_lat,
687        max_lon,
688        collection,
689        column,
690        limit,
691        limit_param,
692    }) = expr
693    {
694        let bound_limit = if let Some(idx) = limit_param {
695            let value = params.get(*idx).ok_or(UserParamError::Arity {
696                expected: idx + 1,
697                got: params.len(),
698            })?;
699            match value {
700                Value::Integer(n) if *n > 0 => *n as usize,
701                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
702                Value::BigInt(n) if *n > 0 => *n as usize,
703                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
704                    return Err(UserParamError::TypeMismatch {
705                        slot: "SEARCH SPATIAL BBOX LIMIT parameter (must be > 0)",
706                        got: value_variant_name(value),
707                    });
708                }
709                other => {
710                    return Err(UserParamError::TypeMismatch {
711                        slot: "SEARCH SPATIAL BBOX LIMIT parameter",
712                        got: value_variant_name(other),
713                    });
714                }
715            }
716        } else {
717            *limit
718        };
719        return Ok(QueryExpr::SearchCommand(SearchCommand::SpatialBbox {
720            min_lat: *min_lat,
721            min_lon: *min_lon,
722            max_lat: *max_lat,
723            max_lon: *max_lon,
724            collection: collection.clone(),
725            column: column.clone(),
726            limit: bound_limit,
727            limit_param: None,
728        }));
729    }
730
731    if let QueryExpr::SearchCommand(SearchCommand::SpatialWithinPolygon {
732        vertices,
733        collection,
734        column,
735        limit,
736        limit_param,
737    }) = expr
738    {
739        let bound_limit = if let Some(idx) = limit_param {
740            let value = params.get(*idx).ok_or(UserParamError::Arity {
741                expected: idx + 1,
742                got: params.len(),
743            })?;
744            match value {
745                Value::Integer(n) if *n > 0 => *n as usize,
746                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
747                Value::BigInt(n) if *n > 0 => *n as usize,
748                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
749                    return Err(UserParamError::TypeMismatch {
750                        slot: "SEARCH SPATIAL WITHIN POLYGON LIMIT parameter (must be > 0)",
751                        got: value_variant_name(value),
752                    });
753                }
754                other => {
755                    return Err(UserParamError::TypeMismatch {
756                        slot: "SEARCH SPATIAL WITHIN POLYGON LIMIT parameter",
757                        got: value_variant_name(other),
758                    });
759                }
760            }
761        } else {
762            *limit
763        };
764        return Ok(QueryExpr::SearchCommand(
765            SearchCommand::SpatialWithinPolygon {
766                vertices: vertices.clone(),
767                collection: collection.clone(),
768                column: column.clone(),
769                limit: bound_limit,
770                limit_param: None,
771            },
772        ));
773    }
774
775    if let QueryExpr::SearchCommand(SearchCommand::Text {
776        query,
777        collection,
778        limit,
779        fuzzy,
780        limit_param,
781    }) = expr
782    {
783        let bound_limit = if let Some(idx) = limit_param {
784            let value = params.get(*idx).ok_or(UserParamError::Arity {
785                expected: idx + 1,
786                got: params.len(),
787            })?;
788            match value {
789                Value::Integer(n) if *n > 0 => *n as usize,
790                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
791                Value::BigInt(n) if *n > 0 => *n as usize,
792                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
793                    return Err(UserParamError::TypeMismatch {
794                        slot: "SEARCH TEXT LIMIT parameter (must be > 0)",
795                        got: value_variant_name(value),
796                    });
797                }
798                other => {
799                    return Err(UserParamError::TypeMismatch {
800                        slot: "SEARCH TEXT LIMIT parameter",
801                        got: value_variant_name(other),
802                    });
803                }
804            }
805        } else {
806            *limit
807        };
808        return Ok(QueryExpr::SearchCommand(SearchCommand::Text {
809            query: query.clone(),
810            collection: collection.clone(),
811            limit: bound_limit,
812            fuzzy: *fuzzy,
813            limit_param: None,
814        }));
815    }
816
817    if let QueryExpr::SearchCommand(SearchCommand::Multimodal {
818        query,
819        collection,
820        limit,
821        limit_param,
822    }) = expr
823    {
824        let bound_limit = if let Some(idx) = limit_param {
825            let value = params.get(*idx).ok_or(UserParamError::Arity {
826                expected: idx + 1,
827                got: params.len(),
828            })?;
829            match value {
830                Value::Integer(n) if *n > 0 => *n as usize,
831                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
832                Value::BigInt(n) if *n > 0 => *n as usize,
833                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
834                    return Err(UserParamError::TypeMismatch {
835                        slot: "SEARCH MULTIMODAL LIMIT parameter (must be > 0)",
836                        got: value_variant_name(value),
837                    });
838                }
839                other => {
840                    return Err(UserParamError::TypeMismatch {
841                        slot: "SEARCH MULTIMODAL LIMIT parameter",
842                        got: value_variant_name(other),
843                    });
844                }
845            }
846        } else {
847            *limit
848        };
849        return Ok(QueryExpr::SearchCommand(SearchCommand::Multimodal {
850            query: query.clone(),
851            collection: collection.clone(),
852            limit: bound_limit,
853            limit_param: None,
854        }));
855    }
856
857    if let QueryExpr::SearchCommand(SearchCommand::Index {
858        index,
859        value,
860        collection,
861        limit,
862        exact,
863        limit_param,
864    }) = expr
865    {
866        let bound_limit = if let Some(idx) = limit_param {
867            let value = params.get(*idx).ok_or(UserParamError::Arity {
868                expected: idx + 1,
869                got: params.len(),
870            })?;
871            match value {
872                Value::Integer(n) if *n > 0 => *n as usize,
873                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
874                Value::BigInt(n) if *n > 0 => *n as usize,
875                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
876                    return Err(UserParamError::TypeMismatch {
877                        slot: "SEARCH INDEX LIMIT parameter (must be > 0)",
878                        got: value_variant_name(value),
879                    });
880                }
881                other => {
882                    return Err(UserParamError::TypeMismatch {
883                        slot: "SEARCH INDEX LIMIT parameter",
884                        got: value_variant_name(other),
885                    });
886                }
887            }
888        } else {
889            *limit
890        };
891        return Ok(QueryExpr::SearchCommand(SearchCommand::Index {
892            index: index.clone(),
893            value: value.clone(),
894            collection: collection.clone(),
895            limit: bound_limit,
896            exact: *exact,
897            limit_param: None,
898        }));
899    }
900
901    if let QueryExpr::SearchCommand(SearchCommand::Context {
902        query,
903        field,
904        collection,
905        limit,
906        depth,
907        limit_param,
908    }) = expr
909    {
910        let bound_limit = if let Some(idx) = limit_param {
911            let value = params.get(*idx).ok_or(UserParamError::Arity {
912                expected: idx + 1,
913                got: params.len(),
914            })?;
915            match value {
916                Value::Integer(n) if *n > 0 => *n as usize,
917                Value::UnsignedInteger(n) if *n > 0 => *n as usize,
918                Value::BigInt(n) if *n > 0 => *n as usize,
919                Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
920                    return Err(UserParamError::TypeMismatch {
921                        slot: "SEARCH CONTEXT LIMIT parameter (must be > 0)",
922                        got: value_variant_name(value),
923                    });
924                }
925                other => {
926                    return Err(UserParamError::TypeMismatch {
927                        slot: "SEARCH CONTEXT LIMIT parameter",
928                        got: value_variant_name(other),
929                    });
930                }
931            }
932        } else {
933            *limit
934        };
935        return Ok(QueryExpr::SearchCommand(SearchCommand::Context {
936            query: query.clone(),
937            field: field.clone(),
938            collection: collection.clone(),
939            limit: bound_limit,
940            depth: *depth,
941            limit_param: None,
942        }));
943    }
944
945    if let QueryExpr::Insert(insert) = expr {
946        let mut bound = insert.clone();
947        let mut new_values: Vec<Vec<Value>> = Vec::with_capacity(bound.value_exprs.len());
948        let new_exprs = bound
949            .value_exprs
950            .into_iter()
951            .map(|row| {
952                row.into_iter()
953                    .map(|e| substitute_params_in_expr(e, params))
954                    .collect::<Result<Vec<_>, _>>()
955            })
956            .collect::<Result<Vec<_>, _>>()?;
957        for row in &new_exprs {
958            let folded = row
959                .iter()
960                .cloned()
961                .map(fold_expr_to_value)
962                .collect::<Result<Vec<_>, _>>()
963                .map_err(|_| UserParamError::UnsupportedShape)?;
964            new_values.push(folded);
965        }
966        if let Some(reddb_rql::ast::OnConflictClause {
967            action: reddb_rql::ast::OnConflictAction::DoUpdate { assignments },
968            ..
969        }) = &mut bound.on_conflict
970        {
971            for (_, assignment) in assignments {
972                *assignment = substitute_params_in_expr(assignment.clone(), params)?;
973            }
974        }
975        bound.value_exprs = new_exprs;
976        bound.values = new_values;
977        return Ok(QueryExpr::Insert(bound));
978    }
979
980    if let QueryExpr::Update(update) = expr {
981        let mut bound = update.clone();
982        let assignment_exprs = bound
983            .assignment_exprs
984            .into_iter()
985            .map(|(column, expr)| Ok((column, substitute_params_in_expr(expr, params)?)))
986            .collect::<Result<Vec<_>, UserParamError>>()?;
987        let assignments = assignment_exprs
988            .iter()
989            .zip(bound.compound_assignment_ops.iter())
990            .filter_map(|((column, expr), compound_op)| {
991                if compound_op.is_some() {
992                    return None;
993                }
994                fold_expr_to_value(expr.clone())
995                    .ok()
996                    .map(|value| (column.clone(), value))
997            })
998            .collect();
999        let where_expr = bound
1000            .where_expr
1001            .map(|expr| substitute_params_in_expr(expr, params))
1002            .transpose()?;
1003        let filter = where_expr.as_ref().map(expr_to_filter);
1004        for clause in &mut bound.order_by {
1005            clause.expr = clause
1006                .expr
1007                .take()
1008                .map(|expression| substitute_params_in_expr(expression, params))
1009                .transpose()?;
1010        }
1011        bound.assignment_exprs = assignment_exprs;
1012        bound.assignments = assignments;
1013        bound.where_expr = where_expr;
1014        bound.filter = filter;
1015        return Ok(QueryExpr::Update(bound));
1016    }
1017
1018    if let QueryExpr::Delete(delete) = expr {
1019        let mut bound = delete.clone();
1020        let where_expr = bound
1021            .where_expr
1022            .map(|expr| substitute_params_in_expr(expr, params))
1023            .transpose()?;
1024        let filter = where_expr.as_ref().map(expr_to_filter);
1025        bound.where_expr = where_expr;
1026        bound.filter = filter;
1027        return Ok(QueryExpr::Delete(bound));
1028    }
1029
1030    if let QueryExpr::Ask(ask) = expr {
1031        let Some(idx) = ask.question_param else {
1032            return Ok(QueryExpr::Ask(ask.clone()));
1033        };
1034        let value = params.get(idx).ok_or(UserParamError::Arity {
1035            expected: idx + 1,
1036            got: params.len(),
1037        })?;
1038        let question = match value {
1039            Value::Text(s) => s.to_string(),
1040            other => {
1041                return Err(UserParamError::TypeMismatch {
1042                    slot: "ASK question parameter",
1043                    got: value_variant_name(other),
1044                });
1045            }
1046        };
1047        let mut bound = ask.clone();
1048        bound.question = question;
1049        bound.question_param = None;
1050        return Ok(QueryExpr::Ask(bound));
1051    }
1052
1053    // SELECT LIMIT / OFFSET $N — the planner's Expr-tree binder doesn't
1054    // see these slots (they live on TableQuery, not inside any Expr).
1055    // Run the Expr-tree bind first, then substitute the non-Expr slots
1056    // post-hoc. Mirrors the SearchCommand::Similar pattern above.
1057    if let QueryExpr::Table(table) = expr {
1058        if table.limit_param.is_some() || table.offset_param.is_some() {
1059            let bound_inner =
1060                bind_user_param_query(expr, params).ok_or(UserParamError::UnsupportedShape)?;
1061            let mut bound_table = match bound_inner {
1062                QueryExpr::Table(t) => t,
1063                _ => return Err(UserParamError::UnsupportedShape),
1064            };
1065            if let Some(idx) = table.limit_param {
1066                let value = params.get(idx).ok_or(UserParamError::Arity {
1067                    expected: idx + 1,
1068                    got: params.len(),
1069                })?;
1070                let n = match value {
1071                    Value::Integer(n) if *n > 0 => *n as u64,
1072                    Value::UnsignedInteger(n) if *n > 0 => *n,
1073                    Value::BigInt(n) if *n > 0 => *n as u64,
1074                    Value::Integer(_) | Value::UnsignedInteger(_) | Value::BigInt(_) => {
1075                        return Err(UserParamError::TypeMismatch {
1076                            slot: "SELECT LIMIT parameter (must be > 0)",
1077                            got: value_variant_name(value),
1078                        });
1079                    }
1080                    other => {
1081                        return Err(UserParamError::TypeMismatch {
1082                            slot: "SELECT LIMIT parameter",
1083                            got: value_variant_name(other),
1084                        });
1085                    }
1086                };
1087                bound_table.limit = Some(n);
1088                bound_table.limit_param = None;
1089            }
1090            if let Some(idx) = table.offset_param {
1091                let value = params.get(idx).ok_or(UserParamError::Arity {
1092                    expected: idx + 1,
1093                    got: params.len(),
1094                })?;
1095                let n = match value {
1096                    Value::Integer(n) if *n >= 0 => *n as u64,
1097                    Value::UnsignedInteger(n) => *n,
1098                    Value::BigInt(n) if *n >= 0 => *n as u64,
1099                    Value::Integer(_) | Value::BigInt(_) => {
1100                        return Err(UserParamError::TypeMismatch {
1101                            slot: "SELECT OFFSET parameter (must be >= 0)",
1102                            got: value_variant_name(value),
1103                        });
1104                    }
1105                    other => {
1106                        return Err(UserParamError::TypeMismatch {
1107                            slot: "SELECT OFFSET parameter",
1108                            got: value_variant_name(other),
1109                        });
1110                    }
1111                };
1112                bound_table.offset = Some(n);
1113                bound_table.offset_param = None;
1114            }
1115            return Ok(QueryExpr::Table(bound_table));
1116        }
1117    }
1118
1119    bind_user_param_query(expr, params).ok_or(UserParamError::UnsupportedShape)
1120}
1121
1122/// One-shot helper matching the parameter-contract ADR wording.
1123pub fn bind_parameters(expr: &QueryExpr, params: &[Value]) -> Result<QueryExpr, BindError> {
1124    bind(expr, params)
1125}
1126
1127fn value_variant_name(value: &Value) -> &'static str {
1128    match value {
1129        Value::Null => "null",
1130        Value::Integer(_) => "integer",
1131        Value::UnsignedInteger(_) => "unsigned integer",
1132        Value::BigInt(_) => "bigint",
1133        Value::Float(_) => "float",
1134        Value::Text(_) => "text",
1135        Value::Boolean(_) => "boolean",
1136        Value::Vector(_) => "vector",
1137        Value::Json(_) => "json",
1138        Value::Blob(_) => "bytes",
1139        _ => "other",
1140    }
1141}
1142
1143fn visit_projection_parameters<F: FnMut(&Expr)>(
1144    projection: &reddb_rql::ast::Projection,
1145    visit: &mut F,
1146) {
1147    use reddb_rql::ast::{Projection, Span};
1148    match projection {
1149        Projection::Column(column) | Projection::Alias(column, _)
1150            if column.starts_with(reddb_rql::sql_lowering::PARAMETER_PROJECTION_PREFIX) =>
1151        {
1152            if let Some(index) = column
1153                .strip_prefix(reddb_rql::sql_lowering::PARAMETER_PROJECTION_PREFIX)
1154                .and_then(|index| index.parse().ok())
1155            {
1156                visit(&Expr::Parameter {
1157                    index,
1158                    span: Span::synthetic(),
1159                });
1160            }
1161        }
1162        Projection::Function(_, arguments) => {
1163            for argument in arguments {
1164                visit_projection_parameters(argument, visit);
1165            }
1166        }
1167        _ => {
1168            if let Some((expression, _)) = reddb_rql::sql_lowering::projection_to_expr(projection) {
1169                visit_expr(&expression, visit);
1170            }
1171        }
1172    }
1173}
1174
1175fn visit_query_expr<F: FnMut(&Expr)>(expr: &QueryExpr, visit: &mut F) {
1176    match expr {
1177        QueryExpr::Function(command) => {
1178            if let reddb_rql::stored_function::FunctionCommand::Call { arguments, .. } =
1179                command.as_ref()
1180            {
1181                for argument in arguments {
1182                    visit_expr(argument, visit);
1183                }
1184            }
1185        }
1186        QueryExpr::Table(q) => {
1187            for item in &q.select_items {
1188                if let reddb_rql::ast::SelectItem::Expr { expr, .. } = item {
1189                    visit_expr(expr, visit);
1190                }
1191            }
1192            if let Some(e) = &q.where_expr {
1193                visit_expr(e, visit);
1194            }
1195            for e in &q.group_by_exprs {
1196                visit_expr(e, visit);
1197            }
1198            if let Some(e) = &q.having_expr {
1199                visit_expr(e, visit);
1200            }
1201            for clause in &q.order_by {
1202                if let Some(e) = &clause.expr {
1203                    visit_expr(e, visit);
1204                }
1205            }
1206            if let Some(reddb_rql::ast::TableSource::Subquery(inner)) = &q.source {
1207                visit_query_expr(inner, visit);
1208            }
1209        }
1210        QueryExpr::Graph(q) => {
1211            for projection in &q.return_ {
1212                visit_projection_parameters(projection, visit);
1213            }
1214            if let Some(filter) = &q.filter {
1215                visit_expr(&reddb_rql::sql_lowering::filter_to_expr(filter), visit);
1216            }
1217        }
1218        QueryExpr::Join(q) => {
1219            visit_query_expr(&q.left, visit);
1220            visit_query_expr(&q.right, visit);
1221            if let Some(having) = &q.having {
1222                visit_expr(having, visit);
1223            }
1224            for item in &q.return_items {
1225                if let reddb_rql::ast::SelectItem::Expr { expr, .. } = item {
1226                    visit_expr(expr, visit);
1227                }
1228            }
1229            for projection in &q.return_ {
1230                visit_projection_parameters(projection, visit);
1231            }
1232            if let Some(filter) = &q.filter {
1233                visit_expr(&reddb_rql::sql_lowering::filter_to_expr(filter), visit);
1234            }
1235            for clause in &q.order_by {
1236                if let Some(expression) = &clause.expr {
1237                    visit_expr(expression, visit);
1238                }
1239            }
1240        }
1241        QueryExpr::Hybrid(q) => {
1242            visit_query_expr(&q.structured, visit);
1243        }
1244        QueryExpr::Insert(q) => {
1245            for row in &q.value_exprs {
1246                for e in row {
1247                    visit_expr(e, visit);
1248                }
1249            }
1250            if let Some(reddb_rql::ast::OnConflictClause {
1251                action: reddb_rql::ast::OnConflictAction::DoUpdate { assignments },
1252                ..
1253            }) = &q.on_conflict
1254            {
1255                for (_, expression) in assignments {
1256                    visit_expr(expression, visit);
1257                }
1258            }
1259        }
1260        QueryExpr::Update(q) => {
1261            for clause in &q.order_by {
1262                if let Some(expression) = &clause.expr {
1263                    visit_expr(expression, visit);
1264                }
1265            }
1266            for (_, e) in &q.assignment_exprs {
1267                visit_expr(e, visit);
1268            }
1269            if let Some(e) = &q.where_expr {
1270                visit_expr(e, visit);
1271            }
1272        }
1273        QueryExpr::Delete(q) => {
1274            if let Some(e) = &q.where_expr {
1275                visit_expr(e, visit);
1276            }
1277        }
1278        // Vector / Graph / Path: parameter slots in #355 / later issues.
1279        _ => {}
1280    }
1281}
1282
1283/// Visit an expression and its children in the current query scope.
1284pub fn visit_expr<F: FnMut(&Expr)>(expr: &Expr, visit: &mut F) {
1285    visit(expr);
1286    match expr {
1287        Expr::Literal { .. } | Expr::Column { .. } | Expr::Parameter { .. } => {}
1288        Expr::BinaryOp { lhs, rhs, .. } => {
1289            visit_expr(lhs, visit);
1290            visit_expr(rhs, visit);
1291        }
1292        Expr::UnaryOp { operand, .. } => visit_expr(operand, visit),
1293        Expr::Cast { inner, .. } => visit_expr(inner, visit),
1294        Expr::FunctionCall { args, .. } => {
1295            for a in args {
1296                visit_expr(a, visit);
1297            }
1298        }
1299        Expr::Case {
1300            branches, else_, ..
1301        } => {
1302            for (c, v) in branches {
1303                visit_expr(c, visit);
1304                visit_expr(v, visit);
1305            }
1306            if let Some(e) = else_ {
1307                visit_expr(e, visit);
1308            }
1309        }
1310        Expr::IsNull { operand, .. } => visit_expr(operand, visit),
1311        Expr::InList { target, values, .. } => {
1312            visit_expr(target, visit);
1313            for v in values {
1314                visit_expr(v, visit);
1315            }
1316        }
1317        Expr::Between {
1318            target, low, high, ..
1319        } => {
1320            visit_expr(target, visit);
1321            visit_expr(low, visit);
1322            visit_expr(high, visit);
1323        }
1324        Expr::Subquery { .. } => {}
1325        Expr::WindowFunctionCall { args, window, .. } => {
1326            for a in args {
1327                visit_expr(a, visit);
1328            }
1329            for e in &window.partition_by {
1330                visit_expr(e, visit);
1331            }
1332            for o in &window.order_by {
1333                visit_expr(&o.expr, visit);
1334            }
1335        }
1336    }
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342    use reddb_rql::modes::parse_multi;
1343
1344    fn parse(sql: &str) -> QueryExpr {
1345        parse_multi(sql).expect("parse")
1346    }
1347
1348    #[test]
1349    fn collect_indices_select_where() {
1350        let q = parse("SELECT * FROM users WHERE id = $1 AND name = $2");
1351        let mut ix = collect_indices(&q);
1352        ix.sort();
1353        assert_eq!(ix, vec![0, 1]);
1354    }
1355
1356    #[test]
1357    fn scan_parameters_reports_index_and_span() {
1358        let sql = "SELECT * FROM users WHERE id = $1 AND name = $2";
1359        let q = parse(sql);
1360        let params = scan_parameters(&q);
1361        assert_eq!(
1362            params.iter().map(|param| param.index).collect::<Vec<_>>(),
1363            vec![0, 1]
1364        );
1365        assert_eq!(
1366            sql[params[0].span.start.offset as usize..params[0].span.end.offset as usize].trim(),
1367            "$1"
1368        );
1369        assert_eq!(
1370            sql[params[1].span.start.offset as usize..params[1].span.end.offset as usize].trim(),
1371            "$2"
1372        );
1373    }
1374
1375    #[test]
1376    fn validate_ok() {
1377        assert!(validate(&[0, 1], 2).is_ok());
1378        assert!(validate(&[0, 1, 0], 2).is_ok());
1379        assert!(validate(&[], 0).is_ok());
1380    }
1381
1382    #[test]
1383    fn validate_arity_too_few() {
1384        let err = validate(&[0, 1], 1).unwrap_err();
1385        assert!(matches!(
1386            err,
1387            UserParamError::Arity {
1388                expected: 2,
1389                got: 1
1390            }
1391        ));
1392    }
1393
1394    #[test]
1395    fn validate_arity_too_many() {
1396        let err = validate(&[0], 3).unwrap_err();
1397        assert!(matches!(
1398            err,
1399            UserParamError::Arity {
1400                expected: 1,
1401                got: 3
1402            }
1403        ));
1404    }
1405
1406    #[test]
1407    fn validate_gap() {
1408        // $1 and $3 used, but not $2.
1409        let err = validate(&[0, 2], 3).unwrap_err();
1410        assert!(matches!(err, UserParamError::Gap { missing: 2, .. }));
1411    }
1412
1413    #[test]
1414    fn bind_substitutes_int_param() {
1415        let q = parse("SELECT * FROM users WHERE id = $1");
1416        let bound = bind(&q, &[Value::Integer(42)]).unwrap();
1417        let QueryExpr::Table(t) = bound else {
1418            panic!("expected Table");
1419        };
1420        let Expr::BinaryOp { rhs, .. } = t.where_expr.unwrap() else {
1421            panic!("expected BinaryOp");
1422        };
1423        assert!(matches!(
1424            *rhs,
1425            Expr::Literal {
1426                value: Value::Integer(42),
1427                ..
1428            }
1429        ));
1430    }
1431
1432    #[test]
1433    fn bind_substitutes_question_numbered_param() {
1434        let q = parse("SELECT * FROM users WHERE id = ?1 AND name = ?2");
1435        let bound = bind(&q, &[Value::Integer(42), Value::text("Alice")]).unwrap();
1436        let QueryExpr::Table(t) = bound else {
1437            panic!("expected Table");
1438        };
1439        let mut literals: Vec<Value> = Vec::new();
1440        visit_expr(&t.where_expr.unwrap(), &mut |e| {
1441            if let Expr::Literal { value, .. } = e {
1442                literals.push(value.clone());
1443            }
1444        });
1445        assert!(literals.iter().any(|v| matches!(v, Value::Integer(42))));
1446        assert!(literals
1447            .iter()
1448            .any(|v| matches!(v, Value::Text(s) if s.as_ref() == "Alice")));
1449    }
1450
1451    #[test]
1452    fn bind_substitutes_text_and_null() {
1453        let q = parse("SELECT * FROM users WHERE name = $1 AND deleted = $2");
1454        let bound = bind(&q, &[Value::text("Alice"), Value::Null]).unwrap();
1455        let QueryExpr::Table(t) = bound else {
1456            panic!("expected Table");
1457        };
1458        let mut literals: Vec<Value> = Vec::new();
1459        visit_expr(&t.where_expr.unwrap(), &mut |e| {
1460            if let Expr::Literal { value, .. } = e {
1461                literals.push(value.clone());
1462            }
1463        });
1464        assert!(literals
1465            .iter()
1466            .any(|v| matches!(v, Value::Text(s) if s.as_ref() == "Alice")));
1467        assert!(literals.iter().any(|v| matches!(v, Value::Null)));
1468    }
1469
1470    #[test]
1471    fn bind_search_similar_vector_param() {
1472        // Tracer for #355: `SEARCH SIMILAR $1 COLLECTION embeddings`
1473        // binds the supplied `Value::Vector` into the vector slot.
1474        let q = parse("SEARCH SIMILAR $1 COLLECTION embeddings LIMIT 5");
1475        let bound = bind(&q, &[Value::Vector(vec![0.1, 0.2, 0.3])]).unwrap();
1476        let QueryExpr::SearchCommand(SearchCommand::Similar {
1477            vector,
1478            vector_param,
1479            collection,
1480            limit,
1481            ..
1482        }) = bound
1483        else {
1484            panic!("expected SearchCommand::Similar");
1485        };
1486        assert_eq!(vector, vec![0.1f32, 0.2, 0.3]);
1487        assert_eq!(vector_param, None, "vector_param must be cleared post-bind");
1488        assert_eq!(collection, "embeddings");
1489        assert_eq!(limit, 5);
1490    }
1491
1492    #[test]
1493    fn bind_search_similar_limit_param() {
1494        // Issue #361: `LIMIT $N` binds an integer parameter.
1495        let q = parse("SEARCH SIMILAR [0.1, 0.2] COLLECTION embeddings LIMIT $1");
1496        let bound = bind(&q, &[Value::Integer(25)]).unwrap();
1497        let QueryExpr::SearchCommand(SearchCommand::Similar {
1498            limit,
1499            limit_param,
1500            min_score_param,
1501            ..
1502        }) = bound
1503        else {
1504            panic!("expected SearchCommand::Similar");
1505        };
1506        assert_eq!(limit, 25);
1507        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1508        assert_eq!(min_score_param, None);
1509    }
1510
1511    #[test]
1512    fn bind_search_similar_min_score_param() {
1513        let q = parse("SEARCH SIMILAR [0.1, 0.2] COLLECTION embeddings MIN_SCORE $1");
1514        let bound = bind(&q, &[Value::Float(0.42)]).unwrap();
1515        let QueryExpr::SearchCommand(SearchCommand::Similar {
1516            min_score,
1517            min_score_param,
1518            ..
1519        }) = bound
1520        else {
1521            panic!("expected SearchCommand::Similar");
1522        };
1523        assert!((min_score - 0.42_f32).abs() < 1e-6);
1524        assert_eq!(min_score_param, None);
1525    }
1526
1527    #[test]
1528    fn bind_search_similar_limit_and_min_score_together() {
1529        let q = parse("SEARCH SIMILAR $1 COLLECTION embeddings LIMIT $2 MIN_SCORE $3");
1530        let bound = bind(
1531            &q,
1532            &[
1533                Value::Vector(vec![0.1, 0.2]),
1534                Value::Integer(7),
1535                Value::Float(0.9),
1536            ],
1537        )
1538        .unwrap();
1539        let QueryExpr::SearchCommand(SearchCommand::Similar {
1540            limit,
1541            min_score,
1542            vector,
1543            vector_param,
1544            limit_param,
1545            min_score_param,
1546            ..
1547        }) = bound
1548        else {
1549            panic!("expected SearchCommand::Similar");
1550        };
1551        assert_eq!(vector, vec![0.1_f32, 0.2]);
1552        assert_eq!(limit, 7);
1553        assert!((min_score - 0.9_f32).abs() < 1e-6);
1554        assert_eq!(vector_param, None);
1555        assert_eq!(limit_param, None);
1556        assert_eq!(min_score_param, None);
1557    }
1558
1559    #[test]
1560    fn bind_ask_question_param() {
1561        let q = parse("ASK $1 USING openai LIMIT 1");
1562        let bound = bind(&q, &[Value::text("why did incident FDD-12313 fail?")]).unwrap();
1563        let QueryExpr::Ask(ask) = bound else {
1564            panic!("expected Ask");
1565        };
1566        assert_eq!(ask.question, "why did incident FDD-12313 fail?");
1567        assert_eq!(ask.question_param, None);
1568        assert_eq!(ask.provider.as_deref(), Some("openai"));
1569    }
1570
1571    #[test]
1572    fn bind_ask_question_param_rejects_non_text() {
1573        let q = parse("ASK $1 USING openai LIMIT 1");
1574        let err = bind(&q, &[Value::Integer(42)]).unwrap_err();
1575        assert!(matches!(
1576            err,
1577            UserParamError::TypeMismatch {
1578                slot: "ASK question parameter",
1579                got: "integer"
1580            }
1581        ));
1582    }
1583
1584    #[test]
1585    fn bind_search_similar_limit_rejects_non_integer() {
1586        let q = parse("SEARCH SIMILAR [0.1] COLLECTION e LIMIT $1");
1587        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1588        assert!(
1589            matches!(
1590                err,
1591                UserParamError::TypeMismatch {
1592                    slot: "SEARCH SIMILAR LIMIT parameter",
1593                    got: "text"
1594                }
1595            ),
1596            "got {err:?}"
1597        );
1598    }
1599
1600    #[test]
1601    fn bind_search_similar_limit_rejects_zero_or_negative() {
1602        let q = parse("SEARCH SIMILAR [0.1] COLLECTION e LIMIT $1");
1603        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1604        assert!(matches!(
1605            err,
1606            UserParamError::TypeMismatch {
1607                slot: "SEARCH SIMILAR LIMIT parameter (must be > 0)",
1608                ..
1609            }
1610        ));
1611        let err = bind(&q, &[Value::Integer(-3)]).unwrap_err();
1612        assert!(matches!(
1613            err,
1614            UserParamError::TypeMismatch {
1615                slot: "SEARCH SIMILAR LIMIT parameter (must be > 0)",
1616                ..
1617            }
1618        ));
1619    }
1620
1621    #[test]
1622    fn bind_search_similar_min_score_rejects_non_numeric() {
1623        let q = parse("SEARCH SIMILAR [0.1] COLLECTION e MIN_SCORE $1");
1624        let err = bind(&q, &[Value::Vector(vec![1.0])]).unwrap_err();
1625        assert!(matches!(
1626            err,
1627            UserParamError::TypeMismatch {
1628                slot: "SEARCH SIMILAR MIN_SCORE parameter",
1629                got: "vector"
1630            }
1631        ));
1632    }
1633
1634    // Note: `?` placeholder at LIMIT/MIN_SCORE is correctly handled by
1635    // `parse_param_slot`, but `parse_multi` routes any `?`-bearing input
1636    // to the SPARQL frontend (see modes::detect). Exercising `?` for
1637    // non-Expr slots will land alongside the SPARQL detector tightening
1638    // tracked separately. The Dollar path covers the same code below.
1639
1640    #[test]
1641    fn bind_search_similar_rejects_non_vector_param() {
1642        let q = parse("SEARCH SIMILAR $1 COLLECTION embeddings");
1643        let err = bind(&q, &[Value::Integer(42)]).unwrap_err();
1644        assert!(
1645            matches!(
1646                err,
1647                UserParamError::TypeMismatch {
1648                    slot: "SEARCH SIMILAR vector parameter",
1649                    got: "integer"
1650                }
1651            ),
1652            "got {err:?}"
1653        );
1654    }
1655
1656    #[test]
1657    fn bind_search_similar_empty_vector_param() {
1658        let q = parse("SEARCH SIMILAR $1 COLLECTION embeddings");
1659        let bound = bind(&q, &[Value::Vector(vec![])]).unwrap();
1660        let QueryExpr::SearchCommand(SearchCommand::Similar { vector, .. }) = bound else {
1661            panic!("expected SearchCommand::Similar");
1662        };
1663        assert!(vector.is_empty());
1664    }
1665
1666    #[test]
1667    fn bind_parameters_substitutes_all_wire_value_variants() {
1668        let q = parse(
1669            "INSERT INTO value_params \
1670             (n, ok, count, score, name, payload, dense, body, seen_at, ident) \
1671             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
1672        );
1673        let uuid = [1_u8; 16];
1674        let params = vec![
1675            Value::Null,
1676            Value::Boolean(true),
1677            Value::Integer(42),
1678            Value::Float(1.5),
1679            Value::text("alice"),
1680            Value::Blob(vec![0, 1, 2]),
1681            Value::Vector(vec![0.25, 0.5]),
1682            Value::Json(br#"{"a":1}"#.to_vec()),
1683            Value::Timestamp(1_700_000_000),
1684            Value::Uuid(uuid),
1685        ];
1686        let bound = bind_parameters(&q, &params).unwrap();
1687        let QueryExpr::Insert(insert) = bound else {
1688            panic!("expected Insert");
1689        };
1690        assert_eq!(insert.values, vec![params]);
1691    }
1692
1693    #[test]
1694    fn bind_parameters_reuses_duplicate_index() {
1695        let q = parse("SELECT * FROM users WHERE id = $1 OR manager_id = $1");
1696        let bound = bind_parameters(&q, &[Value::Integer(7)]).unwrap();
1697        let QueryExpr::Table(table) = bound else {
1698            panic!("expected Table");
1699        };
1700        assert!(table.where_expr.is_some());
1701        assert_eq!(
1702            collect_indices(&QueryExpr::Table(table)),
1703            Vec::<usize>::new()
1704        );
1705    }
1706
1707    #[test]
1708    fn bind_search_hybrid_limit_param() {
1709        // Issue #361: `SEARCH HYBRID ... LIMIT $N` binds integer parameter.
1710        let q = parse("SEARCH HYBRID SIMILAR [0.1, 0.2] TEXT 'q' COLLECTION svc LIMIT $1");
1711        let bound = bind(&q, &[Value::Integer(30)]).unwrap();
1712        let QueryExpr::SearchCommand(SearchCommand::Hybrid {
1713            limit, limit_param, ..
1714        }) = bound
1715        else {
1716            panic!("expected SearchCommand::Hybrid");
1717        };
1718        assert_eq!(limit, 30);
1719        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1720    }
1721
1722    #[test]
1723    fn bind_search_hybrid_k_param() {
1724        // `K $N` is an alias for LIMIT in HYBRID.
1725        let q = parse("SEARCH HYBRID TEXT 'q' COLLECTION svc K $1");
1726        let bound = bind(&q, &[Value::Integer(7)]).unwrap();
1727        let QueryExpr::SearchCommand(SearchCommand::Hybrid {
1728            limit, limit_param, ..
1729        }) = bound
1730        else {
1731            panic!("expected SearchCommand::Hybrid");
1732        };
1733        assert_eq!(limit, 7);
1734        assert_eq!(limit_param, None);
1735    }
1736
1737    #[test]
1738    fn bind_search_hybrid_limit_rejects_non_integer() {
1739        let q = parse("SEARCH HYBRID TEXT 'q' COLLECTION svc LIMIT $1");
1740        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1741        assert!(
1742            matches!(
1743                err,
1744                UserParamError::TypeMismatch {
1745                    slot: "SEARCH HYBRID LIMIT parameter",
1746                    got: "text"
1747                }
1748            ),
1749            "got {err:?}"
1750        );
1751    }
1752
1753    #[test]
1754    fn bind_search_hybrid_limit_rejects_zero() {
1755        let q = parse("SEARCH HYBRID TEXT 'q' COLLECTION svc LIMIT $1");
1756        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1757        assert!(matches!(
1758            err,
1759            UserParamError::TypeMismatch {
1760                slot: "SEARCH HYBRID LIMIT parameter (must be > 0)",
1761                ..
1762            }
1763        ));
1764    }
1765
1766    #[test]
1767    fn bind_search_spatial_nearest_k_param() {
1768        // Issue #361: `SEARCH SPATIAL NEAREST ... K $N` binds an integer.
1769        let q =
1770            parse("SEARCH SPATIAL NEAREST 40.7128 74.0060 K $1 COLLECTION sites COLUMN location");
1771        let bound = bind(&q, &[Value::Integer(7)]).unwrap();
1772        let QueryExpr::SearchCommand(SearchCommand::SpatialNearest { k, k_param, .. }) = bound
1773        else {
1774            panic!("expected SpatialNearest");
1775        };
1776        assert_eq!(k, 7);
1777        assert_eq!(k_param, None, "k_param must be cleared post-bind");
1778    }
1779
1780    #[test]
1781    fn bind_search_spatial_nearest_k_rejects_zero() {
1782        let q =
1783            parse("SEARCH SPATIAL NEAREST 40.7128 74.0060 K $1 COLLECTION sites COLUMN location");
1784        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1785        assert!(matches!(
1786            err,
1787            UserParamError::TypeMismatch {
1788                slot: "SEARCH SPATIAL NEAREST K parameter (must be > 0)",
1789                ..
1790            }
1791        ));
1792    }
1793
1794    #[test]
1795    fn bind_search_spatial_nearest_k_rejects_non_integer() {
1796        let q =
1797            parse("SEARCH SPATIAL NEAREST 40.7128 74.0060 K $1 COLLECTION sites COLUMN location");
1798        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1799        assert!(matches!(
1800            err,
1801            UserParamError::TypeMismatch {
1802                slot: "SEARCH SPATIAL NEAREST K parameter",
1803                got: "text"
1804            }
1805        ));
1806    }
1807
1808    #[test]
1809    fn bind_search_text_limit_param() {
1810        // Issue #361: `SEARCH TEXT ... LIMIT $N` binds an integer.
1811        let q = parse("SEARCH TEXT 'hello' COLLECTION docs LIMIT $1");
1812        let bound = bind(&q, &[Value::Integer(15)]).unwrap();
1813        let QueryExpr::SearchCommand(SearchCommand::Text {
1814            limit, limit_param, ..
1815        }) = bound
1816        else {
1817            panic!("expected SearchCommand::Text");
1818        };
1819        assert_eq!(limit, 15);
1820        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1821    }
1822
1823    #[test]
1824    fn bind_search_text_limit_rejects_zero() {
1825        let q = parse("SEARCH TEXT 'hello' COLLECTION docs LIMIT $1");
1826        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1827        assert!(matches!(
1828            err,
1829            UserParamError::TypeMismatch {
1830                slot: "SEARCH TEXT LIMIT parameter (must be > 0)",
1831                ..
1832            }
1833        ));
1834    }
1835
1836    #[test]
1837    fn bind_search_text_limit_rejects_non_integer() {
1838        let q = parse("SEARCH TEXT 'hello' COLLECTION docs LIMIT $1");
1839        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1840        assert!(matches!(
1841            err,
1842            UserParamError::TypeMismatch {
1843                slot: "SEARCH TEXT LIMIT parameter",
1844                got: "text"
1845            }
1846        ));
1847    }
1848
1849    #[test]
1850    fn bind_search_multimodal_limit_param() {
1851        // Issue #361: `SEARCH MULTIMODAL ... LIMIT $N` binds an integer.
1852        let q = parse("SEARCH MULTIMODAL 'user:123' COLLECTION people LIMIT $1");
1853        let bound = bind(&q, &[Value::Integer(40)]).unwrap();
1854        let QueryExpr::SearchCommand(SearchCommand::Multimodal {
1855            limit, limit_param, ..
1856        }) = bound
1857        else {
1858            panic!("expected SearchCommand::Multimodal");
1859        };
1860        assert_eq!(limit, 40);
1861        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1862    }
1863
1864    #[test]
1865    fn bind_search_multimodal_limit_rejects_zero() {
1866        let q = parse("SEARCH MULTIMODAL 'k' COLLECTION people LIMIT $1");
1867        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1868        assert!(matches!(
1869            err,
1870            UserParamError::TypeMismatch {
1871                slot: "SEARCH MULTIMODAL LIMIT parameter (must be > 0)",
1872                ..
1873            }
1874        ));
1875    }
1876
1877    #[test]
1878    fn bind_search_multimodal_limit_rejects_non_integer() {
1879        let q = parse("SEARCH MULTIMODAL 'k' COLLECTION people LIMIT $1");
1880        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1881        assert!(matches!(
1882            err,
1883            UserParamError::TypeMismatch {
1884                slot: "SEARCH MULTIMODAL LIMIT parameter",
1885                got: "text"
1886            }
1887        ));
1888    }
1889
1890    #[test]
1891    fn bind_search_index_limit_param() {
1892        // Issue #361: `SEARCH INDEX ... LIMIT $N` binds an integer.
1893        let q = parse("SEARCH INDEX cpf VALUE '000.000.000-00' COLLECTION people LIMIT $1");
1894        let bound = bind(&q, &[Value::Integer(50)]).unwrap();
1895        let QueryExpr::SearchCommand(SearchCommand::Index {
1896            limit, limit_param, ..
1897        }) = bound
1898        else {
1899            panic!("expected SearchCommand::Index");
1900        };
1901        assert_eq!(limit, 50);
1902        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1903    }
1904
1905    #[test]
1906    fn bind_search_index_limit_rejects_zero() {
1907        let q = parse("SEARCH INDEX cpf VALUE 'x' COLLECTION people LIMIT $1");
1908        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1909        assert!(matches!(
1910            err,
1911            UserParamError::TypeMismatch {
1912                slot: "SEARCH INDEX LIMIT parameter (must be > 0)",
1913                ..
1914            }
1915        ));
1916    }
1917
1918    #[test]
1919    fn bind_search_index_limit_rejects_non_integer() {
1920        let q = parse("SEARCH INDEX cpf VALUE 'x' COLLECTION people LIMIT $1");
1921        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1922        assert!(matches!(
1923            err,
1924            UserParamError::TypeMismatch {
1925                slot: "SEARCH INDEX LIMIT parameter",
1926                got: "text"
1927            }
1928        ));
1929    }
1930
1931    #[test]
1932    fn bind_search_context_limit_param() {
1933        // Issue #361: `SEARCH CONTEXT ... LIMIT $N` binds an integer.
1934        let q = parse("SEARCH CONTEXT 'hello' COLLECTION docs LIMIT $1");
1935        let bound = bind(&q, &[Value::Integer(60)]).unwrap();
1936        let QueryExpr::SearchCommand(SearchCommand::Context {
1937            limit, limit_param, ..
1938        }) = bound
1939        else {
1940            panic!("expected SearchCommand::Context");
1941        };
1942        assert_eq!(limit, 60);
1943        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1944    }
1945
1946    #[test]
1947    fn bind_search_context_limit_rejects_zero() {
1948        let q = parse("SEARCH CONTEXT 'hello' COLLECTION docs LIMIT $1");
1949        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1950        assert!(matches!(
1951            err,
1952            UserParamError::TypeMismatch {
1953                slot: "SEARCH CONTEXT LIMIT parameter (must be > 0)",
1954                ..
1955            }
1956        ));
1957    }
1958
1959    #[test]
1960    fn bind_search_context_limit_rejects_non_integer() {
1961        let q = parse("SEARCH CONTEXT 'hello' COLLECTION docs LIMIT $1");
1962        let err = bind(&q, &[Value::text("five")]).unwrap_err();
1963        assert!(matches!(
1964            err,
1965            UserParamError::TypeMismatch {
1966                slot: "SEARCH CONTEXT LIMIT parameter",
1967                got: "text"
1968            }
1969        ));
1970    }
1971
1972    #[test]
1973    fn bind_search_spatial_radius_limit_param() {
1974        // Issue #361: `SEARCH SPATIAL RADIUS ... LIMIT $N` binds an integer.
1975        let q = parse(
1976            "SEARCH SPATIAL RADIUS 48.8566 2.3522 10.0 COLLECTION sites COLUMN location LIMIT $1",
1977        );
1978        let bound = bind(&q, &[Value::Integer(50)]).unwrap();
1979        let QueryExpr::SearchCommand(SearchCommand::SpatialRadius {
1980            limit, limit_param, ..
1981        }) = bound
1982        else {
1983            panic!("expected SearchCommand::SpatialRadius");
1984        };
1985        assert_eq!(limit, 50);
1986        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
1987    }
1988
1989    #[test]
1990    fn bind_search_spatial_radius_limit_rejects_zero() {
1991        let q = parse(
1992            "SEARCH SPATIAL RADIUS 48.8566 2.3522 10.0 COLLECTION sites COLUMN location LIMIT $1",
1993        );
1994        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
1995        assert!(matches!(
1996            err,
1997            UserParamError::TypeMismatch {
1998                slot: "SEARCH SPATIAL RADIUS LIMIT parameter (must be > 0)",
1999                ..
2000            }
2001        ));
2002    }
2003
2004    #[test]
2005    fn bind_search_spatial_radius_limit_rejects_non_integer() {
2006        let q = parse(
2007            "SEARCH SPATIAL RADIUS 48.8566 2.3522 10.0 COLLECTION sites COLUMN location LIMIT $1",
2008        );
2009        let err = bind(&q, &[Value::text("five")]).unwrap_err();
2010        assert!(matches!(
2011            err,
2012            UserParamError::TypeMismatch {
2013                slot: "SEARCH SPATIAL RADIUS LIMIT parameter",
2014                got: "text"
2015            }
2016        ));
2017    }
2018
2019    #[test]
2020    fn bind_search_spatial_bbox_limit_param() {
2021        // Issue #361: `SEARCH SPATIAL BBOX ... LIMIT $N` binds an integer.
2022        let q =
2023            parse("SEARCH SPATIAL BBOX 0.0 0.0 1.0 1.0 COLLECTION sites COLUMN location LIMIT $1");
2024        let bound = bind(&q, &[Value::Integer(50)]).unwrap();
2025        let QueryExpr::SearchCommand(SearchCommand::SpatialBbox {
2026            limit, limit_param, ..
2027        }) = bound
2028        else {
2029            panic!("expected SearchCommand::SpatialBbox");
2030        };
2031        assert_eq!(limit, 50);
2032        assert_eq!(limit_param, None, "limit_param must be cleared post-bind");
2033    }
2034
2035    #[test]
2036    fn bind_search_spatial_bbox_limit_rejects_zero() {
2037        let q =
2038            parse("SEARCH SPATIAL BBOX 0.0 0.0 1.0 1.0 COLLECTION sites COLUMN location LIMIT $1");
2039        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
2040        assert!(matches!(
2041            err,
2042            UserParamError::TypeMismatch {
2043                slot: "SEARCH SPATIAL BBOX LIMIT parameter (must be > 0)",
2044                ..
2045            }
2046        ));
2047    }
2048
2049    #[test]
2050    fn bind_search_spatial_bbox_limit_rejects_non_integer() {
2051        let q =
2052            parse("SEARCH SPATIAL BBOX 0.0 0.0 1.0 1.0 COLLECTION sites COLUMN location LIMIT $1");
2053        let err = bind(&q, &[Value::text("five")]).unwrap_err();
2054        assert!(matches!(
2055            err,
2056            UserParamError::TypeMismatch {
2057                slot: "SEARCH SPATIAL BBOX LIMIT parameter",
2058                got: "text"
2059            }
2060        ));
2061    }
2062
2063    #[test]
2064    fn bind_search_similar_text_param() {
2065        // Issue #361: `SEARCH SIMILAR TEXT $N` binds a Value::Text into
2066        // the text slot. The embedding pipeline reads `text` downstream.
2067        let q = parse("SEARCH SIMILAR TEXT $1 COLLECTION docs LIMIT 5 USING openai");
2068        let bound = bind(&q, &[Value::text("find vulnerabilities")]).unwrap();
2069        let QueryExpr::SearchCommand(SearchCommand::Similar {
2070            vector,
2071            text,
2072            text_param,
2073            collection,
2074            limit,
2075            provider,
2076            ..
2077        }) = bound
2078        else {
2079            panic!("expected SearchCommand::Similar");
2080        };
2081        assert!(vector.is_empty());
2082        assert_eq!(text.as_deref(), Some("find vulnerabilities"));
2083        assert_eq!(text_param, None, "text_param must be cleared post-bind");
2084        assert_eq!(collection, "docs");
2085        assert_eq!(limit, 5);
2086        assert_eq!(provider.as_deref(), Some("openai"));
2087    }
2088
2089    #[test]
2090    fn bind_search_similar_text_rejects_non_text() {
2091        let q = parse("SEARCH SIMILAR TEXT $1 COLLECTION docs");
2092        let err = bind(&q, &[Value::Integer(42)]).unwrap_err();
2093        assert!(
2094            matches!(
2095                err,
2096                UserParamError::TypeMismatch {
2097                    slot: "SEARCH SIMILAR TEXT parameter",
2098                    got: "integer"
2099                }
2100            ),
2101            "got {err:?}"
2102        );
2103    }
2104
2105    #[test]
2106    fn bind_search_similar_text_with_limit_param() {
2107        // TEXT $1 + LIMIT $2 — verify both non-Expr param slots bind
2108        // together without cross-talk.
2109        let q = parse("SEARCH SIMILAR TEXT $1 COLLECTION docs LIMIT $2");
2110        let bound = bind(&q, &[Value::text("hello"), Value::Integer(11)]).unwrap();
2111        let QueryExpr::SearchCommand(SearchCommand::Similar {
2112            text,
2113            text_param,
2114            limit,
2115            limit_param,
2116            ..
2117        }) = bound
2118        else {
2119            panic!("expected SearchCommand::Similar");
2120        };
2121        assert_eq!(text.as_deref(), Some("hello"));
2122        assert_eq!(text_param, None);
2123        assert_eq!(limit, 11);
2124        assert_eq!(limit_param, None);
2125    }
2126
2127    #[test]
2128    fn bind_insert_values_with_vector_param() {
2129        // Issue #355 INSERT half: $1 in VALUES is bound to a Value::Vector
2130        // and surfaces in both `value_exprs` (as a Literal) and `values`.
2131        let q = parse("INSERT INTO embeddings (dense, content) VALUES ($1, $2)");
2132        let vec = Value::Vector(vec![0.1, 0.2, 0.3]);
2133        let bound = bind(&q, &[vec.clone(), Value::text("doc text")]).unwrap();
2134        let QueryExpr::Insert(insert) = bound else {
2135            panic!("expected Insert");
2136        };
2137        assert_eq!(insert.values.len(), 1);
2138        assert_eq!(insert.values[0].len(), 2);
2139        assert!(
2140            matches!(insert.values[0][0], Value::Vector(ref v) if v == &vec![0.1f32, 0.2, 0.3])
2141        );
2142        assert!(matches!(insert.values[0][1], Value::Text(ref s) if s.as_ref() == "doc text"));
2143        // value_exprs row 0 col 0 is now a Literal carrying the vector.
2144        let row0 = &insert.value_exprs[0];
2145        assert!(matches!(
2146            &row0[0],
2147            Expr::Literal {
2148                value: Value::Vector(_),
2149                ..
2150            }
2151        ));
2152    }
2153
2154    #[test]
2155    fn bind_insert_on_conflict_update_assignment_param() {
2156        let query = parse(
2157            "INSERT INTO users (email, name) VALUES ($1, $2) \
2158             ON CONFLICT (email) DO UPDATE SET name = $3",
2159        );
2160        let bound = bind(
2161            &query,
2162            &[
2163                Value::text("ada@example.com"),
2164                Value::text("Ada"),
2165                Value::text("Grace"),
2166            ],
2167        )
2168        .expect("all INSERT conflict parameters should bind");
2169        let QueryExpr::Insert(insert) = bound else {
2170            panic!("expected insert");
2171        };
2172        let Some(reddb_rql::ast::OnConflictClause {
2173            action: reddb_rql::ast::OnConflictAction::DoUpdate { assignments },
2174            ..
2175        }) = insert.on_conflict
2176        else {
2177            panic!("expected conflict update");
2178        };
2179
2180        assert!(matches!(
2181            assignments.as_slice(),
2182            [(column, Expr::Literal { value: Value::Text(value), .. })]
2183                if column == "name" && value.as_ref() == "Grace"
2184        ));
2185    }
2186
2187    #[test]
2188    fn bind_insert_arity_mismatch() {
2189        let q = parse("INSERT INTO t (a, b) VALUES ($1, $2)");
2190        let err = bind(&q, &[Value::Integer(1)]).unwrap_err();
2191        assert!(matches!(
2192            err,
2193            UserParamError::Arity {
2194                expected: 2,
2195                got: 1
2196            }
2197        ));
2198    }
2199
2200    #[test]
2201    fn bind_update_assignments_and_where_params() {
2202        let q = parse("UPDATE users SET age = $1, active = $2 WHERE name = $3");
2203        let bound = bind(
2204            &q,
2205            &[
2206                Value::Integer(31),
2207                Value::Boolean(true),
2208                Value::text("Alice"),
2209            ],
2210        )
2211        .unwrap();
2212        let QueryExpr::Update(update) = bound else {
2213            panic!("expected Update");
2214        };
2215        assert_eq!(update.assignments.len(), 2);
2216        assert!(matches!(update.assignments[0].1, Value::Integer(31)));
2217        assert!(matches!(update.assignments[1].1, Value::Boolean(true)));
2218        assert!(update.where_expr.is_some());
2219        assert!(update.filter.is_some());
2220    }
2221
2222    #[test]
2223    fn bind_delete_where_param() {
2224        let q = parse("DELETE FROM users WHERE active = $1");
2225        let bound = bind(&q, &[Value::Boolean(false)]).unwrap();
2226        let QueryExpr::Delete(delete) = bound else {
2227            panic!("expected Delete");
2228        };
2229        assert!(delete.where_expr.is_some());
2230        assert!(delete.filter.is_some());
2231    }
2232
2233    #[test]
2234    fn bind_select_limit_param() {
2235        let q = parse("SELECT * FROM users LIMIT $1");
2236        let bound = bind(&q, &[Value::Integer(7)]).unwrap();
2237        let QueryExpr::Table(t) = bound else {
2238            panic!("expected Table");
2239        };
2240        assert_eq!(t.limit, Some(7));
2241        assert_eq!(t.limit_param, None, "limit_param must be cleared post-bind");
2242        assert_eq!(t.offset, None);
2243        assert_eq!(t.offset_param, None);
2244    }
2245
2246    #[test]
2247    fn bind_select_offset_param() {
2248        let q = parse("SELECT * FROM users LIMIT 10 OFFSET $1");
2249        let bound = bind(&q, &[Value::Integer(20)]).unwrap();
2250        let QueryExpr::Table(t) = bound else {
2251            panic!("expected Table");
2252        };
2253        assert_eq!(t.limit, Some(10));
2254        assert_eq!(t.offset, Some(20));
2255        assert_eq!(t.offset_param, None);
2256    }
2257
2258    #[test]
2259    fn bind_select_limit_and_offset_params_together() {
2260        let q = parse("SELECT * FROM users WHERE id = $1 LIMIT $2 OFFSET $3");
2261        let bound = bind(
2262            &q,
2263            &[Value::Integer(5), Value::Integer(10), Value::Integer(20)],
2264        )
2265        .unwrap();
2266        let QueryExpr::Table(t) = bound else {
2267            panic!("expected Table");
2268        };
2269        assert_eq!(t.limit, Some(10));
2270        assert_eq!(t.offset, Some(20));
2271        assert_eq!(t.limit_param, None);
2272        assert_eq!(t.offset_param, None);
2273        // WHERE id = $1 → Expr-tree bind also ran.
2274        assert!(t.where_expr.is_some());
2275    }
2276
2277    #[test]
2278    fn bind_select_offset_zero_is_valid() {
2279        let q = parse("SELECT * FROM users LIMIT 10 OFFSET $1");
2280        let bound = bind(&q, &[Value::Integer(0)]).unwrap();
2281        let QueryExpr::Table(t) = bound else {
2282            panic!("expected Table");
2283        };
2284        assert_eq!(t.offset, Some(0));
2285    }
2286
2287    #[test]
2288    fn bind_select_limit_rejects_zero() {
2289        let q = parse("SELECT * FROM users LIMIT $1");
2290        let err = bind(&q, &[Value::Integer(0)]).unwrap_err();
2291        assert!(
2292            matches!(
2293                err,
2294                UserParamError::TypeMismatch {
2295                    slot: "SELECT LIMIT parameter (must be > 0)",
2296                    ..
2297                }
2298            ),
2299            "got {err:?}"
2300        );
2301    }
2302
2303    #[test]
2304    fn bind_select_limit_rejects_non_integer() {
2305        let q = parse("SELECT * FROM users LIMIT $1");
2306        let err = bind(&q, &[Value::text("ten")]).unwrap_err();
2307        assert!(
2308            matches!(
2309                err,
2310                UserParamError::TypeMismatch {
2311                    slot: "SELECT LIMIT parameter",
2312                    got: "text"
2313                }
2314            ),
2315            "got {err:?}"
2316        );
2317    }
2318
2319    #[test]
2320    fn bind_select_offset_rejects_negative() {
2321        let q = parse("SELECT * FROM users LIMIT 10 OFFSET $1");
2322        let err = bind(&q, &[Value::Integer(-1)]).unwrap_err();
2323        assert!(
2324            matches!(
2325                err,
2326                UserParamError::TypeMismatch {
2327                    slot: "SELECT OFFSET parameter (must be >= 0)",
2328                    ..
2329                }
2330            ),
2331            "got {err:?}"
2332        );
2333    }
2334
2335    #[test]
2336    fn bind_no_params_is_noop() {
2337        let q = parse("SELECT * FROM users");
2338        let bound = bind(&q, &[]).unwrap();
2339        assert!(matches!(bound, QueryExpr::Table(_)));
2340    }
2341}