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