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