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::{Error, Field, LogicalType, Result, Semantics, Session, ShowBehavior, Value};
17use rudb_functions::{
18    Columns, FILE_ROW_NUMBER, Given, TableFunction, csv_fields, csv_given, files, is_file,
19    is_pattern, parquet_fields, resolve, resolve_pragma, resolve_table,
20};
21use rudb_parse::ast::{self, Ast, Distinct, LiteralKind, Nulls, Order, Quantifier, SetOp};
22use rudb_parse::{NONE, identifier_parts, parse_ast};
23use rudb_plan::{ColumnBinding, Expr, ExprRef, JoinKind, Node, NodeRef, Plan, SetOpKind, SortKey};
24
25use crate::expr::{describe, has_aggregate};
26use crate::parameters::Parameters;
27use crate::scope::{Scope, Visible};
28
29/// Binds a parsed statement against a catalog.
30///
31/// # Errors
32///
33/// If the script does not hold exactly one statement, if a name does not resolve, if a type does
34/// not work out, or if the query uses something M0 does not bind yet.
35pub fn bind(ast: &Ast, catalog: &Catalog) -> Result<Plan> {
36    bind_with(ast, catalog, &Parameters::new(), &Session::new())
37}
38
39/// Binds a parsed query against a catalog, with values for its parameters and its settings.
40///
41/// The session is what `current_setting()` reads, and a caller with no database behind it passes an
42/// empty one, which makes every setting name unrecognized rather than making up an answer.
43///
44/// # Errors
45///
46/// Everything [`bind`] reports, plus an error for a parameter that was given no value.
47pub fn bind_with(
48    ast: &Ast,
49    catalog: &Catalog,
50    parameters: &Parameters,
51    session: &Session,
52) -> Result<Plan> {
53    let query = match ast.statements.as_slice() {
54        [ast::Statement::Query(query)] => *query,
55        [] => return Err(Error::binder("no statement to bind")),
56        // One statement that is not a query is its own answer. Reporting it as a script of several
57        // reads as a count being wrong, and the count is right.
58        [_] => return Err(Error::not_implemented("a statement that is not a query")),
59        _ => return Err(Error::not_implemented("a script of more than one statement")),
60    };
61    let mut binder = Binder::with(catalog, parameters, session);
62    let (root, _) = binder.bind_query(ast, query)?;
63    let mut plan = binder.into_plan();
64    plan.set_root(root);
65    plan.validate()?;
66    Ok(plan)
67}
68
69/// Parses and binds one query, which is the whole front end in one call.
70///
71/// # Errors
72///
73/// Anything the parser or the binder reports.
74pub fn bind_sql(query: &str, catalog: &Catalog) -> Result<Plan> {
75    bind_sql_with(query, catalog, &Session::new())
76}
77
78/// Parses and binds one query, with the settings a call to `current_setting()` reads.
79///
80/// # Errors
81///
82/// Anything the parser or the binder reports.
83pub fn bind_sql_with(query: &str, catalog: &Catalog, session: &Session) -> Result<Plan> {
84    let ast = parse_ast(query)?;
85    bind_with(&ast, catalog, &Parameters::new(), session)
86}
87
88/// What an aggregating select block has decided so far.
89#[derive(Debug)]
90pub(crate) struct Aggregation {
91    /// The table index the aggregate's output binds against.
92    pub(crate) index: u32,
93    /// The group expressions, over the input, which are the first output columns.
94    pub(crate) groups: Vec<ExprRef>,
95    /// The aggregate calls found so far, which follow the groups in the output.
96    pub(crate) aggregates: Vec<ExprRef>,
97}
98
99/// The state one binding run carries.
100#[derive(Debug)]
101pub(crate) struct Binder<'a> {
102    catalog: &'a Catalog,
103    /// What the parameters were given, empty for a statement that is not prepared.
104    pub(crate) parameters: &'a Parameters,
105    /// What the settings are now, which is what `current_setting()` folds to.
106    pub(crate) session: &'a Session,
107    /// Meaning-changing choices copied once and resolved into the plan above execution.
108    pub(crate) semantics: Semantics,
109    plan: Plan,
110    next_index: u32,
111    /// Set while a select block aggregates, which changes what a bare column means.
112    pub(crate) aggregation: Option<Aggregation>,
113    /// Set while an aggregate's own arguments are being bound, so nesting is caught.
114    pub(crate) in_aggregate: bool,
115    /// Where we are, for an error message that says which clause the writer should look at.
116    pub(crate) clause: &'static str,
117    /// The views whose bodies are open on the stack, which is what catches a cycle.
118    expanding: Vec<String>,
119    /// When this statement started, read once and kept, which is what `now()` folds to.
120    started: Option<i64>,
121}
122
123impl<'a> Binder<'a> {
124    pub(crate) fn with(
125        catalog: &'a Catalog,
126        parameters: &'a Parameters,
127        session: &'a Session,
128    ) -> Self {
129        Self {
130            catalog,
131            parameters,
132            session,
133            semantics: session.semantics(),
134            plan: Plan::new(),
135            next_index: 0,
136            aggregation: None,
137            in_aggregate: false,
138            clause: "SELECT clause",
139            expanding: Vec::new(),
140            started: None,
141        }
142    }
143
144    pub(crate) fn catalog(&self) -> &Catalog {
145        self.catalog
146    }
147
148    /// When this statement started, in microseconds since the epoch.
149    ///
150    /// Read from the clock the first time something asks and kept after that, so a query that
151    /// writes `now()` twice gets one answer for both. That is what the pin does and what it reports
152    /// in the `stability` column of `duckdb_functions()`, where every one of these is
153    /// `CONSISTENT_WITHIN_QUERY`. A query that never asks never reads the clock.
154    pub(crate) fn instant(&mut self) -> i64 {
155        *self.started.get_or_insert_with(crate::context::micros_now)
156    }
157
158    pub(crate) fn plan(&self) -> &Plan {
159        &self.plan
160    }
161
162    pub(crate) fn plan_mut(&mut self) -> &mut Plan {
163        &mut self.plan
164    }
165
166    pub(crate) fn into_plan(self) -> Plan {
167        self.plan
168    }
169
170    /// A table index nothing else has.
171    pub(crate) fn fresh_index(&mut self) -> u32 {
172        let index = self.next_index;
173        self.next_index += 1;
174        index
175    }
176
177    /// A reference to one column of an operator's output.
178    fn column(&mut self, index: u32, position: usize, ty: LogicalType) -> ExprRef {
179        let binding = ColumnBinding::new(index, position as u32);
180        self.plan.add_expr(Expr::Column(binding), ty)
181    }
182
183    // ---------------------------------------------------------------- queries
184
185    pub(crate) fn bind_query(
186        &mut self,
187        ast: &Ast,
188        query: ast::QueryRef,
189    ) -> Result<(NodeRef, Scope)> {
190        let written = ast.query(query);
191        match written.body {
192            ast::QueryBody::Select(select) => self.bind_select(ast, select, &written),
193            ast::QueryBody::SetOp { op, quantifier, by_name, left, right } => {
194                if by_name {
195                    return Err(Error::not_implemented("UNION BY NAME"));
196                }
197                self.bind_set_op(ast, &written, op, quantifier, left, right)
198            }
199            ast::QueryBody::Values(rows) => self.bind_values(ast, &written, rows),
200            ast::QueryBody::Describe(inner) => self.bind_describe(ast, &written, inner),
201            ast::QueryBody::Show { name, relation } => {
202                self.bind_show(ast, &written, name, relation)
203            }
204        }
205    }
206
207    /// `SHOW name`, resolved while binding so execution receives an ordinary constant plan.
208    fn bind_show(
209        &mut self,
210        ast: &Ast,
211        query: &ast::Query,
212        name: ast::Slice,
213        relation: ast::QueryRef,
214    ) -> Result<(NodeRef, Scope)> {
215        let text = ast.name_text(name);
216        let parts: Vec<&str> = ast.name(name).collect();
217        let table_exists = self.catalog.resolve(&parts).is_ok();
218        let as_table = match self.semantics.show_behavior() {
219            ShowBehavior::Auto => table_exists,
220            ShowBehavior::Setting => false,
221            ShowBehavior::Table => true,
222        };
223        if as_table {
224            return self.bind_describe(ast, query, relation);
225        }
226        let Some((_, value)) =
227            self.session.iter().find(|(name, _)| name.eq_ignore_ascii_case(&text))
228        else {
229            return Err(Error::catalog(format!("Setting with name \"{text}\" does not exist")));
230        };
231        let field = Field::new(text, LogicalType::Varchar);
232        let expr = self.plan.add_constant(Value::Varchar(value.to_string()));
233        let row = self.plan.add_expr_list(&[expr]);
234        let rows = self.plan.add_rows(&[row]);
235        let columns = self.plan.add_fields(std::slice::from_ref(&field));
236        let index = self.fresh_index();
237        let node = self.plan.add_node(Node::Values { index, columns, rows });
238        let mut scope = Scope::empty();
239        scope.push(Visible {
240            table: String::new(),
241            name: field.name,
242            binding: ColumnBinding::new(index, 0),
243            ty: LogicalType::Varchar,
244            not_null: false,
245        });
246        Ok((node, scope))
247    }
248
249    /// `DESCRIBE <query>`, which is six VARCHAR columns saying what the query returns.
250    ///
251    /// The query is bound and never run, because binding is the whole of the answer: the names and
252    /// the types of a query's columns are settled by the time the binder is done with it, so the
253    /// rows of a describe are a constant from there on. That is why this comes out as a `VALUES`
254    /// whose rows were computed here rather than as an operator of its own, and it is what makes
255    /// `SELECT column_name FROM (DESCRIBE ...) WHERE ...` an ordinary query over an ordinary
256    /// relation with no special case above it.
257    ///
258    /// The six columns, their order and their types are the reference binary's. `key`, `default`
259    /// and `extra` are null for everything this engine can declare, since `PRIMARY KEY`, `UNIQUE`
260    /// and `DEFAULT` are all refused by `CREATE TABLE` today and there is nothing for the first two
261    /// to hold, and `extra` is empty upstream as well on every table it was asked about. They are
262    /// here rather than left out because the width of a result is part of the result, and a program
263    /// that reads the fifth column has to find one.
264    fn bind_describe(
265        &mut self,
266        ast: &Ast,
267        query: &ast::Query,
268        inner: ast::QueryRef,
269    ) -> Result<(NodeRef, Scope)> {
270        let (_, described) = self.bind_query(ast, inner)?;
271        let fields: Vec<Field> = ["column_name", "column_type", "null", "key", "default", "extra"]
272            .iter()
273            .map(|name| Field::new(*name, LogicalType::Varchar))
274            .collect();
275        let mut slices = Vec::with_capacity(described.columns.len());
276        for column in described.columns.clone() {
277            // `NO` and `YES` and not a boolean, because the column is VARCHAR upstream and a
278            // client that prints the result has to get the same four or three characters.
279            let written = [
280                column.name.clone(),
281                column.ty.to_string(),
282                if column.not_null { "NO" } else { "YES" }.to_owned(),
283            ];
284            let mut items: Vec<ExprRef> = written
285                .into_iter()
286                .map(|text| self.plan.add_constant(Value::Varchar(text)))
287                .collect();
288            for _ in 0..3 {
289                let empty = self.plan.add_constant(Value::Null);
290                items.push(self.cast_to(empty, &LogicalType::Varchar));
291            }
292            slices.push(self.plan.add_expr_list(&items));
293        }
294        let rows = self.plan.add_rows(&slices);
295        let columns = self.plan.add_fields(&fields);
296        let index = self.fresh_index();
297        let mut node = self.plan.add_node(Node::Values { index, columns, rows });
298        let mut scope = Scope::empty();
299        for (at, field) in fields.iter().enumerate() {
300            scope.push(Visible {
301                table: String::new(),
302                name: field.name.clone(),
303                binding: ColumnBinding::new(index, at as u32),
304                ty: field.ty.clone(),
305                not_null: false,
306            });
307        }
308        let keys = self.sort_keys(ast, query, &scope, &[])?;
309        if !keys.is_empty() {
310            let keys = self.plan.add_sort_keys(&keys);
311            node = self.plan.add_node(Node::Sort { input: node, keys });
312        }
313        node = self.apply_limit(ast, query, node)?;
314        Ok((node, scope))
315    }
316
317    /// Whether a projected expression is a column passed straight through from below.
318    ///
319    /// Only `DESCRIBE` asks, and only to decide whether the `null` column says `NO`. Anything that
320    /// is computed is nullable however strict its inputs were, which is both the safe reading and
321    /// the one the reference binary gives.
322    fn passes_through(&self, expr: ExprRef, input: &Scope) -> bool {
323        let Expr::Column(binding) = *self.plan.expr(expr) else { return false };
324        input.columns.iter().any(|column| column.binding == binding && column.not_null)
325    }
326
327    /// `VALUES (1, 'a'), (2, 'b')`, as a query in its own right.
328    ///
329    /// The column names are `col0`, `col1` and so on, which is what DuckDB calls them, and the
330    /// column types are what every row in that position promotes to. Promotion is the same rule a
331    /// set operation uses, and for the same reason: a column has one type and the rows have to
332    /// agree on it before anything downstream can read the column.
333    fn bind_values(
334        &mut self,
335        ast: &Ast,
336        query: &ast::Query,
337        rows: ast::Slice,
338    ) -> Result<(NodeRef, Scope)> {
339        let written = ast.rows(rows).to_vec();
340        let Some(first) = written.first() else {
341            return Err(Error::binder("VALUES needs at least one row"));
342        };
343        let width = first.len as usize;
344        for (at, row) in written.iter().enumerate() {
345            if row.len as usize != width {
346                return Err(Error::binder(format!(
347                    "VALUES lists must all be the same length, expected {width} columns but row {} has {}",
348                    at + 1,
349                    row.len
350                )));
351            }
352        }
353        // A row of a `VALUES` cannot see a column, because there is nothing under it to see.
354        let empty = Scope::empty();
355        let previous = std::mem::replace(&mut self.clause, "VALUES clause");
356        let mut bound: Vec<Vec<ExprRef>> = Vec::with_capacity(written.len());
357        for row in &written {
358            let mut items = Vec::with_capacity(width);
359            for &expr in ast.expr_list(*row) {
360                items.push(self.bind_expr(ast, expr, &empty)?);
361            }
362            bound.push(items);
363        }
364        self.clause = previous;
365        let mut types = Vec::with_capacity(width);
366        for at in 0..width {
367            let mut ty = self.plan.expr_type(bound[0][at]).clone();
368            for row in &bound[1..] {
369                let other = self.plan.expr_type(row[at]).clone();
370                ty = ty.promote(&other).ok_or_else(|| {
371                    Error::binder(format!(
372                        "Cannot combine a value of type {ty} with a value of type {other} in column {} of a VALUES",
373                        at + 1
374                    ))
375                })?;
376            }
377            types.push(ty);
378        }
379        let mut slices = Vec::with_capacity(bound.len());
380        for row in &bound {
381            let items: Vec<ExprRef> = row
382                .iter()
383                .zip(&types)
384                .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
385                .collect::<Result<_>>()?;
386            slices.push(self.plan.add_expr_list(&items));
387        }
388        let rows = self.plan.add_rows(&slices);
389        let fields: Vec<Field> = types
390            .iter()
391            .enumerate()
392            .map(|(at, ty)| Field::new(format!("col{at}"), ty.clone()))
393            .collect();
394        let columns = self.plan.add_fields(&fields);
395        let index = self.fresh_index();
396        let mut node = self.plan.add_node(Node::Values { index, columns, rows });
397        let mut scope = Scope::empty();
398        for (at, field) in fields.iter().enumerate() {
399            scope.push(Visible {
400                table: String::new(),
401                name: field.name.clone(),
402                binding: ColumnBinding::new(index, at as u32),
403                ty: field.ty.clone(),
404                not_null: false,
405            });
406        }
407        let keys = self.sort_keys(ast, query, &scope, &[])?;
408        if !keys.is_empty() {
409            let keys = self.plan.add_sort_keys(&keys);
410            node = self.plan.add_node(Node::Sort { input: node, keys });
411        }
412        node = self.apply_limit(ast, query, node)?;
413        Ok((node, scope))
414    }
415
416    fn bind_set_op(
417        &mut self,
418        ast: &Ast,
419        query: &ast::Query,
420        op: SetOp,
421        quantifier: Quantifier,
422        left: ast::QueryRef,
423        right: ast::QueryRef,
424    ) -> Result<(NodeRef, Scope)> {
425        let (left_node, left_scope) = self.bind_query(ast, left)?;
426        let (right_node, right_scope) = self.bind_query(ast, right)?;
427        if left_scope.len() != right_scope.len() {
428            return Err(Error::binder(format!(
429                "Set operations can only apply to expressions with the same number of result columns, but left side has {} and right side has {}",
430                left_scope.len(),
431                right_scope.len()
432            )));
433        }
434        // Both sides have to hand back one set of types, so each column meets the other side's.
435        let mut types = Vec::with_capacity(left_scope.len());
436        for (left, right) in left_scope.columns.iter().zip(&right_scope.columns) {
437            let common = left.ty.promote(&right.ty).ok_or_else(|| {
438                Error::binder(format!(
439                    "Cannot combine a column of type {} with a column of type {} in a set operation",
440                    left.ty, right.ty
441                ))
442            })?;
443            types.push(common);
444        }
445        let left_node = self.conform(left_node, &left_scope, &types)?;
446        let right_node = self.conform(right_node, &right_scope, &types)?;
447        let index = self.fresh_index();
448        let kind = match op {
449            SetOp::Union => SetOpKind::Union,
450            SetOp::Except => SetOpKind::Except,
451            SetOp::Intersect => SetOpKind::Intersect,
452        };
453        // UNION alone removes duplicates and UNION ALL keeps them, which is the one place the
454        // unwritten quantifier and ALL disagree.
455        let all = quantifier == Quantifier::All;
456        let mut node = self.plan.add_node(Node::SetOp {
457            left: left_node,
458            right: right_node,
459            kind,
460            all,
461            index,
462        });
463        let mut scope = Scope::empty();
464        for (at, (column, ty)) in left_scope.columns.iter().zip(&types).enumerate() {
465            scope.push(Visible {
466                table: String::new(),
467                name: column.name.clone(),
468                binding: ColumnBinding::new(index, at as u32),
469                ty: ty.clone(),
470                // A column of a set operation is nullable whatever the two sides were, because a
471                // column that refuses nulls on one side and takes them on the other takes them.
472                not_null: false,
473            });
474        }
475        // Above a set operation there is nothing but the output columns, so an ORDER BY term is
476        // either a position, an output name, or an expression over the output, and never needs a
477        // column projected for it that the query did not ask for.
478        let keys = self.sort_keys(ast, query, &scope, &[])?;
479        if !keys.is_empty() {
480            let keys = self.plan.add_sort_keys(&keys);
481            node = self.plan.add_node(Node::Sort { input: node, keys });
482        }
483        node = self.apply_limit(ast, query, node)?;
484        Ok((node, scope))
485    }
486
487    /// Projects one side of a set operation so that its columns have the agreed types.
488    fn conform(&mut self, node: NodeRef, scope: &Scope, types: &[LogicalType]) -> Result<NodeRef> {
489        if scope.columns.iter().zip(types).all(|(column, ty)| &column.ty == ty) {
490            return Ok(node);
491        }
492        let index = self.fresh_index();
493        let mut exprs = Vec::with_capacity(types.len());
494        let mut names = Vec::with_capacity(types.len());
495        for (column, ty) in scope.columns.iter().zip(types) {
496            let expr = self.plan.add_expr(Expr::Column(column.binding), column.ty.clone());
497            exprs.push(self.checked_cast_to(expr, ty, false)?);
498            names.push(self.plan.intern(&column.name));
499        }
500        let exprs = self.plan.add_expr_list(&exprs);
501        let names = self.plan.add_name_list(&names);
502        Ok(self.plan.add_node(Node::Project { input: node, index, exprs, names }))
503    }
504
505    // ----------------------------------------------------------------- select
506
507    fn bind_select(
508        &mut self,
509        ast: &Ast,
510        select: ast::SelectRef,
511        query: &ast::Query,
512    ) -> Result<(NodeRef, Scope)> {
513        let written = ast.select(select);
514        let (mut node, input) = self.bind_from(ast, written.from)?;
515
516        if written.filter != NONE {
517            self.clause = "WHERE clause";
518            let predicate = self.bind_expr(ast, written.filter, &input)?;
519            let predicate = self.as_boolean(predicate, "WHERE")?;
520            node = self.plan.add_node(Node::Filter { input: node, predicate });
521        }
522
523        let targets = ast.target_list(written.targets).to_vec();
524        if targets.is_empty() {
525            return Err(Error::binder("a SELECT needs at least one expression to select"));
526        }
527
528        let group_items = self.group_items(ast, &written, &targets)?;
529        let aggregating = !group_items.is_empty()
530            || written.having != NONE
531            || targets.iter().any(|target| has_aggregate(ast, target.expr));
532        if aggregating {
533            self.clause = "GROUP BY clause";
534            let mut groups = Vec::with_capacity(group_items.len());
535            for item in &group_items {
536                groups.push(self.bind_expr(ast, *item, &input)?);
537            }
538            let index = self.fresh_index();
539            self.aggregation = Some(Aggregation { index, groups, aggregates: Vec::new() });
540        }
541
542        self.clause = "SELECT clause";
543        let (mut exprs, mut names) = self.bind_targets(ast, &targets, &input)?;
544        let visible = exprs.len();
545
546        let mut having = None;
547        if written.having != NONE {
548            self.clause = "HAVING clause";
549            let predicate = self.bind_expr(ast, written.having, &input)?;
550            let predicate = self.over_aggregate(predicate, &input)?;
551            having = Some(self.as_boolean(predicate, "HAVING")?);
552        }
553
554        // The projection's index has to exist before the sort keys are built, because a key is a
555        // reference to a projected column even when the expression it sorts on is not selected.
556        let project = self.fresh_index();
557        let mut output = Scope::empty();
558        for (at, (expr, name)) in exprs.iter().zip(&names).enumerate() {
559            output.push(Visible {
560                table: String::new(),
561                name: name.clone(),
562                binding: ColumnBinding::new(project, at as u32),
563                ty: self.plan.expr_type(*expr).clone(),
564                not_null: self.passes_through(*expr, &input),
565            });
566        }
567
568        self.clause = "ORDER BY clause";
569        let mut extra = Vec::new();
570        let keys = self.select_sort_keys(
571            ast, query, &input, &output, project, &mut exprs, &mut names, &mut extra,
572        )?;
573        if !extra.is_empty() && written.distinct != Distinct::No {
574            return Err(Error::binder(
575                "For SELECT DISTINCT, ORDER BY expressions must appear in the select list",
576            ));
577        }
578        let on = self.distinct_on(ast, written.distinct, &output)?;
579
580        if let Some(aggregation) = self.aggregation.take() {
581            let index = aggregation.index;
582            let groups = self.plan.add_expr_list(&aggregation.groups);
583            let aggregates = self.plan.add_expr_list(&aggregation.aggregates);
584            node = self.plan.add_node(Node::Aggregate { input: node, index, groups, aggregates });
585        }
586        if let Some(predicate) = having {
587            node = self.plan.add_node(Node::Filter { input: node, predicate });
588        }
589
590        let interned: Vec<u32> = names.iter().map(|name| self.plan.intern(name)).collect();
591        let exprs_slice = self.plan.add_expr_list(&exprs);
592        let names_slice = self.plan.add_name_list(&interned);
593        node = self.plan.add_node(Node::Project {
594            input: node,
595            index: project,
596            exprs: exprs_slice,
597            names: names_slice,
598        });
599
600        if written.distinct != Distinct::No {
601            let on = self.plan.add_expr_list(&on);
602            node = self.plan.add_node(Node::Distinct { input: node, on });
603        }
604        if !keys.is_empty() {
605            let keys = self.plan.add_sort_keys(&keys);
606            node = self.plan.add_node(Node::Sort { input: node, keys });
607        }
608        node = self.apply_limit(ast, query, node)?;
609
610        if extra.is_empty() {
611            output.columns.truncate(visible);
612            return Ok((node, output));
613        }
614        // An expression sorted on but not selected was carried this far to make the sort possible,
615        // and now it goes, because the query did not ask for it.
616        let index = self.fresh_index();
617        let mut kept = Vec::with_capacity(visible);
618        let mut kept_names = Vec::with_capacity(visible);
619        let mut scope = Scope::empty();
620        for (at, name) in names.iter().enumerate().take(visible) {
621            let ty = output.columns[at].ty.clone();
622            kept.push(self.column(project, at, ty.clone()));
623            kept_names.push(self.plan.intern(name));
624            scope.push(Visible {
625                table: String::new(),
626                name: name.clone(),
627                binding: ColumnBinding::new(index, at as u32),
628                ty,
629                not_null: output.columns[at].not_null,
630            });
631        }
632        let exprs = self.plan.add_expr_list(&kept);
633        let names = self.plan.add_name_list(&kept_names);
634        node = self.plan.add_node(Node::Project { input: node, index, exprs, names });
635        Ok((node, scope))
636    }
637
638    /// Binds the target list, expanding every star into the columns it stands for.
639    fn bind_targets(
640        &mut self,
641        ast: &Ast,
642        targets: &[ast::Target],
643        input: &Scope,
644    ) -> Result<(Vec<ExprRef>, Vec<String>)> {
645        let mut exprs = Vec::with_capacity(targets.len());
646        let mut names = Vec::with_capacity(targets.len());
647        for target in targets {
648            if let ast::Expr::Star { qualifier, replacements } = ast.expr(target.expr) {
649                let table = ast.name(qualifier).last().map(str::to_string);
650                let expanded: Vec<Visible> =
651                    input.star(table.as_deref())?.into_iter().cloned().collect();
652                let replacements = ast.target_list(replacements).to_vec();
653                let mut used = vec![false; replacements.len()];
654                for column in expanded {
655                    let found = replacements.iter().zip(&mut used).find(|(replacement, _)| {
656                        same_name(ast.string(replacement.alias), &column.name)
657                    });
658                    // The replacement takes the column's place and its position, and it is named the
659                    // way the replace list spells it rather than the way the table does. That only
660                    // shows when the two differ in case, and `AS EventDate` over a column called
661                    // `eventdate` is exactly the case that shows it.
662                    let (expr, name) = match found {
663                        Some((replacement, used)) => {
664                            *used = true;
665                            let expr = self.bind_expr(ast, replacement.expr, input)?;
666                            (expr, ast.string(replacement.alias).to_string())
667                        }
668                        None => (
669                            self.plan.add_expr(Expr::Column(column.binding), column.ty),
670                            column.name,
671                        ),
672                    };
673                    exprs.push(self.over_aggregate(expr, input)?);
674                    names.push(name);
675                }
676                // A replace list that named something the star did not stand for is a mistake and
677                // not a no op, and it is caught here because this is the first point at which the
678                // set of names the star stands for is known.
679                if let Some((replacement, _)) =
680                    replacements.iter().zip(&used).find(|(_, used)| !**used)
681                {
682                    return Err(missing_replacement(ast.string(replacement.alias), input));
683                }
684                continue;
685            }
686            let expr = self.bind_expr(ast, target.expr, input)?;
687            exprs.push(self.over_aggregate(expr, input)?);
688            names.push(if target.alias == NONE {
689                self.output_name(ast, target.expr, input)
690            } else {
691                ast.string(target.alias).to_string()
692            });
693        }
694        Ok((exprs, names))
695    }
696
697    /// The name an unaliased target gets.
698    ///
699    /// A bare column keeps the spelling the table was created with rather than the spelling the
700    /// query used, so `SELECT USERID FROM hits` has a column called `UserID`. Identifiers match
701    /// without regard to case and the catalog is the one that holds the case.
702    fn output_name(&self, ast: &Ast, target: ast::ExprRef, input: &Scope) -> String {
703        if let ast::Expr::Column { name } = ast.expr(target) {
704            let parts: Vec<&str> = ast.name(name).collect();
705            if let Ok(found) = input.resolve(&parts) {
706                return found.name.clone();
707            }
708        }
709        describe(ast, target, self.semantics)
710    }
711
712    /// The expressions a `GROUP BY` clause names, with positions and output aliases followed.
713    fn group_items(
714        &self,
715        ast: &Ast,
716        select: &ast::Select,
717        targets: &[ast::Target],
718    ) -> Result<Vec<ast::ExprRef>> {
719        if select.group_by_all {
720            // GROUP BY ALL means every target that is not itself an aggregate, which is the set
721            // that would otherwise have to be written out again by hand.
722            return Ok(targets
723                .iter()
724                .filter(|target| !has_aggregate(ast, target.expr))
725                .map(|target| target.expr)
726                .collect());
727        }
728        let mut items = Vec::new();
729        for &item in ast.expr_list(select.group_by) {
730            items.push(self.output_reference(ast, item, targets, "GROUP BY")?.unwrap_or(item));
731        }
732        Ok(items)
733    }
734
735    /// The target a `GROUP BY` or `ORDER BY` term names, when it names one by position or alias.
736    fn output_reference(
737        &self,
738        ast: &Ast,
739        item: ast::ExprRef,
740        targets: &[ast::Target],
741        clause: &str,
742    ) -> Result<Option<ast::ExprRef>> {
743        match ast.expr(item) {
744            ast::Expr::Literal { kind: LiteralKind::Number, text } => {
745                let written = ast.string(text);
746                let position: usize = written.parse().map_err(|_| {
747                    Error::binder(format!("{clause} term {written} is not a column"))
748                })?;
749                if position == 0 || position > targets.len() {
750                    return Err(Error::binder(format!(
751                        "{clause} term out of range - should be between 1 and {}",
752                        targets.len()
753                    )));
754                }
755                Ok(Some(targets[position - 1].expr))
756            }
757            ast::Expr::Column { name } => {
758                let parts: Vec<&str> = ast.name(name).collect();
759                let [written] = parts.as_slice() else { return Ok(None) };
760                let mut found = None;
761                for target in targets {
762                    if target.alias != NONE && same_name(ast.string(target.alias), written) {
763                        if found.is_some() {
764                            return Ok(None);
765                        }
766                        found = Some(target.expr);
767                    }
768                }
769                Ok(found)
770            }
771            _ => Ok(None),
772        }
773    }
774
775    // -------------------------------------------------------------- modifiers
776
777    /// Sort keys for a select, projecting anything sorted on that is not already selected.
778    #[allow(clippy::too_many_arguments)]
779    fn select_sort_keys(
780        &mut self,
781        ast: &Ast,
782        query: &ast::Query,
783        input: &Scope,
784        output: &Scope,
785        project: u32,
786        exprs: &mut Vec<ExprRef>,
787        names: &mut Vec<String>,
788        extra: &mut Vec<usize>,
789    ) -> Result<Vec<SortKey>> {
790        if query.order_by_all {
791            return Ok(self.every_column(output));
792        }
793        let items = ast.order_list(query.order_by).to_vec();
794        let mut keys = Vec::with_capacity(items.len());
795        for item in items {
796            self.check_order_literal(ast, item.expr)?;
797            let position = match self.output_position(ast, item.expr, output)? {
798                Some(position) => position,
799                None => {
800                    let bound = self.bind_expr(ast, item.expr, input)?;
801                    let bound = self.over_aggregate(bound, input)?;
802                    match exprs.iter().position(|&held| self.same_expr(held, bound)) {
803                        Some(position) => position,
804                        None => {
805                            exprs.push(bound);
806                            names.push(describe(ast, item.expr, self.semantics));
807                            extra.push(exprs.len() - 1);
808                            exprs.len() - 1
809                        }
810                    }
811                }
812            };
813            let ty = self.plan.expr_type(exprs[position]).clone();
814            let expr = self.column(project, position, ty);
815            keys.push(self.sort_key(expr, item));
816        }
817        Ok(keys)
818    }
819
820    /// Sort keys over an output that has nothing behind it to project, which is a set operation.
821    fn sort_keys(
822        &mut self,
823        ast: &Ast,
824        query: &ast::Query,
825        output: &Scope,
826        targets: &[ast::Target],
827    ) -> Result<Vec<SortKey>> {
828        if query.order_by_all {
829            return Ok(self.every_column(output));
830        }
831        let items = ast.order_list(query.order_by).to_vec();
832        let mut keys = Vec::with_capacity(items.len());
833        for item in items {
834            self.check_order_literal(ast, item.expr)?;
835            let expr = match self.output_position(ast, item.expr, output)? {
836                Some(position) => {
837                    let column = &output.columns[position];
838                    let (binding, ty) = (column.binding, column.ty.clone());
839                    self.plan.add_expr(Expr::Column(binding), ty)
840                }
841                None => {
842                    let _ = targets;
843                    self.bind_expr(ast, item.expr, output)?
844                }
845            };
846            keys.push(self.sort_key(expr, item));
847        }
848        Ok(keys)
849    }
850
851    fn every_column(&mut self, output: &Scope) -> Vec<SortKey> {
852        let columns: Vec<(ColumnBinding, LogicalType)> =
853            output.columns.iter().map(|column| (column.binding, column.ty.clone())).collect();
854        columns
855            .into_iter()
856            .map(|(binding, ty)| {
857                let expr = self.plan.add_expr(Expr::Column(binding), ty);
858                let descending = self.semantics.default_descending();
859                SortKey { expr, descending, nulls_first: self.semantics.nulls_first(descending) }
860            })
861            .collect()
862    }
863
864    /// A sort key with the session defaults filled in.
865    fn sort_key(&self, expr: ExprRef, item: ast::OrderItem) -> SortKey {
866        let descending = match item.order {
867            Order::Unstated => self.semantics.default_descending(),
868            Order::Ascending => false,
869            Order::Descending => true,
870        };
871        let nulls_first = match item.nulls {
872            Nulls::First => true,
873            Nulls::Last => false,
874            Nulls::Unstated => self.semantics.nulls_first(descending),
875        };
876        SortKey { expr, descending, nulls_first }
877    }
878
879    /// Which output column a term names, by position or by name.
880    fn output_position(
881        &self,
882        ast: &Ast,
883        item: ast::ExprRef,
884        output: &Scope,
885    ) -> Result<Option<usize>> {
886        match ast.expr(item) {
887            ast::Expr::Literal { kind: LiteralKind::Number, text } => {
888                let written = ast.string(text);
889                if written.contains(['.', 'e', 'E']) {
890                    return Ok(None);
891                }
892                let position: usize = written.parse().map_err(|_| {
893                    Error::binder(format!("ORDER BY term {written} is not a column"))
894                })?;
895                if position == 0 || position > output.len() {
896                    return Err(Error::binder(format!(
897                        "ORDER BY term out of range - should be between 1 and {}",
898                        output.len()
899                    )));
900                }
901                Ok(Some(position - 1))
902            }
903            ast::Expr::Column { name } => {
904                let parts: Vec<&str> = ast.name(name).collect();
905                let [written] = parts.as_slice() else { return Ok(None) };
906                Ok(output.position_of(None, written))
907            }
908            _ => Ok(None),
909        }
910    }
911
912    /// Refuses a literal sort key unless the session explicitly accepts its no-op behavior.
913    fn check_order_literal(&self, ast: &Ast, item: ast::ExprRef) -> Result<()> {
914        if !self.semantics.order_by_non_integer_literal()
915            && matches!(
916                ast.expr(item),
917                ast::Expr::Literal { kind, text }
918                    if kind != LiteralKind::Number
919                        || ast.string(text).contains(['.', 'e', 'E'])
920            )
921        {
922            return Err(Error::binder(
923                "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to allow this behavior.",
924            ));
925        }
926        Ok(())
927    }
928
929    /// The expressions a `DISTINCT ON` names, which have to be columns of the output.
930    fn distinct_on(
931        &mut self,
932        ast: &Ast,
933        distinct: Distinct,
934        output: &Scope,
935    ) -> Result<Vec<ExprRef>> {
936        let Distinct::On(items) = distinct else {
937            return Ok(Vec::new());
938        };
939        let items = ast.expr_list(items).to_vec();
940        let mut on = Vec::with_capacity(items.len());
941        for item in items {
942            let Some(position) = self.output_position(ast, item, output)? else {
943                return Err(Error::not_implemented(
944                    "DISTINCT ON an expression that is not in the select list",
945                ));
946            };
947            let column = &output.columns[position];
948            let (binding, ty) = (column.binding, column.ty.clone());
949            on.push(self.plan.add_expr(Expr::Column(binding), ty));
950        }
951        Ok(on)
952    }
953
954    fn apply_limit(&mut self, ast: &Ast, query: &ast::Query, input: NodeRef) -> Result<NodeRef> {
955        if query.limit_percent {
956            return Err(Error::not_implemented("LIMIT with a percentage"));
957        }
958        let count = self.constant_count(ast, query.limit, "LIMIT")?;
959        let offset = self.constant_count(ast, query.offset, "OFFSET")?.unwrap_or(0);
960        if count.is_none() && offset == 0 {
961            return Ok(input);
962        }
963        Ok(self.plan.add_node(Node::Limit { input, count, offset }))
964    }
965
966    /// The row count a `LIMIT` or an `OFFSET` names, which has to be a constant.
967    fn constant_count(
968        &mut self,
969        ast: &Ast,
970        written: ast::ExprRef,
971        clause: &str,
972    ) -> Result<Option<u64>> {
973        if written == NONE {
974            return Ok(None);
975        }
976        self.clause = "LIMIT clause";
977        let scope = Scope::empty();
978        let bound = self.bind_expr(ast, written, &scope)?;
979        let Expr::Constant(value) = *self.plan.expr(bound) else {
980            return Err(Error::not_implemented(format!("a {clause} that is not a constant")));
981        };
982        let count = match self.plan.value(value) {
983            Value::Null => return Ok(None),
984            Value::TinyInt(count) => i128::from(*count),
985            Value::SmallInt(count) => i128::from(*count),
986            Value::Integer(count) => i128::from(*count),
987            Value::BigInt(count) => i128::from(*count),
988            Value::HugeInt(count) => *count,
989            other => {
990                return Err(Error::binder(format!(
991                    "{clause} takes a whole number of rows, not a value of type {}",
992                    other.logical_type()
993                )));
994            }
995        };
996        u64::try_from(count)
997            .map(Some)
998            .map_err(|_| Error::binder(format!("{clause} must not be negative")))
999    }
1000
1001    // ------------------------------------------------------------------- from
1002
1003    fn bind_from(&mut self, ast: &Ast, from: ast::Slice) -> Result<(NodeRef, Scope)> {
1004        let sources = ast.source_list(from).to_vec();
1005        let Some((first, rest)) = sources.split_first() else {
1006            // No FROM clause is one row of no columns, which is what SELECT 1 sits on. Not an
1007            // empty table: an empty table would make SELECT 1 return nothing.
1008            return Ok((self.plan.add_node(Node::Dummy), Scope::empty()));
1009        };
1010        let (mut node, mut scope) = self.bind_source(ast, *first)?;
1011        for source in rest {
1012            let (right, right_scope) = self.bind_source(ast, *source)?;
1013            node = self.plan.add_node(Node::CrossProduct { left: node, right });
1014            scope = scope.concat(right_scope);
1015        }
1016        Ok((node, scope))
1017    }
1018
1019    fn bind_source(&mut self, ast: &Ast, source: ast::SourceRef) -> Result<(NodeRef, Scope)> {
1020        match ast.source(source) {
1021            ast::Source::Table { name, alias, columns } => {
1022                self.bind_table(ast, name, alias, columns)
1023            }
1024            ast::Source::Function { name, args, alias, columns, pragma } => {
1025                self.bind_table_function(ast, name, args, alias, columns, pragma)
1026            }
1027            ast::Source::Subquery { query, alias, columns } => {
1028                let (node, mut scope) = self.bind_query(ast, query)?;
1029                let label = if alias == NONE {
1030                    "unnamed_subquery".to_string()
1031                } else {
1032                    ast.string(alias).to_string()
1033                };
1034                scope.relabel(&label);
1035                if !columns.is_empty() {
1036                    let names: Vec<&str> = ast.name(columns).collect();
1037                    scope.rename(&names, &label)?;
1038                }
1039                Ok((node, scope))
1040            }
1041            ast::Source::Values { rows, alias, columns } => {
1042                let bare = ast::Query::bare(ast::QueryBody::Values(rows));
1043                let (node, mut scope) = self.bind_values(ast, &bare, rows)?;
1044                let label =
1045                    if alias == NONE { String::new() } else { ast.string(alias).to_string() };
1046                scope.relabel(&label);
1047                if !columns.is_empty() {
1048                    let names: Vec<&str> = ast.name(columns).collect();
1049                    scope.rename(&names, &label)?;
1050                }
1051                Ok((node, scope))
1052            }
1053            ast::Source::Join { left, right, kind, natural, on, using } => {
1054                self.bind_join(ast, left, right, kind, natural, on, using)
1055            }
1056        }
1057    }
1058
1059    fn bind_table(
1060        &mut self,
1061        ast: &Ast,
1062        name: ast::Slice,
1063        alias: ast::StrRef,
1064        columns: ast::Slice,
1065    ) -> Result<(NodeRef, Scope)> {
1066        let parts: Vec<&str> = ast.name(name).collect();
1067        let catalog = self.catalog;
1068        // The catalog is asked first and the file is the fallback, which is the order DuckDB uses:
1069        // a table really called `mixed.parquet` wins over a file of that name sitting next to it.
1070        let resolved = match catalog.resolve(&parts) {
1071            Ok(resolved) => resolved,
1072            Err(missing) => {
1073                return self.bind_replacement_scan(ast, &parts, alias, columns, missing);
1074            }
1075        };
1076        if catalog.entry(&resolved)? == Entry::View {
1077            return self.bind_view(ast, &resolved, alias, columns);
1078        }
1079        let table = catalog.table(&resolved)?;
1080        let fields: Vec<Field> = table.columns().to_vec();
1081        let label =
1082            if alias == NONE { resolved.table.clone() } else { ast.string(alias).to_string() };
1083        let index = self.fresh_index();
1084        let mut scope = Scope::empty();
1085        for (at, field) in fields.iter().enumerate() {
1086            scope.push(Visible {
1087                table: label.clone(),
1088                name: field.name.clone(),
1089                binding: ColumnBinding::new(index, at as u32),
1090                ty: field.ty.clone(),
1091                not_null: field.not_null,
1092            });
1093        }
1094        if !columns.is_empty() {
1095            let names: Vec<&str> = ast.name(columns).collect();
1096            scope.rename(&names, &label)?;
1097        }
1098        let catalog_name = self.plan.intern(&resolved.catalog);
1099        let schema = self.plan.intern(&resolved.schema);
1100        let table_name = self.plan.intern(&resolved.table);
1101        let alias = self.plan.intern(&label);
1102        let columns = self.plan.add_fields(&fields);
1103        let node = self.plan.add_node(Node::Get {
1104            catalog: catalog_name,
1105            schema,
1106            table: table_name,
1107            alias,
1108            index,
1109            columns,
1110        });
1111        Ok((node, scope))
1112    }
1113
1114    /// A view where a table goes, which is the body bound again right here.
1115    ///
1116    /// Inline and not behind a node. The view is gone by the time the plan exists, so everything
1117    /// downstream sees the query somebody would have written by hand, and the column pruning that
1118    /// makes `SELECT COUNT(*) FROM 'hits.parquet'` read no columns at all keeps working through
1119    /// `FROM hits`. A `Node::View` would be a barrier with nothing on the other side of it.
1120    ///
1121    /// The scope this builds is a subquery's, right down to the name in the error message. duckdb
1122    /// v1.5.1 reports a view whose column list has gone stale as `table "unnamed_subquery" has 1
1123    /// columns available but 2 columns specified`, which is the sentence its subquery alias rule
1124    /// produces, so a view there is a subquery with the view's name written over it afterwards.
1125    fn bind_view(
1126        &mut self,
1127        ast: &Ast,
1128        name: &QualifiedName,
1129        alias: ast::StrRef,
1130        columns: ast::Slice,
1131    ) -> Result<(NodeRef, Scope)> {
1132        let view = self.catalog.view(name)?;
1133        let full = name.to_string();
1134        if self.expanding.contains(&full) {
1135            // Two quotes each side, which is what the binary prints. It quotes the name on the way
1136            // in and then formats the quoted name into a quoted slot, so a view called `a` comes
1137            // back as `""a""`. That is upstream's wart and copying it is the whole job here.
1138            return Err(Error::binder(format!(
1139                "infinite recursion detected: attempting to recursively bind view \"\"{}\"\"",
1140                name.table
1141            )));
1142        }
1143        let body = parse_ast(view.sql())?;
1144        let query = match body.statements.as_slice() {
1145            [ast::Statement::Query(query)] => *query,
1146            // Only a query can have got past the binder at creation, so this is a view the catalog
1147            // was handed some other way rather than anything a statement can produce.
1148            _ => return Err(Error::binder(format!("view \"{}\" is not a query", name.table))),
1149        };
1150        self.expanding.push(full);
1151        let bound = self.bind_query(&body, query);
1152        self.expanding.pop();
1153        let (node, mut scope) = bound?;
1154
1155        let aliases: Vec<&str> = view.aliases().iter().map(String::as_str).collect();
1156        if !aliases.is_empty() {
1157            scope.rename(&aliases, "unnamed_subquery")?;
1158        }
1159        // What the catalog tables report as this view's columns, written down here because this is
1160        // the moment they are known. Upstream refreshes the same cache at the same point, which was
1161        // measured: both `duckdb_columns()` and `duckdb_views().column_count` keep reporting the old
1162        // list after an `ALTER TABLE` underneath until something reads the view, and then both move.
1163        // It is written before the label and before the `AS t(a, b)` list below, because those two
1164        // rename the view for one query and not for everyone.
1165        view.remember(scope.fields());
1166        let label = if alias == NONE { name.table.clone() } else { ast.string(alias).to_string() };
1167        scope.relabel(&label);
1168        if !columns.is_empty() {
1169            let names: Vec<&str> = ast.name(columns).collect();
1170            scope.rename(&names, &label)?;
1171        }
1172        Ok((node, scope))
1173    }
1174
1175    /// A function call where a table goes, such as `range(10)`.
1176    ///
1177    /// The arguments are bound against an empty scope. A table function that can see the row on its
1178    /// left is `LATERAL`, and this is not it, so a column name in here is not resolved against
1179    /// whatever happens to be to the left in the `FROM` list. Letting it would mean `FROM t,
1180    /// range(t.n)` quietly binding to something whose meaning depends on the order the sources were
1181    /// written in.
1182    fn bind_table_function(
1183        &mut self,
1184        ast: &Ast,
1185        name: ast::Slice,
1186        args: ast::Slice,
1187        alias: ast::StrRef,
1188        columns: ast::Slice,
1189        pragma: bool,
1190    ) -> Result<(NodeRef, Scope)> {
1191        let parts: Vec<&str> = ast.name(name).collect();
1192        // A qualified call names a schema, and the two schemas that exist are the ones every
1193        // built-in lives in. Anything else is a name that has to fail rather than fall through to
1194        // the unqualified lookup and be found somewhere it was not asked for.
1195        let function_name = *parts.last().unwrap_or(&"");
1196        if let Some(schema) = parts.iter().rev().nth(1) {
1197            if !schema.eq_ignore_ascii_case("main") && !schema.eq_ignore_ascii_case("system") {
1198                return Err(Error::catalog(format!(
1199                    "Table Function with name {} does not exist!",
1200                    parts.join(".")
1201                )));
1202            }
1203        }
1204        // The name is looked up before the arguments are bound so that a call of something that is
1205        // not a table function says that, rather than reporting whatever is wrong with the
1206        // arguments of a function that was never going to exist.
1207        let Some(called) = TableFunction::lookup(function_name) else {
1208            if pragma {
1209                // `PRAGMA database_list` is a view upstream and not a function, and the pragma
1210                // namespace holds both, so a name that is not a function gets one more look in the
1211                // catalog before it is turned down. It has to be the no argument form: a view
1212                // takes none, and `pragma_database_list()` with parentheses is a missing function
1213                // on the pin too.
1214                if args.is_empty() && self.catalog.resolve(&parts).is_ok() {
1215                    return self.bind_table(ast, name, alias, columns);
1216                }
1217                let spelled = function_name.strip_prefix("pragma_").unwrap_or(function_name);
1218                return Err(Error::catalog(format!(
1219                    "Pragma Function with name {spelled} does not exist!"
1220                )));
1221            }
1222            return Err(Error::catalog(format!(
1223                "Table Function with name {function_name} does not exist!"
1224            )));
1225        };
1226        let written = ast.target_list(args).to_vec();
1227        let empty = Scope::empty();
1228        let previous = std::mem::replace(&mut self.clause, "table function arguments");
1229        let mut bound = Vec::new();
1230        let mut written_options = Vec::new();
1231        for argument in written {
1232            let expr = self.bind_expr(ast, argument.expr, &empty)?;
1233            if argument.alias == NONE {
1234                bound.push(expr);
1235            } else {
1236                let name = ast.string(argument.alias).to_string();
1237                let (parameter, value) = self.named_argument(called, &name, expr)?;
1238                written_options.push((parameter, value, expr));
1239            }
1240        }
1241        self.clause = previous;
1242        let options = Options::of(&written_options)?;
1243
1244        // The types are what resolve the call, not the count, because `read_parquet(3)` is a
1245        // different answer from `read_parquet('3')` and only the types tell them apart.
1246        let given: Vec<LogicalType> =
1247            bound.iter().map(|&expr| self.plan.expr_type(expr).clone()).collect();
1248        let resolved = if pragma {
1249            resolve_pragma(function_name, &given)?
1250        } else {
1251            resolve_table(function_name, &given)?
1252        };
1253        let mut cast: Vec<ExprRef> = bound
1254            .iter()
1255            .zip(&resolved.arguments)
1256            .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
1257            .collect::<Result<_>>()?;
1258
1259        if resolved.function.takes_a_name() {
1260            let Columns::Fixed(fields) = resolved.columns else {
1261                return Err(Error::internal("a pragma that resolved to a file"));
1262            };
1263            let [argument] = cast[..] else {
1264                return Err(Error::internal("a pragma that resolved to more than one name"));
1265            };
1266            return self.bind_pragma(ast, resolved.function, &fields, argument, alias, columns);
1267        }
1268        let fields = match resolved.columns {
1269            Columns::Fixed(fields) => fields,
1270            columns => {
1271                // The one argument is a pattern, and what replaces it is one constant per file it
1272                // matched. The executor is handed names rather than a pattern, so it never walks a
1273                // directory and the answer cannot change between binding a prepared statement and
1274                // running it, which is the same reason the schema is settled here.
1275                let paths = self.file_paths(cast[0], resolved.function.name())?;
1276                let first = paths.first().map_or("", String::as_str);
1277                let mut fields = match columns {
1278                    // Parquet takes the first file's footer as the answer and CSV sniffs all of
1279                    // them, which is not a choice made here. See `csv_fields`.
1280                    Columns::Csv => csv_fields(&paths, options.given)?,
1281                    _ => parquet_fields(first)?,
1282                };
1283                if options.all_varchar {
1284                    // The sniffer still ran, because the names come out of the same pass over the
1285                    // front of the file and only the types are being overruled. The executor reads
1286                    // the text as VARCHAR because this is the schema it is told to read into, which
1287                    // is the same road a file in a glob takes when the set is wider than the file.
1288                    for field in &mut fields {
1289                        field.ty = LogicalType::Varchar;
1290                    }
1291                }
1292                if options.binary_as_string {
1293                    // A byte array column with no annotation on it is a BLOB, and this is the caller
1294                    // saying that the file's writer meant text. The reader already holds both in the
1295                    // same string column and already validates the bytes, so the whole of the option
1296                    // is what the column is called from here on.
1297                    for field in &mut fields {
1298                        if field.ty == LogicalType::Blob {
1299                            field.ty = LogicalType::Varchar;
1300                        }
1301                    }
1302                }
1303                if options.file_row_number {
1304                    // Not a column of the file, so it goes on the end where a projection cannot be
1305                    // confused about which one it is, and the executor counts it as the rows come
1306                    // out. A file that already has a column of that name is the one case where the
1307                    // option cannot be honoured, and saying so is better than handing back two
1308                    // columns with the same name and letting a reference to it pick one.
1309                    if fields.iter().any(|field| field.name == FILE_ROW_NUMBER) {
1310                        return Err(Error::binder(format!(
1311                            "Duplicate column name \"{FILE_ROW_NUMBER}\": the file already has a \
1312                             column of that name, so file_row_number cannot add one"
1313                        )));
1314                    }
1315                    fields.push(Field::required(FILE_ROW_NUMBER.to_string(), LogicalType::BigInt));
1316                }
1317                cast = paths.iter().map(|path| self.path_constant(path)).collect();
1318                fields
1319            }
1320        };
1321        let label = if alias == NONE {
1322            resolved.function.name().to_string()
1323        } else {
1324            ast.string(alias).to_string()
1325        };
1326        let names: Vec<&str> = ast.name(columns).collect();
1327        self.table_function_source(
1328            resolved.function,
1329            &cast,
1330            &written_options,
1331            fields,
1332            &label,
1333            &names,
1334        )
1335    }
1336
1337    /// `pragma_table_info('t')` or `pragma_show('t')`, answered while it is bound.
1338    ///
1339    /// The same trick `DESCRIBE` uses and for the same reason: the columns of a table are settled by
1340    /// the time the name has resolved, so the rows are a constant from there on and this comes out
1341    /// as a `VALUES` rather than as an operator that reads a catalog while the query runs. It also
1342    /// means `SELECT name FROM pragma_table_info('t') WHERE notnull` is an ordinary query over an
1343    /// ordinary relation, which is the whole reason these exist as functions rather than only as
1344    /// statements.
1345    ///
1346    /// The name arrives as a string rather than as something the parser read, so it is split here
1347    /// under the identifier rule and then resolved like any other name. A name that is not there
1348    /// comes back as the catalog's own complaint, which is what the pin answers with too.
1349    fn bind_pragma(
1350        &mut self,
1351        ast: &Ast,
1352        function: TableFunction,
1353        fields: &[Field],
1354        argument: ExprRef,
1355        alias: ast::StrRef,
1356        columns: ast::Slice,
1357    ) -> Result<(NodeRef, Scope)> {
1358        let written = self.pragma_name(argument, function)?;
1359        let parts = identifier_parts(&written);
1360        let spelled: Vec<&str> = parts.iter().map(String::as_str).collect();
1361        let name = self.catalog.resolve(&spelled)?;
1362        let described = self.described(ast, &name)?;
1363        let mut rows = Vec::with_capacity(described.len());
1364        for (at, field) in described.iter().enumerate() {
1365            let items = if matches!(function, TableFunction::PragmaShow) {
1366                self.describing(field)
1367            } else {
1368                self.table_info(at, field)
1369            };
1370            rows.push(self.plan.add_expr_list(&items));
1371        }
1372        let rows = self.plan.add_rows(&rows);
1373        let held = self.plan.add_fields(fields);
1374        let index = self.fresh_index();
1375        let node = self.plan.add_node(Node::Values { index, columns: held, rows });
1376        let label =
1377            if alias == NONE { function.name().to_string() } else { ast.string(alias).to_string() };
1378        let mut scope = Scope::empty();
1379        for (at, field) in fields.iter().enumerate() {
1380            scope.push(Visible {
1381                table: label.clone(),
1382                name: field.name.clone(),
1383                binding: ColumnBinding::new(index, at as u32),
1384                ty: field.ty.clone(),
1385                not_null: false,
1386            });
1387        }
1388        if !columns.is_empty() {
1389            let names: Vec<&str> = ast.name(columns).collect();
1390            scope.rename(&names, &label)?;
1391        }
1392        Ok((node, scope))
1393    }
1394
1395    /// The name a pragma was called with, which has to be a constant.
1396    ///
1397    /// A null is a name spelled `NULL` rather than an error about nulls, because the pin turns
1398    /// whatever it was handed into text before it goes looking and then says a table of that name
1399    /// does not exist. Writing `pragma_table_info(NULL)` is a mistake either way and this is the
1400    /// sentence the mistake already has.
1401    ///
1402    /// `pragma_table_info('t' || 'x')` is the pin's `tx` and is turned away here, which is the same
1403    /// missing constant folding [`Binder::named_argument`] writes about and closes the same day.
1404    fn pragma_name(&self, argument: ExprRef, function: TableFunction) -> Result<String> {
1405        let Expr::Constant(reference) = *self.plan.expr(argument) else {
1406            return Err(Error::not_implemented(format!(
1407                "{}() given a name that is not a constant",
1408                function.name()
1409            )));
1410        };
1411        match self.plan.value(reference) {
1412            Value::Varchar(name) => Ok(name.clone()),
1413            Value::Null => Ok("NULL".to_string()),
1414            other => {
1415                Err(Error::internal(format!("a pragma name bound as VARCHAR arrived as {other}")))
1416            }
1417        }
1418    }
1419
1420    /// The columns of whatever a pragma was pointed at.
1421    ///
1422    /// A view is bound here, which is how it comes to have columns at all. Reading a view is what
1423    /// binds it and describing one counts as reading it, so a view the engine ships with reports a
1424    /// column count from this point on, the same as it would after a select. The node that binding
1425    /// produces is thrown away, because the answer is the scope and not the query.
1426    ///
1427    /// Every column of a view is nullable whatever the column underneath was declared as, which is
1428    /// the pin's answer through `pragma_table_info()`, `pragma_show()` and `duckdb_columns()` alike.
1429    /// [`Scope::fields`] drops the flag on its own, so there is nothing to clear here.
1430    fn described(&mut self, ast: &Ast, name: &QualifiedName) -> Result<Vec<Field>> {
1431        if self.catalog.entry(name)? == Entry::Table {
1432            return Ok(self.catalog.table(name)?.columns().to_vec());
1433        }
1434        let (_, scope) = self.bind_view(ast, name, NONE, ast::Slice::default())?;
1435        Ok(scope.fields())
1436    }
1437
1438    /// One row of `pragma_show()`, which is one row of `DESCRIBE` written by the other caller.
1439    fn describing(&mut self, field: &Field) -> Vec<ExprRef> {
1440        let written = [
1441            field.name.clone(),
1442            field.ty.to_string(),
1443            if field.not_null { "NO" } else { "YES" }.to_owned(),
1444        ];
1445        let mut items: Vec<ExprRef> =
1446            written.into_iter().map(|text| self.plan.add_constant(Value::Varchar(text))).collect();
1447        for _ in 0..3 {
1448            let empty = self.plan.add_constant(Value::Null);
1449            items.push(self.cast_to(empty, &LogicalType::Varchar));
1450        }
1451        items
1452    }
1453
1454    /// One row of `pragma_table_info()`, which is SQLite's six columns about the same column.
1455    ///
1456    /// `cid` counts from zero, which is SQLite's numbering and not the one based `ordinal_position`
1457    /// the standard views report. `dflt_value` and `pk` are the two nothings rudb has to report
1458    /// until `CREATE TABLE` takes a `DEFAULT` or a key.
1459    fn table_info(&mut self, at: usize, field: &Field) -> Vec<ExprRef> {
1460        let cid = self.plan.add_constant(Value::Integer(i32::try_from(at).unwrap_or(i32::MAX)));
1461        let name = self.plan.add_constant(Value::Varchar(field.name.clone()));
1462        let ty = self.plan.add_constant(Value::Varchar(field.ty.to_string()));
1463        let not_null = self.plan.add_constant(Value::Boolean(field.not_null));
1464        let default = self.plan.add_constant(Value::Null);
1465        let default = self.cast_to(default, &LogicalType::Varchar);
1466        let key = self.plan.add_constant(Value::Boolean(false));
1467        vec![cid, name, ty, not_null, default, key]
1468    }
1469
1470    /// One named parameter of a table function call, folded into what the call was given.
1471    ///
1472    /// The value has to be a constant of the type the parameter wants. It has to be constant
1473    /// because an option can decide what the columns are and the columns are settled here, and it
1474    /// has to be already of the type because there is no constant folding in front of the binder
1475    /// yet. DuckDB folds first, so `binary_as_string=1` and `binary_as_string='yes'` are both true
1476    /// there and both are turned away here, which is a gap that closes on its own the day the
1477    /// optimizer runs before the plan is finished. `binary_as_string=True` is what the ClickBench
1478    /// entry writes and is what has to work.
1479    ///
1480    /// A name that is not a parameter of this function is the binary's sentence followed by what it
1481    /// could have been. The binary puts the candidates on their own indented lines and this puts
1482    /// them on the same line, because an error is one line here.
1483    fn named_argument(
1484        &mut self,
1485        function: TableFunction,
1486        name: &str,
1487        expr: ExprRef,
1488    ) -> Result<(&'static str, Value)> {
1489        let known = function
1490            .parameters()
1491            .iter()
1492            .find(|(parameter, _)| parameter.eq_ignore_ascii_case(name));
1493        let Some((parameter, wanted)) = known else {
1494            let candidates: Vec<String> = function
1495                .parameters()
1496                .iter()
1497                .map(|(parameter, ty)| format!("    {parameter} {ty}"))
1498                .collect();
1499            return Err(Error::binder(format!(
1500                "Invalid named parameter \"{name}\" for function {}\nCandidates:\n{}\n",
1501                function.name(),
1502                candidates.join("\n")
1503            )));
1504        };
1505        let Expr::Constant(reference) = *self.plan.expr(expr) else {
1506            return Err(Error::not_implemented(format!(
1507                "the named parameter {parameter} with a value that is not a constant"
1508            )));
1509        };
1510        let value = self.plan.value(reference).clone();
1511        if value == Value::Null {
1512            return Err(Error::binder(null_parameter(function, parameter)));
1513        }
1514        let given = self.plan.expr_type(expr).clone();
1515        if given != *wanted {
1516            return Err(Error::not_implemented(format!(
1517                "the named parameter {parameter} given a {given} where a {wanted} was wanted"
1518            )));
1519        }
1520        Ok((parameter, value))
1521    }
1522
1523    /// A file where a table name goes, which is what DuckDB calls a replacement scan.
1524    ///
1525    /// `SELECT * FROM 'hits.parquet'` is how most DuckDB queries in the wild are written, ClickBench
1526    /// among them, so this is not sugar over `read_parquet` so much as the spelling people use. The
1527    /// catalog has already been asked and has already said no, and `missing` is what it said, so a
1528    /// name that is not a file comes back with the catalog's own answer rather than with a complaint
1529    /// about files.
1530    ///
1531    /// Only a single unqualified name is a candidate. A qualified one names a schema and a schema
1532    /// that does not exist is not a path.
1533    fn bind_replacement_scan(
1534        &mut self,
1535        ast: &Ast,
1536        parts: &[&str],
1537        alias: ast::StrRef,
1538        columns: ast::Slice,
1539        missing: Error,
1540    ) -> Result<(NodeRef, Scope)> {
1541        let [path] = parts else { return Err(missing) };
1542        let path = *path;
1543        let extension = path.rsplit_once('.').map(|(_, after)| after).unwrap_or_default();
1544        let Some(function) = Self::reader_for(extension) else {
1545            if is_file(path) {
1546                // A file that is really there and that nothing here can read is a different mistake
1547                // from a name that is not a file, and DuckDB says so with both lines, the second of
1548                // which is the way out. A file with no dot in it lands here too, which is why the
1549                // test is on the extension having a reader rather than on there being an extension.
1550                return Err(Error::binder(format!(
1551                    "No extension found that is capable of reading the file \"{path}\"\n* If this \
1552                     file is a supported file format you can explicitly use the reader functions, \
1553                     such as read_csv, read_json or read_parquet"
1554                )));
1555            }
1556            return Err(missing);
1557        };
1558        // The pattern is expanded before it is known to match anything, so a name that ends in .csv
1559        // and is not there gives the reader's own message rather than the catalog's. That is
1560        // DuckDB's order and it is the helpful one: somebody who wrote a file name wants to hear
1561        // about the file.
1562        let paths = files(path)?;
1563        let first = paths.first().map_or("", String::as_str);
1564        let fields = match function {
1565            TableFunction::ReadParquet => parquet_fields(first)?,
1566            _ => csv_fields(&paths, Given::default())?,
1567        };
1568        // The name the columns answer to is the file's stem, so `SELECT mixed.a FROM
1569        // 'data/mixed.parquet'` works. That is DuckDB's choice and it is the useful one, since the
1570        // alternative is a table name with a dot and a slash in it that nothing can write. A pattern
1571        // keeps the whole of what was written instead, which is DuckDB's choice too and was
1572        // measured: there is no stem to take when the name stands for a directory full of files.
1573        let label = if alias == NONE {
1574            if is_pattern(path) {
1575                path.to_string()
1576            } else {
1577                let file = path.rsplit_once('/').map_or(path, |(_, file)| file);
1578                file.rsplit_once('.').map_or(file, |(stem, _)| stem).to_string()
1579            }
1580        } else {
1581            ast.string(alias).to_string()
1582        };
1583        let arguments: Vec<ExprRef> = paths.iter().map(|path| self.path_constant(path)).collect();
1584        let names: Vec<&str> = ast.name(columns).collect();
1585        self.table_function_source(function, &arguments, &[], fields, &label, &names)
1586    }
1587
1588    /// One file name, as a constant expression in the plan.
1589    fn path_constant(&mut self, path: &str) -> ExprRef {
1590        let value = self.plan.add_value(Value::Varchar(path.to_string()));
1591        self.plan.add_expr(Expr::Constant(value), LogicalType::Varchar)
1592    }
1593
1594    /// The table function a file with this extension is read by, and `None` for one nothing reads.
1595    ///
1596    /// Both spellings of a tab separated file go to the CSV reader, which is not a shortcut: the
1597    /// extension picks the reader and the reader sniffs the punctuation, so a `.tsv` file that holds
1598    /// commas is read as commas. That was measured rather than assumed. The comparison ignores case
1599    /// because `UP.CSV` reads in duckdb v1.4.1.
1600    fn reader_for(extension: &str) -> Option<TableFunction> {
1601        if extension.eq_ignore_ascii_case("parquet") {
1602            return Some(TableFunction::ReadParquet);
1603        }
1604        if extension.eq_ignore_ascii_case("csv") || extension.eq_ignore_ascii_case("tsv") {
1605            return Some(TableFunction::ReadCsv);
1606        }
1607        None
1608    }
1609
1610    /// The node and the scope of a table function call whose arguments and columns are settled.
1611    ///
1612    /// The half a written out call shares with a replacement scan, which is everything after the
1613    /// question of what the file is called has been answered one way or the other.
1614    fn table_function_source(
1615        &mut self,
1616        function: TableFunction,
1617        args: &[ExprRef],
1618        written: &[(&'static str, Value, ExprRef)],
1619        fields: Vec<Field>,
1620        label: &str,
1621        names: &[&str],
1622    ) -> Result<(NodeRef, Scope)> {
1623        let index = self.fresh_index();
1624        let mut scope = Scope::empty();
1625        for (at, field) in fields.iter().enumerate() {
1626            scope.push(Visible {
1627                table: label.to_string(),
1628                name: field.name.clone(),
1629                binding: ColumnBinding::new(index, at as u32),
1630                ty: field.ty.clone(),
1631                // A reader takes what the file has, and no file format this reads says a column
1632                // cannot be null. The reference binary answers YES for every column of a Parquet.
1633                not_null: false,
1634            });
1635        }
1636        if !names.is_empty() {
1637            scope.rename(names, label)?;
1638        }
1639        let function = self.plan.intern(function.name());
1640        let args = self.plan.add_expr_list(args);
1641        let named: Vec<u32> =
1642            written.iter().map(|(parameter, _, _)| self.plan.intern(parameter)).collect();
1643        let settings: Vec<ExprRef> = written.iter().map(|(_, _, expr)| *expr).collect();
1644        let options = self.plan.add_name_list(&named);
1645        let settings = self.plan.add_expr_list(&settings);
1646        let columns = self.plan.add_fields(&fields);
1647        let node = self.plan.add_node(Node::TableFunction {
1648            index,
1649            function,
1650            args,
1651            options,
1652            settings,
1653            columns,
1654        });
1655        Ok((node, scope))
1656    }
1657
1658    /// Every file a table function's file argument names, in the order they were written.
1659    ///
1660    /// Each pattern has to find at least one file of its own, which is DuckDB's rule and is why
1661    /// this expands one at a time rather than gathering everything and looking at the total. A
1662    /// list keeps its written order and its duplicates, so a file named twice is read twice, which
1663    /// was measured: the sort and the dedup belong to one pattern rather than to the list.
1664    fn file_paths(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
1665        let mut paths = Vec::new();
1666        for pattern in self.file_patterns(expr, name)? {
1667            paths.extend(files(&pattern)?);
1668        }
1669        Ok(paths)
1670    }
1671
1672    /// The patterns a table function argument names, which have to be constants.
1673    ///
1674    /// A table function that reads a file is resolved by opening the file, and that happens here
1675    /// rather than when the query runs, because the rest of the statement cannot bind until the
1676    /// column names are known. So the path has to be something this binder can work out without
1677    /// running anything, and a literal is that. DuckDB folds a constant expression first, so
1678    /// `read_parquet('a' || '.parquet')` works there, and folding is M1 work that this will pick up
1679    /// for free once the optimizer runs before the plan is finished rather than after.
1680    ///
1681    /// One string is one pattern and a list is one pattern an item, which is DuckDB's pair of
1682    /// overloads. A null is a different sentence in each of them, both of them measured.
1683    fn file_patterns(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
1684        let Expr::Constant(reference) = *self.plan.expr(expr) else {
1685            return Err(Error::not_implemented(
1686                "a table function file name that is not a constant",
1687            ));
1688        };
1689        match self.plan.value(reference) {
1690            Value::Varchar(path) => Ok(vec![path.clone()]),
1691            // DuckDB's own wording, which says list because its other overload takes one.
1692            Value::Null => Err(Error::parser(format!("{name} cannot take NULL list as parameter"))),
1693            Value::List { values, .. } => values
1694                .iter()
1695                .map(|value| match value {
1696                    Value::Varchar(path) => Ok(path.clone()),
1697                    _ => Err(Error::parser(format!(
1698                        "{name} reader cannot take NULL input as parameter"
1699                    ))),
1700                })
1701                .collect(),
1702            other => {
1703                Err(Error::internal(format!("a file name bound as VARCHAR arrived as {other}")))
1704            }
1705        }
1706    }
1707
1708    #[allow(clippy::too_many_arguments)]
1709    fn bind_join(
1710        &mut self,
1711        ast: &Ast,
1712        left: ast::SourceRef,
1713        right: ast::SourceRef,
1714        kind: ast::JoinKind,
1715        natural: bool,
1716        on: ast::ExprRef,
1717        using: ast::Slice,
1718    ) -> Result<(NodeRef, Scope)> {
1719        let (left_node, left_scope) = self.bind_source(ast, left)?;
1720        let (right_node, right_scope) = self.bind_source(ast, right)?;
1721        let split = left_scope.len();
1722        let mut scope = left_scope.concat(right_scope);
1723
1724        // NATURAL is USING over whatever both sides happen to call the same thing, which is why it
1725        // is resolved here and never reaches the plan as its own idea.
1726        let merged: Vec<String> = if natural {
1727            let mut names = Vec::new();
1728            for (at, column) in scope.columns.iter().enumerate().take(split) {
1729                if scope.columns[split..].iter().any(|right| same_name(&right.name, &column.name))
1730                    && !names.iter().any(|held: &String| same_name(held, &column.name))
1731                {
1732                    let _ = at;
1733                    names.push(column.name.clone());
1734                }
1735            }
1736            names
1737        } else {
1738            // A name written twice is one column, not two. `USING (id, id)` is legal and means what
1739            // `USING (id)` means, and the reference binary agrees. Taking it twice would build the
1740            // same equality twice and, worse, drop the right side's copy twice, which takes a
1741            // column out of the answer that nobody named and runs off the end of the scope when the
1742            // copy was the last column in it.
1743            let mut names: Vec<String> = Vec::new();
1744            for name in ast.name(using) {
1745                if !names.iter().any(|held| same_name(held, name)) {
1746                    names.push(name.to_string());
1747                }
1748            }
1749            names
1750        };
1751
1752        let mut conditions = Vec::new();
1753        let mut dropped = Vec::new();
1754        for name in &merged {
1755            let left_at = scope.columns[..split]
1756                .iter()
1757                .position(|column| same_name(&column.name, name))
1758                .ok_or_else(|| {
1759                    Error::binder(format!(
1760                        "column \"{name}\" specified in USING clause does not exist in left table"
1761                    ))
1762                })?;
1763            let right_at = scope.columns[split..]
1764                .iter()
1765                .position(|column| same_name(&column.name, name))
1766                .map(|at| at + split)
1767                .ok_or_else(|| {
1768                    Error::binder(format!(
1769                        "column \"{name}\" specified in USING clause does not exist in right table"
1770                    ))
1771                })?;
1772            let left_column = &scope.columns[left_at];
1773            let (left_binding, left_type) = (left_column.binding, left_column.ty.clone());
1774            let right_column = &scope.columns[right_at];
1775            let (right_binding, right_type) = (right_column.binding, right_column.ty.clone());
1776            let left_expr = self.plan.add_expr(Expr::Column(left_binding), left_type);
1777            let right_expr = self.plan.add_expr(Expr::Column(right_binding), right_type);
1778            conditions.push(self.compare(rudb_plan::CompareOp::Equal, left_expr, right_expr)?);
1779            dropped.push(right_at);
1780        }
1781        // A joined-on column appears once, so the right side's copy goes. Dropping from the back
1782        // keeps the positions of the ones still to drop correct.
1783        dropped.sort_unstable();
1784        for at in dropped.into_iter().rev() {
1785            scope.remove(at);
1786        }
1787
1788        if on != NONE {
1789            if !merged.is_empty() {
1790                return Err(Error::binder("a join cannot have both ON and USING"));
1791            }
1792            self.clause = "JOIN condition";
1793            let predicate = self.bind_expr(ast, on, &scope)?;
1794            conditions.push(self.as_boolean(predicate, "JOIN")?);
1795        }
1796
1797        if kind == ast::JoinKind::Cross {
1798            if !conditions.is_empty() {
1799                return Err(Error::binder("a CROSS JOIN cannot have a condition"));
1800            }
1801            let node =
1802                self.plan.add_node(Node::CrossProduct { left: left_node, right: right_node });
1803            return Ok((node, scope));
1804        }
1805        if conditions.is_empty() && kind == ast::JoinKind::Inner {
1806            let node =
1807                self.plan.add_node(Node::CrossProduct { left: left_node, right: right_node });
1808            return Ok((node, scope));
1809        }
1810        let kind = match kind {
1811            ast::JoinKind::Inner | ast::JoinKind::Cross => JoinKind::Inner,
1812            ast::JoinKind::Left => JoinKind::Left,
1813            ast::JoinKind::Right => JoinKind::Right,
1814            ast::JoinKind::Full => JoinKind::Full,
1815            ast::JoinKind::Semi => JoinKind::Semi,
1816            ast::JoinKind::Anti => JoinKind::Anti,
1817            ast::JoinKind::Positional => JoinKind::Positional,
1818        };
1819        let conditions = self.plan.add_expr_list(&conditions);
1820        let node =
1821            self.plan.add_node(Node::Join { left: left_node, right: right_node, kind, conditions });
1822        Ok((node, scope))
1823    }
1824
1825    // -------------------------------------------------------------- aggregates
1826
1827    /// Binds an aggregate call, records it, and hands back a reference to where its result lands.
1828    pub(crate) fn bind_aggregate(
1829        &mut self,
1830        ast: &Ast,
1831        name: &str,
1832        args: &[ast::ExprRef],
1833        distinct: bool,
1834        scope: &Scope,
1835    ) -> Result<ExprRef> {
1836        if self.in_aggregate {
1837            return Err(Error::binder(format!(
1838                "aggregate function calls cannot be nested, and {name}() is inside one"
1839            )));
1840        }
1841        if self.aggregation.is_none() {
1842            return Err(Error::binder(format!(
1843                "aggregate function calls cannot be used in the {}",
1844                self.clause
1845            )));
1846        }
1847        self.in_aggregate = true;
1848        let mut bound = Vec::with_capacity(args.len());
1849        let mut failure = None;
1850        for &arg in args {
1851            match self.bind_expr(ast, arg, scope) {
1852                Ok(expr) => bound.push(expr),
1853                Err(error) => {
1854                    failure = Some(error);
1855                    break;
1856                }
1857            }
1858        }
1859        self.in_aggregate = false;
1860        if let Some(error) = failure {
1861            return Err(error);
1862        }
1863
1864        let types: Vec<LogicalType> =
1865            bound.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
1866        let resolved = resolve(name, &types)?;
1867        let mut cast = Vec::with_capacity(bound.len());
1868        for (arg, wanted) in bound.iter().zip(&resolved.arguments) {
1869            cast.push(self.checked_cast_to(*arg, wanted, false)?);
1870        }
1871        let args = self.plan.add_expr_list(&cast);
1872        let name = self.plan.intern(resolved.name);
1873        let ty = resolved.returns;
1874        let call =
1875            self.plan.add_expr(Expr::Aggregate { name, args, distinct, filter: None }, ty.clone());
1876
1877        // Two identical aggregates are one column of the aggregate's output. `SELECT sum(x),
1878        // sum(x) / count(*)` computes one sum, not two.
1879        let existing = self.aggregation.as_ref().map(|held| held.aggregates.clone());
1880        let existing = existing.unwrap_or_default();
1881        let at = match existing.iter().position(|&held| self.same_expr(held, call)) {
1882            Some(at) => at,
1883            None => {
1884                let aggregation = self.aggregation.as_mut().expect("checked above");
1885                aggregation.aggregates.push(call);
1886                aggregation.aggregates.len() - 1
1887            }
1888        };
1889        let aggregation = self.aggregation.as_ref().expect("checked above");
1890        let (index, groups) = (aggregation.index, aggregation.groups.len());
1891        Ok(self.column(index, groups + at, ty))
1892    }
1893
1894    /// Rewrites a bound expression into one the aggregate's output can answer.
1895    ///
1896    /// A subexpression that is one of the group expressions becomes a reference to that group. A
1897    /// column that is neither grouped nor inside an aggregate is the error every SQL user has seen,
1898    /// and it is reported here because this is the first point where it is knowable.
1899    pub(crate) fn over_aggregate(&mut self, expr: ExprRef, scope: &Scope) -> Result<ExprRef> {
1900        let Some(aggregation) = self.aggregation.as_ref() else {
1901            return Ok(expr);
1902        };
1903        let index = aggregation.index;
1904        let groups = aggregation.groups.clone();
1905        for (at, group) in groups.iter().enumerate() {
1906            if self.same_expr(expr, *group) {
1907                let ty = self.plan.expr_type(*group).clone();
1908                return Ok(self.column(index, at, ty));
1909            }
1910        }
1911        let ty = self.plan.expr_type(expr).clone();
1912        match self.plan.expr(expr).clone() {
1913            Expr::Column(binding) if binding.table == index => Ok(expr),
1914            Expr::Column(binding) => {
1915                let name =
1916                    scope.columns.iter().find(|column| column.binding == binding).map_or_else(
1917                        || "a column".to_string(),
1918                        |column| format!("\"{}\"", column.name),
1919                    );
1920                Err(Error::binder(format!(
1921                    "column {name} must appear in the GROUP BY clause or must be part of an aggregate function"
1922                )))
1923            }
1924            Expr::Constant(_) | Expr::Aggregate { .. } => Ok(expr),
1925            Expr::Cast { input, try_cast } => {
1926                let input = self.over_aggregate(input, scope)?;
1927                Ok(self.plan.add_expr(Expr::Cast { input, try_cast }, ty))
1928            }
1929            Expr::Compare { op, left, right } => {
1930                let left = self.over_aggregate(left, scope)?;
1931                let right = self.over_aggregate(right, scope)?;
1932                Ok(self.plan.add_expr(Expr::Compare { op, left, right }, ty))
1933            }
1934            Expr::Conjunction { op, children } => {
1935                let written = self.plan.expr_list(children).to_vec();
1936                let mut rewritten = Vec::with_capacity(written.len());
1937                for child in written {
1938                    rewritten.push(self.over_aggregate(child, scope)?);
1939                }
1940                let children = self.plan.add_expr_list(&rewritten);
1941                Ok(self.plan.add_expr(Expr::Conjunction { op, children }, ty))
1942            }
1943            Expr::Function { name, args } => {
1944                let written = self.plan.expr_list(args).to_vec();
1945                let mut rewritten = Vec::with_capacity(written.len());
1946                for arg in written {
1947                    rewritten.push(self.over_aggregate(arg, scope)?);
1948                }
1949                let args = self.plan.add_expr_list(&rewritten);
1950                Ok(self.plan.add_expr(Expr::Function { name, args }, ty))
1951            }
1952            Expr::Case { arms, otherwise } => {
1953                let written = self.plan.arm_list(arms).to_vec();
1954                let mut rewritten = Vec::with_capacity(written.len());
1955                for arm in written {
1956                    let when = self.over_aggregate(arm.when, scope)?;
1957                    let then = self.over_aggregate(arm.then, scope)?;
1958                    rewritten.push(rudb_plan::Arm { when, then });
1959                }
1960                let otherwise = match otherwise {
1961                    Some(expr) => Some(self.over_aggregate(expr, scope)?),
1962                    None => None,
1963                };
1964                let arms = self.plan.add_arms(&rewritten);
1965                Ok(self.plan.add_expr(Expr::Case { arms, otherwise }, ty))
1966            }
1967        }
1968    }
1969
1970    /// Whether two bound expressions are the same expression, by shape rather than by reference.
1971    pub(crate) fn same_expr(&self, left: ExprRef, right: ExprRef) -> bool {
1972        same_expr(&self.plan, left, right)
1973    }
1974}
1975
1976/// The named parameters a table function call was written with.
1977///
1978/// A struct rather than the fields loose, because the seventeen DuckDB has on `read_parquet` and the
1979/// thirty on `read_csv` are all going to want somewhere to go, and because a call with none of them
1980/// written should read as the default of this rather than as a bare false somewhere.
1981///
1982/// The CSV half goes on to the reader and is opened with, here and again in the executor. The
1983/// Parquet half is answered here and nothing downstream sees it, which is what `binary_as_string`
1984/// turning a BLOB column into a VARCHAR one is.
1985#[derive(Debug, Default)]
1986struct Options {
1987    /// `binary_as_string`, which says an unannotated byte array column in a Parquet file holds
1988    /// text. The ClickBench file has twenty eight of those and every query reads them as strings.
1989    binary_as_string: bool,
1990    /// `all_varchar`, which reads every column of a CSV file as text rather than sniffing a type.
1991    all_varchar: bool,
1992    /// `file_row_number`, which adds a column holding each row's ordinal inside its own file.
1993    ///
1994    /// The one Parquet option here that the executor has to act on rather than the binder, since
1995    /// the column is not in the file and has to be counted as the rows come out of it.
1996    file_row_number: bool,
1997    /// `delim`, `sep`, `quote`, `escape` and `header`, which are what the sniffer would decide.
1998    given: Given,
1999}
2000
2001impl Options {
2002    /// What these named parameters add up to.
2003    ///
2004    /// Each one was already checked against the function's list, so a name in here is a name that
2005    /// function takes and the value is already the type it wants. What is left is reading them, and
2006    /// the last one written wins, which is DuckDB's answer to `delim='|', delim=','` and was
2007    /// measured rather than assumed.
2008    fn of(written: &[(&'static str, Value, ExprRef)]) -> Result<Self> {
2009        let mut options = Self::default();
2010        for (parameter, value, _) in written {
2011            match (*parameter, value) {
2012                ("binary_as_string", Value::Boolean(on)) => options.binary_as_string = *on,
2013                ("all_varchar", Value::Boolean(on)) => options.all_varchar = *on,
2014                ("file_row_number", Value::Boolean(on)) => options.file_row_number = *on,
2015                _ => {}
2016            }
2017        }
2018        let named: Vec<(&str, Value)> =
2019            written.iter().map(|(parameter, value, _)| (*parameter, value.clone())).collect();
2020        options.given = csv_given(&named)?;
2021        Ok(options)
2022    }
2023}
2024
2025/// DuckDB's complaint about a named parameter that was given a null, which is a different sentence
2026/// for almost every parameter.
2027///
2028/// Three of them were measured on `v2.0.0-dev84237` and no two agree: `binary_as_string` is the
2029/// first, `all_varchar` is the second and `header` is the third. They read like three people each
2030/// writing the message in front of them, which is what they are, and a harness that compares error
2031/// text compares all of it. Anything not measured gets the first one, which is the most general of
2032/// the three.
2033fn null_parameter(function: TableFunction, parameter: &str) -> String {
2034    match parameter {
2035        "header" => format!("\"{parameter}\" expects a non-null boolean value (e.g. TRUE or 1)"),
2036        "all_varchar" => format!("{} \"{parameter}\" cannot be NULL", function.name()),
2037        _ => format!("Cannot use NULL as argument to \"{parameter}\""),
2038    }
2039}
2040
2041/// The complaint about a `REPLACE` entry that named a column the star did not stand for.
2042///
2043/// It reads like the complaint about any other name that is not there, down to the list of names
2044/// that are, because from the writer's side it is the same mistake.
2045fn missing_replacement(name: &str, input: &Scope) -> Error {
2046    Error::binder(format!(
2047        "Column \"{name}\" in REPLACE list not found in FROM clause{}",
2048        input.candidates()
2049    ))
2050}
2051
2052/// Structural equality over two expressions of one plan.
2053fn same_expr(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
2054    if left == right {
2055        return true;
2056    }
2057    if plan.expr_type(left) != plan.expr_type(right) {
2058        return false;
2059    }
2060    let lists = |left, right| {
2061        let left: &[ExprRef] = plan.expr_list(left);
2062        let right: &[ExprRef] = plan.expr_list(right);
2063        left.len() == right.len()
2064            && left.iter().zip(right).all(|(&left, &right)| same_expr(plan, left, right))
2065    };
2066    match (plan.expr(left), plan.expr(right)) {
2067        (Expr::Column(left), Expr::Column(right)) => left == right,
2068        (Expr::Constant(left), Expr::Constant(right)) => plan.value(*left) == plan.value(*right),
2069        (
2070            Expr::Cast { input: left, try_cast: left_try },
2071            Expr::Cast { input: right, try_cast: right_try },
2072        ) => left_try == right_try && same_expr(plan, *left, *right),
2073        (
2074            Expr::Compare { op: left_op, left: left_a, right: left_b },
2075            Expr::Compare { op: right_op, left: right_a, right: right_b },
2076        ) => {
2077            left_op == right_op
2078                && same_expr(plan, *left_a, *right_a)
2079                && same_expr(plan, *left_b, *right_b)
2080        }
2081        (
2082            Expr::Conjunction { op: left_op, children: left_children },
2083            Expr::Conjunction { op: right_op, children: right_children },
2084        ) => left_op == right_op && lists(*left_children, *right_children),
2085        (
2086            Expr::Function { name: left_name, args: left_args },
2087            Expr::Function { name: right_name, args: right_args },
2088        ) => plan.string(*left_name) == plan.string(*right_name) && lists(*left_args, *right_args),
2089        (
2090            Expr::Aggregate {
2091                name: left_name,
2092                args: left_args,
2093                distinct: left_distinct,
2094                filter: left_filter,
2095            },
2096            Expr::Aggregate {
2097                name: right_name,
2098                args: right_args,
2099                distinct: right_distinct,
2100                filter: right_filter,
2101            },
2102        ) => {
2103            plan.string(*left_name) == plan.string(*right_name)
2104                && left_distinct == right_distinct
2105                && match (left_filter, right_filter) {
2106                    (None, None) => true,
2107                    (Some(left), Some(right)) => same_expr(plan, *left, *right),
2108                    _ => false,
2109                }
2110                && lists(*left_args, *right_args)
2111        }
2112        (
2113            Expr::Case { arms: left_arms, otherwise: left_otherwise },
2114            Expr::Case { arms: right_arms, otherwise: right_otherwise },
2115        ) => {
2116            let left_arms = plan.arm_list(*left_arms);
2117            let right_arms = plan.arm_list(*right_arms);
2118            left_arms.len() == right_arms.len()
2119                && left_arms.iter().zip(right_arms).all(|(left, right)| {
2120                    same_expr(plan, left.when, right.when) && same_expr(plan, left.then, right.then)
2121                })
2122                && match (left_otherwise, right_otherwise) {
2123                    (None, None) => true,
2124                    (Some(left), Some(right)) => same_expr(plan, *left, *right),
2125                    _ => false,
2126                }
2127        }
2128        _ => false,
2129    }
2130}