Skip to main content

rudb_bind/
binder.rs

1//! From an `Ast` to a `Plan`.
2//!
3//! The binder walks the written query once, in the order the operators end up in rather than the
4//! order the clauses are written in, which is `FROM`, `WHERE`, `GROUP BY`, `HAVING`, `SELECT`,
5//! `DISTINCT`, `ORDER BY`, `LIMIT`. That order is not a stylistic choice: it is the reason `WHERE`
6//! cannot see an output alias and `HAVING` cannot see a column that was not grouped, and doing it
7//! in any other order means special casing both of those instead of getting them for free.
8//!
9//! Two things leave here settled that nothing downstream reconsiders. Every column is a table index
10//! and a position rather than a name, so the optimizer never has to ask which `id` a name meant.
11//! And every expression has a type, with the casts that make the types line up already written into
12//! the plan as [`Expr::Cast`] nodes, so an executor never has to decide what a comparison between
13//! an `INTEGER` and a `BIGINT` does.
14
15use rudb_catalog::{Catalog, Entry, QualifiedName, same_name};
16use rudb_common::{
17    Error, Field, LogicalType, Result, Semantics, Session, ShowBehavior, Span, Value,
18};
19use rudb_functions::{
20    Columns, FILE_ROW_NUMBER, FunctionKind, Given, Resolved, TableFunction, csv_fields, csv_given,
21    files, is_file, is_pattern, kind_of, parquet_fields, resolve, resolve_pragma, resolve_table,
22};
23use rudb_parse::ast::{self, Ast, Distinct, LiteralKind, Nulls, Order, Quantifier, SetOp};
24use rudb_parse::{NONE, identifier_parts, parse_ast_with_case};
25use rudb_plan::{
26    BuildSide, ColumnBinding, Expr, ExprRef, JoinKind, Node, NodeRef, Plan, SetOpKind, SortKey,
27    WindowBound, WindowExclude, WindowFrame, WindowUnit,
28};
29
30use crate::expr::{describe, has_aggregate};
31use crate::parameters::Parameters;
32use crate::scope::{Scope, Visible};
33
34/// Binds a parsed statement against a catalog.
35///
36/// # Errors
37///
38/// If the script does not hold exactly one statement, if a name does not resolve, if a type does
39/// not work out, or if the query uses something M0 does not bind yet.
40pub fn bind(ast: &Ast, catalog: &Catalog) -> Result<Plan> {
41    bind_with(ast, catalog, &Parameters::new(), &Session::new())
42}
43
44/// Binds a parsed query against a catalog, with values for its parameters and its settings.
45///
46/// The session is what `current_setting()` reads, and a caller with no database behind it passes an
47/// empty one, which makes every setting name unrecognized rather than making up an answer.
48///
49/// # Errors
50///
51/// Everything [`bind`] reports, plus an error for a parameter that was given no value.
52pub fn bind_with(
53    ast: &Ast,
54    catalog: &Catalog,
55    parameters: &Parameters,
56    session: &Session,
57) -> Result<Plan> {
58    let query = match ast.statements.as_slice() {
59        [ast::Statement::Query(query)] => *query,
60        [] => return Err(Error::binder("no statement to bind")),
61        // One statement that is not a query is its own answer. Reporting it as a script of several
62        // reads as a count being wrong, and the count is right.
63        [_] => return Err(Error::not_implemented("a statement that is not a query")),
64        _ => return Err(Error::not_implemented("a script of more than one statement")),
65    };
66    let mut binder = Binder::with(catalog, parameters, session);
67    let (root, _) = binder.bind_query(ast, query)?;
68    let mut plan = binder.into_plan();
69    plan.set_root(root);
70    plan.validate()?;
71    Ok(plan)
72}
73
74/// Parses and binds one query, which is the whole front end in one call.
75///
76/// # Errors
77///
78/// Anything the parser or the binder reports.
79pub fn bind_sql(query: &str, catalog: &Catalog) -> Result<Plan> {
80    bind_sql_with(query, catalog, &Session::new())
81}
82
83/// Parses and binds one query, with the settings a call to `current_setting()` reads.
84///
85/// # Errors
86///
87/// Anything the parser or the binder reports.
88pub fn bind_sql_with(query: &str, catalog: &Catalog, session: &Session) -> Result<Plan> {
89    let ast = parse_ast_with_case(query, session.semantics().identifier_case())?;
90    bind_with(&ast, catalog, &Parameters::new(), session)
91}
92
93/// What an aggregating select block has decided so far.
94#[derive(Debug)]
95pub(crate) struct Aggregation {
96    /// The table index the aggregate's output binds against.
97    pub(crate) index: u32,
98    /// The group expressions, over the input, which are the first output columns.
99    pub(crate) groups: Vec<ExprRef>,
100    /// The aggregate calls found so far, which follow the groups in the output.
101    pub(crate) aggregates: Vec<ExprRef>,
102}
103
104/// One run of window calls that agree on where the rows come from and in what order.
105///
106/// The run is the unit the plan has an operator for, so two calls that write the same partition,
107/// the same order and the same frame are one operator and one sort, and a third that writes a
108/// different order is a second operator stacked on the first. Nothing here merges runs that only
109/// look compatible, because a window is evaluated over the rows the operator below it produced and
110/// deciding two runs are the same is the optimizer's job rather than the binder's.
111#[derive(Debug)]
112pub(crate) struct WindowRun {
113    /// The table index the run's result columns bind against.
114    index: u32,
115    /// What divides the input into independent partitions.
116    partition: Vec<ExprRef>,
117    /// The order within a partition.
118    order: Vec<SortKey>,
119    /// The frame every call in the run shares.
120    frame: WindowFrame,
121    /// The calls, in the order their columns are appended.
122    calls: Vec<ExprRef>,
123}
124
125/// One window call as it was written, before any of it has been bound.
126///
127/// These six travel together from the parser all the way to the run they end up filed under, and
128/// carrying them as one thing keeps the call that binds them readable.
129pub(crate) struct WindowCall<'a> {
130    /// The function name, as written and not yet resolved.
131    pub(crate) name: &'a str,
132    /// The arguments, which may include a star that only `count` is allowed to be given.
133    pub(crate) args: &'a [ast::ExprRef],
134    /// Whether `DISTINCT` was written inside the parens.
135    pub(crate) distinct: bool,
136    /// The `FILTER (WHERE ...)` predicate, which is written before the `OVER`, or `NONE`.
137    pub(crate) filter: ast::ExprRef,
138    /// Whether `IGNORE NULLS` was written inside the parens, which is where DuckDB puts it.
139    pub(crate) ignore_nulls: bool,
140    /// The `OVER`, which the parser has already resolved against any `WINDOW` clause.
141    pub(crate) spec: ast::WindowRef,
142}
143
144/// Everything inside one window call once it is bound, which is what decides its run.
145struct WindowParts {
146    /// The arguments, before the casts the resolved signature asks for.
147    args: Vec<ExprRef>,
148    /// What divides the input into independent partitions.
149    partition: Vec<ExprRef>,
150    /// The order within a partition.
151    order: Vec<SortKey>,
152    /// The frame, with both ends and the exclusion.
153    frame: WindowFrame,
154}
155
156/// A materialised `WITH` definition that has been bound and can be read by name.
157#[derive(Debug)]
158struct Materialized {
159    /// Which written definition this is, as an index into `Ast::ctes`.
160    written: u32,
161    /// The number the plan uses to pair a read with what it reads.
162    cte: u32,
163    /// The name it was written with, which is the table name a read is reachable through.
164    name: String,
165    /// What it produces, in order, under the declared names when a column list was written.
166    fields: Vec<Field>,
167}
168
169#[derive(Debug)]
170pub(crate) struct PendingSubquery {
171    pub(crate) node: NodeRef,
172    pub(crate) kind: JoinKind,
173    pub(crate) conditions: Vec<ExprRef>,
174    pub(crate) dependent: bool,
175}
176
177/// The state one binding run carries.
178#[derive(Debug)]
179pub(crate) struct Binder<'a> {
180    catalog: &'a Catalog,
181    /// What the parameters were given, empty for a statement that is not prepared.
182    pub(crate) parameters: &'a Parameters,
183    /// What the settings are now, which is what `current_setting()` folds to.
184    pub(crate) session: &'a Session,
185    /// Meaning-changing choices copied once and resolved into the plan above execution.
186    pub(crate) semantics: Semantics,
187    plan: Plan,
188    next_index: u32,
189    /// Source range inherited by plan objects built for the current AST expression or query.
190    pub(crate) current_span: Span,
191    /// Set while a select block aggregates, which changes what a bare column means.
192    pub(crate) aggregation: Option<Aggregation>,
193    /// Set while an aggregate's own arguments are being bound, so nesting is caught.
194    pub(crate) in_aggregate: bool,
195    /// Set while an aggregate's `FILTER` is being bound, which is refused its own aggregate.
196    pub(crate) in_filter: bool,
197    /// The window runs this select block has collected, in the order they were first written.
198    pub(crate) windows: Vec<WindowRun>,
199    /// Set while a window call's own arguments and keys are being bound, so nesting is caught.
200    pub(crate) in_window: bool,
201    /// Uncorrelated scalar queries waiting to be joined into the select block that uses them.
202    pub(crate) scalar_subqueries: Vec<PendingSubquery>,
203    pub(crate) outer_scopes: Vec<Scope>,
204    /// Which of the outer scopes are a FROM entry's left neighbours rather than an enclosing query.
205    ///
206    /// The two are resolved the same way and refused differently. An aggregate may read a column of
207    /// the query it is written in and may not read one a LATERAL brought in from the left, so the
208    /// check needs to know which scope the name came out of. Each entry is a position in
209    /// `outer_scopes`.
210    pub(crate) lateral_scopes: Vec<usize>,
211    pub(crate) correlations: Vec<Vec<ColumnBinding>>,
212    /// Where we are, for an error message that says which clause the writer should look at.
213    pub(crate) clause: &'static str,
214    /// The views whose bodies are open on the stack, which is what catches a cycle.
215    expanding: Vec<String>,
216    /// The materialised `WITH` definitions whose bodies are being bound, innermost last.
217    ///
218    /// A stack rather than a map from what was written, because a plain `WITH` is put into every
219    /// place it is named, so a materialised one written inside a plain one is bound once per use
220    /// and each of those is a materialisation of its own with a number of its own.
221    materialized: Vec<Materialized>,
222    /// How many materialisations have been numbered, which is where the next number comes from.
223    next_cte: u32,
224    /// When this statement started, read once and kept, which is what `now()` folds to.
225    started: Option<i64>,
226}
227
228impl<'a> Binder<'a> {
229    pub(crate) fn with(
230        catalog: &'a Catalog,
231        parameters: &'a Parameters,
232        session: &'a Session,
233    ) -> Self {
234        Self {
235            catalog,
236            parameters,
237            session,
238            semantics: session.semantics(),
239            plan: Plan::new(),
240            next_index: 0,
241            current_span: Span::new(0, 0),
242            aggregation: None,
243            in_aggregate: false,
244            in_filter: false,
245            windows: Vec::new(),
246            in_window: false,
247            scalar_subqueries: Vec::new(),
248            outer_scopes: Vec::new(),
249            lateral_scopes: Vec::new(),
250            correlations: Vec::new(),
251            clause: "SELECT clause",
252            expanding: Vec::new(),
253            materialized: Vec::new(),
254            next_cte: 0,
255            started: None,
256        }
257    }
258
259    pub(crate) fn catalog(&self) -> &Catalog {
260        self.catalog
261    }
262
263    /// When this statement started, in microseconds since the epoch.
264    ///
265    /// Read from the clock the first time something asks and kept after that, so a query that
266    /// writes `now()` twice gets one answer for both. That is what the pin does and what it reports
267    /// in the `stability` column of `duckdb_functions()`, where every one of these is
268    /// `CONSISTENT_WITHIN_QUERY`. A query that never asks never reads the clock.
269    pub(crate) fn instant(&mut self) -> i64 {
270        *self.started.get_or_insert_with(crate::context::micros_now)
271    }
272
273    pub(crate) fn plan(&self) -> &Plan {
274        &self.plan
275    }
276
277    pub(crate) fn plan_mut(&mut self) -> &mut Plan {
278        &mut self.plan
279    }
280
281    pub(crate) fn add_expr(&mut self, expr: Expr, ty: LogicalType) -> ExprRef {
282        self.plan.add_expr_at(expr, ty, self.current_span)
283    }
284
285    pub(crate) fn add_constant(&mut self, value: Value) -> ExprRef {
286        let ty = value.logical_type();
287        let reference = self.plan.add_value(value);
288        self.plan.add_expr_at(Expr::Constant(reference), ty, self.current_span)
289    }
290
291    pub(crate) fn add_node(&mut self, node: Node) -> NodeRef {
292        self.plan.add_node_at(node, self.current_span)
293    }
294
295    pub(crate) fn into_plan(self) -> Plan {
296        self.plan
297    }
298
299    /// A table index nothing else has.
300    pub(crate) fn fresh_index(&mut self) -> u32 {
301        let index = self.next_index;
302        self.next_index += 1;
303        index
304    }
305
306    /// A reference to one column of an operator's output.
307    fn column(&mut self, index: u32, position: usize, ty: LogicalType) -> ExprRef {
308        let binding = ColumnBinding::new(index, position as u32);
309        self.plan.add_expr(Expr::Column(binding), ty)
310    }
311
312    /// Joins scalar query results into the row stream that contains their expressions.
313    fn attach_scalar_subqueries(&mut self, mut input: NodeRef) -> NodeRef {
314        let subqueries = std::mem::take(&mut self.scalar_subqueries);
315        for pending in subqueries {
316            let PendingSubquery { node: mut right, kind, conditions, dependent } = pending;
317            if kind == JoinKind::Single && !self.semantics.scalar_subquery_error_on_multiple_rows()
318            {
319                right = self.add_node(Node::Limit { input: right, count: Some(1), offset: 0 });
320            }
321            let conditions = self.plan.add_expr_list(&conditions);
322            input = if dependent {
323                self.add_node(Node::DependentJoin { left: input, right, kind, conditions })
324            } else {
325                self.add_node(Node::Join {
326                    left: input,
327                    right,
328                    kind,
329                    conditions,
330                    build: BuildSide::default(),
331                })
332            };
333        }
334        input
335    }
336
337    // ---------------------------------------------------------------- queries
338
339    pub(crate) fn bind_query(
340        &mut self,
341        ast: &Ast,
342        query: ast::QueryRef,
343    ) -> Result<(NodeRef, Scope)> {
344        let span = ast.query_span(query);
345        let outer = std::mem::replace(&mut self.current_span, span);
346        let result =
347            self.bind_query_inner(ast, query).map_err(|error| error.with_fallback_span(span));
348        self.current_span = outer;
349        result
350    }
351
352    fn bind_query_inner(&mut self, ast: &Ast, query: ast::QueryRef) -> Result<(NodeRef, Scope)> {
353        let written = ast.query(query);
354        if written.ctes.is_empty() {
355            return self.bind_body(ast, &written);
356        }
357        // The names a query introduces are gone again once it is bound, and they go whether the
358        // binding worked or not, which is why the stack is cut back here rather than at the end of
359        // the call that pushed onto it.
360        let depth = self.materialized.len();
361        let result = self.bind_materialized(ast, &written);
362        self.materialized.truncate(depth);
363        result
364    }
365
366    /// A query with materialised `WITH` definitions in front of it.
367    ///
368    /// The definitions are bound first and in the order they were written, so that a later one can
369    /// read an earlier one, and then the body. The wrapping runs backwards so that the first
370    /// definition ends up outermost, which is the order they have to be filled in.
371    fn bind_materialized(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
372        let depth = self.materialized.len();
373        let held = ast.cte_list(written.ctes).to_vec();
374        let mut definitions = Vec::with_capacity(held.len());
375        for &index in &held {
376            definitions.push(self.bind_definition(ast, index)?);
377        }
378        let (mut node, scope) = self.bind_body(ast, written)?;
379        for (at, definition) in definitions.into_iter().enumerate().rev() {
380            let entry = &self.materialized[depth + at];
381            let cte = entry.cte;
382            let name = entry.name.clone();
383            let fields = entry.fields.clone();
384            let name = self.plan.intern(&name);
385            let columns = self.plan.add_fields(&fields);
386            node =
387                self.add_node(Node::MaterializedCte { definition, body: node, name, cte, columns });
388        }
389        Ok((node, scope))
390    }
391
392    /// Binds one materialised `WITH` definition and makes its name readable from there on.
393    ///
394    /// The definition is projected onto exactly the columns a read of it sees, under the names the
395    /// column list declared when there was one. That projection is not decoration: what is held is
396    /// what a read gets back, so the held rows have to be the rows of the definition's own select
397    /// list and nothing it happened to carry along underneath.
398    ///
399    /// A column list with more names in it than the definition has columns is not an error here,
400    /// which is the pinned build's rule and is written out on [`Scope::rename_prefix`].
401    fn bind_definition(&mut self, ast: &Ast, index: u32) -> Result<NodeRef> {
402        let held = ast.cte(index);
403        let name = ast.string(held.name).to_string();
404        let (node, mut scope) = self.bind_query(ast, held.query)?;
405        if !held.columns.is_empty() {
406            let names: Vec<&str> = ast.name(held.columns).collect();
407            scope.rename_prefix(&names);
408        }
409        let table = self.fresh_index();
410        let mut exprs = Vec::with_capacity(scope.len());
411        let mut names = Vec::with_capacity(scope.len());
412        for column in &scope.columns {
413            exprs.push(self.plan.add_expr(Expr::Column(column.binding), column.ty.clone()));
414            names.push(self.plan.intern(&column.name));
415        }
416        let exprs = self.plan.add_expr_list(&exprs);
417        let names = self.plan.add_name_list(&names);
418        let node = self.add_node(Node::Project { input: node, index: table, exprs, names });
419        let cte = self.next_cte;
420        self.next_cte += 1;
421        self.materialized.push(Materialized { written: index, cte, name, fields: scope.fields() });
422        Ok(node)
423    }
424
425    fn bind_body(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
426        match written.body {
427            ast::QueryBody::Select(select) => self.bind_select(ast, select, written),
428            ast::QueryBody::SetOp { op, quantifier, by_name, left, right } => {
429                if by_name {
430                    return Err(Error::not_implemented("UNION BY NAME"));
431                }
432                self.bind_set_op(ast, written, op, quantifier, left, right)
433            }
434            ast::QueryBody::Values(rows) => self.bind_values(ast, written, rows),
435            ast::QueryBody::Describe(inner) => self.bind_describe(ast, written, inner),
436            ast::QueryBody::Show { name, relation } => self.bind_show(ast, written, name, relation),
437        }
438    }
439
440    /// `SHOW name`, resolved while binding so execution receives an ordinary constant plan.
441    fn bind_show(
442        &mut self,
443        ast: &Ast,
444        query: &ast::Query,
445        name: ast::Slice,
446        relation: ast::QueryRef,
447    ) -> Result<(NodeRef, Scope)> {
448        let text = ast.name_text(name);
449        let parts: Vec<&str> = ast.name(name).collect();
450        let table_exists = self.catalog.resolve(&parts).is_ok();
451        let as_table = match self.semantics.show_behavior() {
452            ShowBehavior::Auto => table_exists,
453            ShowBehavior::Setting => false,
454            ShowBehavior::Table => true,
455        };
456        if as_table {
457            return self.bind_describe(ast, query, relation);
458        }
459        let Some((_, value)) =
460            self.session.iter().find(|(name, _)| name.eq_ignore_ascii_case(&text))
461        else {
462            return Err(Error::catalog(format!("Setting with name \"{text}\" does not exist")));
463        };
464        let field = Field::new(text, LogicalType::Varchar);
465        let expr = self.plan.add_constant(Value::Varchar(value.to_string()));
466        let row = self.plan.add_expr_list(&[expr]);
467        let rows = self.plan.add_rows(&[row]);
468        let columns = self.plan.add_fields(std::slice::from_ref(&field));
469        let index = self.fresh_index();
470        let node = self.add_node(Node::Values { index, columns, rows });
471        let mut scope = Scope::empty();
472        scope.push(Visible {
473            table: String::new(),
474            name: field.name,
475            binding: ColumnBinding::new(index, 0),
476            ty: LogicalType::Varchar,
477            not_null: false,
478        });
479        Ok((node, scope))
480    }
481
482    /// `DESCRIBE <query>`, which is six VARCHAR columns saying what the query returns.
483    ///
484    /// The query is bound and never run, because binding is the whole of the answer: the names and
485    /// the types of a query's columns are settled by the time the binder is done with it, so the
486    /// rows of a describe are a constant from there on. That is why this comes out as a `VALUES`
487    /// whose rows were computed here rather than as an operator of its own, and it is what makes
488    /// `SELECT column_name FROM (DESCRIBE ...) WHERE ...` an ordinary query over an ordinary
489    /// relation with no special case above it.
490    ///
491    /// The six columns, their order and their types are the reference binary's. `key`, `default`
492    /// and `extra` are null for everything this engine can declare, since `PRIMARY KEY`, `UNIQUE`
493    /// and `DEFAULT` are all refused by `CREATE TABLE` today and there is nothing for the first two
494    /// to hold, and `extra` is empty upstream as well on every table it was asked about. They are
495    /// here rather than left out because the width of a result is part of the result, and a program
496    /// that reads the fifth column has to find one.
497    fn bind_describe(
498        &mut self,
499        ast: &Ast,
500        query: &ast::Query,
501        inner: ast::QueryRef,
502    ) -> Result<(NodeRef, Scope)> {
503        let (_, described) = self.bind_query(ast, inner)?;
504        let fields: Vec<Field> = ["column_name", "column_type", "null", "key", "default", "extra"]
505            .iter()
506            .map(|name| Field::new(*name, LogicalType::Varchar))
507            .collect();
508        let mut slices = Vec::with_capacity(described.columns.len());
509        for column in described.columns.clone() {
510            // `NO` and `YES` and not a boolean, because the column is VARCHAR upstream and a
511            // client that prints the result has to get the same four or three characters.
512            let written = [
513                column.name.clone(),
514                column.ty.to_string(),
515                if column.not_null { "NO" } else { "YES" }.to_owned(),
516            ];
517            let mut items: Vec<ExprRef> = written
518                .into_iter()
519                .map(|text| self.plan.add_constant(Value::Varchar(text)))
520                .collect();
521            for _ in 0..3 {
522                let empty = self.plan.add_constant(Value::Null);
523                items.push(self.cast_to(empty, &LogicalType::Varchar));
524            }
525            slices.push(self.plan.add_expr_list(&items));
526        }
527        let rows = self.plan.add_rows(&slices);
528        let columns = self.plan.add_fields(&fields);
529        let index = self.fresh_index();
530        let mut node = self.add_node(Node::Values { index, columns, rows });
531        let mut scope = Scope::empty();
532        for (at, field) in fields.iter().enumerate() {
533            scope.push(Visible {
534                table: String::new(),
535                name: field.name.clone(),
536                binding: ColumnBinding::new(index, at as u32),
537                ty: field.ty.clone(),
538                not_null: false,
539            });
540        }
541        let keys = self.sort_keys(ast, query, &scope, &[])?;
542        if !keys.is_empty() {
543            let keys = self.plan.add_sort_keys(&keys);
544            node = self.add_node(Node::Sort { input: node, keys });
545        }
546        node = self.apply_limit(ast, query, node)?;
547        Ok((node, scope))
548    }
549
550    /// Whether a projected expression is a column passed straight through from below.
551    ///
552    /// Only `DESCRIBE` asks, and only to decide whether the `null` column says `NO`. Anything that
553    /// is computed is nullable however strict its inputs were, which is both the safe reading and
554    /// the one the reference binary gives.
555    fn passes_through(&self, expr: ExprRef, input: &Scope) -> bool {
556        let Expr::Column(binding) = *self.plan.expr(expr) else { return false };
557        input.columns.iter().any(|column| column.binding == binding && column.not_null)
558    }
559
560    /// `VALUES (1, 'a'), (2, 'b')`, as a query in its own right.
561    ///
562    /// The column names are `col0`, `col1` and so on, which is what DuckDB calls them, and the
563    /// column types are what every row in that position promotes to. Promotion is the same rule a
564    /// set operation uses, and for the same reason: a column has one type and the rows have to
565    /// agree on it before anything downstream can read the column.
566    fn bind_values(
567        &mut self,
568        ast: &Ast,
569        query: &ast::Query,
570        rows: ast::Slice,
571    ) -> Result<(NodeRef, Scope)> {
572        let written = ast.rows(rows).to_vec();
573        let Some(first) = written.first() else {
574            return Err(Error::binder("VALUES needs at least one row"));
575        };
576        let width = first.len as usize;
577        for (at, row) in written.iter().enumerate() {
578            if row.len as usize != width {
579                return Err(Error::binder(format!(
580                    "VALUES lists must all be the same length, expected {width} columns but row {} has {}",
581                    at + 1,
582                    row.len
583                )));
584            }
585        }
586        // A row of a `VALUES` cannot see a column, because there is nothing under it to see.
587        let empty = Scope::empty();
588        let previous = std::mem::replace(&mut self.clause, "VALUES clause");
589        let mut bound: Vec<Vec<ExprRef>> = Vec::with_capacity(written.len());
590        for row in &written {
591            let mut items = Vec::with_capacity(width);
592            for &expr in ast.expr_list(*row) {
593                items.push(self.bind_expr(ast, expr, &empty)?);
594            }
595            bound.push(items);
596        }
597        self.clause = previous;
598        let mut types = Vec::with_capacity(width);
599        for at in 0..width {
600            let mut ty = self.plan.expr_type(bound[0][at]).clone();
601            for row in &bound[1..] {
602                let other = self.plan.expr_type(row[at]).clone();
603                ty = ty.promote(&other).ok_or_else(|| {
604                    Error::binder(format!(
605                        "Cannot combine a value of type {ty} with a value of type {other} in column {} of a VALUES",
606                        at + 1
607                    ))
608                })?;
609            }
610            types.push(ty);
611        }
612        let mut slices = Vec::with_capacity(bound.len());
613        for row in &bound {
614            let items: Vec<ExprRef> = row
615                .iter()
616                .zip(&types)
617                .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
618                .collect::<Result<_>>()?;
619            slices.push(self.plan.add_expr_list(&items));
620        }
621        let rows = self.plan.add_rows(&slices);
622        let fields: Vec<Field> = types
623            .iter()
624            .enumerate()
625            .map(|(at, ty)| Field::new(format!("col{at}"), ty.clone()))
626            .collect();
627        let columns = self.plan.add_fields(&fields);
628        let index = self.fresh_index();
629        let mut node = self.add_node(Node::Values { index, columns, rows });
630        let mut scope = Scope::empty();
631        for (at, field) in fields.iter().enumerate() {
632            scope.push(Visible {
633                table: String::new(),
634                name: field.name.clone(),
635                binding: ColumnBinding::new(index, at as u32),
636                ty: field.ty.clone(),
637                not_null: false,
638            });
639        }
640        let keys = self.sort_keys(ast, query, &scope, &[])?;
641        if !keys.is_empty() {
642            let keys = self.plan.add_sort_keys(&keys);
643            node = self.add_node(Node::Sort { input: node, keys });
644        }
645        node = self.apply_limit(ast, query, node)?;
646        Ok((node, scope))
647    }
648
649    fn bind_set_op(
650        &mut self,
651        ast: &Ast,
652        query: &ast::Query,
653        op: SetOp,
654        quantifier: Quantifier,
655        left: ast::QueryRef,
656        right: ast::QueryRef,
657    ) -> Result<(NodeRef, Scope)> {
658        let (left_node, left_scope) = self.bind_query(ast, left)?;
659        let (right_node, right_scope) = self.bind_query(ast, right)?;
660        if left_scope.len() != right_scope.len() {
661            return Err(Error::binder(format!(
662                "Set operations can only apply to expressions with the same number of result columns, but left side has {} and right side has {}",
663                left_scope.len(),
664                right_scope.len()
665            )));
666        }
667        // Both sides have to hand back one set of types, so each column meets the other side's.
668        let mut types = Vec::with_capacity(left_scope.len());
669        for (left, right) in left_scope.columns.iter().zip(&right_scope.columns) {
670            let common = left.ty.promote(&right.ty).ok_or_else(|| {
671                Error::binder(format!(
672                    "Cannot combine a column of type {} with a column of type {} in a set operation",
673                    left.ty, right.ty
674                ))
675            })?;
676            types.push(common);
677        }
678        let left_node = self.conform(left_node, &left_scope, &types)?;
679        let right_node = self.conform(right_node, &right_scope, &types)?;
680        let index = self.fresh_index();
681        let kind = match op {
682            SetOp::Union => SetOpKind::Union,
683            SetOp::Except => SetOpKind::Except,
684            SetOp::Intersect => SetOpKind::Intersect,
685        };
686        // UNION alone removes duplicates and UNION ALL keeps them, which is the one place the
687        // unwritten quantifier and ALL disagree.
688        let all = quantifier == Quantifier::All;
689        let mut node =
690            self.add_node(Node::SetOp { left: left_node, right: right_node, kind, all, index });
691        let mut scope = Scope::empty();
692        for (at, (column, ty)) in left_scope.columns.iter().zip(&types).enumerate() {
693            scope.push(Visible {
694                table: String::new(),
695                name: column.name.clone(),
696                binding: ColumnBinding::new(index, at as u32),
697                ty: ty.clone(),
698                // A column of a set operation is nullable whatever the two sides were, because a
699                // column that refuses nulls on one side and takes them on the other takes them.
700                not_null: false,
701            });
702        }
703        // Above a set operation there is nothing but the output columns, so an ORDER BY term is
704        // either a position, an output name, or an expression over the output, and never needs a
705        // column projected for it that the query did not ask for.
706        let keys = self.sort_keys(ast, query, &scope, &[])?;
707        if !keys.is_empty() {
708            let keys = self.plan.add_sort_keys(&keys);
709            node = self.add_node(Node::Sort { input: node, keys });
710        }
711        node = self.apply_limit(ast, query, node)?;
712        Ok((node, scope))
713    }
714
715    /// Projects one side of a set operation so that its columns have the agreed types.
716    fn conform(&mut self, node: NodeRef, scope: &Scope, types: &[LogicalType]) -> Result<NodeRef> {
717        if scope.columns.iter().zip(types).all(|(column, ty)| &column.ty == ty) {
718            return Ok(node);
719        }
720        let index = self.fresh_index();
721        let mut exprs = Vec::with_capacity(types.len());
722        let mut names = Vec::with_capacity(types.len());
723        for (column, ty) in scope.columns.iter().zip(types) {
724            let expr = self.plan.add_expr(Expr::Column(column.binding), column.ty.clone());
725            exprs.push(self.checked_cast_to(expr, ty, false)?);
726            names.push(self.plan.intern(&column.name));
727        }
728        let exprs = self.plan.add_expr_list(&exprs);
729        let names = self.plan.add_name_list(&names);
730        Ok(self.add_node(Node::Project { input: node, index, exprs, names }))
731    }
732
733    // ----------------------------------------------------------------- select
734
735    fn bind_select(
736        &mut self,
737        ast: &Ast,
738        select: ast::SelectRef,
739        query: &ast::Query,
740    ) -> Result<(NodeRef, Scope)> {
741        let written = ast.select(select);
742        // A window belongs to the block that wrote it, and a block can be bound inside another one
743        // without a subquery in between, so the outer block's runs are put aside for the duration
744        // rather than left where a nested block would append to them.
745        let outer_windows = std::mem::take(&mut self.windows);
746        let (mut node, input) = self.bind_from(ast, written.from)?;
747        node = self.attach_scalar_subqueries(node);
748
749        if written.filter != NONE {
750            self.clause = "WHERE clause";
751            let predicate = self.bind_expr(ast, written.filter, &input)?;
752            let predicate = self.as_boolean(predicate, "WHERE")?;
753            node = self.attach_scalar_subqueries(node);
754            node = self.add_node(Node::Filter { input: node, predicate });
755        }
756
757        let targets = ast.target_list(written.targets).to_vec();
758        if targets.is_empty() {
759            return Err(Error::binder("a SELECT needs at least one expression to select"));
760        }
761
762        let group_items = self.group_items(ast, &written, &targets)?;
763        let aggregating = !group_items.is_empty()
764            || written.having != NONE
765            || targets.iter().any(|target| has_aggregate(ast, target.expr));
766        if aggregating {
767            self.clause = "GROUP BY clause";
768            let mut groups = Vec::with_capacity(group_items.len());
769            for item in &group_items {
770                groups.push(self.bind_expr(ast, *item, &input)?);
771            }
772            let index = self.fresh_index();
773            self.aggregation = Some(Aggregation { index, groups, aggregates: Vec::new() });
774        }
775
776        self.clause = "SELECT clause";
777        let (mut exprs, mut names) = self.bind_targets(ast, &targets, &input)?;
778        let visible = exprs.len();
779
780        let mut having = None;
781        if written.having != NONE {
782            self.clause = "HAVING clause";
783            let predicate = self.bind_expr(ast, written.having, &input)?;
784            let predicate = self.over_aggregate(predicate, &input)?;
785            having = Some(self.as_boolean(predicate, "HAVING")?);
786        }
787
788        // The projection's index has to exist before the sort keys are built, because a key is a
789        // reference to a projected column even when the expression it sorts on is not selected.
790        let project = self.fresh_index();
791        let mut output = Scope::empty();
792        for (at, (expr, name)) in exprs.iter().zip(&names).enumerate() {
793            output.push(Visible {
794                table: String::new(),
795                name: name.clone(),
796                binding: ColumnBinding::new(project, at as u32),
797                ty: self.plan.expr_type(*expr).clone(),
798                not_null: self.passes_through(*expr, &input),
799            });
800        }
801
802        self.clause = "ORDER BY clause";
803        let mut extra = Vec::new();
804        let keys = self.select_sort_keys(
805            ast, query, &input, &output, project, &mut exprs, &mut names, &mut extra,
806        )?;
807        if !extra.is_empty() && written.distinct != Distinct::No {
808            return Err(Error::binder(
809                "For SELECT DISTINCT, ORDER BY expressions must appear in the select list",
810            ));
811        }
812        let on = self.distinct_on(ast, written.distinct, &output)?;
813
814        node = self.attach_scalar_subqueries(node);
815
816        if let Some(aggregation) = self.aggregation.take() {
817            let index = aggregation.index;
818            let groups = self.plan.add_expr_list(&aggregation.groups);
819            let aggregates = self.plan.add_expr_list(&aggregation.aggregates);
820            node = self.add_node(Node::Aggregate { input: node, index, groups, aggregates });
821        }
822        if let Some(predicate) = having {
823            node = self.add_node(Node::Filter { input: node, predicate });
824        }
825
826        // After the grouping and after `HAVING`, which is where the reference binary puts it:
827        // `SELECT j, sum(count(i)) OVER () FROM t GROUP BY j HAVING count(i) > 1` totals only the
828        // groups that survived the filter.
829        for run in std::mem::replace(&mut self.windows, outer_windows) {
830            let partition = self.plan.add_expr_list(&run.partition);
831            let order = self.plan.add_sort_keys(&run.order);
832            let expressions = self.plan.add_expr_list(&run.calls);
833            node = self.add_node(Node::Window {
834                input: node,
835                index: run.index,
836                partition,
837                order,
838                frame: run.frame,
839                expressions,
840            });
841        }
842
843        let interned: Vec<u32> = names.iter().map(|name| self.plan.intern(name)).collect();
844        let exprs_slice = self.plan.add_expr_list(&exprs);
845        let names_slice = self.plan.add_name_list(&interned);
846        node = self.add_node(Node::Project {
847            input: node,
848            index: project,
849            exprs: exprs_slice,
850            names: names_slice,
851        });
852
853        if written.distinct != Distinct::No {
854            let on = self.plan.add_expr_list(&on);
855            node = self.add_node(Node::Distinct { input: node, on });
856        }
857        if !keys.is_empty() {
858            let keys = self.plan.add_sort_keys(&keys);
859            node = self.add_node(Node::Sort { input: node, keys });
860        }
861        node = self.apply_limit(ast, query, node)?;
862
863        if extra.is_empty() {
864            output.columns.truncate(visible);
865            return Ok((node, output));
866        }
867        // An expression sorted on but not selected was carried this far to make the sort possible,
868        // and now it goes, because the query did not ask for it.
869        let index = self.fresh_index();
870        let mut kept = Vec::with_capacity(visible);
871        let mut kept_names = Vec::with_capacity(visible);
872        let mut scope = Scope::empty();
873        for (at, name) in names.iter().enumerate().take(visible) {
874            let ty = output.columns[at].ty.clone();
875            kept.push(self.column(project, at, ty.clone()));
876            kept_names.push(self.plan.intern(name));
877            scope.push(Visible {
878                table: String::new(),
879                name: name.clone(),
880                binding: ColumnBinding::new(index, at as u32),
881                ty,
882                not_null: output.columns[at].not_null,
883            });
884        }
885        let exprs = self.plan.add_expr_list(&kept);
886        let names = self.plan.add_name_list(&kept_names);
887        node = self.add_node(Node::Project { input: node, index, exprs, names });
888        Ok((node, scope))
889    }
890
891    /// Binds the target list, expanding every star into the columns it stands for.
892    fn bind_targets(
893        &mut self,
894        ast: &Ast,
895        targets: &[ast::Target],
896        input: &Scope,
897    ) -> Result<(Vec<ExprRef>, Vec<String>)> {
898        let mut exprs = Vec::with_capacity(targets.len());
899        let mut names = Vec::with_capacity(targets.len());
900        for target in targets {
901            if let ast::Expr::Star { qualifier, replacements } = ast.expr(target.expr) {
902                let table = ast.name(qualifier).last().map(str::to_string);
903                let expanded: Vec<Visible> =
904                    input.star(table.as_deref())?.into_iter().cloned().collect();
905                let replacements = ast.target_list(replacements).to_vec();
906                let mut used = vec![false; replacements.len()];
907                for column in expanded {
908                    let found = replacements.iter().zip(&mut used).find(|(replacement, _)| {
909                        same_name(ast.string(replacement.alias), &column.name)
910                    });
911                    // The replacement takes the column's place and its position, and it is named the
912                    // way the replace list spells it rather than the way the table does. That only
913                    // shows when the two differ in case, and `AS EventDate` over a column called
914                    // `eventdate` is exactly the case that shows it.
915                    let (expr, name) = match found {
916                        Some((replacement, used)) => {
917                            *used = true;
918                            let expr = self.bind_expr(ast, replacement.expr, input)?;
919                            (expr, ast.string(replacement.alias).to_string())
920                        }
921                        None => (
922                            self.plan.add_expr(Expr::Column(column.binding), column.ty),
923                            column.name,
924                        ),
925                    };
926                    exprs.push(self.over_aggregate(expr, input)?);
927                    names.push(name);
928                }
929                // A replace list that named something the star did not stand for is a mistake and
930                // not a no op, and it is caught here because this is the first point at which the
931                // set of names the star stands for is known.
932                if let Some((replacement, _)) =
933                    replacements.iter().zip(&used).find(|(_, used)| !**used)
934                {
935                    return Err(missing_replacement(ast.string(replacement.alias), input));
936                }
937                continue;
938            }
939            let expr = self.bind_expr(ast, target.expr, input)?;
940            exprs.push(self.over_aggregate(expr, input)?);
941            names.push(if target.alias == NONE {
942                self.output_name(ast, target.expr, input)
943            } else {
944                ast.string(target.alias).to_string()
945            });
946        }
947        Ok((exprs, names))
948    }
949
950    /// The name an unaliased target gets.
951    ///
952    /// A bare column keeps the spelling the table was created with rather than the spelling the
953    /// query used, so `SELECT USERID FROM hits` has a column called `UserID`. Identifiers match
954    /// without regard to case and the catalog is the one that holds the case.
955    fn output_name(&self, ast: &Ast, target: ast::ExprRef, input: &Scope) -> String {
956        if let ast::Expr::Column { name } = ast.expr(target) {
957            let parts: Vec<&str> = ast.name(name).collect();
958            if let Ok(found) = input.resolve(&parts) {
959                return found.name.clone();
960            }
961        }
962        describe(ast, target, self.semantics)
963    }
964
965    /// The expressions a `GROUP BY` clause names, with positions and output aliases followed.
966    fn group_items(
967        &self,
968        ast: &Ast,
969        select: &ast::Select,
970        targets: &[ast::Target],
971    ) -> Result<Vec<ast::ExprRef>> {
972        if select.group_by_all {
973            // GROUP BY ALL means every target that is not itself an aggregate, which is the set
974            // that would otherwise have to be written out again by hand.
975            return Ok(targets
976                .iter()
977                .filter(|target| !has_aggregate(ast, target.expr))
978                .map(|target| target.expr)
979                .collect());
980        }
981        let mut items = Vec::new();
982        for &item in ast.expr_list(select.group_by) {
983            items.push(self.output_reference(ast, item, targets, "GROUP BY")?.unwrap_or(item));
984        }
985        Ok(items)
986    }
987
988    /// The target a `GROUP BY` or `ORDER BY` term names, when it names one by position or alias.
989    fn output_reference(
990        &self,
991        ast: &Ast,
992        item: ast::ExprRef,
993        targets: &[ast::Target],
994        clause: &str,
995    ) -> Result<Option<ast::ExprRef>> {
996        match ast.expr(item) {
997            ast::Expr::Literal { kind: LiteralKind::Number, text } => {
998                let written = ast.string(text);
999                let position: usize = written.parse().map_err(|_| {
1000                    Error::binder(format!("{clause} term {written} is not a column"))
1001                })?;
1002                if position == 0 || position > targets.len() {
1003                    return Err(Error::binder(format!(
1004                        "{clause} term out of range - should be between 1 and {}",
1005                        targets.len()
1006                    )));
1007                }
1008                Ok(Some(targets[position - 1].expr))
1009            }
1010            ast::Expr::Column { name } => {
1011                let parts: Vec<&str> = ast.name(name).collect();
1012                let [written] = parts.as_slice() else { return Ok(None) };
1013                let mut found = None;
1014                for target in targets {
1015                    if target.alias != NONE && same_name(ast.string(target.alias), written) {
1016                        if found.is_some() {
1017                            return Ok(None);
1018                        }
1019                        found = Some(target.expr);
1020                    }
1021                }
1022                Ok(found)
1023            }
1024            _ => Ok(None),
1025        }
1026    }
1027
1028    // -------------------------------------------------------------- modifiers
1029
1030    /// Sort keys for a select, projecting anything sorted on that is not already selected.
1031    #[allow(clippy::too_many_arguments)]
1032    fn select_sort_keys(
1033        &mut self,
1034        ast: &Ast,
1035        query: &ast::Query,
1036        input: &Scope,
1037        output: &Scope,
1038        project: u32,
1039        exprs: &mut Vec<ExprRef>,
1040        names: &mut Vec<String>,
1041        extra: &mut Vec<usize>,
1042    ) -> Result<Vec<SortKey>> {
1043        if query.order_by_all {
1044            return Ok(self.every_column(output));
1045        }
1046        let items = ast.order_list(query.order_by).to_vec();
1047        let mut keys = Vec::with_capacity(items.len());
1048        for item in items {
1049            self.check_order_literal(ast, item.expr)?;
1050            let position = match self.output_position(ast, item.expr, output)? {
1051                Some(position) => position,
1052                None => {
1053                    let bound = self.bind_expr(ast, item.expr, input)?;
1054                    let bound = self.over_aggregate(bound, input)?;
1055                    match exprs.iter().position(|&held| self.same_expr(held, bound)) {
1056                        Some(position) => position,
1057                        None => {
1058                            exprs.push(bound);
1059                            names.push(describe(ast, item.expr, self.semantics));
1060                            extra.push(exprs.len() - 1);
1061                            exprs.len() - 1
1062                        }
1063                    }
1064                }
1065            };
1066            let ty = self.plan.expr_type(exprs[position]).clone();
1067            let expr = self.column(project, position, ty);
1068            keys.push(self.sort_key(expr, item));
1069        }
1070        Ok(keys)
1071    }
1072
1073    /// Sort keys over an output that has nothing behind it to project, which is a set operation.
1074    fn sort_keys(
1075        &mut self,
1076        ast: &Ast,
1077        query: &ast::Query,
1078        output: &Scope,
1079        targets: &[ast::Target],
1080    ) -> Result<Vec<SortKey>> {
1081        if query.order_by_all {
1082            return Ok(self.every_column(output));
1083        }
1084        let items = ast.order_list(query.order_by).to_vec();
1085        let mut keys = Vec::with_capacity(items.len());
1086        for item in items {
1087            self.check_order_literal(ast, item.expr)?;
1088            let expr = match self.output_position(ast, item.expr, output)? {
1089                Some(position) => {
1090                    let column = &output.columns[position];
1091                    let (binding, ty) = (column.binding, column.ty.clone());
1092                    self.plan.add_expr(Expr::Column(binding), ty)
1093                }
1094                None => {
1095                    let _ = targets;
1096                    self.bind_expr(ast, item.expr, output)?
1097                }
1098            };
1099            keys.push(self.sort_key(expr, item));
1100        }
1101        Ok(keys)
1102    }
1103
1104    fn every_column(&mut self, output: &Scope) -> Vec<SortKey> {
1105        let columns: Vec<(ColumnBinding, LogicalType)> =
1106            output.columns.iter().map(|column| (column.binding, column.ty.clone())).collect();
1107        columns
1108            .into_iter()
1109            .map(|(binding, ty)| {
1110                let expr = self.plan.add_expr(Expr::Column(binding), ty);
1111                let descending = self.semantics.default_descending();
1112                SortKey { expr, descending, nulls_first: self.semantics.nulls_first(descending) }
1113            })
1114            .collect()
1115    }
1116
1117    /// A sort key with the session defaults filled in.
1118    fn sort_key(&self, expr: ExprRef, item: ast::OrderItem) -> SortKey {
1119        let descending = match item.order {
1120            Order::Unstated => self.semantics.default_descending(),
1121            Order::Ascending => false,
1122            Order::Descending => true,
1123        };
1124        let nulls_first = match item.nulls {
1125            Nulls::First => true,
1126            Nulls::Last => false,
1127            Nulls::Unstated => self.semantics.nulls_first(descending),
1128        };
1129        SortKey { expr, descending, nulls_first }
1130    }
1131
1132    /// Which output column a term names, by position or by name.
1133    fn output_position(
1134        &self,
1135        ast: &Ast,
1136        item: ast::ExprRef,
1137        output: &Scope,
1138    ) -> Result<Option<usize>> {
1139        match ast.expr(item) {
1140            ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1141                let written = ast.string(text);
1142                if written.contains(['.', 'e', 'E']) {
1143                    return Ok(None);
1144                }
1145                let position: usize = written.parse().map_err(|_| {
1146                    Error::binder(format!("ORDER BY term {written} is not a column"))
1147                })?;
1148                if position == 0 || position > output.len() {
1149                    return Err(Error::binder(format!(
1150                        "ORDER BY term out of range - should be between 1 and {}",
1151                        output.len()
1152                    )));
1153                }
1154                Ok(Some(position - 1))
1155            }
1156            ast::Expr::Column { name } => {
1157                let parts: Vec<&str> = ast.name(name).collect();
1158                let [written] = parts.as_slice() else { return Ok(None) };
1159                Ok(output.position_of(None, written))
1160            }
1161            _ => Ok(None),
1162        }
1163    }
1164
1165    /// Refuses a literal sort key unless the session explicitly accepts its no-op behavior.
1166    fn check_order_literal(&self, ast: &Ast, item: ast::ExprRef) -> Result<()> {
1167        if !self.semantics.order_by_non_integer_literal()
1168            && matches!(
1169                ast.expr(item),
1170                ast::Expr::Literal { kind, text }
1171                    if kind != LiteralKind::Number
1172                        || ast.string(text).contains(['.', 'e', 'E'])
1173            )
1174        {
1175            return Err(Error::binder(
1176                "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to allow this behavior.",
1177            ));
1178        }
1179        Ok(())
1180    }
1181
1182    /// The expressions a `DISTINCT ON` names, which have to be columns of the output.
1183    fn distinct_on(
1184        &mut self,
1185        ast: &Ast,
1186        distinct: Distinct,
1187        output: &Scope,
1188    ) -> Result<Vec<ExprRef>> {
1189        let Distinct::On(items) = distinct else {
1190            return Ok(Vec::new());
1191        };
1192        let items = ast.expr_list(items).to_vec();
1193        let mut on = Vec::with_capacity(items.len());
1194        for item in items {
1195            let Some(position) = self.output_position(ast, item, output)? else {
1196                return Err(Error::not_implemented(
1197                    "DISTINCT ON an expression that is not in the select list",
1198                ));
1199            };
1200            let column = &output.columns[position];
1201            let (binding, ty) = (column.binding, column.ty.clone());
1202            on.push(self.plan.add_expr(Expr::Column(binding), ty));
1203        }
1204        Ok(on)
1205    }
1206
1207    fn apply_limit(&mut self, ast: &Ast, query: &ast::Query, input: NodeRef) -> Result<NodeRef> {
1208        if query.limit_percent {
1209            return Err(Error::not_implemented("LIMIT with a percentage"));
1210        }
1211        let count = self.constant_count(ast, query.limit, "LIMIT")?;
1212        let offset = self.constant_count(ast, query.offset, "OFFSET")?.unwrap_or(0);
1213        if count.is_none() && offset == 0 {
1214            return Ok(input);
1215        }
1216        Ok(self.add_node(Node::Limit { input, count, offset }))
1217    }
1218
1219    /// The row count a `LIMIT` or an `OFFSET` names, which has to be a constant.
1220    fn constant_count(
1221        &mut self,
1222        ast: &Ast,
1223        written: ast::ExprRef,
1224        clause: &str,
1225    ) -> Result<Option<u64>> {
1226        if written == NONE {
1227            return Ok(None);
1228        }
1229        self.clause = "LIMIT clause";
1230        let scope = Scope::empty();
1231        let bound = self.bind_expr(ast, written, &scope)?;
1232        let Expr::Constant(value) = *self.plan.expr(bound) else {
1233            return Err(Error::not_implemented(format!("a {clause} that is not a constant")));
1234        };
1235        let count = match self.plan.value(value) {
1236            Value::Null => return Ok(None),
1237            Value::TinyInt(count) => i128::from(*count),
1238            Value::SmallInt(count) => i128::from(*count),
1239            Value::Integer(count) => i128::from(*count),
1240            Value::BigInt(count) => i128::from(*count),
1241            Value::HugeInt(count) => *count,
1242            other => {
1243                return Err(Error::binder(format!(
1244                    "{clause} takes a whole number of rows, not a value of type {}",
1245                    other.logical_type()
1246                )));
1247            }
1248        };
1249        u64::try_from(count)
1250            .map(Some)
1251            .map_err(|_| Error::binder(format!("{clause} must not be negative")))
1252    }
1253
1254    // ------------------------------------------------------------------- from
1255
1256    fn bind_from(&mut self, ast: &Ast, from: ast::Slice) -> Result<(NodeRef, Scope)> {
1257        let sources = ast.source_list(from).to_vec();
1258        let Some((first, rest)) = sources.split_first() else {
1259            // No FROM clause is one row of no columns, which is what SELECT 1 sits on. Not an
1260            // empty table: an empty table would make SELECT 1 return nothing.
1261            return Ok((self.add_node(Node::Dummy), Scope::empty()));
1262        };
1263        let (mut node, mut scope) = self.bind_source(ast, *first)?;
1264        for source in rest {
1265            let (right, right_scope, correlations) = self.bind_lateral(ast, *source, &scope)?;
1266            node = if correlations.is_empty() {
1267                self.add_node(Node::CrossProduct { left: node, right })
1268            } else {
1269                let conditions = self.plan.add_expr_list(&[]);
1270                self.add_node(Node::DependentJoin {
1271                    left: node,
1272                    right,
1273                    kind: JoinKind::Inner,
1274                    conditions,
1275                })
1276            };
1277            scope = scope.concat(right_scope);
1278        }
1279        Ok((node, scope))
1280    }
1281
1282    /// Binds one FROM entry with everything written to its left already visible.
1283    ///
1284    /// That is what LATERAL means, and it is what a comma separated FROM does here whether the word
1285    /// was written or not, because the pinned build resolves `FROM o, (SELECT o.k + 1)` without it.
1286    /// The keyword therefore changes nothing and is accepted rather than acted on.
1287    ///
1288    /// The columns of the left that the entry read come back with it, and an entry that read none
1289    /// is an ordinary product. The rest are somebody else's: a name that resolved past the left
1290    /// neighbours belongs to an enclosing query, so it is handed up to whichever frame is waiting
1291    /// for it rather than counted here, or the subquery this FROM sits in would lose track of its
1292    /// own correlation.
1293    fn bind_lateral(
1294        &mut self,
1295        ast: &Ast,
1296        source: ast::SourceRef,
1297        left: &Scope,
1298    ) -> Result<(NodeRef, Scope, Vec<ColumnBinding>)> {
1299        self.lateral_scopes.push(self.outer_scopes.len());
1300        self.outer_scopes.push(left.clone());
1301        self.correlations.push(Vec::new());
1302        let bound = self.bind_source(ast, source);
1303        let read = self.correlations.pop().expect("correlation frame");
1304        self.outer_scopes.pop();
1305        self.lateral_scopes.pop();
1306        let (node, scope) = bound?;
1307
1308        let mut here = Vec::new();
1309        for binding in read {
1310            if left.columns.iter().any(|column| column.binding == binding) {
1311                here.push(binding);
1312            } else if let Some(enclosing) = self.correlations.last_mut() {
1313                if !enclosing.contains(&binding) {
1314                    enclosing.push(binding);
1315                }
1316            }
1317        }
1318        // A table function's arguments are evaluated to produce the rows rather than over rows that
1319        // already exist, so there is nothing underneath it for the domain to be pushed into and no
1320        // projection over the domain that would say the same thing, the way there is for a VALUES.
1321        // Answering it wants an operator that evaluates a source once per value and there is none.
1322        // Said here rather than left to the executor, so the message names what was written.
1323        if !here.is_empty() && matches!(ast.source(source), ast::Source::Function { .. }) {
1324            return Err(Error::not_implemented("a table function reading a LATERAL column"));
1325        }
1326        Ok((node, scope, here))
1327    }
1328
1329    fn bind_source(&mut self, ast: &Ast, source: ast::SourceRef) -> Result<(NodeRef, Scope)> {
1330        match ast.source(source) {
1331            ast::Source::Table { name, alias, columns } => {
1332                self.bind_table(ast, name, alias, columns)
1333            }
1334            ast::Source::Function { name, args, alias, columns, pragma } => {
1335                self.bind_table_function(ast, name, args, alias, columns, pragma)
1336            }
1337            ast::Source::Subquery { query, alias, columns } => {
1338                let (node, mut scope) = self.bind_query(ast, query)?;
1339                let label = if alias == NONE {
1340                    "unnamed_subquery".to_string()
1341                } else {
1342                    ast.string(alias).to_string()
1343                };
1344                scope.relabel(&label);
1345                if !columns.is_empty() {
1346                    let names: Vec<&str> = ast.name(columns).collect();
1347                    scope.rename(&names, &label)?;
1348                }
1349                Ok((node, scope))
1350            }
1351            ast::Source::Values { rows, alias, columns } => {
1352                let bare = ast::Query::bare(ast::QueryBody::Values(rows));
1353                let (node, mut scope) = self.bind_values(ast, &bare, rows)?;
1354                let label =
1355                    if alias == NONE { String::new() } else { ast.string(alias).to_string() };
1356                scope.relabel(&label);
1357                if !columns.is_empty() {
1358                    let names: Vec<&str> = ast.name(columns).collect();
1359                    scope.rename(&names, &label)?;
1360                }
1361                Ok((node, scope))
1362            }
1363            ast::Source::Cte { cte, alias, columns } => {
1364                self.bind_cte_scan(ast, cte, alias, columns)
1365            }
1366            ast::Source::Join { left, right, kind, natural, on, using } => {
1367                self.bind_join(ast, left, right, kind, natural, on, using)
1368            }
1369        }
1370    }
1371
1372    /// A read of a materialised `WITH`, which is a leaf the same way a table scan is.
1373    ///
1374    /// Which definition it reads was settled by the parser, so there is no name to look up here and
1375    /// no shadowing left to think about. What is looked up is the materialisation that definition
1376    /// turned into, and the search runs backwards because the same definition is bound again for
1377    /// each use of a plain `WITH` it sits inside, and a read means the innermost of those.
1378    fn bind_cte_scan(
1379        &mut self,
1380        ast: &Ast,
1381        written: u32,
1382        alias: ast::StrRef,
1383        columns: ast::Slice,
1384    ) -> Result<(NodeRef, Scope)> {
1385        let Some(held) = self.materialized.iter().rev().find(|held| held.written == written) else {
1386            let name = ast.string(ast.cte(written).name);
1387            return Err(Error::binder(format!("Table with name {name} does not exist!")));
1388        };
1389        let cte = held.cte;
1390        let fields = held.fields.clone();
1391        let text = held.name.clone();
1392        let label = if alias == NONE { text.clone() } else { ast.string(alias).to_string() };
1393        let name = self.plan.intern(&text);
1394        let index = self.fresh_index();
1395        let mut scope = Scope::empty();
1396        for (at, field) in fields.iter().enumerate() {
1397            scope.push(Visible {
1398                table: label.clone(),
1399                name: field.name.clone(),
1400                binding: ColumnBinding::new(index, at as u32),
1401                ty: field.ty.clone(),
1402                not_null: field.not_null,
1403            });
1404        }
1405        if !columns.is_empty() {
1406            let names: Vec<&str> = ast.name(columns).collect();
1407            scope.rename(&names, &label)?;
1408        }
1409        let columns = self.plan.add_fields(&fields);
1410        let node = self.add_node(Node::CteScan { index, cte, name, columns });
1411        Ok((node, scope))
1412    }
1413
1414    fn bind_table(
1415        &mut self,
1416        ast: &Ast,
1417        name: ast::Slice,
1418        alias: ast::StrRef,
1419        columns: ast::Slice,
1420    ) -> Result<(NodeRef, Scope)> {
1421        let parts: Vec<&str> = ast.name(name).collect();
1422        let catalog = self.catalog;
1423        // The catalog is asked first and the file is the fallback, which is the order DuckDB uses:
1424        // a table really called `mixed.parquet` wins over a file of that name sitting next to it.
1425        let resolved = match catalog.resolve(&parts) {
1426            Ok(resolved) => resolved,
1427            Err(missing) => {
1428                return self.bind_replacement_scan(ast, &parts, alias, columns, missing);
1429            }
1430        };
1431        if catalog.entry(&resolved)? == Entry::View {
1432            return self.bind_view(ast, &resolved, alias, columns);
1433        }
1434        let table = catalog.table(&resolved)?;
1435        let fields: Vec<Field> = table.columns().to_vec();
1436        let label =
1437            if alias == NONE { resolved.table.clone() } else { ast.string(alias).to_string() };
1438        let index = self.fresh_index();
1439        let mut scope = Scope::empty();
1440        for (at, field) in fields.iter().enumerate() {
1441            scope.push(Visible {
1442                table: label.clone(),
1443                name: field.name.clone(),
1444                binding: ColumnBinding::new(index, at as u32),
1445                ty: field.ty.clone(),
1446                not_null: field.not_null,
1447            });
1448        }
1449        if !columns.is_empty() {
1450            let names: Vec<&str> = ast.name(columns).collect();
1451            scope.rename(&names, &label)?;
1452        }
1453        let catalog_name = self.plan.intern(&resolved.catalog);
1454        let schema = self.plan.intern(&resolved.schema);
1455        let table_name = self.plan.intern(&resolved.table);
1456        let alias = self.plan.intern(&label);
1457        let columns = self.plan.add_fields(&fields);
1458        let node = self.add_node(Node::Get {
1459            catalog: catalog_name,
1460            schema,
1461            table: table_name,
1462            alias,
1463            index,
1464            columns,
1465        });
1466        Ok((node, scope))
1467    }
1468
1469    /// A view where a table goes, which is the body bound again right here.
1470    ///
1471    /// Inline and not behind a node. The view is gone by the time the plan exists, so everything
1472    /// downstream sees the query somebody would have written by hand, and the column pruning that
1473    /// makes `SELECT COUNT(*) FROM 'hits.parquet'` read no columns at all keeps working through
1474    /// `FROM hits`. A `Node::View` would be a barrier with nothing on the other side of it.
1475    ///
1476    /// The scope this builds is a subquery's, right down to the name in the error message. duckdb
1477    /// v1.5.1 reports a view whose column list has gone stale as `table "unnamed_subquery" has 1
1478    /// columns available but 2 columns specified`, which is the sentence its subquery alias rule
1479    /// produces, so a view there is a subquery with the view's name written over it afterwards.
1480    fn bind_view(
1481        &mut self,
1482        ast: &Ast,
1483        name: &QualifiedName,
1484        alias: ast::StrRef,
1485        columns: ast::Slice,
1486    ) -> Result<(NodeRef, Scope)> {
1487        let view = self.catalog.view(name)?;
1488        let full = name.to_string();
1489        if self.expanding.contains(&full) {
1490            // Two quotes each side, which is what the binary prints. It quotes the name on the way
1491            // in and then formats the quoted name into a quoted slot, so a view called `a` comes
1492            // back as `""a""`. That is upstream's wart and copying it is the whole job here.
1493            return Err(Error::binder(format!(
1494                "infinite recursion detected: attempting to recursively bind view \"\"{}\"\"",
1495                name.table
1496            )));
1497        }
1498        let body = parse_ast_with_case(view.sql(), self.semantics.identifier_case())?;
1499        let query = match body.statements.as_slice() {
1500            [ast::Statement::Query(query)] => *query,
1501            // Only a query can have got past the binder at creation, so this is a view the catalog
1502            // was handed some other way rather than anything a statement can produce.
1503            _ => return Err(Error::binder(format!("view \"{}\" is not a query", name.table))),
1504        };
1505        self.expanding.push(full);
1506        let bound = self.bind_query(&body, query);
1507        self.expanding.pop();
1508        let (node, mut scope) = bound?;
1509
1510        let aliases: Vec<&str> = view.aliases().iter().map(String::as_str).collect();
1511        if !aliases.is_empty() {
1512            scope.rename(&aliases, "unnamed_subquery")?;
1513        }
1514        // What the catalog tables report as this view's columns, written down here because this is
1515        // the moment they are known. Upstream refreshes the same cache at the same point, which was
1516        // measured: both `duckdb_columns()` and `duckdb_views().column_count` keep reporting the old
1517        // list after an `ALTER TABLE` underneath until something reads the view, and then both move.
1518        // It is written before the label and before the `AS t(a, b)` list below, because those two
1519        // rename the view for one query and not for everyone.
1520        view.remember(scope.fields());
1521        let label = if alias == NONE { name.table.clone() } else { ast.string(alias).to_string() };
1522        scope.relabel(&label);
1523        if !columns.is_empty() {
1524            let names: Vec<&str> = ast.name(columns).collect();
1525            scope.rename(&names, &label)?;
1526        }
1527        Ok((node, scope))
1528    }
1529
1530    /// A function call where a table goes, such as `range(10)`.
1531    ///
1532    /// The arguments are bound against an empty scope. A table function that can see the row on its
1533    /// left is `LATERAL`, and this is not it, so a column name in here is not resolved against
1534    /// whatever happens to be to the left in the `FROM` list. Letting it would mean `FROM t,
1535    /// range(t.n)` quietly binding to something whose meaning depends on the order the sources were
1536    /// written in.
1537    fn bind_table_function(
1538        &mut self,
1539        ast: &Ast,
1540        name: ast::Slice,
1541        args: ast::Slice,
1542        alias: ast::StrRef,
1543        columns: ast::Slice,
1544        pragma: bool,
1545    ) -> Result<(NodeRef, Scope)> {
1546        let parts: Vec<&str> = ast.name(name).collect();
1547        // A qualified call names a schema, and the two schemas that exist are the ones every
1548        // built-in lives in. Anything else is a name that has to fail rather than fall through to
1549        // the unqualified lookup and be found somewhere it was not asked for.
1550        let function_name = *parts.last().unwrap_or(&"");
1551        if let Some(schema) = parts.iter().rev().nth(1) {
1552            if !schema.eq_ignore_ascii_case("main") && !schema.eq_ignore_ascii_case("system") {
1553                return Err(Error::catalog(format!(
1554                    "Table Function with name {} does not exist!",
1555                    parts.join(".")
1556                )));
1557            }
1558        }
1559        // The name is looked up before the arguments are bound so that a call of something that is
1560        // not a table function says that, rather than reporting whatever is wrong with the
1561        // arguments of a function that was never going to exist.
1562        let Some(called) = TableFunction::lookup(function_name) else {
1563            if pragma {
1564                // `PRAGMA database_list` is a view upstream and not a function, and the pragma
1565                // namespace holds both, so a name that is not a function gets one more look in the
1566                // catalog before it is turned down. It has to be the no argument form: a view
1567                // takes none, and `pragma_database_list()` with parentheses is a missing function
1568                // on the pin too.
1569                if args.is_empty() && self.catalog.resolve(&parts).is_ok() {
1570                    return self.bind_table(ast, name, alias, columns);
1571                }
1572                let spelled = function_name.strip_prefix("pragma_").unwrap_or(function_name);
1573                return Err(Error::catalog(format!(
1574                    "Pragma Function with name {spelled} does not exist!"
1575                )));
1576            }
1577            return Err(Error::catalog(format!(
1578                "Table Function with name {function_name} does not exist!"
1579            )));
1580        };
1581        let written = ast.target_list(args).to_vec();
1582        let empty = Scope::empty();
1583        let previous = std::mem::replace(&mut self.clause, "table function arguments");
1584        let mut bound = Vec::new();
1585        let mut written_options = Vec::new();
1586        for argument in written {
1587            let expr = self.bind_expr(ast, argument.expr, &empty)?;
1588            if argument.alias == NONE {
1589                bound.push(expr);
1590            } else {
1591                let name = ast.string(argument.alias).to_string();
1592                let (parameter, value) = self.named_argument(called, &name, expr)?;
1593                written_options.push((parameter, value, expr));
1594            }
1595        }
1596        self.clause = previous;
1597        let options = Options::of(&written_options)?;
1598
1599        // The types are what resolve the call, not the count, because `read_parquet(3)` is a
1600        // different answer from `read_parquet('3')` and only the types tell them apart.
1601        let given: Vec<LogicalType> =
1602            bound.iter().map(|&expr| self.plan.expr_type(expr).clone()).collect();
1603        let resolved = if pragma {
1604            resolve_pragma(function_name, &given)?
1605        } else {
1606            resolve_table(function_name, &given)?
1607        };
1608        let mut cast: Vec<ExprRef> = bound
1609            .iter()
1610            .zip(&resolved.arguments)
1611            .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
1612            .collect::<Result<_>>()?;
1613
1614        if resolved.function.takes_a_name() {
1615            let Columns::Fixed(fields) = resolved.columns else {
1616                return Err(Error::internal("a pragma that resolved to a file"));
1617            };
1618            let [argument] = cast[..] else {
1619                return Err(Error::internal("a pragma that resolved to more than one name"));
1620            };
1621            return self.bind_pragma(ast, resolved.function, &fields, argument, alias, columns);
1622        }
1623        let fields = match resolved.columns {
1624            Columns::Fixed(fields) => fields,
1625            columns => {
1626                // The one argument is a pattern, and what replaces it is one constant per file it
1627                // matched. The executor is handed names rather than a pattern, so it never walks a
1628                // directory and the answer cannot change between binding a prepared statement and
1629                // running it, which is the same reason the schema is settled here.
1630                let paths = self.file_paths(cast[0], resolved.function.name())?;
1631                let first = paths.first().map_or("", String::as_str);
1632                let mut fields = match columns {
1633                    // Parquet takes the first file's footer as the answer and CSV sniffs all of
1634                    // them, which is not a choice made here. See `csv_fields`.
1635                    Columns::Csv => csv_fields(&paths, options.given)?,
1636                    _ => parquet_fields(first)?,
1637                };
1638                if options.all_varchar {
1639                    // The sniffer still ran, because the names come out of the same pass over the
1640                    // front of the file and only the types are being overruled. The executor reads
1641                    // the text as VARCHAR because this is the schema it is told to read into, which
1642                    // is the same road a file in a glob takes when the set is wider than the file.
1643                    for field in &mut fields {
1644                        field.ty = LogicalType::Varchar;
1645                    }
1646                }
1647                if options.binary_as_string {
1648                    // A byte array column with no annotation on it is a BLOB, and this is the caller
1649                    // saying that the file's writer meant text. The reader already holds both in the
1650                    // same string column and already validates the bytes, so the whole of the option
1651                    // is what the column is called from here on.
1652                    for field in &mut fields {
1653                        if field.ty == LogicalType::Blob {
1654                            field.ty = LogicalType::Varchar;
1655                        }
1656                    }
1657                }
1658                if options.file_row_number {
1659                    // Not a column of the file, so it goes on the end where a projection cannot be
1660                    // confused about which one it is, and the executor counts it as the rows come
1661                    // out. A file that already has a column of that name is the one case where the
1662                    // option cannot be honoured, and saying so is better than handing back two
1663                    // columns with the same name and letting a reference to it pick one.
1664                    if fields.iter().any(|field| field.name == FILE_ROW_NUMBER) {
1665                        return Err(Error::binder(format!(
1666                            "Duplicate column name \"{FILE_ROW_NUMBER}\": the file already has a \
1667                             column of that name, so file_row_number cannot add one"
1668                        )));
1669                    }
1670                    fields.push(Field::required(FILE_ROW_NUMBER.to_string(), LogicalType::BigInt));
1671                }
1672                cast = paths.iter().map(|path| self.path_constant(path)).collect();
1673                fields
1674            }
1675        };
1676        let label = if alias == NONE {
1677            resolved.function.name().to_string()
1678        } else {
1679            ast.string(alias).to_string()
1680        };
1681        let names: Vec<&str> = ast.name(columns).collect();
1682        self.table_function_source(
1683            resolved.function,
1684            &cast,
1685            &written_options,
1686            fields,
1687            &label,
1688            &names,
1689        )
1690    }
1691
1692    /// `pragma_table_info('t')` or `pragma_show('t')`, answered while it is bound.
1693    ///
1694    /// The same trick `DESCRIBE` uses and for the same reason: the columns of a table are settled by
1695    /// the time the name has resolved, so the rows are a constant from there on and this comes out
1696    /// as a `VALUES` rather than as an operator that reads a catalog while the query runs. It also
1697    /// means `SELECT name FROM pragma_table_info('t') WHERE notnull` is an ordinary query over an
1698    /// ordinary relation, which is the whole reason these exist as functions rather than only as
1699    /// statements.
1700    ///
1701    /// The name arrives as a string rather than as something the parser read, so it is split here
1702    /// under the identifier rule and then resolved like any other name. A name that is not there
1703    /// comes back as the catalog's own complaint, which is what the pin answers with too.
1704    fn bind_pragma(
1705        &mut self,
1706        ast: &Ast,
1707        function: TableFunction,
1708        fields: &[Field],
1709        argument: ExprRef,
1710        alias: ast::StrRef,
1711        columns: ast::Slice,
1712    ) -> Result<(NodeRef, Scope)> {
1713        let written = self.pragma_name(argument, function)?;
1714        let parts = identifier_parts(&written);
1715        let spelled: Vec<&str> = parts.iter().map(String::as_str).collect();
1716        let name = self.catalog.resolve(&spelled)?;
1717        let described = self.described(ast, &name)?;
1718        let mut rows = Vec::with_capacity(described.len());
1719        for (at, field) in described.iter().enumerate() {
1720            let items = if matches!(function, TableFunction::PragmaShow) {
1721                self.describing(field)
1722            } else {
1723                self.table_info(at, field)
1724            };
1725            rows.push(self.plan.add_expr_list(&items));
1726        }
1727        let rows = self.plan.add_rows(&rows);
1728        let held = self.plan.add_fields(fields);
1729        let index = self.fresh_index();
1730        let node = self.add_node(Node::Values { index, columns: held, rows });
1731        let label =
1732            if alias == NONE { function.name().to_string() } else { ast.string(alias).to_string() };
1733        let mut scope = Scope::empty();
1734        for (at, field) in fields.iter().enumerate() {
1735            scope.push(Visible {
1736                table: label.clone(),
1737                name: field.name.clone(),
1738                binding: ColumnBinding::new(index, at as u32),
1739                ty: field.ty.clone(),
1740                not_null: false,
1741            });
1742        }
1743        if !columns.is_empty() {
1744            let names: Vec<&str> = ast.name(columns).collect();
1745            scope.rename(&names, &label)?;
1746        }
1747        Ok((node, scope))
1748    }
1749
1750    /// The name a pragma was called with, which has to be a constant.
1751    ///
1752    /// A null is a name spelled `NULL` rather than an error about nulls, because the pin turns
1753    /// whatever it was handed into text before it goes looking and then says a table of that name
1754    /// does not exist. Writing `pragma_table_info(NULL)` is a mistake either way and this is the
1755    /// sentence the mistake already has.
1756    ///
1757    /// `pragma_table_info('t' || 'x')` is the pin's `tx` and is turned away here, which is the same
1758    /// missing constant folding [`Binder::named_argument`] writes about and closes the same day.
1759    fn pragma_name(&self, argument: ExprRef, function: TableFunction) -> Result<String> {
1760        let Expr::Constant(reference) = *self.plan.expr(argument) else {
1761            return Err(Error::not_implemented(format!(
1762                "{}() given a name that is not a constant",
1763                function.name()
1764            )));
1765        };
1766        match self.plan.value(reference) {
1767            Value::Varchar(name) => Ok(name.clone()),
1768            Value::Null => Ok("NULL".to_string()),
1769            other => {
1770                Err(Error::internal(format!("a pragma name bound as VARCHAR arrived as {other}")))
1771            }
1772        }
1773    }
1774
1775    /// The columns of whatever a pragma was pointed at.
1776    ///
1777    /// A view is bound here, which is how it comes to have columns at all. Reading a view is what
1778    /// binds it and describing one counts as reading it, so a view the engine ships with reports a
1779    /// column count from this point on, the same as it would after a select. The node that binding
1780    /// produces is thrown away, because the answer is the scope and not the query.
1781    ///
1782    /// Every column of a view is nullable whatever the column underneath was declared as, which is
1783    /// the pin's answer through `pragma_table_info()`, `pragma_show()` and `duckdb_columns()` alike.
1784    /// [`Scope::fields`] drops the flag on its own, so there is nothing to clear here.
1785    fn described(&mut self, ast: &Ast, name: &QualifiedName) -> Result<Vec<Field>> {
1786        if self.catalog.entry(name)? == Entry::Table {
1787            return Ok(self.catalog.table(name)?.columns().to_vec());
1788        }
1789        let (_, scope) = self.bind_view(ast, name, NONE, ast::Slice::default())?;
1790        Ok(scope.fields())
1791    }
1792
1793    /// One row of `pragma_show()`, which is one row of `DESCRIBE` written by the other caller.
1794    fn describing(&mut self, field: &Field) -> Vec<ExprRef> {
1795        let written = [
1796            field.name.clone(),
1797            field.ty.to_string(),
1798            if field.not_null { "NO" } else { "YES" }.to_owned(),
1799        ];
1800        let mut items: Vec<ExprRef> =
1801            written.into_iter().map(|text| self.plan.add_constant(Value::Varchar(text))).collect();
1802        for _ in 0..3 {
1803            let empty = self.plan.add_constant(Value::Null);
1804            items.push(self.cast_to(empty, &LogicalType::Varchar));
1805        }
1806        items
1807    }
1808
1809    /// One row of `pragma_table_info()`, which is SQLite's six columns about the same column.
1810    ///
1811    /// `cid` counts from zero, which is SQLite's numbering and not the one based `ordinal_position`
1812    /// the standard views report. `dflt_value` and `pk` are the two nothings rudb has to report
1813    /// until `CREATE TABLE` takes a `DEFAULT` or a key.
1814    fn table_info(&mut self, at: usize, field: &Field) -> Vec<ExprRef> {
1815        let cid = self.plan.add_constant(Value::Integer(i32::try_from(at).unwrap_or(i32::MAX)));
1816        let name = self.plan.add_constant(Value::Varchar(field.name.clone()));
1817        let ty = self.plan.add_constant(Value::Varchar(field.ty.to_string()));
1818        let not_null = self.plan.add_constant(Value::Boolean(field.not_null));
1819        let default = self.plan.add_constant(Value::Null);
1820        let default = self.cast_to(default, &LogicalType::Varchar);
1821        let key = self.plan.add_constant(Value::Boolean(false));
1822        vec![cid, name, ty, not_null, default, key]
1823    }
1824
1825    /// One named parameter of a table function call, folded into what the call was given.
1826    ///
1827    /// The value has to be a constant of the type the parameter wants. It has to be constant
1828    /// because an option can decide what the columns are and the columns are settled here, and it
1829    /// has to be already of the type because there is no constant folding in front of the binder
1830    /// yet. DuckDB folds first, so `binary_as_string=1` and `binary_as_string='yes'` are both true
1831    /// there and both are turned away here, which is a gap that closes on its own the day the
1832    /// optimizer runs before the plan is finished. `binary_as_string=True` is what the ClickBench
1833    /// entry writes and is what has to work.
1834    ///
1835    /// A name that is not a parameter of this function is the binary's sentence followed by what it
1836    /// could have been. The binary puts the candidates on their own indented lines and this puts
1837    /// them on the same line, because an error is one line here.
1838    fn named_argument(
1839        &mut self,
1840        function: TableFunction,
1841        name: &str,
1842        expr: ExprRef,
1843    ) -> Result<(&'static str, Value)> {
1844        let known = function
1845            .parameters()
1846            .iter()
1847            .find(|(parameter, _)| parameter.eq_ignore_ascii_case(name));
1848        let Some((parameter, wanted)) = known else {
1849            let candidates: Vec<String> = function
1850                .parameters()
1851                .iter()
1852                .map(|(parameter, ty)| format!("    {parameter} {ty}"))
1853                .collect();
1854            return Err(Error::binder(format!(
1855                "Invalid named parameter \"{name}\" for function {}\nCandidates:\n{}\n",
1856                function.name(),
1857                candidates.join("\n")
1858            )));
1859        };
1860        let Expr::Constant(reference) = *self.plan.expr(expr) else {
1861            return Err(Error::not_implemented(format!(
1862                "the named parameter {parameter} with a value that is not a constant"
1863            )));
1864        };
1865        let value = self.plan.value(reference).clone();
1866        if value == Value::Null {
1867            return Err(Error::binder(null_parameter(function, parameter)));
1868        }
1869        let given = self.plan.expr_type(expr).clone();
1870        if given != *wanted {
1871            return Err(Error::not_implemented(format!(
1872                "the named parameter {parameter} given a {given} where a {wanted} was wanted"
1873            )));
1874        }
1875        Ok((parameter, value))
1876    }
1877
1878    /// A file where a table name goes, which is what DuckDB calls a replacement scan.
1879    ///
1880    /// `SELECT * FROM 'hits.parquet'` is how most DuckDB queries in the wild are written, ClickBench
1881    /// among them, so this is not sugar over `read_parquet` so much as the spelling people use. The
1882    /// catalog has already been asked and has already said no, and `missing` is what it said, so a
1883    /// name that is not a file comes back with the catalog's own answer rather than with a complaint
1884    /// about files.
1885    ///
1886    /// Only a single unqualified name is a candidate. A qualified one names a schema and a schema
1887    /// that does not exist is not a path.
1888    fn bind_replacement_scan(
1889        &mut self,
1890        ast: &Ast,
1891        parts: &[&str],
1892        alias: ast::StrRef,
1893        columns: ast::Slice,
1894        missing: Error,
1895    ) -> Result<(NodeRef, Scope)> {
1896        let [path] = parts else { return Err(missing) };
1897        let path = *path;
1898        let extension = path.rsplit_once('.').map(|(_, after)| after).unwrap_or_default();
1899        let Some(function) = Self::reader_for(extension) else {
1900            if is_file(path) {
1901                // A file that is really there and that nothing here can read is a different mistake
1902                // from a name that is not a file, and DuckDB says so with both lines, the second of
1903                // which is the way out. A file with no dot in it lands here too, which is why the
1904                // test is on the extension having a reader rather than on there being an extension.
1905                return Err(Error::binder(format!(
1906                    "No extension found that is capable of reading the file \"{path}\"\n* If this \
1907                     file is a supported file format you can explicitly use the reader functions, \
1908                     such as read_csv, read_json or read_parquet"
1909                )));
1910            }
1911            return Err(missing);
1912        };
1913        // The pattern is expanded before it is known to match anything, so a name that ends in .csv
1914        // and is not there gives the reader's own message rather than the catalog's. That is
1915        // DuckDB's order and it is the helpful one: somebody who wrote a file name wants to hear
1916        // about the file.
1917        let paths = files(path)?;
1918        let first = paths.first().map_or("", String::as_str);
1919        let fields = match function {
1920            TableFunction::ReadParquet => parquet_fields(first)?,
1921            _ => csv_fields(&paths, Given::default())?,
1922        };
1923        // The name the columns answer to is the file's stem, so `SELECT mixed.a FROM
1924        // 'data/mixed.parquet'` works. That is DuckDB's choice and it is the useful one, since the
1925        // alternative is a table name with a dot and a slash in it that nothing can write. A pattern
1926        // keeps the whole of what was written instead, which is DuckDB's choice too and was
1927        // measured: there is no stem to take when the name stands for a directory full of files.
1928        let label = if alias == NONE {
1929            if is_pattern(path) {
1930                path.to_string()
1931            } else {
1932                let file = path.rsplit_once('/').map_or(path, |(_, file)| file);
1933                file.rsplit_once('.').map_or(file, |(stem, _)| stem).to_string()
1934            }
1935        } else {
1936            ast.string(alias).to_string()
1937        };
1938        let arguments: Vec<ExprRef> = paths.iter().map(|path| self.path_constant(path)).collect();
1939        let names: Vec<&str> = ast.name(columns).collect();
1940        self.table_function_source(function, &arguments, &[], fields, &label, &names)
1941    }
1942
1943    /// One file name, as a constant expression in the plan.
1944    fn path_constant(&mut self, path: &str) -> ExprRef {
1945        let value = self.plan.add_value(Value::Varchar(path.to_string()));
1946        self.plan.add_expr(Expr::Constant(value), LogicalType::Varchar)
1947    }
1948
1949    /// The table function a file with this extension is read by, and `None` for one nothing reads.
1950    ///
1951    /// Both spellings of a tab separated file go to the CSV reader, which is not a shortcut: the
1952    /// extension picks the reader and the reader sniffs the punctuation, so a `.tsv` file that holds
1953    /// commas is read as commas. That was measured rather than assumed. The comparison ignores case
1954    /// because `UP.CSV` reads in duckdb v1.4.1.
1955    fn reader_for(extension: &str) -> Option<TableFunction> {
1956        if extension.eq_ignore_ascii_case("parquet") {
1957            return Some(TableFunction::ReadParquet);
1958        }
1959        if extension.eq_ignore_ascii_case("csv") || extension.eq_ignore_ascii_case("tsv") {
1960            return Some(TableFunction::ReadCsv);
1961        }
1962        None
1963    }
1964
1965    /// The node and the scope of a table function call whose arguments and columns are settled.
1966    ///
1967    /// The half a written out call shares with a replacement scan, which is everything after the
1968    /// question of what the file is called has been answered one way or the other.
1969    fn table_function_source(
1970        &mut self,
1971        function: TableFunction,
1972        args: &[ExprRef],
1973        written: &[(&'static str, Value, ExprRef)],
1974        fields: Vec<Field>,
1975        label: &str,
1976        names: &[&str],
1977    ) -> Result<(NodeRef, Scope)> {
1978        let index = self.fresh_index();
1979        let mut scope = Scope::empty();
1980        for (at, field) in fields.iter().enumerate() {
1981            scope.push(Visible {
1982                table: label.to_string(),
1983                name: field.name.clone(),
1984                binding: ColumnBinding::new(index, at as u32),
1985                ty: field.ty.clone(),
1986                // A reader takes what the file has, and no file format this reads says a column
1987                // cannot be null. The reference binary answers YES for every column of a Parquet.
1988                not_null: false,
1989            });
1990        }
1991        if !names.is_empty() {
1992            scope.rename(names, label)?;
1993        }
1994        let function = self.plan.intern(function.name());
1995        let args = self.plan.add_expr_list(args);
1996        let named: Vec<u32> =
1997            written.iter().map(|(parameter, _, _)| self.plan.intern(parameter)).collect();
1998        let settings: Vec<ExprRef> = written.iter().map(|(_, _, expr)| *expr).collect();
1999        let options = self.plan.add_name_list(&named);
2000        let settings = self.plan.add_expr_list(&settings);
2001        let columns = self.plan.add_fields(&fields);
2002        let node = self.add_node(Node::TableFunction {
2003            index,
2004            function,
2005            args,
2006            options,
2007            settings,
2008            columns,
2009        });
2010        Ok((node, scope))
2011    }
2012
2013    /// Every file a table function's file argument names, in the order they were written.
2014    ///
2015    /// Each pattern has to find at least one file of its own, which is DuckDB's rule and is why
2016    /// this expands one at a time rather than gathering everything and looking at the total. A
2017    /// list keeps its written order and its duplicates, so a file named twice is read twice, which
2018    /// was measured: the sort and the dedup belong to one pattern rather than to the list.
2019    fn file_paths(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2020        let mut paths = Vec::new();
2021        for pattern in self.file_patterns(expr, name)? {
2022            paths.extend(files(&pattern)?);
2023        }
2024        Ok(paths)
2025    }
2026
2027    /// The patterns a table function argument names, which have to be constants.
2028    ///
2029    /// A table function that reads a file is resolved by opening the file, and that happens here
2030    /// rather than when the query runs, because the rest of the statement cannot bind until the
2031    /// column names are known. So the path has to be something this binder can work out without
2032    /// running anything, and a literal is that. DuckDB folds a constant expression first, so
2033    /// `read_parquet('a' || '.parquet')` works there, and folding is M1 work that this will pick up
2034    /// for free once the optimizer runs before the plan is finished rather than after.
2035    ///
2036    /// One string is one pattern and a list is one pattern an item, which is DuckDB's pair of
2037    /// overloads. A null is a different sentence in each of them, both of them measured.
2038    fn file_patterns(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2039        let Expr::Constant(reference) = *self.plan.expr(expr) else {
2040            return Err(Error::not_implemented(
2041                "a table function file name that is not a constant",
2042            ));
2043        };
2044        match self.plan.value(reference) {
2045            Value::Varchar(path) => Ok(vec![path.clone()]),
2046            // DuckDB's own wording, which says list because its other overload takes one.
2047            Value::Null => Err(Error::parser(format!("{name} cannot take NULL list as parameter"))),
2048            Value::List { values, .. } => values
2049                .iter()
2050                .map(|value| match value {
2051                    Value::Varchar(path) => Ok(path.clone()),
2052                    _ => Err(Error::parser(format!(
2053                        "{name} reader cannot take NULL input as parameter"
2054                    ))),
2055                })
2056                .collect(),
2057            other => {
2058                Err(Error::internal(format!("a file name bound as VARCHAR arrived as {other}")))
2059            }
2060        }
2061    }
2062
2063    #[allow(clippy::too_many_arguments)]
2064    fn bind_join(
2065        &mut self,
2066        ast: &Ast,
2067        left: ast::SourceRef,
2068        right: ast::SourceRef,
2069        kind: ast::JoinKind,
2070        natural: bool,
2071        on: ast::ExprRef,
2072        using: ast::Slice,
2073    ) -> Result<(NodeRef, Scope)> {
2074        let (left_node, left_scope) = self.bind_source(ast, left)?;
2075        let (right_node, right_scope, correlated) = self.bind_lateral(ast, right, &left_scope)?;
2076        // A row of the right side exists only for the left row it was evaluated against, so a kind
2077        // that has to produce right rows with no left row has nothing to produce them from. The
2078        // pinned build says this and names only the two kinds that work.
2079        if !correlated.is_empty()
2080            && !matches!(kind, ast::JoinKind::Inner | ast::JoinKind::Cross | ast::JoinKind::Left)
2081        {
2082            return Err(Error::binder(
2083                "The combining JOIN type must be INNER or LEFT for a LATERAL reference",
2084            ));
2085        }
2086        let split = left_scope.len();
2087        let mut scope = left_scope.concat(right_scope);
2088
2089        // NATURAL is USING over whatever both sides happen to call the same thing, which is why it
2090        // is resolved here and never reaches the plan as its own idea.
2091        let merged: Vec<String> = if natural {
2092            let mut names = Vec::new();
2093            for (at, column) in scope.columns.iter().enumerate().take(split) {
2094                if scope.columns[split..].iter().any(|right| same_name(&right.name, &column.name))
2095                    && !names.iter().any(|held: &String| same_name(held, &column.name))
2096                {
2097                    let _ = at;
2098                    names.push(column.name.clone());
2099                }
2100            }
2101            names
2102        } else {
2103            // A name written twice is one column, not two. `USING (id, id)` is legal and means what
2104            // `USING (id)` means, and the reference binary agrees. Taking it twice would build the
2105            // same equality twice and, worse, drop the right side's copy twice, which takes a
2106            // column out of the answer that nobody named and runs off the end of the scope when the
2107            // copy was the last column in it.
2108            let mut names: Vec<String> = Vec::new();
2109            for name in ast.name(using) {
2110                if !names.iter().any(|held| same_name(held, name)) {
2111                    names.push(name.to_string());
2112                }
2113            }
2114            names
2115        };
2116
2117        let mut conditions = Vec::new();
2118        let mut dropped = Vec::new();
2119        for name in &merged {
2120            let left_at = scope.columns[..split]
2121                .iter()
2122                .position(|column| same_name(&column.name, name))
2123                .ok_or_else(|| {
2124                    Error::binder(format!(
2125                        "column \"{name}\" specified in USING clause does not exist in left table"
2126                    ))
2127                })?;
2128            let right_at = scope.columns[split..]
2129                .iter()
2130                .position(|column| same_name(&column.name, name))
2131                .map(|at| at + split)
2132                .ok_or_else(|| {
2133                    Error::binder(format!(
2134                        "column \"{name}\" specified in USING clause does not exist in right table"
2135                    ))
2136                })?;
2137            let left_column = &scope.columns[left_at];
2138            let (left_binding, left_type) = (left_column.binding, left_column.ty.clone());
2139            let right_column = &scope.columns[right_at];
2140            let (right_binding, right_type) = (right_column.binding, right_column.ty.clone());
2141            let left_expr = self.plan.add_expr(Expr::Column(left_binding), left_type);
2142            let right_expr = self.plan.add_expr(Expr::Column(right_binding), right_type);
2143            conditions.push(self.compare(rudb_plan::CompareOp::Equal, left_expr, right_expr)?);
2144            dropped.push(right_at);
2145        }
2146        // A joined-on column appears once, so the right side's copy goes. Dropping from the back
2147        // keeps the positions of the ones still to drop correct.
2148        dropped.sort_unstable();
2149        for at in dropped.into_iter().rev() {
2150            scope.remove(at);
2151        }
2152
2153        if on != NONE {
2154            if !merged.is_empty() {
2155                return Err(Error::binder("a join cannot have both ON and USING"));
2156            }
2157            self.clause = "JOIN condition";
2158            let predicate = self.bind_expr(ast, on, &scope)?;
2159            conditions.push(self.as_boolean(predicate, "JOIN")?);
2160        }
2161
2162        if kind == ast::JoinKind::Cross && !conditions.is_empty() {
2163            return Err(Error::binder("a CROSS JOIN cannot have a condition"));
2164        }
2165        // A product is the join with nothing to join on, and it is not one when the right side has
2166        // to be evaluated per left row, because then there is a dependency to lower even though
2167        // there is no condition to test.
2168        if correlated.is_empty()
2169            && conditions.is_empty()
2170            && matches!(kind, ast::JoinKind::Cross | ast::JoinKind::Inner)
2171        {
2172            let node = self.add_node(Node::CrossProduct { left: left_node, right: right_node });
2173            return Ok((node, scope));
2174        }
2175        let kind = match kind {
2176            ast::JoinKind::Inner | ast::JoinKind::Cross => JoinKind::Inner,
2177            ast::JoinKind::Left => JoinKind::Left,
2178            ast::JoinKind::Right => JoinKind::Right,
2179            ast::JoinKind::Full => JoinKind::Full,
2180            ast::JoinKind::Semi => JoinKind::Semi,
2181            ast::JoinKind::Anti => JoinKind::Anti,
2182            ast::JoinKind::Positional => JoinKind::Positional,
2183        };
2184        let conditions = self.plan.add_expr_list(&conditions);
2185        let node = if correlated.is_empty() {
2186            self.add_node(Node::Join {
2187                left: left_node,
2188                right: right_node,
2189                kind,
2190                conditions,
2191                build: BuildSide::default(),
2192            })
2193        } else {
2194            self.add_node(Node::DependentJoin {
2195                left: left_node,
2196                right: right_node,
2197                kind,
2198                conditions,
2199            })
2200        };
2201        Ok((node, scope))
2202    }
2203
2204    // -------------------------------------------------------------- aggregates
2205
2206    /// Binds a `FILTER (WHERE ...)` predicate, or says there was none.
2207    ///
2208    /// The predicate is a condition over the input rows and not over the answer, so it is bound in
2209    /// the scope the arguments are bound in, and it is cast to `BOOLEAN` the way a `WHERE` is:
2210    /// `FILTER (WHERE i)` over an integer column is a filter on whether the integer is not zero.
2211    fn bind_filter(
2212        &mut self,
2213        ast: &Ast,
2214        filter: ast::ExprRef,
2215        scope: &Scope,
2216    ) -> Result<Option<ExprRef>> {
2217        if filter == NONE {
2218            return Ok(None);
2219        }
2220        let bound = self.bind_expr(ast, filter, scope)?;
2221        Ok(Some(self.checked_cast_to(bound, &LogicalType::Boolean, false)?))
2222    }
2223
2224    /// Binds an aggregate call, records it, and hands back a reference to where its result lands.
2225    pub(crate) fn bind_aggregate(
2226        &mut self,
2227        ast: &Ast,
2228        name: &str,
2229        args: &[ast::ExprRef],
2230        distinct: bool,
2231        filter: ast::ExprRef,
2232        scope: &Scope,
2233    ) -> Result<ExprRef> {
2234        if self.in_filter {
2235            return Err(Error::binder("aggregate functions are not allowed in FILTER"));
2236        }
2237        if self.in_aggregate {
2238            return Err(Error::binder(format!(
2239                "aggregate function calls cannot be nested, and {name}() is inside one"
2240            )));
2241        }
2242        if self.aggregation.is_none() {
2243            return Err(Error::binder(format!(
2244                "aggregate function calls cannot be used in the {}",
2245                self.clause
2246            )));
2247        }
2248        // The predicate goes first, which is the order the messages come out in upstream: a call
2249        // whose argument and whose filter both name columns that are not there is refused over the
2250        // filter. It is bound as if it were inside the call, so an aggregate in it is caught, and a
2251        // window in it is refused with the words a window inside an aggregate is refused with.
2252        self.in_aggregate = true;
2253        self.in_filter = true;
2254        let filter = self.bind_filter(ast, filter, scope);
2255        self.in_filter = false;
2256        self.in_aggregate = false;
2257        let filter = filter?;
2258
2259        self.in_aggregate = true;
2260        let mut bound = Vec::with_capacity(args.len());
2261        let mut failure = None;
2262        for &arg in args {
2263            match self.bind_expr(ast, arg, scope) {
2264                Ok(expr) => bound.push(expr),
2265                Err(error) => {
2266                    failure = Some(error);
2267                    break;
2268                }
2269            }
2270        }
2271        self.in_aggregate = false;
2272        if let Some(error) = failure {
2273            return Err(error);
2274        }
2275
2276        let types: Vec<LogicalType> =
2277            bound.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2278        let resolved = resolve(name, &types)?;
2279        let mut cast = Vec::with_capacity(bound.len());
2280        for (arg, wanted) in bound.iter().zip(&resolved.arguments) {
2281            cast.push(self.checked_cast_to(*arg, wanted, false)?);
2282        }
2283        let args = self.plan.add_expr_list(&cast);
2284        let name = self.plan.intern(resolved.name);
2285        let ty = resolved.returns;
2286        let call = self.plan.add_expr(Expr::Aggregate { name, args, distinct, filter }, ty.clone());
2287
2288        // Two identical aggregates are one column of the aggregate's output. `SELECT sum(x),
2289        // sum(x) / count(*)` computes one sum, not two.
2290        let existing = self.aggregation.as_ref().map(|held| held.aggregates.clone());
2291        let existing = existing.unwrap_or_default();
2292        let at = match existing.iter().position(|&held| self.same_expr(held, call)) {
2293            Some(at) => at,
2294            None => {
2295                let aggregation = self.aggregation.as_mut().expect("checked above");
2296                aggregation.aggregates.push(call);
2297                aggregation.aggregates.len() - 1
2298            }
2299        };
2300        let aggregation = self.aggregation.as_ref().expect("checked above");
2301        let (index, groups) = (aggregation.index, aggregation.groups.len());
2302        Ok(self.column(index, groups + at, ty))
2303    }
2304
2305    // ----------------------------------------------------------------- windows
2306
2307    /// Binds a window call, files it under the run it belongs to, and hands back its column.
2308    ///
2309    /// The result is a column of a [`Node::Window`] rather than the call itself, for the reason the
2310    /// aggregate path returns a column too: the operator produces the value and everything above it
2311    /// reads the value, so a target that wraps a window in arithmetic is arithmetic over a column.
2312    pub(crate) fn bind_window(
2313        &mut self,
2314        ast: &Ast,
2315        written: &WindowCall<'_>,
2316        scope: &Scope,
2317    ) -> Result<ExprRef> {
2318        let WindowCall { name, args, distinct, filter, ignore_nulls, spec } = *written;
2319        if self.in_aggregate {
2320            return Err(Error::binder(
2321                "aggregate function calls cannot contain window function calls",
2322            ));
2323        }
2324        if self.in_window {
2325            return Err(Error::binder("window function calls cannot be nested"));
2326        }
2327        // A join condition is part of the `WHERE` clause as far as this one sentence is concerned,
2328        // which is upstream's wording and not a simplification: `ON sum(a.i) OVER () = b.i` is
2329        // refused there with the words a window in a `WHERE` is refused with.
2330        let clause = if self.clause == "JOIN condition" { "WHERE clause" } else { self.clause };
2331        if clause != "SELECT clause" && clause != "ORDER BY clause" {
2332            return Err(Error::binder(format!("{clause} cannot contain window functions!")));
2333        }
2334
2335        // `count(*)` is a different function from `count(x)` here for the reason it is a different
2336        // function in an ordinary call: one counts rows and the other counts the rows where its
2337        // argument is not null. A star is not an expression and nothing below this binds one.
2338        let starred = args.iter().any(|&arg| {
2339            matches!(ast.expr(arg), ast::Expr::Star { qualifier, replacements }
2340                if qualifier.is_empty() && replacements.is_empty())
2341        });
2342        let (name, args): (&str, &[ast::ExprRef]) = if starred {
2343            if !same_name(name, "count") || args.len() != 1 {
2344                return Err(Error::binder(format!("* is not allowed in {name}()")));
2345            }
2346            ("count_star", &[])
2347        } else if same_name(name, "count") && args.is_empty() {
2348            // `count()` with nothing in it is upstream's other spelling of `count(*)`. It counts
2349            // rows the same way and it is not an arity mistake.
2350            ("count_star", &[])
2351        } else {
2352            (name, args)
2353        };
2354
2355        let held = ast.window(spec);
2356        self.in_window = true;
2357        let parts = self.window_parts(ast, args, held, scope);
2358        // The predicate goes last here, which is the other way round from an ordinary aggregate and
2359        // is again the order the messages come out in upstream. It is still inside the window, so a
2360        // window in it is a nested window, while an aggregate in it is an ordinary aggregate over
2361        // the same rows and is answered.
2362        let filter = if parts.is_ok() { self.bind_filter(ast, filter, scope) } else { Ok(None) };
2363        self.in_window = false;
2364        let parts = parts?;
2365        let filter = filter?;
2366        // Upstream's rule, in its words. A `RANGE` offset is a distance from the current row's sort
2367        // key, so there has to be exactly one sort key for it to be a distance from.
2368        let offsets = [parts.frame.start, parts.frame.end]
2369            .iter()
2370            .any(|end| matches!(end, WindowBound::Preceding(_) | WindowBound::Following(_)));
2371        if parts.frame.unit == WindowUnit::Range && offsets && parts.order.len() != 1 {
2372            return Err(Error::binder("RANGE frames must have only one ORDER BY expression"));
2373        }
2374
2375        let types: Vec<LogicalType> =
2376            parts.args.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2377        let resolved = window_signature(name, &types)?;
2378        // `fill` reads the sort key rather than the frame, so what it needs from the query is not
2379        // what any other window needs and it is refused on its own terms.
2380        if resolved.name == "fill" {
2381            let keys: Vec<LogicalType> =
2382                parts.order.iter().map(|key| self.plan.expr_type(key.expr).clone()).collect();
2383            refuse_fill(&types[0], &keys, distinct, ignore_nulls)?;
2384        }
2385        // Upstream's sentence, doubled quotes and all. A DISTINCT over an aggregate inside an OVER
2386        // is ordinary and answered, and a DISTINCT over a ranking window is refused there, because
2387        // there is nothing for it to collapse when the call reads no values in the first place.
2388        if distinct && kind_of(resolved.name) == Some(FunctionKind::Window) {
2389            return Err(Error::binder(format!(
2390                "DISTINCT is not implemented for the window function \"\"{name}\"\""
2391            )));
2392        }
2393        // The same sentence for the same reason. A ranking window reads no values, so there is
2394        // nothing for a predicate over the values to keep or drop.
2395        if filter.is_some() && kind_of(resolved.name) == Some(FunctionKind::Window) {
2396            return Err(Error::binder(format!(
2397                "FILTER is not implemented for the window function \"\"{name}\"\""
2398            )));
2399        }
2400        let mut cast = Vec::with_capacity(parts.args.len());
2401        for (arg, wanted) in parts.args.iter().zip(&resolved.arguments) {
2402            cast.push(self.checked_cast_to(*arg, wanted, false)?);
2403        }
2404        let args = self.plan.add_expr_list(&cast);
2405        let name = self.plan.intern(resolved.name);
2406        let ty = resolved.returns;
2407        let call = self
2408            .plan
2409            .add_expr(Expr::Window { name, args, distinct, filter, ignore_nulls }, ty.clone());
2410
2411        let at = self.window_run(parts.partition, parts.order, parts.frame, call);
2412        let index = self.windows.last().expect("the run was just filed").index;
2413        Ok(self.column(index, at, ty))
2414    }
2415
2416    /// Files a call under the run that matches it, or opens a new run, and says which column it is.
2417    ///
2418    /// The run that matches is only ever the last one, because a query that goes back to an earlier
2419    /// partitioning after using a different one in between wants the operators in the order it wrote
2420    /// them. Merging the two would be a rewrite, and a rewrite over a window is the optimizer's to
2421    /// make once it knows what the sort below each one costs.
2422    fn window_run(
2423        &mut self,
2424        partition: Vec<ExprRef>,
2425        order: Vec<SortKey>,
2426        frame: WindowFrame,
2427        call: ExprRef,
2428    ) -> usize {
2429        let matches = self.windows.last().is_some_and(|run| {
2430            run.frame == frame
2431                && run.partition.len() == partition.len()
2432                && run.order.len() == order.len()
2433                && run.partition.iter().zip(&partition).all(|(&l, &r)| self.same_expr(l, r))
2434                && run.order.iter().zip(&order).all(|(l, r)| {
2435                    l.descending == r.descending
2436                        && l.nulls_first == r.nulls_first
2437                        && self.same_expr(l.expr, r.expr)
2438                })
2439        });
2440        if !matches {
2441            let index = self.fresh_index();
2442            self.windows.push(WindowRun { index, partition, order, frame, calls: Vec::new() });
2443        }
2444        // Two identical calls over one run are one column, the same way two identical aggregates
2445        // over one grouping are. `SELECT sum(i) OVER (), sum(i) OVER () + 1` totals once.
2446        let calls = self.windows.last().expect("a run is open").calls.clone();
2447        if let Some(at) = calls.iter().position(|&held| self.same_expr(held, call)) {
2448            return at;
2449        }
2450        let run = self.windows.last_mut().expect("a run is open");
2451        run.calls.push(call);
2452        run.calls.len() - 1
2453    }
2454
2455    /// Binds the arguments and everything inside the `OVER`, with the aggregate rule applied.
2456    ///
2457    /// The aggregate rule applies to all of it, which is measured rather than assumed: over a
2458    /// grouped block `sum(count(i)) OVER ()` binds and `sum(i) OVER ()` is the ungrouped column
2459    /// complaint, and the same pair of answers comes back for a partition key and for an order key.
2460    fn window_parts(
2461        &mut self,
2462        ast: &Ast,
2463        args: &[ast::ExprRef],
2464        held: ast::WindowSpec,
2465        scope: &Scope,
2466    ) -> Result<WindowParts> {
2467        let mut bound = Vec::with_capacity(args.len());
2468        for &arg in args {
2469            let expr = self.bind_expr(ast, arg, scope)?;
2470            bound.push(self.over_aggregate(expr, scope)?);
2471        }
2472        let mut partition = Vec::new();
2473        for &key in ast.expr_list(held.partition) {
2474            let expr = self.bind_expr(ast, key, scope)?;
2475            partition.push(self.over_aggregate(expr, scope)?);
2476        }
2477        let mut order = Vec::new();
2478        for item in ast.order_list(held.order).to_vec() {
2479            let expr = self.bind_expr(ast, item.expr, scope)?;
2480            let expr = self.over_aggregate(expr, scope)?;
2481            order.push(self.sort_key(expr, item));
2482        }
2483        let frame = WindowFrame {
2484            unit: match held.unit {
2485                ast::WindowUnit::Rows => WindowUnit::Rows,
2486                ast::WindowUnit::Range => WindowUnit::Range,
2487                ast::WindowUnit::Groups => WindowUnit::Groups,
2488            },
2489            start: self.window_bound(ast, held.start, scope)?,
2490            end: self.window_bound(ast, held.end, scope)?,
2491            exclude: match held.exclude {
2492                ast::WindowExclude::NoOthers => WindowExclude::NoOthers,
2493                ast::WindowExclude::CurrentRow => WindowExclude::CurrentRow,
2494                ast::WindowExclude::Group => WindowExclude::Group,
2495                ast::WindowExclude::Ties => WindowExclude::Ties,
2496            },
2497        };
2498        Ok(WindowParts { args: bound, partition, order, frame })
2499    }
2500
2501    /// One end of a frame, with its offset bound where it has one.
2502    fn window_bound(
2503        &mut self,
2504        ast: &Ast,
2505        bound: ast::WindowBound,
2506        scope: &Scope,
2507    ) -> Result<WindowBound> {
2508        let offset = |binder: &mut Self, written| {
2509            let expr = binder.bind_expr(ast, written, scope)?;
2510            binder.over_aggregate(expr, scope)
2511        };
2512        Ok(match bound {
2513            ast::WindowBound::UnboundedPreceding => WindowBound::UnboundedPreceding,
2514            ast::WindowBound::CurrentRow => WindowBound::CurrentRow,
2515            ast::WindowBound::UnboundedFollowing => WindowBound::UnboundedFollowing,
2516            ast::WindowBound::Preceding(written) => WindowBound::Preceding(offset(self, written)?),
2517            ast::WindowBound::Following(written) => WindowBound::Following(offset(self, written)?),
2518        })
2519    }
2520
2521    /// Whether a column is the result of a window this block is building.
2522    fn is_window_output(&self, binding: ColumnBinding) -> bool {
2523        self.windows.iter().any(|run| run.index == binding.table)
2524    }
2525
2526    /// Rewrites a bound expression into one the aggregate's output can answer.
2527    ///
2528    /// A subexpression that is one of the group expressions becomes a reference to that group. A
2529    /// column that is neither grouped nor inside an aggregate is the error every SQL user has seen,
2530    /// and it is reported here because this is the first point where it is knowable.
2531    pub(crate) fn over_aggregate(&mut self, expr: ExprRef, scope: &Scope) -> Result<ExprRef> {
2532        let Some(aggregation) = self.aggregation.as_ref() else {
2533            return Ok(expr);
2534        };
2535        let index = aggregation.index;
2536        let groups = aggregation.groups.clone();
2537        for (at, group) in groups.iter().enumerate() {
2538            if self.same_expr(expr, *group) {
2539                let ty = self.plan.expr_type(*group).clone();
2540                return Ok(self.column(index, at, ty));
2541            }
2542        }
2543        let ty = self.plan.expr_type(expr).clone();
2544        match self.plan.expr(expr).clone() {
2545            Expr::Column(binding) if binding.table == index => Ok(expr),
2546            // A window result is not a column of the input and the grouping rule has nothing to say
2547            // about it. It reads the aggregate's output rather than the table's, which is why
2548            // `SELECT sum(count(i)) OVER () FROM t GROUP BY j` binds and `sum(i) OVER ()` over the
2549            // same block does not.
2550            Expr::Column(binding) if self.is_window_output(binding) => Ok(expr),
2551            Expr::Column(binding) => {
2552                let name =
2553                    scope.columns.iter().find(|column| column.binding == binding).map_or_else(
2554                        || "a column".to_string(),
2555                        |column| format!("\"{}\"", column.name),
2556                    );
2557                Err(Error::binder(format!(
2558                    "column {name} must appear in the GROUP BY clause or must be part of an aggregate function"
2559                )))
2560            }
2561            Expr::Constant(_) | Expr::Aggregate { .. } | Expr::Window { .. } => Ok(expr),
2562            Expr::Cast { input, try_cast } => {
2563                let input = self.over_aggregate(input, scope)?;
2564                Ok(self.plan.add_expr(Expr::Cast { input, try_cast }, ty))
2565            }
2566            Expr::Compare { op, left, right } => {
2567                let left = self.over_aggregate(left, scope)?;
2568                let right = self.over_aggregate(right, scope)?;
2569                Ok(self.plan.add_expr(Expr::Compare { op, left, right }, ty))
2570            }
2571            Expr::Conjunction { op, children } => {
2572                let written = self.plan.expr_list(children).to_vec();
2573                let mut rewritten = Vec::with_capacity(written.len());
2574                for child in written {
2575                    rewritten.push(self.over_aggregate(child, scope)?);
2576                }
2577                let children = self.plan.add_expr_list(&rewritten);
2578                Ok(self.plan.add_expr(Expr::Conjunction { op, children }, ty))
2579            }
2580            Expr::Function { name, args } => {
2581                let written = self.plan.expr_list(args).to_vec();
2582                let mut rewritten = Vec::with_capacity(written.len());
2583                for arg in written {
2584                    rewritten.push(self.over_aggregate(arg, scope)?);
2585                }
2586                let args = self.plan.add_expr_list(&rewritten);
2587                Ok(self.plan.add_expr(Expr::Function { name, args }, ty))
2588            }
2589            Expr::Case { arms, otherwise } => {
2590                let written = self.plan.arm_list(arms).to_vec();
2591                let mut rewritten = Vec::with_capacity(written.len());
2592                for arm in written {
2593                    let when = self.over_aggregate(arm.when, scope)?;
2594                    let then = self.over_aggregate(arm.then, scope)?;
2595                    rewritten.push(rudb_plan::Arm { when, then });
2596                }
2597                let otherwise = match otherwise {
2598                    Some(expr) => Some(self.over_aggregate(expr, scope)?),
2599                    None => None,
2600                };
2601                let arms = self.plan.add_arms(&rewritten);
2602                Ok(self.plan.add_expr(Expr::Case { arms, otherwise }, ty))
2603            }
2604        }
2605    }
2606
2607    /// Whether two bound expressions are the same expression, by shape rather than by reference.
2608    pub(crate) fn same_expr(&self, left: ExprRef, right: ExprRef) -> bool {
2609        same_expr(&self.plan, left, right)
2610    }
2611}
2612
2613/// The named parameters a table function call was written with.
2614///
2615/// A struct rather than the fields loose, because the seventeen DuckDB has on `read_parquet` and the
2616/// thirty on `read_csv` are all going to want somewhere to go, and because a call with none of them
2617/// written should read as the default of this rather than as a bare false somewhere.
2618///
2619/// The CSV half goes on to the reader and is opened with, here and again in the executor. The
2620/// Parquet half is answered here and nothing downstream sees it, which is what `binary_as_string`
2621/// turning a BLOB column into a VARCHAR one is.
2622#[derive(Debug, Default)]
2623struct Options {
2624    /// `binary_as_string`, which says an unannotated byte array column in a Parquet file holds
2625    /// text. The ClickBench file has twenty eight of those and every query reads them as strings.
2626    binary_as_string: bool,
2627    /// `all_varchar`, which reads every column of a CSV file as text rather than sniffing a type.
2628    all_varchar: bool,
2629    /// `file_row_number`, which adds a column holding each row's ordinal inside its own file.
2630    ///
2631    /// The one Parquet option here that the executor has to act on rather than the binder, since
2632    /// the column is not in the file and has to be counted as the rows come out of it.
2633    file_row_number: bool,
2634    /// `delim`, `sep`, `quote`, `escape` and `header`, which are what the sniffer would decide.
2635    given: Given,
2636}
2637
2638impl Options {
2639    /// What these named parameters add up to.
2640    ///
2641    /// Each one was already checked against the function's list, so a name in here is a name that
2642    /// function takes and the value is already the type it wants. What is left is reading them, and
2643    /// the last one written wins, which is DuckDB's answer to `delim='|', delim=','` and was
2644    /// measured rather than assumed.
2645    fn of(written: &[(&'static str, Value, ExprRef)]) -> Result<Self> {
2646        let mut options = Self::default();
2647        for (parameter, value, _) in written {
2648            match (*parameter, value) {
2649                ("binary_as_string", Value::Boolean(on)) => options.binary_as_string = *on,
2650                ("all_varchar", Value::Boolean(on)) => options.all_varchar = *on,
2651                ("file_row_number", Value::Boolean(on)) => options.file_row_number = *on,
2652                _ => {}
2653            }
2654        }
2655        let named: Vec<(&str, Value)> =
2656            written.iter().map(|(parameter, value, _)| (*parameter, value.clone())).collect();
2657        options.given = csv_given(&named)?;
2658        Ok(options)
2659    }
2660}
2661
2662/// DuckDB's complaint about a named parameter that was given a null, which is a different sentence
2663/// for almost every parameter.
2664///
2665/// Three of them were measured on `v2.0.0-dev84237` and no two agree: `binary_as_string` is the
2666/// first, `all_varchar` is the second and `header` is the third. They read like three people each
2667/// writing the message in front of them, which is what they are, and a harness that compares error
2668/// text compares all of it. Anything not measured gets the first one, which is the most general of
2669/// the three.
2670fn null_parameter(function: TableFunction, parameter: &str) -> String {
2671    match parameter {
2672        "header" => format!("\"{parameter}\" expects a non-null boolean value (e.g. TRUE or 1)"),
2673        "all_varchar" => format!("{} \"{parameter}\" cannot be NULL", function.name()),
2674        _ => format!("Cannot use NULL as argument to \"{parameter}\""),
2675    }
2676}
2677
2678/// The complaint about a `REPLACE` entry that named a column the star did not stand for.
2679///
2680/// It reads like the complaint about any other name that is not there, down to the list of names
2681/// that are, because from the writer's side it is the same mistake.
2682fn missing_replacement(name: &str, input: &Scope) -> Error {
2683    Error::binder(format!(
2684        "Column \"{name}\" in REPLACE list not found in FROM clause{}",
2685        input.candidates()
2686    ))
2687}
2688
2689/// Whether a type is one `fill` can interpolate over, which is the pin's phrase for it.
2690///
2691/// The pin refuses `fill` with `FILL argument must support subtraction` and its sort key with
2692/// `FILL ordering must support subtraction`, and the two lists are not the same list, which is why
2693/// this takes a flag rather than answering one question. Every number is on both, so are `DATE`,
2694/// `TIME` and the two timestamps, and `TIME WITH TIME ZONE` is a sort key there but not an
2695/// argument. `INTERVAL` is on neither, which is worth saying out loud because an interval does
2696/// subtract: the sentence names subtraction and the rule is narrower than the sentence.
2697fn subtractable(ty: &LogicalType, ordering: bool) -> bool {
2698    if ty.is_numeric() {
2699        return true;
2700    }
2701    match ty {
2702        LogicalType::Date
2703        | LogicalType::Time
2704        | LogicalType::Timestamp
2705        | LogicalType::TimestampS
2706        | LogicalType::TimestampMs
2707        | LogicalType::TimestampNs
2708        | LogicalType::TimestampTz => true,
2709        LogicalType::TimeTz => ordering,
2710        _ => false,
2711    }
2712}
2713
2714/// Refuses a `fill` call the way the pin refuses one, in the pin's order.
2715///
2716/// The order was measured and it is not the order the clauses are written in. A `fill` over a
2717/// `VARCHAR` with no `ORDER BY` at all complains about the argument, so the argument is looked at
2718/// before the sort key is counted, and a `fill` with `DISTINCT` and no `ORDER BY` complains about
2719/// the `ORDER BY`, so the count comes before the clauses. `IGNORE NULLS` is refused here rather
2720/// than being answered as a no-op, since there is nothing for it to skip: `fill` is the one window
2721/// whose whole job is the nulls.
2722fn refuse_fill(
2723    argument: &LogicalType,
2724    order: &[LogicalType],
2725    distinct: bool,
2726    ignore_nulls: bool,
2727) -> Result<()> {
2728    if !subtractable(argument, false) {
2729        return Err(Error::binder("FILL argument must support subtraction"));
2730    }
2731    let [key] = order else {
2732        return Err(Error::binder("FILL functions must have only one ORDER BY expression"));
2733    };
2734    if !subtractable(key, true) {
2735        return Err(Error::binder("FILL ordering must support subtraction"));
2736    }
2737    if distinct {
2738        return Err(Error::binder(
2739            "DISTINCT is not implemented for the window function \"\"fill\"\"",
2740        ));
2741    }
2742    if ignore_nulls {
2743        return Err(Error::binder(
2744            "RESPECT/IGNORE NULLS is not supported for the window function \"fill\"",
2745        ));
2746    }
2747    Ok(())
2748}
2749
2750/// Resolves the call written inside an `OVER`.
2751///
2752/// Every aggregate is also a window, which is why this goes through the same signature table the
2753/// aggregate path uses, and the ranking windows go through it too because they are rows in the same
2754/// table. Everything else is one of three refusals, and all three are the reference binary's: a name
2755/// it knows as a scalar and a name it does not know at all each get their own sentence there.
2756fn window_signature(name: &str, types: &[LogicalType]) -> Result<Resolved> {
2757    match kind_of(name) {
2758        Some(FunctionKind::Aggregate | FunctionKind::Window) => resolve(name, types),
2759        Some(FunctionKind::Scalar) => {
2760            Err(Error::catalog(format!("{name} is not an aggregate function")))
2761        }
2762        None => Err(Error::catalog(format!("Aggregate Function with name {name} does not exist!"))),
2763    }
2764}
2765
2766/// Structural equality over two expressions of one plan.
2767fn same_expr(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
2768    if left == right {
2769        return true;
2770    }
2771    if plan.expr_type(left) != plan.expr_type(right) {
2772        return false;
2773    }
2774    let lists = |left, right| {
2775        let left: &[ExprRef] = plan.expr_list(left);
2776        let right: &[ExprRef] = plan.expr_list(right);
2777        left.len() == right.len()
2778            && left.iter().zip(right).all(|(&left, &right)| same_expr(plan, left, right))
2779    };
2780    match (plan.expr(left), plan.expr(right)) {
2781        (Expr::Column(left), Expr::Column(right)) => left == right,
2782        (Expr::Constant(left), Expr::Constant(right)) => plan.value(*left) == plan.value(*right),
2783        (
2784            Expr::Cast { input: left, try_cast: left_try },
2785            Expr::Cast { input: right, try_cast: right_try },
2786        ) => left_try == right_try && same_expr(plan, *left, *right),
2787        (
2788            Expr::Compare { op: left_op, left: left_a, right: left_b },
2789            Expr::Compare { op: right_op, left: right_a, right: right_b },
2790        ) => {
2791            left_op == right_op
2792                && same_expr(plan, *left_a, *right_a)
2793                && same_expr(plan, *left_b, *right_b)
2794        }
2795        (
2796            Expr::Conjunction { op: left_op, children: left_children },
2797            Expr::Conjunction { op: right_op, children: right_children },
2798        ) => left_op == right_op && lists(*left_children, *right_children),
2799        (
2800            Expr::Function { name: left_name, args: left_args },
2801            Expr::Function { name: right_name, args: right_args },
2802        ) => plan.string(*left_name) == plan.string(*right_name) && lists(*left_args, *right_args),
2803        (
2804            Expr::Aggregate {
2805                name: left_name,
2806                args: left_args,
2807                distinct: left_distinct,
2808                filter: left_filter,
2809            },
2810            Expr::Aggregate {
2811                name: right_name,
2812                args: right_args,
2813                distinct: right_distinct,
2814                filter: right_filter,
2815            },
2816        ) => {
2817            plan.string(*left_name) == plan.string(*right_name)
2818                && left_distinct == right_distinct
2819                && match (left_filter, right_filter) {
2820                    (None, None) => true,
2821                    (Some(left), Some(right)) => same_expr(plan, *left, *right),
2822                    _ => false,
2823                }
2824                && lists(*left_args, *right_args)
2825        }
2826        // The partition, the order and the frame are not compared here and do not need to be. Two
2827        // window calls are only ever asked about when they are already in the same run, which is
2828        // what agreeing on all three means.
2829        (
2830            Expr::Window {
2831                name: left_name,
2832                args: left_args,
2833                distinct: left_distinct,
2834                filter: left_filter,
2835                ignore_nulls: left_nulls,
2836            },
2837            Expr::Window {
2838                name: right_name,
2839                args: right_args,
2840                distinct: right_distinct,
2841                filter: right_filter,
2842                ignore_nulls: right_nulls,
2843            },
2844        ) => {
2845            plan.string(*left_name) == plan.string(*right_name)
2846                && left_distinct == right_distinct
2847                && left_nulls == right_nulls
2848                && match (left_filter, right_filter) {
2849                    (None, None) => true,
2850                    (Some(left), Some(right)) => same_expr(plan, *left, *right),
2851                    _ => false,
2852                }
2853                && lists(*left_args, *right_args)
2854        }
2855        (
2856            Expr::Case { arms: left_arms, otherwise: left_otherwise },
2857            Expr::Case { arms: right_arms, otherwise: right_otherwise },
2858        ) => {
2859            let left_arms = plan.arm_list(*left_arms);
2860            let right_arms = plan.arm_list(*right_arms);
2861            left_arms.len() == right_arms.len()
2862                && left_arms.iter().zip(right_arms).all(|(left, right)| {
2863                    same_expr(plan, left.when, right.when) && same_expr(plan, left.then, right.then)
2864                })
2865                && match (left_otherwise, right_otherwise) {
2866                    (None, None) => true,
2867                    (Some(left), Some(right)) => same_expr(plan, *left, *right),
2868                    _ => false,
2869                }
2870        }
2871        _ => false,
2872    }
2873}