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 std::sync::Arc;
16
17use rudb_catalog::{Catalog, Entry, FileStamp, QualifiedName, same_name};
18use rudb_common::bounds::Zones;
19use rudb_common::{
20 Error, Field, LogicalType, Result, Semantics, Session, ShowBehavior, Span, Stat, Value,
21};
22use rudb_functions::{
23 Columns, FILE_ROW_NUMBER, Footers, FunctionKind, Given, Resolved, TableFunction, csv_fields,
24 csv_given, files, is_file, is_pattern, kind_of, parquet_footers, parquet_outline, resolve,
25 resolve_pragma, resolve_table,
26};
27use rudb_kernels::{percentage, row_count};
28use rudb_parse::ast::{self, Ast, Distinct, LiteralKind, Nulls, Order, Quantifier, SetOp};
29use rudb_parse::{NONE, identifier_parts, parse_ast_with_case};
30use rudb_plan::{
31 Bound, BuildSide, ColumnBinding, ConjunctionOp, Expr, ExprRef, JoinKind, Node, NodeRef, Plan,
32 SetOpKind, Share, SortKey, WindowBound, WindowExclude, WindowFrame, WindowUnit,
33};
34
35use crate::expr::{describe, has_aggregate};
36use crate::fold;
37use crate::parameters::Parameters;
38use crate::scope::{Scope, Visible};
39
40/// Binds a parsed statement against a catalog.
41///
42/// # Errors
43///
44/// If the script does not hold exactly one statement, if a name does not resolve, if a type does
45/// not work out, or if the query uses something M0 does not bind yet.
46pub fn bind(ast: &Ast, catalog: &Catalog) -> Result<Plan> {
47 bind_with(ast, catalog, &Parameters::new(), &Session::new())
48}
49
50/// Binds a parsed query against a catalog, with values for its parameters and its settings.
51///
52/// The session is what `current_setting()` reads, and a caller with no database behind it passes an
53/// empty one, which makes every setting name unrecognized rather than making up an answer.
54///
55/// # Errors
56///
57/// Everything [`bind`] reports, plus an error for a parameter that was given no value.
58pub fn bind_with(
59 ast: &Ast,
60 catalog: &Catalog,
61 parameters: &Parameters,
62 session: &Session,
63) -> Result<Plan> {
64 let query = match ast.statements.as_slice() {
65 [ast::Statement::Query(query)] => *query,
66 [] => return Err(Error::binder("no statement to bind")),
67 // One statement that is not a query is its own answer. Reporting it as a script of several
68 // reads as a count being wrong, and the count is right.
69 [_] => return Err(Error::not_implemented("a statement that is not a query")),
70 _ => return Err(Error::not_implemented("a script of more than one statement")),
71 };
72 let mut binder = Binder::with(catalog, parameters, session);
73 let (root, _) = binder.bind_query(ast, query)?;
74 let mut plan = binder.into_plan();
75 plan.set_root(root);
76 plan.validate()?;
77 Ok(plan)
78}
79
80/// Parses and binds one query, which is the whole front end in one call.
81///
82/// # Errors
83///
84/// Anything the parser or the binder reports.
85pub fn bind_sql(query: &str, catalog: &Catalog) -> Result<Plan> {
86 bind_sql_with(query, catalog, &Session::new())
87}
88
89/// Parses and binds one query, with the settings a call to `current_setting()` reads.
90///
91/// # Errors
92///
93/// Anything the parser or the binder reports.
94pub fn bind_sql_with(query: &str, catalog: &Catalog, session: &Session) -> Result<Plan> {
95 let ast = parse_ast_with_case(query, session.semantics().identifier_case())?;
96 bind_with(&ast, catalog, &Parameters::new(), session)
97}
98
99/// What an aggregating select block has decided so far.
100#[derive(Debug)]
101pub(crate) struct Aggregation {
102 /// The table index the aggregate's output binds against.
103 pub(crate) index: u32,
104 /// The group expressions, over the input, which are the first output columns.
105 pub(crate) groups: Vec<ExprRef>,
106 /// The aggregate calls found so far, which follow the groups in the output.
107 pub(crate) aggregates: Vec<ExprRef>,
108}
109
110/// One run of window calls that agree on where the rows come from and in what order.
111///
112/// The run is the unit the plan has an operator for, so two calls that write the same partition,
113/// the same order and the same frame are one operator and one sort, and a third that writes a
114/// different order is a second operator stacked on the first. Nothing here merges runs that only
115/// look compatible, because a window is evaluated over the rows the operator below it produced and
116/// deciding two runs are the same is the optimizer's job rather than the binder's.
117#[derive(Debug)]
118pub(crate) struct WindowRun {
119 /// The table index the run's result columns bind against.
120 index: u32,
121 /// What divides the input into independent partitions.
122 partition: Vec<ExprRef>,
123 /// The order within a partition.
124 order: Vec<SortKey>,
125 /// The frame every call in the run shares.
126 frame: WindowFrame,
127 /// The calls, in the order their columns are appended.
128 calls: Vec<ExprRef>,
129}
130
131/// One window call as it was written, before any of it has been bound.
132///
133/// These six travel together from the parser all the way to the run they end up filed under, and
134/// carrying them as one thing keeps the call that binds them readable.
135pub(crate) struct WindowCall<'a> {
136 /// The function name, as written and not yet resolved.
137 pub(crate) name: &'a str,
138 /// The arguments, which may include a star that only `count` is allowed to be given.
139 pub(crate) args: &'a [ast::ExprRef],
140 /// Whether `DISTINCT` was written inside the parens.
141 pub(crate) distinct: bool,
142 /// The `FILTER (WHERE ...)` predicate, which is written before the `OVER`, or `NONE`.
143 pub(crate) filter: ast::ExprRef,
144 /// Whether `IGNORE NULLS` was written inside the parens, which is where DuckDB puts it.
145 pub(crate) ignore_nulls: bool,
146 /// The `ORDER BY` written inside the parens, which says what order the call reads the rows of
147 /// its frame in and is a different clause from the one in the `OVER`.
148 pub(crate) order: ast::Slice,
149 /// The `OVER`, which the parser has already resolved against any `WINDOW` clause.
150 pub(crate) spec: ast::WindowRef,
151}
152
153/// Everything inside one window call once it is bound, which is what decides its run.
154struct WindowParts {
155 /// The arguments, before the casts the resolved signature asks for.
156 args: Vec<ExprRef>,
157 /// What divides the input into independent partitions.
158 partition: Vec<ExprRef>,
159 /// The order within a partition.
160 order: Vec<SortKey>,
161 /// The order the call reads the rows of its frame in, which is the `ORDER BY` written inside
162 /// the brackets rather than the one in the `OVER` and is empty far more often than not.
163 inner: Vec<SortKey>,
164 /// The frame, with both ends and the exclusion.
165 frame: WindowFrame,
166}
167
168/// What opening the files behind a table function call said about them.
169///
170/// The answers travel together because they come out of the same footer. A Parquet file states its
171/// columns, its row count and its statistics in the same few kilobytes at the end of it, so a
172/// binder that has read one has read all of them, and splitting them into four arguments would
173/// mean four ways to forget one.
174#[derive(Debug)]
175struct Read {
176 /// The columns the call produces, in the order the file stores them.
177 fields: Vec<Field>,
178 /// How many rows all of the files hold, where anybody counted.
179 rows: Stat<u64>,
180 /// How many distinct values a column holds, by name, for the columns anybody counted.
181 distincts: Vec<(String, Stat<u64>)>,
182 /// The bounds the files keep per part of themselves, where anything can answer for them.
183 zones: Option<Arc<dyn Zones>>,
184}
185
186impl Read {
187 /// Columns that came from somewhere other than a file, so nothing counted anything.
188 fn uncounted(fields: Vec<Field>) -> Self {
189 Self { fields, rows: Stat::Unknown, distincts: Vec::new(), zones: None }
190 }
191}
192
193/// A materialised `WITH` definition that has been bound and can be read by name.
194#[derive(Debug)]
195struct Materialized {
196 /// Which written definition this is, as an index into `Ast::ctes`.
197 written: u32,
198 /// The number the plan uses to pair a read with what it reads.
199 cte: u32,
200 /// The name it was written with, which is the table name a read is reachable through.
201 name: String,
202 /// What it produces, in order, under the declared names when a column list was written.
203 fields: Vec<Field>,
204}
205
206#[derive(Debug)]
207pub(crate) struct PendingSubquery {
208 pub(crate) node: NodeRef,
209 pub(crate) kind: JoinKind,
210 pub(crate) conditions: Vec<ExprRef>,
211 pub(crate) dependent: bool,
212 /// The outer columns the query's body read, which is what `dependent` counts.
213 ///
214 /// Kept rather than reduced to the flag because a join's `ON` has to decide which of its two
215 /// inputs the query is joined into, and the answer is the side those columns come from. A
216 /// query that reads neither side can go on either.
217 pub(crate) reads: Vec<ColumnBinding>,
218 /// The table index this query's join adds to the rows it is joined into.
219 ///
220 /// Kept so that a `HAVING` which reads one of these can say which columns came from a query
221 /// joined above the grouping rather than from the table underneath it. Those columns are not
222 /// the table's and the grouping rule has nothing to say about them.
223 pub(crate) index: u32,
224 /// Whether the query was written inside an aggregate call's argument or its `FILTER`.
225 ///
226 /// One written there is read once per row going into the aggregate, so it has to be joined in
227 /// underneath the grouping however uncorrelated it is. Every other query a grouped block writes
228 /// is one row for the whole block and is lifted over the grouping instead, which is what
229 /// [`Binder::lift_over_aggregate`] decides.
230 pub(crate) inside_aggregate: bool,
231}
232
233/// Which input of a join a query written in that join's `ON` is joined into.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235enum Side {
236 Left,
237 Right,
238}
239
240/// The state one binding run carries.
241#[derive(Debug)]
242pub(crate) struct Binder<'a> {
243 catalog: &'a Catalog,
244 /// What the parameters were given, empty for a statement that is not prepared.
245 pub(crate) parameters: &'a Parameters,
246 /// What the settings are now, which is what `current_setting()` folds to.
247 pub(crate) session: &'a Session,
248 /// Meaning-changing choices copied once and resolved into the plan above execution.
249 pub(crate) semantics: Semantics,
250 plan: Plan,
251 next_index: u32,
252 /// Source range inherited by plan objects built for the current AST expression or query.
253 pub(crate) current_span: Span,
254 /// Set while a select block aggregates, which changes what a bare column means.
255 pub(crate) aggregation: Option<Aggregation>,
256 /// A grouped block may need stored column order to close groups while it scans. Other queries
257 /// leave the summaries in the file instead of reading every column's section while binding.
258 want_ascending: bool,
259 /// Set while an aggregate's own arguments are being bound, so nesting is caught.
260 pub(crate) in_aggregate: bool,
261 /// Set while an aggregate's `FILTER` is being bound, which is refused its own aggregate.
262 pub(crate) in_filter: bool,
263 /// The window runs this select block has collected, in the order they were first written.
264 pub(crate) windows: Vec<WindowRun>,
265 /// Set while a window call's own arguments and keys are being bound, so nesting is caught.
266 pub(crate) in_window: bool,
267 /// Uncorrelated scalar queries waiting to be joined into the select block that uses them.
268 pub(crate) scalar_subqueries: Vec<PendingSubquery>,
269 /// Table indices of the queries this block will join in above its grouping, not below it.
270 ///
271 /// Only ever set while a `HAVING` is being rewritten over the aggregate. A column from one of
272 /// these is not a column of the grouped table, so the rule about grouping every column does not
273 /// reach it, and the join that produces it goes on top of the `Aggregate` rather than under it.
274 pub(crate) joined_above: Vec<u32>,
275 pub(crate) outer_scopes: Vec<Scope>,
276 /// Which of the outer scopes are a FROM entry's left neighbours rather than an enclosing query.
277 ///
278 /// The two are resolved the same way and refused differently. An aggregate may read a column of
279 /// the query it is written in and may not read one a LATERAL brought in from the left, so the
280 /// check needs to know which scope the name came out of. Each entry is a position in
281 /// `outer_scopes`.
282 pub(crate) lateral_scopes: Vec<usize>,
283 pub(crate) correlations: Vec<Vec<ColumnBinding>>,
284 /// The lambdas whose bodies are being bound, innermost last. See `crate::lambda`.
285 pub(crate) lambda_frames: Vec<crate::lambda::Frame>,
286 /// Where we are, for an error message that says which clause the writer should look at.
287 pub(crate) clause: &'static str,
288 /// Whether a Parquet file that could be read through a native mirror is bound from its outline
289 /// alone, which is the columns and the row count and none of the row groups.
290 ///
291 /// Set by a bind whose plan is thrown away: a `CREATE VIEW`, and the first bind of a query that
292 /// may be bound again once its mirrors are in. A plan bound this way knows no bounds and no
293 /// distinct counts for the file, so the caller must not run it, and every read it did this for
294 /// asked for a mirror, which is how the caller knows to bind again. See
295 /// [`rudb_parquet::Outline`].
296 pub(crate) outlined: bool,
297 /// The views whose bodies are open on the stack, which is what catches a cycle.
298 expanding: Vec<String>,
299 /// The materialised `WITH` definitions whose bodies are being bound, innermost last.
300 ///
301 /// A stack rather than a map from what was written, because a plain `WITH` is put into every
302 /// place it is named, so a materialised one written inside a plain one is bound once per use
303 /// and each of those is a materialisation of its own with a number of its own.
304 materialized: Vec<Materialized>,
305 /// How many materialisations have been numbered, which is where the next number comes from.
306 next_cte: u32,
307 /// When this statement started, read once and kept, which is what `now()` folds to.
308 started: Option<i64>,
309}
310
311impl<'a> Binder<'a> {
312 pub(crate) fn with(
313 catalog: &'a Catalog,
314 parameters: &'a Parameters,
315 session: &'a Session,
316 ) -> Self {
317 Self {
318 catalog,
319 parameters,
320 session,
321 semantics: session.semantics(),
322 plan: Plan::new(),
323 next_index: 0,
324 current_span: Span::new(0, 0),
325 aggregation: None,
326 want_ascending: false,
327 in_aggregate: false,
328 in_filter: false,
329 windows: Vec::new(),
330 in_window: false,
331 scalar_subqueries: Vec::new(),
332 joined_above: Vec::new(),
333 outer_scopes: Vec::new(),
334 lateral_scopes: Vec::new(),
335 correlations: Vec::new(),
336 lambda_frames: Vec::new(),
337 clause: "SELECT clause",
338 outlined: false,
339 expanding: Vec::new(),
340 materialized: Vec::new(),
341 next_cte: 0,
342 started: None,
343 }
344 }
345
346 pub(crate) fn catalog(&self) -> &Catalog {
347 self.catalog
348 }
349
350 /// When this statement started, in microseconds since the epoch.
351 ///
352 /// Read from the clock the first time something asks and kept after that, so a query that
353 /// writes `now()` twice gets one answer for both. That is what the pin does and what it reports
354 /// in the `stability` column of `duckdb_functions()`, where every one of these is
355 /// `CONSISTENT_WITHIN_QUERY`. A query that never asks never reads the clock.
356 pub(crate) fn instant(&mut self) -> i64 {
357 *self.started.get_or_insert_with(crate::context::micros_now)
358 }
359
360 pub(crate) fn plan(&self) -> &Plan {
361 &self.plan
362 }
363
364 pub(crate) fn plan_mut(&mut self) -> &mut Plan {
365 &mut self.plan
366 }
367
368 pub(crate) fn add_expr(&mut self, expr: Expr, ty: LogicalType) -> ExprRef {
369 self.plan.add_expr_at(expr, ty, self.current_span)
370 }
371
372 pub(crate) fn add_constant(&mut self, value: Value) -> ExprRef {
373 let ty = value.logical_type();
374 let reference = self.plan.add_value(value);
375 self.plan.add_expr_at(Expr::Constant(reference), ty, self.current_span)
376 }
377
378 pub(crate) fn add_node(&mut self, node: Node) -> NodeRef {
379 self.plan.add_node_at(node, self.current_span)
380 }
381
382 pub(crate) fn into_plan(self) -> Plan {
383 self.plan
384 }
385
386 /// A table index nothing else has.
387 pub(crate) fn fresh_index(&mut self) -> u32 {
388 let index = self.next_index;
389 self.next_index += 1;
390 index
391 }
392
393 /// A reference to one column of an operator's output.
394 fn column(&mut self, index: u32, position: usize, ty: LogicalType) -> ExprRef {
395 let binding = ColumnBinding::new(index, position as u32);
396 self.plan.add_expr(Expr::Column(binding), ty)
397 }
398
399 /// Joins scalar query results into the row stream that contains their expressions.
400 fn attach_scalar_subqueries(&mut self, mut input: NodeRef) -> NodeRef {
401 let subqueries = std::mem::take(&mut self.scalar_subqueries);
402 for pending in subqueries {
403 input = self.attach_subquery(input, pending);
404 }
405 input
406 }
407
408 /// Joins one query's result into a row stream, which is where its columns come from.
409 ///
410 /// Split out from [`Self::attach_scalar_subqueries`] because a join's `ON` does not attach its
411 /// queries to the rows the whole `FROM` produced. It attaches them to one of the join's two
412 /// inputs, since a join condition is evaluated by the join and can only read what the join was
413 /// given.
414 fn attach_subquery(&mut self, input: NodeRef, pending: PendingSubquery) -> NodeRef {
415 let PendingSubquery {
416 node: mut right,
417 kind,
418 conditions,
419 dependent,
420 reads: _,
421 index: _,
422 inside_aggregate: _,
423 } = pending;
424 if kind == JoinKind::Single && !self.semantics.scalar_subquery_error_on_multiple_rows() {
425 right = self.add_node(Node::Limit {
426 input: right,
427 count: Bound::Rows(1),
428 offset: Bound::Rows(0),
429 });
430 }
431 let conditions = self.plan.add_expr_list(&conditions);
432 if dependent {
433 self.add_node(Node::DependentJoin { left: input, right, kind, conditions })
434 } else {
435 self.add_node(Node::Join {
436 left: input,
437 right,
438 kind,
439 conditions,
440 build: BuildSide::default(),
441 })
442 }
443 }
444
445 // ---------------------------------------------------------------- queries
446
447 pub(crate) fn bind_query(
448 &mut self,
449 ast: &Ast,
450 query: ast::QueryRef,
451 ) -> Result<(NodeRef, Scope)> {
452 let span = ast.query_span(query);
453 let outer = std::mem::replace(&mut self.current_span, span);
454 let result =
455 self.bind_query_inner(ast, query).map_err(|error| error.with_fallback_span(span));
456 self.current_span = outer;
457 result
458 }
459
460 fn bind_query_inner(&mut self, ast: &Ast, query: ast::QueryRef) -> Result<(NodeRef, Scope)> {
461 let written = ast.query(query);
462 if written.ctes.is_empty() {
463 return self.bind_body(ast, &written);
464 }
465 // The names a query introduces are gone again once it is bound, and they go whether the
466 // binding worked or not, which is why the stack is cut back here rather than at the end of
467 // the call that pushed onto it.
468 let depth = self.materialized.len();
469 let result = self.bind_materialized(ast, &written);
470 self.materialized.truncate(depth);
471 result
472 }
473
474 /// A query with materialised `WITH` definitions in front of it.
475 ///
476 /// The definitions are bound first and in the order they were written, so that a later one can
477 /// read an earlier one, and then the body. The wrapping runs backwards so that the first
478 /// definition ends up outermost, which is the order they have to be filled in.
479 fn bind_materialized(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
480 let depth = self.materialized.len();
481 let held = ast.cte_list(written.ctes).to_vec();
482 let mut definitions = Vec::with_capacity(held.len());
483 for &index in &held {
484 definitions.push(self.bind_definition(ast, index)?);
485 }
486 let (mut node, scope) = self.bind_body(ast, written)?;
487 for (at, definition) in definitions.into_iter().enumerate().rev() {
488 let entry = &self.materialized[depth + at];
489 let cte = entry.cte;
490 let name = entry.name.clone();
491 let fields = entry.fields.clone();
492 let name = self.plan.intern(&name);
493 let columns = self.plan.add_fields(&fields);
494 node =
495 self.add_node(Node::MaterializedCte { definition, body: node, name, cte, columns });
496 }
497 Ok((node, scope))
498 }
499
500 /// Binds one materialised `WITH` definition and makes its name readable from there on.
501 ///
502 /// The definition is projected onto exactly the columns a read of it sees, under the names the
503 /// column list declared when there was one. That projection is not decoration: what is held is
504 /// what a read gets back, so the held rows have to be the rows of the definition's own select
505 /// list and nothing it happened to carry along underneath.
506 ///
507 /// A column list with more names in it than the definition has columns is not an error here,
508 /// which is the pinned build's rule and is written out on [`Scope::rename_prefix`].
509 fn bind_definition(&mut self, ast: &Ast, index: u32) -> Result<NodeRef> {
510 let held = ast.cte(index);
511 let name = ast.string(held.name).to_string();
512 let (node, mut scope) = self.bind_query(ast, held.query)?;
513 if !held.columns.is_empty() {
514 let names: Vec<&str> = ast.name(held.columns).collect();
515 scope.rename_prefix(&names);
516 }
517 let table = self.fresh_index();
518 let mut exprs = Vec::with_capacity(scope.len());
519 let mut names = Vec::with_capacity(scope.len());
520 for column in &scope.columns {
521 exprs.push(self.plan.add_expr(Expr::Column(column.binding), column.ty.clone()));
522 names.push(self.plan.intern(&column.name));
523 }
524 let exprs = self.plan.add_expr_list(&exprs);
525 let names = self.plan.add_name_list(&names);
526 let node = self.add_node(Node::Project { input: node, index: table, exprs, names });
527 let cte = self.next_cte;
528 self.next_cte += 1;
529 self.materialized.push(Materialized { written: index, cte, name, fields: scope.fields() });
530 Ok(node)
531 }
532
533 fn bind_body(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
534 match written.body {
535 ast::QueryBody::Select(select) => self.bind_select(ast, select, written),
536 ast::QueryBody::SetOp { op, quantifier, by_name, left, right } => {
537 let operator = Operator { op, quantifier, by_name };
538 self.bind_set_op(ast, written, operator, left, right)
539 }
540 ast::QueryBody::Values(rows) => self.bind_values(ast, written, rows),
541 ast::QueryBody::Describe(inner) => self.bind_describe(ast, written, inner),
542 ast::QueryBody::Show { name, relation } => self.bind_show(ast, written, name, relation),
543 }
544 }
545
546 /// `SHOW name`, resolved while binding so execution receives an ordinary constant plan.
547 fn bind_show(
548 &mut self,
549 ast: &Ast,
550 query: &ast::Query,
551 name: ast::Slice,
552 relation: ast::QueryRef,
553 ) -> Result<(NodeRef, Scope)> {
554 let text = ast.name_text(name);
555 let parts: Vec<&str> = ast.name(name).collect();
556 let table_exists = self.catalog.resolve(&parts).is_ok();
557 let as_table = match self.semantics.show_behavior() {
558 ShowBehavior::Auto => table_exists,
559 ShowBehavior::Setting => false,
560 ShowBehavior::Table => true,
561 };
562 if as_table {
563 return self.bind_describe(ast, query, relation);
564 }
565 // A name the session has no answer for is either a setting rudb has and DuckDB does not, in
566 // which case [`Binder::beyond`] reads it, or it is nothing, in which case that says so in
567 // upstream's words. `SHOW` prints and printing is text, so a rule's boolean comes back here
568 // as the word it reads back as rather than as a boolean column.
569 let shown = match self.session.iter().find(|(name, _)| name.eq_ignore_ascii_case(&text)) {
570 Some((_, value)) => value.to_string(),
571 None => match self.beyond(&text)? {
572 Some(Value::Varchar(declared)) => declared,
573 Some(other) => other.to_string(),
574 None => {
575 return Err(Error::catalog(format!(
576 "Setting with name \"{text}\" does not exist"
577 )));
578 }
579 },
580 };
581 let field = Field::new(text, LogicalType::Varchar);
582 let expr = self.plan.add_constant(Value::Varchar(shown));
583 let row = self.plan.add_expr_list(&[expr]);
584 let rows = self.plan.add_rows(&[row]);
585 let columns = self.plan.add_fields(std::slice::from_ref(&field));
586 let index = self.fresh_index();
587 let node = self.add_node(Node::Values { index, columns, rows });
588 let mut scope = Scope::empty();
589 scope.push(Visible {
590 table: String::new(),
591 name: field.name,
592 binding: ColumnBinding::new(index, 0),
593 ty: LogicalType::Varchar,
594 not_null: false,
595 });
596 Ok((node, scope))
597 }
598
599 /// `DESCRIBE <query>`, which is six VARCHAR columns saying what the query returns.
600 ///
601 /// The query is bound and never run, because binding is the whole of the answer: the names and
602 /// the types of a query's columns are settled by the time the binder is done with it, so the
603 /// rows of a describe are a constant from there on. That is why this comes out as a `VALUES`
604 /// whose rows were computed here rather than as an operator of its own, and it is what makes
605 /// `SELECT column_name FROM (DESCRIBE ...) WHERE ...` an ordinary query over an ordinary
606 /// relation with no special case above it.
607 ///
608 /// The six columns, their order and their types are the reference binary's. `key`, `default`
609 /// and `extra` are null for everything this engine can declare, since `PRIMARY KEY`, `UNIQUE`
610 /// and `DEFAULT` are all refused by `CREATE TABLE` today and there is nothing for the first two
611 /// to hold, and `extra` is empty upstream as well on every table it was asked about. They are
612 /// here rather than left out because the width of a result is part of the result, and a program
613 /// that reads the fifth column has to find one.
614 fn bind_describe(
615 &mut self,
616 ast: &Ast,
617 query: &ast::Query,
618 inner: ast::QueryRef,
619 ) -> Result<(NodeRef, Scope)> {
620 let (_, described) = self.bind_query(ast, inner)?;
621 let fields: Vec<Field> = ["column_name", "column_type", "null", "key", "default", "extra"]
622 .iter()
623 .map(|name| Field::new(*name, LogicalType::Varchar))
624 .collect();
625 let mut slices = Vec::with_capacity(described.columns.len());
626 for column in described.columns.clone() {
627 // `NO` and `YES` and not a boolean, because the column is VARCHAR upstream and a
628 // client that prints the result has to get the same four or three characters.
629 let written = [
630 column.name.clone(),
631 column.ty.to_string(),
632 if column.not_null { "NO" } else { "YES" }.to_owned(),
633 ];
634 let mut items: Vec<ExprRef> = written
635 .into_iter()
636 .map(|text| self.plan.add_constant(Value::Varchar(text)))
637 .collect();
638 for _ in 0..3 {
639 let empty = self.plan.add_constant(Value::Null);
640 items.push(self.cast_to(empty, &LogicalType::Varchar));
641 }
642 slices.push(self.plan.add_expr_list(&items));
643 }
644 let rows = self.plan.add_rows(&slices);
645 let columns = self.plan.add_fields(&fields);
646 let index = self.fresh_index();
647 let mut node = self.add_node(Node::Values { index, columns, rows });
648 let mut scope = Scope::empty();
649 for (at, field) in fields.iter().enumerate() {
650 scope.push(Visible {
651 table: String::new(),
652 name: field.name.clone(),
653 binding: ColumnBinding::new(index, at as u32),
654 ty: field.ty.clone(),
655 not_null: false,
656 });
657 }
658 let keys = self.sort_keys(ast, query, &scope, &[])?;
659 if !keys.is_empty() {
660 let keys = self.plan.add_sort_keys(&keys);
661 node = self.add_node(Node::Sort { input: node, keys });
662 }
663 node = self.apply_limit(ast, query, node, &mut scope)?;
664 Ok((node, scope))
665 }
666
667 /// Whether a projected expression is a column passed straight through from below.
668 ///
669 /// Only `DESCRIBE` asks, and only to decide whether the `null` column says `NO`. Anything that
670 /// is computed is nullable however strict its inputs were, which is both the safe reading and
671 /// the one the reference binary gives.
672 fn passes_through(&self, expr: ExprRef, input: &Scope) -> bool {
673 let Expr::Column(binding) = *self.plan.expr(expr) else { return false };
674 input.columns.iter().any(|column| column.binding == binding && column.not_null)
675 }
676
677 /// `VALUES (1, 'a'), (2, 'b')`, as a query in its own right.
678 ///
679 /// The column names are `col0`, `col1` and so on, which is what DuckDB calls them, and the
680 /// column types are what every row in that position promotes to. Promotion is the same rule a
681 /// set operation uses, and for the same reason: a column has one type and the rows have to
682 /// agree on it before anything downstream can read the column.
683 fn bind_values(
684 &mut self,
685 ast: &Ast,
686 query: &ast::Query,
687 rows: ast::Slice,
688 ) -> Result<(NodeRef, Scope)> {
689 let written = ast.rows(rows).to_vec();
690 let Some(first) = written.first() else {
691 return Err(Error::binder("VALUES needs at least one row"));
692 };
693 let width = first.len as usize;
694 for (at, row) in written.iter().enumerate() {
695 if row.len as usize != width {
696 return Err(Error::binder(format!(
697 "VALUES lists must all be the same length, expected {width} columns but row {} has {}",
698 at + 1,
699 row.len
700 )));
701 }
702 }
703 // A row of a `VALUES` cannot see a column, because there is nothing under it to see.
704 let empty = Scope::empty();
705 let previous = std::mem::replace(&mut self.clause, "VALUES clause");
706 let mut bound: Vec<Vec<ExprRef>> = Vec::with_capacity(written.len());
707 for row in &written {
708 let mut items = Vec::with_capacity(width);
709 for &expr in ast.expr_list(*row) {
710 items.push(self.bind_expr(ast, expr, &empty)?);
711 }
712 bound.push(items);
713 }
714 self.clause = previous;
715 let mut types = Vec::with_capacity(width);
716 for at in 0..width {
717 let mut ty = self.plan.expr_type(bound[0][at]).clone();
718 for row in &bound[1..] {
719 let other = self.plan.expr_type(row[at]).clone();
720 ty = ty.promote(&other).ok_or_else(|| {
721 Error::binder(format!(
722 "Cannot combine a value of type {ty} with a value of type {other} in column {} of a VALUES",
723 at + 1
724 ))
725 })?;
726 }
727 types.push(ty);
728 }
729 let mut slices = Vec::with_capacity(bound.len());
730 for row in &bound {
731 let items: Vec<ExprRef> = row
732 .iter()
733 .zip(&types)
734 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
735 .collect::<Result<_>>()?;
736 slices.push(self.plan.add_expr_list(&items));
737 }
738 let rows = self.plan.add_rows(&slices);
739 let fields: Vec<Field> = types
740 .iter()
741 .enumerate()
742 .map(|(at, ty)| Field::new(format!("col{at}"), ty.clone()))
743 .collect();
744 let columns = self.plan.add_fields(&fields);
745 let index = self.fresh_index();
746 let mut node = self.add_node(Node::Values { index, columns, rows });
747 let mut scope = Scope::empty();
748 for (at, field) in fields.iter().enumerate() {
749 scope.push(Visible {
750 table: String::new(),
751 name: field.name.clone(),
752 binding: ColumnBinding::new(index, at as u32),
753 ty: field.ty.clone(),
754 not_null: false,
755 });
756 }
757 let keys = self.sort_keys(ast, query, &scope, &[])?;
758 if !keys.is_empty() {
759 let keys = self.plan.add_sort_keys(&keys);
760 node = self.add_node(Node::Sort { input: node, keys });
761 }
762 node = self.apply_limit(ast, query, node, &mut scope)?;
763 Ok((node, scope))
764 }
765
766 fn bind_set_op(
767 &mut self,
768 ast: &Ast,
769 query: &ast::Query,
770 operator: Operator,
771 left: ast::QueryRef,
772 right: ast::QueryRef,
773 ) -> Result<(NodeRef, Scope)> {
774 let (left_node, left_scope) = self.bind_query(ast, left)?;
775 let (right_node, right_scope) = self.bind_query(ast, right)?;
776 let merged = if operator.by_name {
777 match_by_name(&left_scope, &right_scope)?
778 } else {
779 match_by_position(&left_scope, &right_scope)?
780 };
781 let left_node = self.conform(left_node, &left_scope, &merged, |column| column.left)?;
782 let right_node = self.conform(right_node, &right_scope, &merged, |column| column.right)?;
783 let index = self.fresh_index();
784 let kind = match operator.op {
785 SetOp::Union => SetOpKind::Union,
786 SetOp::Except => SetOpKind::Except,
787 SetOp::Intersect => SetOpKind::Intersect,
788 };
789 // UNION alone removes duplicates and UNION ALL keeps them, which is the one place the
790 // unwritten quantifier and ALL disagree.
791 let all = operator.quantifier == Quantifier::All;
792 let mut node =
793 self.add_node(Node::SetOp { left: left_node, right: right_node, kind, all, index });
794 let mut scope = Scope::empty();
795 for (at, column) in merged.iter().enumerate() {
796 scope.push(Visible {
797 table: String::new(),
798 name: column.name.clone(),
799 binding: ColumnBinding::new(index, at as u32),
800 ty: column.ty.clone(),
801 // A column of a set operation is nullable whatever the two sides were, because a
802 // column that refuses nulls on one side and takes them on the other takes them.
803 not_null: false,
804 });
805 }
806 // Above a set operation there is nothing but the output columns, so an ORDER BY term is
807 // either a position, an output name, or an expression over the output, and never needs a
808 // column projected for it that the query did not ask for.
809 let keys = self.sort_keys(ast, query, &scope, &[])?;
810 if !keys.is_empty() {
811 let keys = self.plan.add_sort_keys(&keys);
812 node = self.add_node(Node::Sort { input: node, keys });
813 }
814 node = self.apply_limit(ast, query, node, &mut scope)?;
815 Ok((node, scope))
816 }
817
818 /// Projects one side of a set operation onto the columns the operation comes out with.
819 ///
820 /// `pick` says which column of this side each output column is. It answers nothing for a
821 /// column only the other side wrote, which happens under `BY NAME` and which this side fills
822 /// with a null, since that is the row it would have written if it had written the column.
823 fn conform(
824 &mut self,
825 node: NodeRef,
826 scope: &Scope,
827 merged: &[Merged],
828 pick: impl Fn(&Merged) -> Option<usize>,
829 ) -> Result<NodeRef> {
830 let unchanged = merged.len() == scope.len()
831 && merged
832 .iter()
833 .enumerate()
834 .all(|(at, column)| pick(column) == Some(at) && column.ty == scope.columns[at].ty);
835 if unchanged {
836 return Ok(node);
837 }
838 let index = self.fresh_index();
839 let mut exprs = Vec::with_capacity(merged.len());
840 let mut names = Vec::with_capacity(merged.len());
841 for column in merged {
842 let expr = match pick(column) {
843 Some(at) => {
844 let held = &scope.columns[at];
845 self.plan.add_expr(Expr::Column(held.binding), held.ty.clone())
846 }
847 None => self.plan.add_constant(Value::Null),
848 };
849 exprs.push(self.checked_cast_to(expr, &column.ty, false)?);
850 names.push(self.plan.intern(&column.name));
851 }
852 let exprs = self.plan.add_expr_list(&exprs);
853 let names = self.plan.add_name_list(&names);
854 Ok(self.add_node(Node::Project { input: node, index, exprs, names }))
855 }
856
857 // ----------------------------------------------------------------- select
858
859 fn bind_select(
860 &mut self,
861 ast: &Ast,
862 select: ast::SelectRef,
863 query: &ast::Query,
864 ) -> Result<(NodeRef, Scope)> {
865 let written = ast.select(select);
866 self.want_ascending |= !written.group_by.is_empty() || written.group_by_all;
867 // A window belongs to the block that wrote it, and a block can be bound inside another one
868 // without a subquery in between, so the outer block's runs are put aside for the duration
869 // rather than left where a nested block would append to them.
870 let outer_windows = std::mem::take(&mut self.windows);
871 // Same argument for the queries lifted over this block's grouping. They are recorded while
872 // the select list is being bound and read until the sort keys are done, and a block bound
873 // inside that stretch has its own set, so the outer block's is put aside rather than left
874 // where the inner one would clear it.
875 let outer_joined_above = std::mem::take(&mut self.joined_above);
876 let (mut node, input) = self.bind_from(ast, written.from)?;
877 node = self.attach_scalar_subqueries(node);
878
879 if written.filter != NONE {
880 self.clause = "WHERE clause";
881 let predicate = self.bind_expr(ast, written.filter, &input)?;
882 let predicate = self.as_boolean(predicate, "WHERE")?;
883 node = self.attach_scalar_subqueries(node);
884 node = self.add_node(Node::Filter { input: node, predicate });
885 }
886
887 let targets = ast.target_list(written.targets).to_vec();
888 if targets.is_empty() {
889 return Err(Error::binder("a SELECT needs at least one expression to select"));
890 }
891
892 let group_items = self.group_items(ast, &written, &targets)?;
893 let aggregating = !group_items.is_empty()
894 || written.having != NONE
895 || targets.iter().any(|target| has_aggregate(ast, target.expr));
896 if aggregating {
897 self.clause = "GROUP BY clause";
898 let mut groups = Vec::with_capacity(group_items.len());
899 for item in &group_items {
900 groups.push(self.bind_expr(ast, *item, &input)?);
901 }
902 let index = self.fresh_index();
903 self.aggregation = Some(Aggregation { index, groups, aggregates: Vec::new() });
904 }
905
906 // The queries this block's clauses wrote that are joined in above the grouping rather than
907 // below it. TPC-H q11 is the case in a `HAVING`: `HAVING sum(ps_supplycost * ps_availqty) >
908 // (SELECT sum(...))` compares one group's total against a total over the whole table, and
909 // the second total is one row that has nothing to do with the groups. Joined underneath the
910 // grouping it would be a column of every input row and the grouping rule would ask for it in
911 // the GROUP BY, which is the complaint this used to make.
912 let mut above = Vec::new();
913
914 self.clause = "SELECT clause";
915 let (mut exprs, mut names) = self.bind_targets(ast, &targets, &input, &mut above)?;
916 let visible = exprs.len();
917
918 let mut having = None;
919 if written.having != NONE {
920 self.clause = "HAVING clause";
921 let before = self.scalar_subqueries.len();
922 let predicate = self.bind_expr(ast, written.having, &input)?;
923 self.lift_over_aggregate(before, &mut above, &input)?;
924 let predicate = self.over_aggregate(predicate, &input)?;
925 having = Some(self.as_boolean(predicate, "HAVING")?);
926 }
927
928 // The projection's index has to exist before the sort keys are built, because a key is a
929 // reference to a projected column even when the expression it sorts on is not selected.
930 let project = self.fresh_index();
931 let mut output = Scope::empty();
932 for (at, (expr, name)) in exprs.iter().zip(&names).enumerate() {
933 output.push(Visible {
934 table: String::new(),
935 name: name.clone(),
936 binding: ColumnBinding::new(project, at as u32),
937 ty: self.plan.expr_type(*expr).clone(),
938 not_null: self.passes_through(*expr, &input),
939 });
940 }
941
942 self.clause = "ORDER BY clause";
943 let mut extra = Vec::new();
944 let keys = self.select_sort_keys(
945 ast, query, &input, &output, project, &mut exprs, &mut names, &mut extra, &mut above,
946 )?;
947 self.joined_above = outer_joined_above;
948 if !extra.is_empty() && written.distinct != Distinct::No {
949 return Err(Error::binder(
950 "For SELECT DISTINCT, ORDER BY expressions must appear in the select list",
951 ));
952 }
953 let on = self.distinct_on(ast, written.distinct, &output)?;
954
955 node = self.attach_scalar_subqueries(node);
956
957 if let Some(aggregation) = self.aggregation.take() {
958 let index = aggregation.index;
959 let groups = self.plan.add_expr_list(&aggregation.groups);
960 let aggregates = self.plan.add_expr_list(&aggregation.aggregates);
961 node = self.add_node(Node::Aggregate { input: node, index, groups, aggregates });
962 }
963 if !above.is_empty() {
964 debug_assert!(self.scalar_subqueries.is_empty(), "a query is waiting to be joined");
965 self.scalar_subqueries = above;
966 node = self.attach_scalar_subqueries(node);
967 }
968 if let Some(predicate) = having {
969 node = self.add_node(Node::Filter { input: node, predicate });
970 }
971
972 // After the grouping and after `HAVING`, which is where the reference binary puts it:
973 // `SELECT j, sum(count(i)) OVER () FROM t GROUP BY j HAVING count(i) > 1` totals only the
974 // groups that survived the filter.
975 for run in std::mem::replace(&mut self.windows, outer_windows) {
976 let partition = self.plan.add_expr_list(&run.partition);
977 let order = self.plan.add_sort_keys(&run.order);
978 let expressions = self.plan.add_expr_list(&run.calls);
979 node = self.add_node(Node::Window {
980 input: node,
981 index: run.index,
982 partition,
983 order,
984 frame: run.frame,
985 expressions,
986 });
987 }
988
989 let interned: Vec<u32> = names.iter().map(|name| self.plan.intern(name)).collect();
990 let exprs_slice = self.plan.add_expr_list(&exprs);
991 let names_slice = self.plan.add_name_list(&interned);
992 node = self.add_node(Node::Project {
993 input: node,
994 index: project,
995 exprs: exprs_slice,
996 names: names_slice,
997 });
998
999 if written.distinct != Distinct::No {
1000 let on = self.plan.add_expr_list(&on);
1001 node = self.add_node(Node::Distinct { input: node, on });
1002 }
1003 if !keys.is_empty() {
1004 let keys = self.plan.add_sort_keys(&keys);
1005 node = self.add_node(Node::Sort { input: node, keys });
1006 }
1007 node = self.apply_limit(ast, query, node, &mut output)?;
1008
1009 if extra.is_empty() {
1010 output.columns.truncate(visible);
1011 return Ok((node, output));
1012 }
1013 // An expression sorted on but not selected was carried this far to make the sort possible,
1014 // and now it goes, because the query did not ask for it.
1015 let index = self.fresh_index();
1016 let mut kept = Vec::with_capacity(visible);
1017 let mut kept_names = Vec::with_capacity(visible);
1018 let mut scope = Scope::empty();
1019 for (at, name) in names.iter().enumerate().take(visible) {
1020 let ty = output.columns[at].ty.clone();
1021 // Through the scope rather than through `project`, because a limit that had a query
1022 // joined in under it put a projection of its own over the top and these columns are
1023 // that projection's now.
1024 let binding = output.columns[at].binding;
1025 kept.push(self.plan.add_expr(Expr::Column(binding), ty.clone()));
1026 kept_names.push(self.plan.intern(name));
1027 scope.push(Visible {
1028 table: String::new(),
1029 name: name.clone(),
1030 binding: ColumnBinding::new(index, at as u32),
1031 ty,
1032 not_null: output.columns[at].not_null,
1033 });
1034 }
1035 let exprs = self.plan.add_expr_list(&kept);
1036 let names = self.plan.add_name_list(&kept_names);
1037 node = self.add_node(Node::Project { input: node, index, exprs, names });
1038 Ok((node, scope))
1039 }
1040
1041 /// Binds the target list, expanding every star into the columns it stands for.
1042 /// Moves the queries a clause just wrote from under this block's grouping to over it.
1043 ///
1044 /// A query written in a select list, a `HAVING` or an `ORDER BY` is one row that has nothing to
1045 /// do with the groups, so it belongs on top of the grouping and not underneath it. Underneath,
1046 /// its column is a column of every row going into the aggregate, which the grouping rule then
1047 /// asks for in the `GROUP BY`, and the aggregate carries nothing but its groups and its
1048 /// aggregates upward, so the projection could not read the column even if the rule let it
1049 /// through. That is both halves of #1027.
1050 ///
1051 /// A correlated one goes over the grouping too when what it correlates to is a column the block
1052 /// groups by, which is [`Self::lift_correlated`], and stays underneath when it is not. One
1053 /// written inside an aggregate call stays underneath whatever it correlates to, since that is
1054 /// read once per row going into the aggregate and lifting it over would put it where the
1055 /// aggregate that reads it cannot.
1056 ///
1057 /// `before` is what [`Self::scalar_subqueries`] held before the clause was bound, so only the
1058 /// queries that clause wrote are considered.
1059 fn lift_over_aggregate(
1060 &mut self,
1061 before: usize,
1062 above: &mut Vec<PendingSubquery>,
1063 scope: &Scope,
1064 ) -> Result<()> {
1065 if self.aggregation.is_none() {
1066 return Ok(());
1067 }
1068 let mut lifted = Vec::new();
1069 for mut pending in self.scalar_subqueries.split_off(before) {
1070 let stays = pending.inside_aggregate
1071 || (pending.dependent && !self.lift_correlated(&mut pending));
1072 if stays {
1073 self.scalar_subqueries.push(pending);
1074 } else {
1075 self.joined_above.push(pending.index);
1076 lifted.push(pending);
1077 }
1078 }
1079 // A mark join carries its comparison rather than the expression carrying it, and that
1080 // comparison is written over the outer rows, so it needs the same rewrite the expression
1081 // gets. It is done in a second pass so that a comparison reading another query lifted by
1082 // the same clause finds that query's index already recorded.
1083 for pending in &mut lifted {
1084 let conditions = std::mem::take(&mut pending.conditions);
1085 let mut over = Vec::with_capacity(conditions.len());
1086 for condition in conditions {
1087 over.push(self.over_aggregate(condition, scope)?);
1088 }
1089 pending.conditions = over;
1090 }
1091 above.append(&mut lifted);
1092 Ok(())
1093 }
1094
1095 /// Moves one correlated query over this block's grouping, if the grouping lets it.
1096 ///
1097 /// It does when every outer column the query reads is a column this block groups by. That value
1098 /// is the group's own column above the aggregate, the same value read from a different operator,
1099 /// so the query can be joined against the groups instead of against the rows going into them,
1100 /// and what the query answers per group is what it answered per row of a group since every row
1101 /// of a group agreed on it. The rewrite is the references inside the query's body, which were
1102 /// bound against the table underneath and have to read the aggregate's output instead.
1103 ///
1104 /// A correlation on a column that is neither grouped nor aggregated is a different question with
1105 /// a different answer and there is nothing above the grouping that holds it, so that query stays
1106 /// where it is and [`Self::over_aggregate`] reports it as the missing `GROUP BY` it is. That is
1107 /// #1032.
1108 ///
1109 /// The query stays a dependent join either way. What changed is which operator the outer rows
1110 /// come from, not that there are any.
1111 fn lift_correlated(&mut self, pending: &mut PendingSubquery) -> bool {
1112 let Some(index) = self.aggregation.as_ref().map(|aggregation| aggregation.index) else {
1113 return false;
1114 };
1115 let mut moved = Vec::with_capacity(pending.reads.len());
1116 for read in &pending.reads {
1117 let Some(at) = self.group_of(*read) else {
1118 return false;
1119 };
1120 moved.push((*read, ColumnBinding::new(index, at as u32)));
1121 }
1122 let mut rewrites = Vec::new();
1123 self.plan.subtree_columns(pending.node, &mut |reference, binding| {
1124 if let Some(&(_, to)) = moved.iter().find(|(from, _)| *from == binding) {
1125 rewrites.push((reference, to));
1126 }
1127 });
1128 for (reference, to) in rewrites {
1129 self.plan.rebind(reference, to);
1130 }
1131 pending.reads = moved.into_iter().map(|(_, to)| to).collect();
1132 true
1133 }
1134
1135 fn bind_targets(
1136 &mut self,
1137 ast: &Ast,
1138 targets: &[ast::Target],
1139 input: &Scope,
1140 above: &mut Vec<PendingSubquery>,
1141 ) -> Result<(Vec<ExprRef>, Vec<String>)> {
1142 let mut exprs = Vec::with_capacity(targets.len());
1143 let mut names = Vec::with_capacity(targets.len());
1144 for target in targets {
1145 if let ast::Expr::Star { qualifier, replacements } = ast.expr(target.expr) {
1146 let table = ast.name(qualifier).last().map(str::to_string);
1147 let expanded: Vec<Visible> =
1148 input.star(table.as_deref())?.into_iter().cloned().collect();
1149 let replacements = ast.target_list(replacements).to_vec();
1150 let mut used = vec![false; replacements.len()];
1151 for column in expanded {
1152 let found = replacements.iter().zip(&mut used).find(|(replacement, _)| {
1153 same_name(ast.string(replacement.alias), &column.name)
1154 });
1155 // The replacement takes the column's place and its position, and it is named the
1156 // way the replace list spells it rather than the way the table does. That only
1157 // shows when the two differ in case, and `AS EventDate` over a column called
1158 // `eventdate` is exactly the case that shows it.
1159 let before = self.scalar_subqueries.len();
1160 let (expr, name) = match found {
1161 Some((replacement, used)) => {
1162 *used = true;
1163 let expr = self.bind_expr(ast, replacement.expr, input)?;
1164 (expr, ast.string(replacement.alias).to_string())
1165 }
1166 None => (
1167 self.plan.add_expr(Expr::Column(column.binding), column.ty),
1168 column.name,
1169 ),
1170 };
1171 self.lift_over_aggregate(before, above, input)?;
1172 exprs.push(self.over_aggregate(expr, input)?);
1173 names.push(name);
1174 }
1175 // A replace list that named something the star did not stand for is a mistake and
1176 // not a no op, and it is caught here because this is the first point at which the
1177 // set of names the star stands for is known.
1178 if let Some((replacement, _)) =
1179 replacements.iter().zip(&used).find(|(_, used)| !**used)
1180 {
1181 return Err(missing_replacement(ast.string(replacement.alias), input));
1182 }
1183 continue;
1184 }
1185 let before = self.scalar_subqueries.len();
1186 let expr = self.bind_expr(ast, target.expr, input)?;
1187 self.lift_over_aggregate(before, above, input)?;
1188 exprs.push(self.over_aggregate(expr, input)?);
1189 names.push(if target.alias == NONE {
1190 self.output_name(ast, target.expr, input)
1191 } else {
1192 ast.string(target.alias).to_string()
1193 });
1194 }
1195 Ok((exprs, names))
1196 }
1197
1198 /// The name an unaliased target gets.
1199 ///
1200 /// A bare column keeps the spelling the table was created with rather than the spelling the
1201 /// query used, so `SELECT USERID FROM hits` has a column called `UserID`. Identifiers match
1202 /// without regard to case and the catalog is the one that holds the case.
1203 fn output_name(&self, ast: &Ast, target: ast::ExprRef, input: &Scope) -> String {
1204 if let ast::Expr::Column { name } = ast.expr(target) {
1205 let parts: Vec<&str> = ast.name(name).collect();
1206 if let Ok(found) = input.resolve(&parts) {
1207 return found.name.clone();
1208 }
1209 }
1210 describe(ast, target, self.semantics)
1211 }
1212
1213 /// The expressions a `GROUP BY` clause names, with positions and output aliases followed.
1214 fn group_items(
1215 &self,
1216 ast: &Ast,
1217 select: &ast::Select,
1218 targets: &[ast::Target],
1219 ) -> Result<Vec<ast::ExprRef>> {
1220 if select.group_by_all {
1221 // GROUP BY ALL means every target that is not itself an aggregate, which is the set
1222 // that would otherwise have to be written out again by hand.
1223 return Ok(targets
1224 .iter()
1225 .filter(|target| !has_aggregate(ast, target.expr))
1226 .map(|target| target.expr)
1227 .collect());
1228 }
1229 let mut items = Vec::new();
1230 for &item in ast.expr_list(select.group_by) {
1231 items.push(self.output_reference(ast, item, targets, "GROUP BY")?.unwrap_or(item));
1232 }
1233 Ok(items)
1234 }
1235
1236 /// The target a `GROUP BY` or `ORDER BY` term names, when it names one by position or alias.
1237 fn output_reference(
1238 &self,
1239 ast: &Ast,
1240 item: ast::ExprRef,
1241 targets: &[ast::Target],
1242 clause: &str,
1243 ) -> Result<Option<ast::ExprRef>> {
1244 match ast.expr(item) {
1245 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1246 let written = ast.string(text);
1247 let position: usize = written.parse().map_err(|_| {
1248 Error::binder(format!("{clause} term {written} is not a column"))
1249 })?;
1250 if position == 0 || position > targets.len() {
1251 return Err(Error::binder(format!(
1252 "{clause} term out of range - should be between 1 and {}",
1253 targets.len()
1254 )));
1255 }
1256 Ok(Some(targets[position - 1].expr))
1257 }
1258 ast::Expr::Column { name } => {
1259 let parts: Vec<&str> = ast.name(name).collect();
1260 let [written] = parts.as_slice() else { return Ok(None) };
1261 let mut found = None;
1262 for target in targets {
1263 if target.alias != NONE && same_name(ast.string(target.alias), written) {
1264 if found.is_some() {
1265 return Ok(None);
1266 }
1267 found = Some(target.expr);
1268 }
1269 }
1270 Ok(found)
1271 }
1272 _ => Ok(None),
1273 }
1274 }
1275
1276 // -------------------------------------------------------------- modifiers
1277
1278 /// Sort keys for a select, projecting anything sorted on that is not already selected.
1279 #[allow(clippy::too_many_arguments)]
1280 fn select_sort_keys(
1281 &mut self,
1282 ast: &Ast,
1283 query: &ast::Query,
1284 input: &Scope,
1285 output: &Scope,
1286 project: u32,
1287 exprs: &mut Vec<ExprRef>,
1288 names: &mut Vec<String>,
1289 extra: &mut Vec<usize>,
1290 above: &mut Vec<PendingSubquery>,
1291 ) -> Result<Vec<SortKey>> {
1292 if query.order_by_all {
1293 return Ok(self.every_column(output));
1294 }
1295 let items = ast.order_list(query.order_by).to_vec();
1296 let mut keys = Vec::with_capacity(items.len());
1297 for item in items {
1298 self.check_order_literal(ast, item.expr)?;
1299 let position = match self.output_position(ast, item.expr, output)? {
1300 Some(position) => position,
1301 None => {
1302 let before = self.scalar_subqueries.len();
1303 let bound = self.bind_expr(ast, item.expr, input)?;
1304 self.lift_over_aggregate(before, above, input)?;
1305 let bound = self.over_aggregate(bound, input)?;
1306 match exprs.iter().position(|&held| self.same_expr(held, bound)) {
1307 Some(position) => position,
1308 None => {
1309 exprs.push(bound);
1310 names.push(describe(ast, item.expr, self.semantics));
1311 extra.push(exprs.len() - 1);
1312 exprs.len() - 1
1313 }
1314 }
1315 }
1316 };
1317 let ty = self.plan.expr_type(exprs[position]).clone();
1318 let expr = self.column(project, position, ty);
1319 keys.push(self.sort_key(expr, item));
1320 }
1321 Ok(keys)
1322 }
1323
1324 /// Sort keys over an output that has nothing behind it to project, which is a set operation.
1325 fn sort_keys(
1326 &mut self,
1327 ast: &Ast,
1328 query: &ast::Query,
1329 output: &Scope,
1330 targets: &[ast::Target],
1331 ) -> Result<Vec<SortKey>> {
1332 if query.order_by_all {
1333 return Ok(self.every_column(output));
1334 }
1335 let items = ast.order_list(query.order_by).to_vec();
1336 let mut keys = Vec::with_capacity(items.len());
1337 for item in items {
1338 self.check_order_literal(ast, item.expr)?;
1339 let expr = match self.output_position(ast, item.expr, output)? {
1340 Some(position) => {
1341 let column = &output.columns[position];
1342 let (binding, ty) = (column.binding, column.ty.clone());
1343 self.plan.add_expr(Expr::Column(binding), ty)
1344 }
1345 None => {
1346 let _ = targets;
1347 self.bind_expr(ast, item.expr, output)?
1348 }
1349 };
1350 keys.push(self.sort_key(expr, item));
1351 }
1352 Ok(keys)
1353 }
1354
1355 fn every_column(&mut self, output: &Scope) -> Vec<SortKey> {
1356 let columns: Vec<(ColumnBinding, LogicalType)> =
1357 output.columns.iter().map(|column| (column.binding, column.ty.clone())).collect();
1358 columns
1359 .into_iter()
1360 .map(|(binding, ty)| {
1361 let expr = self.plan.add_expr(Expr::Column(binding), ty);
1362 let descending = self.semantics.default_descending();
1363 SortKey { expr, descending, nulls_first: self.semantics.nulls_first(descending) }
1364 })
1365 .collect()
1366 }
1367
1368 /// A sort key with the session defaults filled in.
1369 fn sort_key(&self, expr: ExprRef, item: ast::OrderItem) -> SortKey {
1370 let descending = match item.order {
1371 Order::Unstated => self.semantics.default_descending(),
1372 Order::Ascending => false,
1373 Order::Descending => true,
1374 };
1375 let nulls_first = match item.nulls {
1376 Nulls::First => true,
1377 Nulls::Last => false,
1378 Nulls::Unstated => self.semantics.nulls_first(descending),
1379 };
1380 SortKey { expr, descending, nulls_first }
1381 }
1382
1383 /// Which output column a term names, by position or by name.
1384 fn output_position(
1385 &self,
1386 ast: &Ast,
1387 item: ast::ExprRef,
1388 output: &Scope,
1389 ) -> Result<Option<usize>> {
1390 match ast.expr(item) {
1391 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1392 let written = ast.string(text);
1393 if written.contains(['.', 'e', 'E']) {
1394 return Ok(None);
1395 }
1396 let position: usize = written.parse().map_err(|_| {
1397 Error::binder(format!("ORDER BY term {written} is not a column"))
1398 })?;
1399 if position == 0 || position > output.len() {
1400 return Err(Error::binder(format!(
1401 "ORDER BY term out of range - should be between 1 and {}",
1402 output.len()
1403 )));
1404 }
1405 Ok(Some(position - 1))
1406 }
1407 ast::Expr::Column { name } => {
1408 let parts: Vec<&str> = ast.name(name).collect();
1409 let [written] = parts.as_slice() else { return Ok(None) };
1410 Ok(output.position_of(None, written))
1411 }
1412 _ => Ok(None),
1413 }
1414 }
1415
1416 /// Refuses a literal sort key unless the session explicitly accepts its no-op behavior.
1417 fn check_order_literal(&self, ast: &Ast, item: ast::ExprRef) -> Result<()> {
1418 if !self.semantics.order_by_non_integer_literal()
1419 && matches!(
1420 ast.expr(item),
1421 ast::Expr::Literal { kind, text }
1422 if kind != LiteralKind::Number
1423 || ast.string(text).contains(['.', 'e', 'E'])
1424 )
1425 {
1426 return Err(Error::binder(
1427 "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to allow this behavior.",
1428 ));
1429 }
1430 Ok(())
1431 }
1432
1433 /// The expressions a `DISTINCT ON` names, which have to be columns of the output.
1434 fn distinct_on(
1435 &mut self,
1436 ast: &Ast,
1437 distinct: Distinct,
1438 output: &Scope,
1439 ) -> Result<Vec<ExprRef>> {
1440 let Distinct::On(items) = distinct else {
1441 return Ok(Vec::new());
1442 };
1443 let items = ast.expr_list(items).to_vec();
1444 let mut on = Vec::with_capacity(items.len());
1445 for item in items {
1446 let Some(position) = self.output_position(ast, item, output)? else {
1447 return Err(Error::not_implemented(
1448 "DISTINCT ON an expression that is not in the select list",
1449 ));
1450 };
1451 let column = &output.columns[position];
1452 let (binding, ty) = (column.binding, column.ty.clone());
1453 on.push(self.plan.add_expr(Expr::Column(binding), ty));
1454 }
1455 Ok(on)
1456 }
1457
1458 /// The `LIMIT` and the `OFFSET`, over the rows everything else in the query produced.
1459 ///
1460 /// The scope is taken by reference because a limit the binder could not work out reads its
1461 /// number off a query joined in underneath, and that join puts a column in the rows which the
1462 /// query did not ask for. A projection over the limit drops it again, and the scope has to say
1463 /// so, since its bindings are what anything above this reads.
1464 fn apply_limit(
1465 &mut self,
1466 ast: &Ast,
1467 query: &ast::Query,
1468 input: NodeRef,
1469 scope: &mut Scope,
1470 ) -> Result<NodeRef> {
1471 let waiting = self.scalar_subqueries.len();
1472 if query.limit_percent {
1473 let percent = self.share(ast, query.limit)?;
1474 let offset = self.skipped(ast, query.offset)?;
1475 let node = |binder: &mut Self, input| match percent {
1476 Some(percent) => binder.add_node(Node::LimitPercent { input, percent, offset }),
1477 // A null share is no limit at all, the same as a null row count, so what is left
1478 // is whatever the offset asked for.
1479 None => binder.limited(input, Bound::All, offset),
1480 };
1481 return self.over_subqueries(waiting, input, scope, node);
1482 }
1483 let count = self.count_bound(ast, query.limit, "LIMIT")?;
1484 let offset = self.skipped(ast, query.offset)?;
1485 let node = |binder: &mut Self, input| binder.limited(input, count, offset);
1486 self.over_subqueries(waiting, input, scope, node)
1487 }
1488
1489 /// The offset a query wrote, as nought rows skipped when it wrote none.
1490 ///
1491 /// An offset the query left off is nought rows skipped, where a limit it left off is every row
1492 /// emitted, so the two clauses read the same word differently.
1493 fn skipped(&mut self, ast: &Ast, written: ast::ExprRef) -> Result<Bound> {
1494 Ok(match self.count_bound(ast, written, "OFFSET")? {
1495 Bound::All => Bound::Rows(0),
1496 named => named,
1497 })
1498 }
1499
1500 /// Builds a limit node over `input`, joining in whatever queries its bounds turned out to need.
1501 ///
1502 /// A bound the binder could not work out reads its number off a column, and that column comes
1503 /// from a query joined in underneath. The join puts a column in the rows nobody asked for, so a
1504 /// projection over the limit drops it again and the scope is told to read that projection. When
1505 /// no query had to be joined in there is nothing to drop and the limit stands on its own.
1506 fn over_subqueries(
1507 &mut self,
1508 waiting: usize,
1509 input: NodeRef,
1510 scope: &mut Scope,
1511 node: impl FnOnce(&mut Self, NodeRef) -> NodeRef,
1512 ) -> Result<NodeRef> {
1513 let joined = self.scalar_subqueries.split_off(waiting);
1514 if joined.is_empty() {
1515 return Ok(node(self, input));
1516 }
1517 let mut input = input;
1518 for pending in joined {
1519 input = self.attach_subquery(input, pending);
1520 }
1521 let limit = node(self, input);
1522 Ok(self.reproject(limit, scope))
1523 }
1524
1525 /// A row count limit over `input`, or `input` itself when neither half of the clause asks for
1526 /// anything.
1527 fn limited(&mut self, input: NodeRef, count: Bound, offset: Bound) -> NodeRef {
1528 if count == Bound::All && offset == Bound::Rows(0) {
1529 return input;
1530 }
1531 self.add_node(Node::Limit { input, count, offset })
1532 }
1533
1534 /// A projection over `node` handing back exactly the columns `scope` names.
1535 ///
1536 /// The scope's bindings are rewritten to this projection's, because its columns are the ones
1537 /// anything above reads. Only a limit that had a query joined in under it wants this, and only
1538 /// because there is not always a projection above to drop the column that join added.
1539 fn reproject(&mut self, node: NodeRef, scope: &mut Scope) -> NodeRef {
1540 let index = self.fresh_index();
1541 let mut exprs = Vec::with_capacity(scope.columns.len());
1542 let mut names = Vec::with_capacity(scope.columns.len());
1543 for column in &scope.columns {
1544 exprs.push(self.plan.add_expr(Expr::Column(column.binding), column.ty.clone()));
1545 names.push(self.plan.intern(&column.name));
1546 }
1547 for (at, column) in scope.columns.iter_mut().enumerate() {
1548 column.binding = ColumnBinding::new(index, at as u32);
1549 }
1550 let exprs = self.plan.add_expr_list(&exprs);
1551 let names = self.plan.add_name_list(&names);
1552 self.add_node(Node::Project { input: node, index, exprs, names })
1553 }
1554
1555 /// The share of the input a `LIMIT n PERCENT` names.
1556 ///
1557 /// The same evaluation as a row count and a different type at the end of it: the value is cast
1558 /// to `DOUBLE` rather than to `BIGINT`, so `LIMIT '30'%` is thirty percent and `LIMIT true%` is
1559 /// one percent, which is what the pin answers. A null is no limit at all.
1560 ///
1561 /// The range is checked here because the pin checks it here. `LIMIT 101 PERCENT` fails an
1562 /// `EXPLAIN` on the pinned binary, so it is refused while the query is planned and not when it
1563 /// is run, and a `NAN` is outside the range like any other value that is not between nought and
1564 /// a hundred.
1565 ///
1566 /// What the binder cannot work out is a subquery and a call that answers differently every
1567 /// time, the same two things a row count cannot work out, and those become a [`Share::Read`]
1568 /// over the expression. The value is checked where it turns up instead, which is the executor.
1569 /// Only the sign can be written that way, because the grammar refuses `PERCENT` after a closing
1570 /// bracket, but nothing below here depends on which of the two was typed.
1571 fn share(&mut self, ast: &Ast, written: ast::ExprRef) -> Result<Option<Share>> {
1572 if written == NONE {
1573 return Ok(None);
1574 }
1575 self.clause = "LIMIT clause";
1576 let scope = Scope::empty();
1577 let bound = self.bind_expr(ast, written, &scope)?;
1578 let Some(value) = fold::value_of(&self.plan, bound)? else {
1579 return Ok(Some(Share::Read(bound)));
1580 };
1581 if value.is_null() {
1582 return Ok(None);
1583 }
1584 let percent = percentage(&value)?;
1585 if !(0.0..=100.0).contains(&percent) {
1586 return Err(Error::out_of_range(
1587 "Limit percent out of range, should be between 0% and 100%",
1588 ));
1589 }
1590 Ok(Some(Share::Percent(percent)))
1591 }
1592
1593 /// The row count a `LIMIT` or an `OFFSET` names.
1594 ///
1595 /// It does not have to be a literal. Anything whose value is settled before the first row is
1596 /// read will do, so `LIMIT 1 + 1` and `LIMIT CAST(3 AS BIGINT)` are both two, and that is what
1597 /// the pin does with them: its binder evaluates the expression and writes the number down.
1598 ///
1599 /// What is left over is an expression the binder cannot settle, which is a subquery, because it
1600 /// has to run first, and a call that answers differently every time it is made, such as
1601 /// `RANDOM()` or `nextval`. Those become a [`Bound::Read`] holding the expression, and the
1602 /// number comes off the first chunk that reaches the limit. The pin takes both and answers them
1603 /// the same way.
1604 ///
1605 /// The value is cast to `BIGINT` whatever it was written as, which is the whole of the type
1606 /// rule. `LIMIT '3'` is three rows because the string converts, `LIMIT 2.5` is three rows
1607 /// because the conversion rounds, `LIMIT true` is one row, and `LIMIT DATE '2020-01-01'` is the
1608 /// cast refusing a date. Every one of those messages is the cast's own, which is why there is
1609 /// no type check here to write a worse one. A limit that is read while the query runs is cast
1610 /// the same way by the operator that reads it, so the two paths answer alike.
1611 fn count_bound(&mut self, ast: &Ast, written: ast::ExprRef, clause: &str) -> Result<Bound> {
1612 if written == NONE {
1613 return Ok(Bound::All);
1614 }
1615 self.clause = "LIMIT clause";
1616 let scope = Scope::empty();
1617 let bound = self.bind_expr(ast, written, &scope)?;
1618 let Some(value) = fold::value_of(&self.plan, bound)? else {
1619 return Ok(Bound::Read(bound));
1620 };
1621 // A null is no limit at all, the same as leaving the clause off, and the pin agrees:
1622 // `LIMIT NULL` and `LIMIT CAST(NULL AS INTEGER)` both answer every row.
1623 if value.is_null() {
1624 return Ok(Bound::All);
1625 }
1626 row_count(&value, clause).map(Bound::Rows)
1627 }
1628
1629 // ------------------------------------------------------------------- from
1630
1631 fn bind_from(&mut self, ast: &Ast, from: ast::Slice) -> Result<(NodeRef, Scope)> {
1632 let sources = ast.source_list(from).to_vec();
1633 let Some((first, rest)) = sources.split_first() else {
1634 // No FROM clause is one row of no columns, which is what SELECT 1 sits on. Not an
1635 // empty table: an empty table would make SELECT 1 return nothing.
1636 return Ok((self.add_node(Node::Dummy), Scope::empty()));
1637 };
1638 let (mut node, mut scope) = self.bind_source(ast, *first)?;
1639 for source in rest {
1640 let (right, right_scope, correlations) = self.bind_lateral(ast, *source, &scope)?;
1641 node = if correlations.is_empty() {
1642 self.add_node(Node::CrossProduct { left: node, right })
1643 } else {
1644 let conditions = self.plan.add_expr_list(&[]);
1645 self.add_node(Node::DependentJoin {
1646 left: node,
1647 right,
1648 kind: JoinKind::Inner,
1649 conditions,
1650 })
1651 };
1652 scope = scope.concat(right_scope);
1653 }
1654 Ok((node, scope))
1655 }
1656
1657 /// Binds one FROM entry with everything written to its left already visible.
1658 ///
1659 /// That is what LATERAL means, and it is what a comma separated FROM does here whether the word
1660 /// was written or not, because the pinned build resolves `FROM o, (SELECT o.k + 1)` without it.
1661 /// The keyword therefore changes nothing and is accepted rather than acted on.
1662 ///
1663 /// The columns of the left that the entry read come back with it, and an entry that read none
1664 /// is an ordinary product. The rest are somebody else's: a name that resolved past the left
1665 /// neighbours belongs to an enclosing query, so it is handed up to whichever frame is waiting
1666 /// for it rather than counted here, or the subquery this FROM sits in would lose track of its
1667 /// own correlation.
1668 fn bind_lateral(
1669 &mut self,
1670 ast: &Ast,
1671 source: ast::SourceRef,
1672 left: &Scope,
1673 ) -> Result<(NodeRef, Scope, Vec<ColumnBinding>)> {
1674 self.lateral_scopes.push(self.outer_scopes.len());
1675 self.outer_scopes.push(left.clone());
1676 self.correlations.push(Vec::new());
1677 let bound = self.bind_source(ast, source);
1678 let read = self.correlations.pop().expect("correlation frame");
1679 self.outer_scopes.pop();
1680 self.lateral_scopes.pop();
1681 let (node, scope) = bound?;
1682
1683 let mut here = Vec::new();
1684 for binding in read {
1685 if left.columns.iter().any(|column| column.binding == binding) {
1686 here.push(binding);
1687 } else if let Some(enclosing) = self.correlations.last_mut() {
1688 if !enclosing.contains(&binding) {
1689 enclosing.push(binding);
1690 }
1691 }
1692 }
1693 // A table function is allowed to read the left the same as anything else here. There is
1694 // nothing underneath one for the domain to be pushed into, since its arguments are what
1695 // produce its rows, so the unnesting pass turns it into a `LateralFunction` and the call is
1696 // made once per domain value. That is `domain.rs`.
1697 //
1698 // Nothing has to be turned down here for the functions that would not survive it. The only
1699 // table functions taking an argument that is not a name are the series family, which is the
1700 // family that operator answers, and a name that is not a constant is refused where the
1701 // columns are settled, because settling them means opening the file or reading the catalog.
1702 Ok((node, scope, here))
1703 }
1704
1705 fn bind_source(&mut self, ast: &Ast, source: ast::SourceRef) -> Result<(NodeRef, Scope)> {
1706 match ast.source(source) {
1707 ast::Source::Table { name, alias, columns } => {
1708 self.bind_table(ast, name, alias, columns)
1709 }
1710 ast::Source::Function { name, args, alias, columns, pragma } => {
1711 self.bind_table_function(ast, name, args, alias, columns, pragma)
1712 }
1713 ast::Source::Subquery { query, alias, columns } => {
1714 let (node, mut scope) = self.bind_query(ast, query)?;
1715 let label = if alias == NONE {
1716 "unnamed_subquery".to_string()
1717 } else {
1718 ast.string(alias).to_string()
1719 };
1720 scope.relabel(&label);
1721 if !columns.is_empty() {
1722 let names: Vec<&str> = ast.name(columns).collect();
1723 scope.rename(&names, &label)?;
1724 }
1725 Ok((node, scope))
1726 }
1727 ast::Source::Values { rows, alias, columns } => {
1728 let bare = ast::Query::bare(ast::QueryBody::Values(rows));
1729 let (node, mut scope) = self.bind_values(ast, &bare, rows)?;
1730 let label =
1731 if alias == NONE { String::new() } else { ast.string(alias).to_string() };
1732 scope.relabel(&label);
1733 if !columns.is_empty() {
1734 let names: Vec<&str> = ast.name(columns).collect();
1735 scope.rename(&names, &label)?;
1736 }
1737 Ok((node, scope))
1738 }
1739 ast::Source::Cte { cte, alias, columns } => {
1740 self.bind_cte_scan(ast, cte, alias, columns)
1741 }
1742 ast::Source::Join { left, right, kind, natural, on, using } => {
1743 self.bind_join(ast, left, right, kind, natural, on, using)
1744 }
1745 }
1746 }
1747
1748 /// A read of a materialised `WITH`, which is a leaf the same way a table scan is.
1749 ///
1750 /// Which definition it reads was settled by the parser, so there is no name to look up here and
1751 /// no shadowing left to think about. What is looked up is the materialisation that definition
1752 /// turned into, and the search runs backwards because the same definition is bound again for
1753 /// each use of a plain `WITH` it sits inside, and a read means the innermost of those.
1754 fn bind_cte_scan(
1755 &mut self,
1756 ast: &Ast,
1757 written: u32,
1758 alias: ast::StrRef,
1759 columns: ast::Slice,
1760 ) -> Result<(NodeRef, Scope)> {
1761 let Some(held) = self.materialized.iter().rev().find(|held| held.written == written) else {
1762 let name = ast.string(ast.cte(written).name);
1763 return Err(Error::binder(format!("Table with name {name} does not exist!")));
1764 };
1765 let cte = held.cte;
1766 let fields = held.fields.clone();
1767 let text = held.name.clone();
1768 let label = if alias == NONE { text.clone() } else { ast.string(alias).to_string() };
1769 let name = self.plan.intern(&text);
1770 let index = self.fresh_index();
1771 let mut scope = Scope::empty();
1772 for (at, field) in fields.iter().enumerate() {
1773 scope.push(Visible {
1774 table: label.clone(),
1775 name: field.name.clone(),
1776 binding: ColumnBinding::new(index, at as u32),
1777 ty: field.ty.clone(),
1778 not_null: field.not_null,
1779 });
1780 }
1781 if !columns.is_empty() {
1782 let names: Vec<&str> = ast.name(columns).collect();
1783 scope.rename(&names, &label)?;
1784 }
1785 let columns = self.plan.add_fields(&fields);
1786 let node = self.add_node(Node::CteScan { index, cte, name, columns });
1787 Ok((node, scope))
1788 }
1789
1790 fn bind_table(
1791 &mut self,
1792 ast: &Ast,
1793 name: ast::Slice,
1794 alias: ast::StrRef,
1795 columns: ast::Slice,
1796 ) -> Result<(NodeRef, Scope)> {
1797 let parts: Vec<&str> = ast.name(name).collect();
1798 let catalog = self.catalog;
1799 // The catalog is asked first and the file is the fallback, which is the order DuckDB uses:
1800 // a table really called `mixed.parquet` wins over a file of that name sitting next to it.
1801 let resolved = match catalog.resolve(&parts) {
1802 Ok(resolved) => resolved,
1803 Err(missing) => {
1804 return self.bind_replacement_scan(ast, &parts, alias, columns, missing);
1805 }
1806 };
1807 if catalog.entry(&resolved)? == Entry::View {
1808 return self.bind_view(ast, &resolved, alias, columns);
1809 }
1810 let label =
1811 if alias == NONE { resolved.table.clone() } else { ast.string(alias).to_string() };
1812 self.bind_catalog_table(ast, &resolved, label, columns)
1813 }
1814
1815 /// A table the catalog holds, under the name `label`, which is where [`Self::bind_table`] ends
1816 /// and where a Parquet file with a native mirror goes instead of to its reader.
1817 fn bind_catalog_table(
1818 &mut self,
1819 ast: &Ast,
1820 resolved: &QualifiedName,
1821 label: String,
1822 columns: ast::Slice,
1823 ) -> Result<(NodeRef, Scope)> {
1824 let table = self.catalog.table(resolved)?;
1825 let fields: Vec<Field> = table.columns().to_vec();
1826 let index = self.fresh_index();
1827 let mut scope = Scope::empty();
1828 for (at, field) in fields.iter().enumerate() {
1829 scope.push(Visible {
1830 table: label.clone(),
1831 name: field.name.clone(),
1832 binding: ColumnBinding::new(index, at as u32),
1833 ty: field.ty.clone(),
1834 not_null: field.not_null,
1835 });
1836 }
1837 if !columns.is_empty() {
1838 let names: Vec<&str> = ast.name(columns).collect();
1839 scope.rename(&names, &label)?;
1840 }
1841 let catalog_name = self.plan.intern(&resolved.catalog);
1842 let schema = self.plan.intern(&resolved.schema);
1843 let table_name = self.plan.intern(&resolved.table);
1844 let alias = self.plan.intern(&label);
1845 let columns = self.plan.add_fields(&fields);
1846 // What the store wrote down about itself, against the table index the same way a Parquet
1847 // footer is. A table with nothing to say records nothing and the estimate falls back to the
1848 // constants it used before, which is what every table did until the file had a directory
1849 // worth asking.
1850 if let Some(zones) = table.rows().zones() {
1851 self.plan.set_zones(index, zones);
1852 }
1853 if let Some(frequencies) = table.frequencies() {
1854 self.plan.set_frequencies(index, frequencies);
1855 }
1856 for (column, distinct) in table.distincts() {
1857 self.plan.measure_distinct(index, &column, distinct);
1858 }
1859 if self.want_ascending {
1860 for column in table.ascending() {
1861 self.plan.mark_ascending(index, &column);
1862 }
1863 }
1864 let node = self.add_node(Node::Get {
1865 catalog: catalog_name,
1866 schema,
1867 table: table_name,
1868 alias,
1869 index,
1870 columns,
1871 });
1872 Ok((node, scope))
1873 }
1874
1875 /// A view where a table goes, which is the body bound again right here.
1876 ///
1877 /// Inline and not behind a node. The view is gone by the time the plan exists, so everything
1878 /// downstream sees the query somebody would have written by hand, and the column pruning that
1879 /// makes `SELECT COUNT(*) FROM 'hits.parquet'` read no columns at all keeps working through
1880 /// `FROM hits`. A `Node::View` would be a barrier with nothing on the other side of it.
1881 ///
1882 /// The scope this builds is a subquery's, right down to the name in the error message. duckdb
1883 /// v1.5.1 reports a view whose column list has gone stale as `table "unnamed_subquery" has 1
1884 /// columns available but 2 columns specified`, which is the sentence its subquery alias rule
1885 /// produces, so a view there is a subquery with the view's name written over it afterwards.
1886 fn bind_view(
1887 &mut self,
1888 ast: &Ast,
1889 name: &QualifiedName,
1890 alias: ast::StrRef,
1891 columns: ast::Slice,
1892 ) -> Result<(NodeRef, Scope)> {
1893 let view = self.catalog.view(name)?;
1894 let full = name.to_string();
1895 if self.expanding.contains(&full) {
1896 // Two quotes each side, which is what the binary prints. It quotes the name on the way
1897 // in and then formats the quoted name into a quoted slot, so a view called `a` comes
1898 // back as `""a""`. That is upstream's wart and copying it is the whole job here.
1899 return Err(Error::binder(format!(
1900 "infinite recursion detected: attempting to recursively bind view \"\"{}\"\"",
1901 name.table
1902 )));
1903 }
1904 let body = parse_ast_with_case(view.sql(), self.semantics.identifier_case())?;
1905 let query = match body.statements.as_slice() {
1906 [ast::Statement::Query(query)] => *query,
1907 // Only a query can have got past the binder at creation, so this is a view the catalog
1908 // was handed some other way rather than anything a statement can produce.
1909 _ => return Err(Error::binder(format!("view \"{}\" is not a query", name.table))),
1910 };
1911 self.expanding.push(full);
1912 let bound = self.bind_query(&body, query);
1913 self.expanding.pop();
1914 let (node, mut scope) = bound?;
1915
1916 let aliases: Vec<&str> = view.aliases().iter().map(String::as_str).collect();
1917 if !aliases.is_empty() {
1918 scope.rename(&aliases, "unnamed_subquery")?;
1919 }
1920 // What the catalog tables report as this view's columns, written down here because this is
1921 // the moment they are known. Upstream refreshes the same cache at the same point, which was
1922 // measured: both `duckdb_columns()` and `duckdb_views().column_count` keep reporting the old
1923 // list after an `ALTER TABLE` underneath until something reads the view, and then both move.
1924 // It is written before the label and before the `AS t(a, b)` list below, because those two
1925 // rename the view for one query and not for everyone.
1926 view.remember(scope.fields());
1927 let label = if alias == NONE { name.table.clone() } else { ast.string(alias).to_string() };
1928 scope.relabel(&label);
1929 if !columns.is_empty() {
1930 let names: Vec<&str> = ast.name(columns).collect();
1931 scope.rename(&names, &label)?;
1932 }
1933 Ok((node, scope))
1934 }
1935
1936 /// A function call where a table goes, such as `range(10)`.
1937 ///
1938 /// The arguments are bound against an empty scope. A table function that can see the row on its
1939 /// left is `LATERAL`, and this is not it, so a column name in here is not resolved against
1940 /// whatever happens to be to the left in the `FROM` list. Letting it would mean `FROM t,
1941 /// range(t.n)` quietly binding to something whose meaning depends on the order the sources were
1942 /// written in.
1943 fn bind_table_function(
1944 &mut self,
1945 ast: &Ast,
1946 name: ast::Slice,
1947 args: ast::Slice,
1948 alias: ast::StrRef,
1949 columns: ast::Slice,
1950 pragma: bool,
1951 ) -> Result<(NodeRef, Scope)> {
1952 // The column names written after the alias, kept under a name of their own because the
1953 // match on what the function's columns are below binds `columns` to something else.
1954 let renamed = columns;
1955 let parts: Vec<&str> = ast.name(name).collect();
1956 // A qualified call names a schema, and the two schemas that exist are the ones every
1957 // built-in lives in. Anything else is a name that has to fail rather than fall through to
1958 // the unqualified lookup and be found somewhere it was not asked for.
1959 let function_name = *parts.last().unwrap_or(&"");
1960 if let Some(schema) = parts.iter().rev().nth(1) {
1961 if !schema.eq_ignore_ascii_case("main") && !schema.eq_ignore_ascii_case("system") {
1962 return Err(Error::catalog(format!(
1963 "Table Function with name {} does not exist!",
1964 parts.join(".")
1965 )));
1966 }
1967 }
1968 // The name is looked up before the arguments are bound so that a call of something that is
1969 // not a table function says that, rather than reporting whatever is wrong with the
1970 // arguments of a function that was never going to exist.
1971 let Some(called) = TableFunction::lookup(function_name) else {
1972 if pragma {
1973 // `PRAGMA database_list` is a view upstream and not a function, and the pragma
1974 // namespace holds both, so a name that is not a function gets one more look in the
1975 // catalog before it is turned down. It has to be the no argument form: a view
1976 // takes none, and `pragma_database_list()` with parentheses is a missing function
1977 // on the pin too.
1978 if args.is_empty() && self.catalog.resolve(&parts).is_ok() {
1979 return self.bind_table(ast, name, alias, columns);
1980 }
1981 let spelled = function_name.strip_prefix("pragma_").unwrap_or(function_name);
1982 return Err(Error::catalog(format!(
1983 "Pragma Function with name {spelled} does not exist!"
1984 )));
1985 }
1986 return Err(Error::catalog(format!(
1987 "Table Function with name {function_name} does not exist!"
1988 )));
1989 };
1990 let written = ast.target_list(args).to_vec();
1991 let empty = Scope::empty();
1992 let previous = std::mem::replace(&mut self.clause, "table function arguments");
1993 let mut bound = Vec::new();
1994 let mut written_options = Vec::new();
1995 for argument in written {
1996 let expr = self.bind_expr(ast, argument.expr, &empty)?;
1997 if argument.alias == NONE {
1998 bound.push(expr);
1999 } else {
2000 let name = ast.string(argument.alias).to_string();
2001 let (parameter, value) = self.named_argument(called, &name, expr)?;
2002 written_options.push((parameter, value, expr));
2003 }
2004 }
2005 self.clause = previous;
2006 let options = Options::of(&written_options)?;
2007
2008 // The types are what resolve the call, not the count, because `read_parquet(3)` is a
2009 // different answer from `read_parquet('3')` and only the types tell them apart.
2010 let given: Vec<LogicalType> =
2011 bound.iter().map(|&expr| self.plan.expr_type(expr).clone()).collect();
2012 let resolved = if pragma {
2013 resolve_pragma(function_name, &given)?
2014 } else {
2015 resolve_table(function_name, &given)?
2016 };
2017 let mut cast: Vec<ExprRef> = bound
2018 .iter()
2019 .zip(&resolved.arguments)
2020 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
2021 .collect::<Result<_>>()?;
2022
2023 if resolved.function.answered_when_bound() {
2024 let Columns::Fixed(fields) = resolved.columns else {
2025 return Err(Error::internal("a pragma that resolved to a file"));
2026 };
2027 let [argument] = cast[..] else {
2028 return Err(Error::internal("a pragma that resolved to more than one name"));
2029 };
2030 return self.bind_pragma(ast, resolved.function, &fields, argument, alias, columns);
2031 }
2032 // Filled in by the arm below that has the file names, and left alone by a function whose
2033 // columns are fixed, because none of those reads a file to find out how tall it is.
2034 let mut measured = Stat::Unknown;
2035 let mut counted: Vec<(String, Stat<u64>)> = Vec::new();
2036 let mut bounded: Option<Arc<dyn Zones>> = None;
2037 let fields = match resolved.columns {
2038 Columns::Fixed(fields) => fields,
2039 columns => {
2040 // The one argument is a pattern, and what replaces it is one constant per file it
2041 // matched. The executor is handed names rather than a pattern, so it never walks a
2042 // directory and the answer cannot change between binding a prepared statement and
2043 // running it, which is the same reason the schema is settled here.
2044 let paths = self.file_paths(cast[0], resolved.function.name())?;
2045 let mut mirrorable = None;
2046 if resolved.function == TableFunction::ReadParquet && !options.file_row_number {
2047 if let Some((path, stamp)) = mirror_target(&paths) {
2048 if let Some(name) =
2049 self.catalog.mirror(&path, options.binary_as_string, stamp)
2050 {
2051 let name = name.clone();
2052 let label = if alias == NONE {
2053 resolved.function.name().to_string()
2054 } else {
2055 ast.string(alias).to_string()
2056 };
2057 return self.bind_catalog_table(ast, &name, label, renamed);
2058 }
2059 mirrorable = Some(path);
2060 }
2061 }
2062 let mut fields = match columns {
2063 // Parquet takes the first file's footer as the answer and CSV sniffs all of
2064 // them, which is not a choice made here. See `csv_fields`.
2065 Columns::Csv => csv_fields(&paths, options.given)?,
2066 _ => {
2067 let footers = self.footers(&paths, mirrorable.as_deref())?;
2068 if let Some(path) = mirrorable.as_deref() {
2069 self.want_mirror(path, options.binary_as_string, &footers.rows);
2070 }
2071 measured = footers.rows;
2072 counted = footers.distincts;
2073 bounded = footers.zones;
2074 footers.fields
2075 }
2076 };
2077 if options.all_varchar {
2078 // The sniffer still ran, because the names come out of the same pass over the
2079 // front of the file and only the types are being overruled. The executor reads
2080 // the text as VARCHAR because this is the schema it is told to read into, which
2081 // is the same road a file in a glob takes when the set is wider than the file.
2082 for field in &mut fields {
2083 field.ty = LogicalType::Varchar;
2084 }
2085 }
2086 if options.binary_as_string {
2087 // A byte array column with no annotation on it is a BLOB, and this is the caller
2088 // saying that the file's writer meant text. The reader already holds both in the
2089 // same string column and already validates the bytes, so the whole of the option
2090 // is what the column is called from here on.
2091 for field in &mut fields {
2092 if field.ty == LogicalType::Blob {
2093 field.ty = LogicalType::Varchar;
2094 }
2095 }
2096 }
2097 if options.file_row_number {
2098 // Not a column of the file, so it goes on the end where a projection cannot be
2099 // confused about which one it is, and the executor counts it as the rows come
2100 // out. A file that already has a column of that name is the one case where the
2101 // option cannot be honoured, and saying so is better than handing back two
2102 // columns with the same name and letting a reference to it pick one.
2103 if fields.iter().any(|field| field.name == FILE_ROW_NUMBER) {
2104 return Err(Error::binder(format!(
2105 "Duplicate column name \"{FILE_ROW_NUMBER}\": the file already has a \
2106 column of that name, so file_row_number cannot add one"
2107 )));
2108 }
2109 fields.push(Field::required(FILE_ROW_NUMBER.to_string(), LogicalType::BigInt));
2110 }
2111 cast = paths.iter().map(|path| self.path_constant(path)).collect();
2112 fields
2113 }
2114 };
2115 let label = if alias == NONE {
2116 resolved.function.name().to_string()
2117 } else {
2118 ast.string(alias).to_string()
2119 };
2120 let names: Vec<&str> = ast.name(columns).collect();
2121 self.table_function_source(
2122 resolved.function,
2123 &cast,
2124 &written_options,
2125 Read { fields, rows: measured, distincts: counted, zones: bounded },
2126 &label,
2127 &names,
2128 )
2129 }
2130
2131 /// `pragma_table_info('t')` or `pragma_show('t')`, answered while it is bound.
2132 ///
2133 /// The same trick `DESCRIBE` uses and for the same reason: the columns of a table are settled by
2134 /// the time the name has resolved, so the rows are a constant from there on and this comes out
2135 /// as a `VALUES` rather than as an operator that reads a catalog while the query runs. It also
2136 /// means `SELECT name FROM pragma_table_info('t') WHERE notnull` is an ordinary query over an
2137 /// ordinary relation, which is the whole reason these exist as functions rather than only as
2138 /// statements.
2139 ///
2140 /// The name arrives as a string rather than as something the parser read, so it is split here
2141 /// under the identifier rule and then resolved like any other name. A name that is not there
2142 /// comes back as the catalog's own complaint, which is what the pin answers with too.
2143 fn bind_pragma(
2144 &mut self,
2145 ast: &Ast,
2146 function: TableFunction,
2147 fields: &[Field],
2148 argument: ExprRef,
2149 alias: ast::StrRef,
2150 columns: ast::Slice,
2151 ) -> Result<(NodeRef, Scope)> {
2152 let written = self.pragma_name(argument, function)?;
2153 let parts = identifier_parts(&written);
2154 let spelled: Vec<&str> = parts.iter().map(String::as_str).collect();
2155 let name = self.catalog.resolve(&spelled)?;
2156 let described = self.described(ast, &name)?;
2157 let mut rows = Vec::with_capacity(described.len());
2158 for (at, field) in described.iter().enumerate() {
2159 let items = if matches!(function, TableFunction::PragmaShow) {
2160 self.describing(field)
2161 } else {
2162 self.table_info(at, field)
2163 };
2164 rows.push(self.plan.add_expr_list(&items));
2165 }
2166 let rows = self.plan.add_rows(&rows);
2167 let held = self.plan.add_fields(fields);
2168 let index = self.fresh_index();
2169 let node = self.add_node(Node::Values { index, columns: held, rows });
2170 let label =
2171 if alias == NONE { function.name().to_string() } else { ast.string(alias).to_string() };
2172 let mut scope = Scope::empty();
2173 for (at, field) in fields.iter().enumerate() {
2174 scope.push(Visible {
2175 table: label.clone(),
2176 name: field.name.clone(),
2177 binding: ColumnBinding::new(index, at as u32),
2178 ty: field.ty.clone(),
2179 not_null: false,
2180 });
2181 }
2182 if !columns.is_empty() {
2183 let names: Vec<&str> = ast.name(columns).collect();
2184 scope.rename(&names, &label)?;
2185 }
2186 Ok((node, scope))
2187 }
2188
2189 /// The name a pragma was called with, which has to be a constant.
2190 ///
2191 /// A null is a name spelled `NULL` rather than an error about nulls, because the pin turns
2192 /// whatever it was handed into text before it goes looking and then says a table of that name
2193 /// does not exist. Writing `pragma_table_info(NULL)` is a mistake either way and this is the
2194 /// sentence the mistake already has.
2195 ///
2196 /// `pragma_table_info('t' || 'x')` is the pin's `tx` and is turned away here, which is the same
2197 /// missing constant folding [`Binder::named_argument`] writes about and closes the same day.
2198 fn pragma_name(&self, argument: ExprRef, function: TableFunction) -> Result<String> {
2199 let Expr::Constant(reference) = *self.plan.expr(argument) else {
2200 return Err(Error::not_implemented(format!(
2201 "{}() given a name that is not a constant",
2202 function.name()
2203 )));
2204 };
2205 match self.plan.value(reference) {
2206 Value::Varchar(name) => Ok(name.clone()),
2207 Value::Null => Ok("NULL".to_string()),
2208 other => {
2209 Err(Error::internal(format!("a pragma name bound as VARCHAR arrived as {other}")))
2210 }
2211 }
2212 }
2213
2214 /// The columns of whatever a pragma was pointed at.
2215 ///
2216 /// A view is bound here, which is how it comes to have columns at all. Reading a view is what
2217 /// binds it and describing one counts as reading it, so a view the engine ships with reports a
2218 /// column count from this point on, the same as it would after a select. The node that binding
2219 /// produces is thrown away, because the answer is the scope and not the query.
2220 ///
2221 /// Every column of a view is nullable whatever the column underneath was declared as, which is
2222 /// the pin's answer through `pragma_table_info()`, `pragma_show()` and `duckdb_columns()` alike.
2223 /// [`Scope::fields`] drops the flag on its own, so there is nothing to clear here.
2224 fn described(&mut self, ast: &Ast, name: &QualifiedName) -> Result<Vec<Field>> {
2225 if self.catalog.entry(name)? == Entry::Table {
2226 return Ok(self.catalog.table(name)?.columns().to_vec());
2227 }
2228 let (_, scope) = self.bind_view(ast, name, NONE, ast::Slice::default())?;
2229 Ok(scope.fields())
2230 }
2231
2232 /// One row of `pragma_show()`, which is one row of `DESCRIBE` written by the other caller.
2233 fn describing(&mut self, field: &Field) -> Vec<ExprRef> {
2234 let written = [
2235 field.name.clone(),
2236 field.ty.to_string(),
2237 if field.not_null { "NO" } else { "YES" }.to_owned(),
2238 ];
2239 let mut items: Vec<ExprRef> =
2240 written.into_iter().map(|text| self.plan.add_constant(Value::Varchar(text))).collect();
2241 for _ in 0..3 {
2242 let empty = self.plan.add_constant(Value::Null);
2243 items.push(self.cast_to(empty, &LogicalType::Varchar));
2244 }
2245 items
2246 }
2247
2248 /// One row of `pragma_table_info()`, which is SQLite's six columns about the same column.
2249 ///
2250 /// `cid` counts from zero, which is SQLite's numbering and not the one based `ordinal_position`
2251 /// the standard views report. `dflt_value` and `pk` are the two nothings rudb has to report
2252 /// until `CREATE TABLE` takes a `DEFAULT` or a key.
2253 fn table_info(&mut self, at: usize, field: &Field) -> Vec<ExprRef> {
2254 let cid = self.plan.add_constant(Value::Integer(i32::try_from(at).unwrap_or(i32::MAX)));
2255 let name = self.plan.add_constant(Value::Varchar(field.name.clone()));
2256 let ty = self.plan.add_constant(Value::Varchar(field.ty.to_string()));
2257 let not_null = self.plan.add_constant(Value::Boolean(field.not_null));
2258 let default = self.plan.add_constant(Value::Null);
2259 let default = self.cast_to(default, &LogicalType::Varchar);
2260 let key = self.plan.add_constant(Value::Boolean(false));
2261 vec![cid, name, ty, not_null, default, key]
2262 }
2263
2264 /// One named parameter of a table function call, folded into what the call was given.
2265 ///
2266 /// The value has to be a constant of the type the parameter wants. It has to be constant
2267 /// because an option can decide what the columns are and the columns are settled here, and it
2268 /// has to be already of the type because there is no constant folding in front of the binder
2269 /// yet. DuckDB folds first, so `binary_as_string=1` and `binary_as_string='yes'` are both true
2270 /// there and both are turned away here, which is a gap that closes on its own the day the
2271 /// optimizer runs before the plan is finished. `binary_as_string=True` is what the ClickBench
2272 /// entry writes and is what has to work.
2273 ///
2274 /// A name that is not a parameter of this function is the binary's sentence followed by what it
2275 /// could have been. The binary puts the candidates on their own indented lines and this puts
2276 /// them on the same line, because an error is one line here.
2277 fn named_argument(
2278 &mut self,
2279 function: TableFunction,
2280 name: &str,
2281 expr: ExprRef,
2282 ) -> Result<(&'static str, Value)> {
2283 let known = function
2284 .parameters()
2285 .iter()
2286 .find(|(parameter, _)| parameter.eq_ignore_ascii_case(name));
2287 let Some((parameter, wanted)) = known else {
2288 let candidates: Vec<String> = function
2289 .parameters()
2290 .iter()
2291 .map(|(parameter, ty)| format!(" {parameter} {ty}"))
2292 .collect();
2293 return Err(Error::binder(format!(
2294 "Invalid named parameter \"{name}\" for function {}\nCandidates:\n{}\n",
2295 function.name(),
2296 candidates.join("\n")
2297 )));
2298 };
2299 let Expr::Constant(reference) = *self.plan.expr(expr) else {
2300 return Err(Error::not_implemented(format!(
2301 "the named parameter {parameter} with a value that is not a constant"
2302 )));
2303 };
2304 let value = self.plan.value(reference).clone();
2305 if value == Value::Null {
2306 return Err(Error::binder(null_parameter(function, parameter)));
2307 }
2308 let given = self.plan.expr_type(expr).clone();
2309 if given != *wanted {
2310 return Err(Error::not_implemented(format!(
2311 "the named parameter {parameter} given a {given} where a {wanted} was wanted"
2312 )));
2313 }
2314 Ok((parameter, value))
2315 }
2316
2317 /// A file where a table name goes, which is what DuckDB calls a replacement scan.
2318 ///
2319 /// `SELECT * FROM 'hits.parquet'` is how most DuckDB queries in the wild are written, ClickBench
2320 /// among them, so this is not sugar over `read_parquet` so much as the spelling people use. The
2321 /// catalog has already been asked and has already said no, and `missing` is what it said, so a
2322 /// name that is not a file comes back with the catalog's own answer rather than with a complaint
2323 /// about files.
2324 ///
2325 /// Only a single unqualified name is a candidate. A qualified one names a schema and a schema
2326 /// that does not exist is not a path.
2327 fn bind_replacement_scan(
2328 &mut self,
2329 ast: &Ast,
2330 parts: &[&str],
2331 alias: ast::StrRef,
2332 columns: ast::Slice,
2333 missing: Error,
2334 ) -> Result<(NodeRef, Scope)> {
2335 let [path] = parts else { return Err(missing) };
2336 let path = *path;
2337 let extension = path.rsplit_once('.').map(|(_, after)| after).unwrap_or_default();
2338 let Some(function) = Self::reader_for(extension) else {
2339 if is_file(path) {
2340 // A file that is really there and that nothing here can read is a different mistake
2341 // from a name that is not a file, and DuckDB says so with both lines, the second of
2342 // which is the way out. A file with no dot in it lands here too, which is why the
2343 // test is on the extension having a reader rather than on there being an extension.
2344 return Err(Error::binder(format!(
2345 "No extension found that is capable of reading the file \"{path}\"\n* If this \
2346 file is a supported file format you can explicitly use the reader functions, \
2347 such as read_csv, read_json or read_parquet"
2348 )));
2349 }
2350 return Err(missing);
2351 };
2352 // The pattern is expanded before it is known to match anything, so a name that ends in .csv
2353 // and is not there gives the reader's own message rather than the catalog's. That is
2354 // DuckDB's order and it is the helpful one: somebody who wrote a file name wants to hear
2355 // about the file.
2356 let paths = files(path)?;
2357 // The name the columns answer to is the file's stem, so `SELECT mixed.a FROM
2358 // 'data/mixed.parquet'` works. That is DuckDB's choice and it is the useful one, since the
2359 // alternative is a table name with a dot and a slash in it that nothing can write. A pattern
2360 // keeps the whole of what was written instead, which is DuckDB's choice too and was
2361 // measured: there is no stem to take when the name stands for a directory full of files.
2362 let label = if alias == NONE {
2363 if is_pattern(path) {
2364 path.to_string()
2365 } else {
2366 let file = path.rsplit_once('/').map_or(path, |(_, file)| file);
2367 file.rsplit_once('.').map_or(file, |(stem, _)| stem).to_string()
2368 }
2369 } else {
2370 ast.string(alias).to_string()
2371 };
2372 let mut mirrorable = None;
2373 if function == TableFunction::ReadParquet {
2374 if let Some((canonical, stamp)) = mirror_target(&paths) {
2375 if let Some(name) = self.catalog.mirror(&canonical, false, stamp) {
2376 let name = name.clone();
2377 return self.bind_catalog_table(ast, &name, label, columns);
2378 }
2379 mirrorable = Some(canonical);
2380 }
2381 }
2382 let read = match function {
2383 TableFunction::ReadParquet => {
2384 let footers = self.footers(&paths, mirrorable.as_deref())?;
2385 if let Some(canonical) = mirrorable.as_deref() {
2386 self.want_mirror(canonical, false, &footers.rows);
2387 }
2388 Read {
2389 fields: footers.fields,
2390 rows: footers.rows,
2391 distincts: footers.distincts,
2392 zones: footers.zones,
2393 }
2394 }
2395 _ => Read::uncounted(csv_fields(&paths, Given::default())?),
2396 };
2397 let arguments: Vec<ExprRef> = paths.iter().map(|path| self.path_constant(path)).collect();
2398 let names: Vec<&str> = ast.name(columns).collect();
2399 self.table_function_source(function, &arguments, &[], read, &label, &names)
2400 }
2401
2402 /// What the footers of `paths` say, from the outline alone where this bind is outlined and the
2403 /// read could go through a mirror.
2404 ///
2405 /// An outline that does not state a row count is read again in full, because a read that asks
2406 /// for no mirror would leave the plan outlined with nothing telling the caller to bind again.
2407 fn footers(&self, paths: &[String], mirrorable: Option<&str>) -> Result<Footers> {
2408 if let Some(path) = mirrorable.filter(|_| self.outlined) {
2409 let outline = parquet_outline(path)?;
2410 if outline.rows.value().is_some() {
2411 return Ok(outline);
2412 }
2413 }
2414 parquet_footers(paths)
2415 }
2416
2417 /// Says the Parquet file at `path` could have been read through a native mirror, when its
2418 /// footer says how many rows it holds, which is what the database decides whether one would
2419 /// repay itself by.
2420 fn want_mirror(&mut self, path: &str, binary_as_string: bool, rows: &Stat<u64>) {
2421 if let Some(&rows) = rows.value() {
2422 self.plan.want_mirror(path, binary_as_string, rows);
2423 }
2424 }
2425
2426 /// One file name, as a constant expression in the plan.
2427 fn path_constant(&mut self, path: &str) -> ExprRef {
2428 let value = self.plan.add_value(Value::Varchar(path.to_string()));
2429 self.plan.add_expr(Expr::Constant(value), LogicalType::Varchar)
2430 }
2431
2432 /// The table function a file with this extension is read by, and `None` for one nothing reads.
2433 ///
2434 /// Both spellings of a tab separated file go to the CSV reader, which is not a shortcut: the
2435 /// extension picks the reader and the reader sniffs the punctuation, so a `.tsv` file that holds
2436 /// commas is read as commas. That was measured rather than assumed. The comparison ignores case
2437 /// because `UP.CSV` reads in duckdb v1.4.1.
2438 fn reader_for(extension: &str) -> Option<TableFunction> {
2439 if extension.eq_ignore_ascii_case("parquet") {
2440 return Some(TableFunction::ReadParquet);
2441 }
2442 if extension.eq_ignore_ascii_case("csv") || extension.eq_ignore_ascii_case("tsv") {
2443 return Some(TableFunction::ReadCsv);
2444 }
2445 None
2446 }
2447
2448 /// The node and the scope of a table function call whose arguments and columns are settled.
2449 ///
2450 /// The half a written out call shares with a replacement scan, which is everything after the
2451 /// question of what the file is called has been answered one way or the other.
2452 ///
2453 /// `read` is what the caller found out about the files, which comes in here rather than being
2454 /// read here because this function has the names and not the files: a replacement scan has
2455 /// already expanded its pattern and a written out call has already cast its argument, and
2456 /// neither of them wants to do it twice.
2457 fn table_function_source(
2458 &mut self,
2459 function: TableFunction,
2460 args: &[ExprRef],
2461 written: &[(&'static str, Value, ExprRef)],
2462 read: Read,
2463 label: &str,
2464 names: &[&str],
2465 ) -> Result<(NodeRef, Scope)> {
2466 let Read { fields, rows, distincts, zones } = read;
2467 let index = self.fresh_index();
2468 // Against the table index rather than against the node, because a pass is free to move the
2469 // node and none of them can move an index: an index is what a column reference names and
2470 // rewriting one would mean rewriting every expression above it. Nothing is recorded for a
2471 // function nobody measured, since an absent entry already reads back as unknown.
2472 if rows.is_known() {
2473 self.plan.measure(index, rows);
2474 }
2475 for (column, distinct) in distincts {
2476 self.plan.measure_distinct(index, &column, distinct);
2477 }
2478 if let Some(zones) = zones {
2479 self.plan.set_zones(index, zones);
2480 }
2481 let mut scope = Scope::empty();
2482 for (at, field) in fields.iter().enumerate() {
2483 scope.push(Visible {
2484 table: label.to_string(),
2485 name: field.name.clone(),
2486 binding: ColumnBinding::new(index, at as u32),
2487 ty: field.ty.clone(),
2488 // A reader takes what the file has, and no file format this reads says a column
2489 // cannot be null. The reference binary answers YES for every column of a Parquet.
2490 not_null: false,
2491 });
2492 }
2493 if !names.is_empty() {
2494 scope.rename(names, label)?;
2495 }
2496 let function = self.plan.intern(function.name());
2497 let args = self.plan.add_expr_list(args);
2498 let named: Vec<u32> =
2499 written.iter().map(|(parameter, _, _)| self.plan.intern(parameter)).collect();
2500 let settings: Vec<ExprRef> = written.iter().map(|(_, _, expr)| *expr).collect();
2501 let options = self.plan.add_name_list(&named);
2502 let settings = self.plan.add_expr_list(&settings);
2503 let columns = self.plan.add_fields(&fields);
2504 let node = self.add_node(Node::TableFunction {
2505 index,
2506 function,
2507 args,
2508 options,
2509 settings,
2510 columns,
2511 });
2512 Ok((node, scope))
2513 }
2514
2515 /// Every file a table function's file argument names, in the order they were written.
2516 ///
2517 /// Each pattern has to find at least one file of its own, which is DuckDB's rule and is why
2518 /// this expands one at a time rather than gathering everything and looking at the total. A
2519 /// list keeps its written order and its duplicates, so a file named twice is read twice, which
2520 /// was measured: the sort and the dedup belong to one pattern rather than to the list.
2521 fn file_paths(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2522 let mut paths = Vec::new();
2523 for pattern in self.file_patterns(expr, name)? {
2524 paths.extend(files(&pattern)?);
2525 }
2526 Ok(paths)
2527 }
2528
2529 /// The patterns a table function argument names, which have to be constants.
2530 ///
2531 /// A table function that reads a file is resolved by opening the file, and that happens here
2532 /// rather than when the query runs, because the rest of the statement cannot bind until the
2533 /// column names are known. So the path has to be something this binder can work out without
2534 /// running anything, and a literal is that. DuckDB folds a constant expression first, so
2535 /// `read_parquet('a' || '.parquet')` works there, and folding is M1 work that this will pick up
2536 /// for free once the optimizer runs before the plan is finished rather than after.
2537 ///
2538 /// One string is one pattern and a list is one pattern an item, which is DuckDB's pair of
2539 /// overloads. A null is a different sentence in each of them, both of them measured.
2540 ///
2541 /// The argument is folded rather than required to be a literal. A list is a call to `list_value`
2542 /// as of the work on #467, so requiring a literal here would have turned every `read_parquet`
2543 /// over a list into the message about a name that is not a constant, and the sentence this
2544 /// comment used to carry about folding being picked up for free was the plan for exactly that.
2545 /// What it buys beyond keeping the list working is `read_parquet('a' || '.parquet')`, which the
2546 /// pin answers and which used to be refused here.
2547 fn file_patterns(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2548 let Some(value) = fold::value_of(&self.plan, expr)? else {
2549 return Err(Error::not_implemented(
2550 "a table function file name that is not a constant",
2551 ));
2552 };
2553 match value {
2554 Value::Varchar(path) => Ok(vec![path]),
2555 // DuckDB's own wording, which says list because its other overload takes one.
2556 Value::Null => Err(Error::parser(format!("{name} cannot take NULL list as parameter"))),
2557 // An empty list reaches the reader rather than failing to bind, because `[]` carries an
2558 // element type of the untyped null and a null promotes to VARCHAR, so the call resolves.
2559 // The pin says this, and it says it as an IO error rather than as a binder one, since
2560 // the list was a fine list and the objection is that there is no file in it.
2561 Value::List { values, .. } if values.is_empty() => {
2562 Err(Error::io(format!("\"{name}\" needs at least one file to read")))
2563 }
2564 Value::List { values, .. } => values
2565 .iter()
2566 .map(|value| match value {
2567 Value::Varchar(path) => Ok(path.clone()),
2568 _ => Err(Error::parser(format!(
2569 "{name} reader cannot take NULL input as parameter"
2570 ))),
2571 })
2572 .collect(),
2573 other => {
2574 Err(Error::internal(format!("a file name bound as VARCHAR arrived as {other}")))
2575 }
2576 }
2577 }
2578
2579 /// Which input of a join a query written in its `ON` has to be joined into.
2580 ///
2581 /// A join condition is evaluated by the join, over the rows its two inputs handed it, so a
2582 /// column the condition reads has to be produced by one of those two. A query written in the
2583 /// `ON` produces columns the condition reads, which means the query cannot be joined in above
2584 /// the join the way one written in a `WHERE` or a `SELECT` is. It has to go underneath, into
2585 /// one input or the other.
2586 ///
2587 /// Which input is decided by what the query reads. A query whose body reads the right side can
2588 /// only be evaluated where those rows are, so it goes into the right input, and the same for
2589 /// the left. A query that reads neither could go into either and goes into the left, which is
2590 /// also where an `IN` puts one whose left hand side reads the left and whose body reads
2591 /// nothing.
2592 ///
2593 /// The one that has no answer is a query that reads both sides. There is no single input that
2594 /// produces what it needs, and the shape upstream calls a pair dependent join is what handles
2595 /// it. `None` is that case, and the caller turns it into a refusal rather than a plan.
2596 fn side_of(
2597 &self,
2598 pending: &PendingSubquery,
2599 left_tables: &[u32],
2600 right_tables: &[u32],
2601 ) -> Option<Side> {
2602 let mut needs_left = false;
2603 let mut needs_right = false;
2604 let mut note = |binding: ColumnBinding| {
2605 needs_left |= left_tables.contains(&binding.table);
2606 needs_right |= right_tables.contains(&binding.table);
2607 };
2608 for &binding in &pending.reads {
2609 note(binding);
2610 }
2611 // A mark join carries the comparison rather than the condition carrying it, and that
2612 // comparison is written over the join's own rows. `l.a IN (SELECT ...)` reads the left side
2613 // there and nowhere else, so leaving it out would put the query on whichever side its body
2614 // happened to name and let the comparison ask a join for a column it was not given.
2615 for &condition in &pending.conditions {
2616 self.plan.read_columns(condition, &mut |_, binding| note(binding));
2617 }
2618 match (needs_left, needs_right) {
2619 (true, true) => None,
2620 (_, true) => Some(Side::Right),
2621 _ => Some(Side::Left),
2622 }
2623 }
2624
2625 /// A join whose condition holds a query that reads rows from both of its inputs.
2626 ///
2627 /// This is the one [`Binder::side_of`] has no side for. The query has to be evaluated once per
2628 /// pair of rows, and there is no input that produces a pair, so it cannot go into either input
2629 /// the way the other two cases do. What produces a pair is the join itself, so the join becomes
2630 /// a product, the query is joined into the product's rows the way a query in a `WHERE` is joined
2631 /// into the rows the whole `FROM` produced, and the condition becomes a filter above that.
2632 ///
2633 /// That rewrite is only the same query for an inner join. An inner join keeps the pairs its
2634 /// condition holds and drops the rest, which is what a product and a filter do. Every other kind
2635 /// does something with the pairs it dropped, a left join pads them, a semi join counts them, and
2636 /// a filter above a product has already thrown away which left row a dropped pair came from, so
2637 /// those are refused by name. Upstream plans them as a pair dependent join and rudb does not
2638 /// have one yet, which is what tamnd/rudb#913 stays open for.
2639 ///
2640 /// The product is not the plan that runs. The condition goes back into the join as a condition
2641 /// when filter pushdown looks at it, which is the pass that already turns a filter over an inner
2642 /// join into a join condition, so an equality in the `ON` is still an equality the hash join can
2643 /// build on. What cannot be pushed back down is the part that reads the query's output, and that
2644 /// part could not have been a join condition in the first place.
2645 #[allow(clippy::too_many_arguments)]
2646 fn bind_pair_dependent_join(
2647 &mut self,
2648 kind: ast::JoinKind,
2649 independent: bool,
2650 left: NodeRef,
2651 right: NodeRef,
2652 pair: Vec<PendingSubquery>,
2653 conditions: Vec<ExprRef>,
2654 scope: Scope,
2655 ) -> Result<(NodeRef, Scope)> {
2656 if kind != ast::JoinKind::Inner {
2657 return Err(Error::not_implemented(
2658 "a subquery that reads both sides of that join, written in the condition of a join \
2659 that is not an inner join"
2660 .to_string(),
2661 ));
2662 }
2663 // A lateral right side is already evaluated per left row, so the product this would build is
2664 // not the product the query means.
2665 if !independent {
2666 return Err(Error::not_implemented(
2667 "a subquery that reads both sides of that join, written in the condition of a join \
2668 whose right side is lateral"
2669 .to_string(),
2670 ));
2671 }
2672 let mut node = self.add_node(Node::CrossProduct { left, right });
2673 for pending in pair {
2674 node = self.attach_subquery(node, pending);
2675 }
2676 // `ON` and `USING` cannot both be written, and this is only reached from the `ON` path, so
2677 // the list is the one bound condition. The fold is here so that it stays right if that stops
2678 // being true rather than for a case that exists today.
2679 let mut conditions = conditions.into_iter();
2680 let mut predicate = conditions.next().expect("a join condition was bound");
2681 for next in conditions {
2682 let children = self.plan.add_expr_list(&[predicate, next]);
2683 let conjunction = Expr::Conjunction { op: ConjunctionOp::And, children };
2684 predicate = self.plan.add_expr(conjunction, LogicalType::Boolean);
2685 }
2686 let node = self.add_node(Node::Filter { input: node, predicate });
2687 Ok((node, scope))
2688 }
2689
2690 #[allow(clippy::too_many_arguments)]
2691 fn bind_join(
2692 &mut self,
2693 ast: &Ast,
2694 left: ast::SourceRef,
2695 right: ast::SourceRef,
2696 kind: ast::JoinKind,
2697 natural: bool,
2698 on: ast::ExprRef,
2699 using: ast::Slice,
2700 ) -> Result<(NodeRef, Scope)> {
2701 let (left_node, left_scope) = self.bind_source(ast, left)?;
2702 let (right_node, right_scope, correlated) = self.bind_lateral(ast, right, &left_scope)?;
2703 // A row of the right side exists only for the left row it was evaluated against, so a kind
2704 // that has to produce right rows with no left row has nothing to produce them from. The
2705 // pinned build says this and names only the two kinds that work.
2706 if !correlated.is_empty()
2707 && !matches!(kind, ast::JoinKind::Inner | ast::JoinKind::Cross | ast::JoinKind::Left)
2708 {
2709 return Err(Error::binder(
2710 "The combining JOIN type must be INNER or LEFT for a LATERAL reference",
2711 ));
2712 }
2713 let split = left_scope.len();
2714 // Which table index came from which side, kept before the two scopes become one. A query
2715 // written in the `ON` is joined into one of the inputs rather than above the join, and this
2716 // is what says which. A `USING` drops the right side's copy of a joined-on column out of
2717 // the scope below, and dropping a column does not change the index it came from, so the
2718 // answer this gives is still right afterwards.
2719 let left_tables: Vec<u32> =
2720 left_scope.columns.iter().map(|column| column.binding.table).collect();
2721 let right_tables: Vec<u32> =
2722 right_scope.columns.iter().map(|column| column.binding.table).collect();
2723 let mut scope = left_scope.concat(right_scope);
2724
2725 // NATURAL is USING over whatever both sides happen to call the same thing, which is why it
2726 // is resolved here and never reaches the plan as its own idea.
2727 let merged: Vec<String> = if natural {
2728 let mut names = Vec::new();
2729 for (at, column) in scope.columns.iter().enumerate().take(split) {
2730 if scope.columns[split..].iter().any(|right| same_name(&right.name, &column.name))
2731 && !names.iter().any(|held: &String| same_name(held, &column.name))
2732 {
2733 let _ = at;
2734 names.push(column.name.clone());
2735 }
2736 }
2737 names
2738 } else {
2739 // A name written twice is one column, not two. `USING (id, id)` is legal and means what
2740 // `USING (id)` means, and the reference binary agrees. Taking it twice would build the
2741 // same equality twice and, worse, drop the right side's copy twice, which takes a
2742 // column out of the answer that nobody named and runs off the end of the scope when the
2743 // copy was the last column in it.
2744 let mut names: Vec<String> = Vec::new();
2745 for name in ast.name(using) {
2746 if !names.iter().any(|held| same_name(held, name)) {
2747 names.push(name.to_string());
2748 }
2749 }
2750 names
2751 };
2752
2753 let mut conditions = Vec::new();
2754 let mut dropped = Vec::new();
2755 for name in &merged {
2756 let left_at = scope.columns[..split]
2757 .iter()
2758 .position(|column| same_name(&column.name, name))
2759 .ok_or_else(|| {
2760 Error::binder(format!(
2761 "column \"{name}\" specified in USING clause does not exist in left table"
2762 ))
2763 })?;
2764 let right_at = scope.columns[split..]
2765 .iter()
2766 .position(|column| same_name(&column.name, name))
2767 .map(|at| at + split)
2768 .ok_or_else(|| {
2769 Error::binder(format!(
2770 "column \"{name}\" specified in USING clause does not exist in right table"
2771 ))
2772 })?;
2773 let left_column = &scope.columns[left_at];
2774 let (left_binding, left_type) = (left_column.binding, left_column.ty.clone());
2775 let right_column = &scope.columns[right_at];
2776 let (right_binding, right_type) = (right_column.binding, right_column.ty.clone());
2777 let left_expr = self.plan.add_expr(Expr::Column(left_binding), left_type);
2778 let right_expr = self.plan.add_expr(Expr::Column(right_binding), right_type);
2779 conditions.push(self.compare(rudb_plan::CompareOp::Equal, left_expr, right_expr)?);
2780 dropped.push(right_at);
2781 }
2782 // A joined-on column appears once, so the right side's copy goes. Dropping from the back
2783 // keeps the positions of the ones still to drop correct.
2784 dropped.sort_unstable();
2785 for at in dropped.into_iter().rev() {
2786 scope.remove(at);
2787 }
2788
2789 let mut left_node = left_node;
2790 let mut right_node = right_node;
2791 let mut pair = Vec::new();
2792 if on != NONE {
2793 if !merged.is_empty() {
2794 return Err(Error::binder("a join cannot have both ON and USING"));
2795 }
2796 self.clause = "JOIN condition";
2797 let waiting = self.scalar_subqueries.len();
2798 let predicate = self.bind_expr(ast, on, &scope)?;
2799 conditions.push(self.as_boolean(predicate, "JOIN")?);
2800 for pending in self.scalar_subqueries.split_off(waiting) {
2801 match self.side_of(&pending, &left_tables, &right_tables) {
2802 Some(Side::Right) => right_node = self.attach_subquery(right_node, pending),
2803 Some(Side::Left) => left_node = self.attach_subquery(left_node, pending),
2804 None => pair.push(pending),
2805 }
2806 }
2807 }
2808
2809 if kind == ast::JoinKind::Cross && !conditions.is_empty() {
2810 return Err(Error::binder("a CROSS JOIN cannot have a condition"));
2811 }
2812 if !pair.is_empty() {
2813 return self.bind_pair_dependent_join(
2814 kind,
2815 correlated.is_empty(),
2816 left_node,
2817 right_node,
2818 pair,
2819 conditions,
2820 scope,
2821 );
2822 }
2823 // A product is the join with nothing to join on, and it is not one when the right side has
2824 // to be evaluated per left row, because then there is a dependency to lower even though
2825 // there is no condition to test.
2826 if correlated.is_empty()
2827 && conditions.is_empty()
2828 && matches!(kind, ast::JoinKind::Cross | ast::JoinKind::Inner)
2829 {
2830 let node = self.add_node(Node::CrossProduct { left: left_node, right: right_node });
2831 return Ok((node, scope));
2832 }
2833 // A semi join and an anti join ask a question about the right side rather than producing
2834 // any of it, so what is in scope after one is the left side alone. The condition is bound
2835 // above and is the last thing that can name the right side. Without this, `SELECT *` over
2836 // one expanded to both sides and the projection asked a join whose output is the left side
2837 // for columns it does not have, which came out as an internal error about a column not
2838 // being in the schema. That is tamnd/rudb#847. The reference binary refuses `b.w` here with
2839 // a binder error naming `a` as the only candidate table, which is the same rule said from
2840 // the other end.
2841 if matches!(kind, ast::JoinKind::Semi | ast::JoinKind::Anti) {
2842 scope.truncate(split);
2843 }
2844 let kind = match kind {
2845 ast::JoinKind::Inner | ast::JoinKind::Cross => JoinKind::Inner,
2846 ast::JoinKind::Left => JoinKind::Left,
2847 ast::JoinKind::Right => JoinKind::Right,
2848 ast::JoinKind::Full => JoinKind::Full,
2849 ast::JoinKind::Semi => JoinKind::Semi,
2850 ast::JoinKind::Anti => JoinKind::Anti,
2851 ast::JoinKind::Positional => JoinKind::Positional,
2852 };
2853 let conditions = self.plan.add_expr_list(&conditions);
2854 let node = if correlated.is_empty() {
2855 self.add_node(Node::Join {
2856 left: left_node,
2857 right: right_node,
2858 kind,
2859 conditions,
2860 build: BuildSide::default(),
2861 })
2862 } else {
2863 self.add_node(Node::DependentJoin {
2864 left: left_node,
2865 right: right_node,
2866 kind,
2867 conditions,
2868 })
2869 };
2870 Ok((node, scope))
2871 }
2872
2873 // -------------------------------------------------------------- aggregates
2874
2875 /// Binds a `FILTER (WHERE ...)` predicate, or says there was none.
2876 ///
2877 /// The predicate is a condition over the input rows and not over the answer, so it is bound in
2878 /// the scope the arguments are bound in, and it is cast to `BOOLEAN` the way a `WHERE` is:
2879 /// `FILTER (WHERE i)` over an integer column is a filter on whether the integer is not zero.
2880 fn bind_filter(
2881 &mut self,
2882 ast: &Ast,
2883 filter: ast::ExprRef,
2884 scope: &Scope,
2885 ) -> Result<Option<ExprRef>> {
2886 if filter == NONE {
2887 return Ok(None);
2888 }
2889 let bound = self.bind_expr(ast, filter, scope)?;
2890 Ok(Some(self.checked_cast_to(bound, &LogicalType::Boolean, false)?))
2891 }
2892
2893 /// Binds an aggregate call, records it, and hands back a reference to where its result lands.
2894 ///
2895 /// An aggregate inside a lambda's body is computed over the rows and not over the elements,
2896 /// so its arguments cannot see the lambda's parameters. See `crate::lambda`.
2897 pub(crate) fn bind_aggregate(
2898 &mut self,
2899 ast: &Ast,
2900 name: &str,
2901 args: &[ast::ExprRef],
2902 distinct: bool,
2903 filter: ast::ExprRef,
2904 scope: &Scope,
2905 ) -> Result<ExprRef> {
2906 let frames = std::mem::take(&mut self.lambda_frames);
2907 let bound = self.bind_aggregate_over_rows(ast, name, args, distinct, filter, scope);
2908 self.lambda_frames = frames;
2909 bound
2910 }
2911
2912 fn bind_aggregate_over_rows(
2913 &mut self,
2914 ast: &Ast,
2915 name: &str,
2916 args: &[ast::ExprRef],
2917 distinct: bool,
2918 filter: ast::ExprRef,
2919 scope: &Scope,
2920 ) -> Result<ExprRef> {
2921 if self.in_filter {
2922 return Err(Error::binder("aggregate functions are not allowed in FILTER"));
2923 }
2924 if self.in_aggregate {
2925 return Err(Error::binder(format!(
2926 "aggregate function calls cannot be nested, and {name}() is inside one"
2927 )));
2928 }
2929 if self.aggregation.is_none() {
2930 return Err(Error::binder(format!(
2931 "aggregate function calls cannot be used in the {}",
2932 self.clause
2933 )));
2934 }
2935 // The predicate goes first, which is the order the messages come out in upstream: a call
2936 // whose argument and whose filter both name columns that are not there is refused over the
2937 // filter. It is bound as if it were inside the call, so an aggregate in it is caught, and a
2938 // window in it is refused with the words a window inside an aggregate is refused with.
2939 self.in_aggregate = true;
2940 self.in_filter = true;
2941 let filter = self.bind_filter(ast, filter, scope);
2942 self.in_filter = false;
2943 self.in_aggregate = false;
2944 let filter = filter?;
2945
2946 self.in_aggregate = true;
2947 let mut bound = Vec::with_capacity(args.len());
2948 let mut failure = None;
2949 for &arg in args {
2950 match self.bind_expr(ast, arg, scope) {
2951 Ok(expr) => bound.push(expr),
2952 Err(error) => {
2953 failure = Some(error);
2954 break;
2955 }
2956 }
2957 }
2958 self.in_aggregate = false;
2959 if let Some(error) = failure {
2960 return Err(error);
2961 }
2962
2963 let types: Vec<LogicalType> =
2964 bound.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2965 let resolved = resolve(name, &types)?;
2966 let mut cast = Vec::with_capacity(bound.len());
2967 for (arg, wanted) in bound.iter().zip(&resolved.arguments) {
2968 cast.push(self.checked_cast_to(*arg, wanted, false)?);
2969 }
2970 let args = self.plan.add_expr_list(&cast);
2971 let name = self.plan.intern(resolved.name);
2972 let ty = resolved.returns;
2973 let call = self.plan.add_expr(Expr::Aggregate { name, args, distinct, filter }, ty.clone());
2974
2975 // Two identical aggregates are one column of the aggregate's output. `SELECT sum(x),
2976 // sum(x) / count(*)` computes one sum, not two.
2977 let existing = self.aggregation.as_ref().map(|held| held.aggregates.clone());
2978 let existing = existing.unwrap_or_default();
2979 let at = match existing.iter().position(|&held| self.same_expr(held, call)) {
2980 Some(at) => at,
2981 None => {
2982 let aggregation = self.aggregation.as_mut().expect("checked above");
2983 aggregation.aggregates.push(call);
2984 aggregation.aggregates.len() - 1
2985 }
2986 };
2987 let aggregation = self.aggregation.as_ref().expect("checked above");
2988 let (index, groups) = (aggregation.index, aggregation.groups.len());
2989 Ok(self.column(index, groups + at, ty))
2990 }
2991
2992 // ----------------------------------------------------------------- windows
2993
2994 /// Binds a window call, files it under the run it belongs to, and hands back its column.
2995 ///
2996 /// The result is a column of a [`Node::Window`] rather than the call itself, for the reason the
2997 /// aggregate path returns a column too: the operator produces the value and everything above it
2998 /// reads the value, so a target that wraps a window in arithmetic is arithmetic over a column.
2999 ///
3000 /// A window inside a lambda's body is computed over the rows for the reason an aggregate is,
3001 /// so it cannot see the lambda's parameters either.
3002 pub(crate) fn bind_window(
3003 &mut self,
3004 ast: &Ast,
3005 written: &WindowCall<'_>,
3006 scope: &Scope,
3007 ) -> Result<ExprRef> {
3008 let frames = std::mem::take(&mut self.lambda_frames);
3009 let bound = self.bind_window_over_rows(ast, written, scope);
3010 self.lambda_frames = frames;
3011 bound
3012 }
3013
3014 fn bind_window_over_rows(
3015 &mut self,
3016 ast: &Ast,
3017 written: &WindowCall<'_>,
3018 scope: &Scope,
3019 ) -> Result<ExprRef> {
3020 let WindowCall { name, args, distinct, filter, ignore_nulls, spec, .. } = *written;
3021 if self.in_aggregate {
3022 return Err(Error::binder(
3023 "aggregate function calls cannot contain window function calls",
3024 ));
3025 }
3026 if self.in_window {
3027 return Err(Error::binder("window function calls cannot be nested"));
3028 }
3029 // A join condition is part of the `WHERE` clause as far as this one sentence is concerned,
3030 // which is upstream's wording and not a simplification: `ON sum(a.i) OVER () = b.i` is
3031 // refused there with the words a window in a `WHERE` is refused with.
3032 let clause = if self.clause == "JOIN condition" { "WHERE clause" } else { self.clause };
3033 if clause != "SELECT clause" && clause != "ORDER BY clause" {
3034 return Err(Error::binder(format!("{clause} cannot contain window functions!")));
3035 }
3036
3037 // `count(*)` is a different function from `count(x)` here for the reason it is a different
3038 // function in an ordinary call: one counts rows and the other counts the rows where its
3039 // argument is not null. A star is not an expression and nothing below this binds one.
3040 let starred = args.iter().any(|&arg| {
3041 matches!(ast.expr(arg), ast::Expr::Star { qualifier, replacements }
3042 if qualifier.is_empty() && replacements.is_empty())
3043 });
3044 let (name, args): (&str, &[ast::ExprRef]) = if starred {
3045 if !same_name(name, "count") || args.len() != 1 {
3046 return Err(Error::binder(format!("* is not allowed in {name}()")));
3047 }
3048 ("count_star", &[])
3049 } else if same_name(name, "count") && args.is_empty() {
3050 // `count()` with nothing in it is upstream's other spelling of `count(*)`. It counts
3051 // rows the same way and it is not an arity mistake.
3052 ("count_star", &[])
3053 } else {
3054 (name, args)
3055 };
3056
3057 let held = ast.window(spec);
3058 self.in_window = true;
3059 let parts = self.window_parts(ast, written, args, held, scope);
3060 // The predicate goes last here, which is the other way round from an ordinary aggregate and
3061 // is again the order the messages come out in upstream. It is still inside the window, so a
3062 // window in it is a nested window, while an aggregate in it is an ordinary aggregate over
3063 // the same rows and is answered.
3064 let filter = if parts.is_ok() { self.bind_filter(ast, filter, scope) } else { Ok(None) };
3065 self.in_window = false;
3066 let parts = parts?;
3067 let filter = filter?;
3068 // Upstream's rule, in its words. A `RANGE` offset is a distance from the current row's sort
3069 // key, so there has to be exactly one sort key for it to be a distance from.
3070 let offsets = [parts.frame.start, parts.frame.end]
3071 .iter()
3072 .any(|end| matches!(end, WindowBound::Preceding(_) | WindowBound::Following(_)));
3073 if parts.frame.unit == WindowUnit::Range && offsets && parts.order.len() != 1 {
3074 return Err(Error::binder("RANGE frames must have only one ORDER BY expression"));
3075 }
3076
3077 let types: Vec<LogicalType> =
3078 parts.args.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
3079 let resolved = window_signature(name, &types)?;
3080 // `fill` reads the sort key rather than the frame, so what it needs from the query is not
3081 // what any other window needs and it is refused on its own terms.
3082 if resolved.name == "fill" {
3083 let keys: Vec<LogicalType> =
3084 parts.order.iter().map(|key| self.plan.expr_type(key.expr).clone()).collect();
3085 refuse_fill(&types[0], &keys, distinct, ignore_nulls)?;
3086 }
3087 // Upstream's sentence, doubled quotes and all. A DISTINCT over an aggregate inside an OVER
3088 // is ordinary and answered, and a DISTINCT over a ranking window is refused there, because
3089 // there is nothing for it to collapse when the call reads no values in the first place.
3090 if distinct && kind_of(resolved.name) == Some(FunctionKind::Window) {
3091 return Err(Error::binder(format!(
3092 "DISTINCT is not implemented for the window function \"\"{name}\"\""
3093 )));
3094 }
3095 // The same sentence for the same reason. A ranking window reads no values, so there is
3096 // nothing for a predicate over the values to keep or drop.
3097 if filter.is_some() && kind_of(resolved.name) == Some(FunctionKind::Window) {
3098 return Err(Error::binder(format!(
3099 "FILTER is not implemented for the window function \"\"{name}\"\""
3100 )));
3101 }
3102 // An `ORDER BY` inside the brackets puts the rows of the frame in a different order for
3103 // this one call to read them in, which is a question every aggregate and the three that
3104 // count through the frame have an answer to. The rest of the window functions read
3105 // something other than the frame, and what the reference binary does with them under an
3106 // order of their own is a different reading again, so they are turned down rather than
3107 // guessed at. The exclusion is refused first and in the reference binary's own sentence,
3108 // because that is the one it reaches for when both apply. Per #1204.
3109 if !parts.inner.is_empty() && kind_of(resolved.name) == Some(FunctionKind::Window) {
3110 let counts = matches!(resolved.name, "first_value" | "last_value" | "nth_value");
3111 if !counts {
3112 if parts.frame.exclude != WindowExclude::NoOthers {
3113 return Err(Error::binder(format!(
3114 "EXCLUDE is not supported for the window function \"\"{}\"\"",
3115 resolved.name
3116 )));
3117 }
3118 return Err(Error::not_implemented(format!(
3119 "ORDER BY inside the arguments of the window function \"{}\"",
3120 resolved.name
3121 )));
3122 }
3123 }
3124 let mut cast = Vec::with_capacity(parts.args.len());
3125 for (arg, wanted) in parts.args.iter().zip(&resolved.arguments) {
3126 cast.push(self.checked_cast_to(*arg, wanted, false)?);
3127 }
3128 let args = self.plan.add_expr_list(&cast);
3129 let order = self.plan.add_sort_keys(&parts.inner);
3130 let name = self.plan.intern(resolved.name);
3131 let ty = resolved.returns;
3132 let call = self.plan.add_expr(
3133 Expr::Window { name, args, distinct, filter, ignore_nulls, order },
3134 ty.clone(),
3135 );
3136
3137 let at = self.window_run(parts.partition, parts.order, parts.frame, call);
3138 let index = self.windows.last().expect("the run was just filed").index;
3139 Ok(self.column(index, at, ty))
3140 }
3141
3142 /// Files a call under the run that matches it, or opens a new run, and says which column it is.
3143 ///
3144 /// The run that matches is only ever the last one, because a query that goes back to an earlier
3145 /// partitioning after using a different one in between wants the operators in the order it wrote
3146 /// them. Merging the two would be a rewrite, and a rewrite over a window is the optimizer's to
3147 /// make once it knows what the sort below each one costs.
3148 fn window_run(
3149 &mut self,
3150 partition: Vec<ExprRef>,
3151 order: Vec<SortKey>,
3152 frame: WindowFrame,
3153 call: ExprRef,
3154 ) -> usize {
3155 let matches = self.windows.last().is_some_and(|run| {
3156 run.frame == frame
3157 && run.partition.len() == partition.len()
3158 && run.order.len() == order.len()
3159 && run.partition.iter().zip(&partition).all(|(&l, &r)| self.same_expr(l, r))
3160 && run.order.iter().zip(&order).all(|(l, r)| {
3161 l.descending == r.descending
3162 && l.nulls_first == r.nulls_first
3163 && self.same_expr(l.expr, r.expr)
3164 })
3165 });
3166 if !matches {
3167 let index = self.fresh_index();
3168 self.windows.push(WindowRun { index, partition, order, frame, calls: Vec::new() });
3169 }
3170 // Two identical calls over one run are one column, the same way two identical aggregates
3171 // over one grouping are. `SELECT sum(i) OVER (), sum(i) OVER () + 1` totals once.
3172 let calls = self.windows.last().expect("a run is open").calls.clone();
3173 if let Some(at) = calls.iter().position(|&held| self.same_expr(held, call)) {
3174 return at;
3175 }
3176 let run = self.windows.last_mut().expect("a run is open");
3177 run.calls.push(call);
3178 run.calls.len() - 1
3179 }
3180
3181 /// Binds the arguments and everything inside the `OVER`, with the aggregate rule applied.
3182 ///
3183 /// The aggregate rule applies to all of it, which is measured rather than assumed: over a
3184 /// grouped block `sum(count(i)) OVER ()` binds and `sum(i) OVER ()` is the ungrouped column
3185 /// complaint, and the same pair of answers comes back for a partition key and for an order key.
3186 fn window_parts(
3187 &mut self,
3188 ast: &Ast,
3189 written: &WindowCall<'_>,
3190 args: &[ast::ExprRef],
3191 held: ast::WindowSpec,
3192 scope: &Scope,
3193 ) -> Result<WindowParts> {
3194 let mut bound = Vec::with_capacity(args.len());
3195 for &arg in args {
3196 let expr = self.bind_expr(ast, arg, scope)?;
3197 bound.push(self.over_aggregate(expr, scope)?);
3198 }
3199 // The keys inside the brackets are bound against the same rows the arguments are, because
3200 // that is what they sort: the call reads its frame in this order, and the frame is made of
3201 // the operator's input rows.
3202 let mut inner = Vec::new();
3203 for item in ast.order_list(written.order).to_vec() {
3204 let expr = self.bind_expr(ast, item.expr, scope)?;
3205 let expr = self.over_aggregate(expr, scope)?;
3206 inner.push(self.sort_key(expr, item));
3207 }
3208 let mut partition = Vec::new();
3209 for &key in ast.expr_list(held.partition) {
3210 let expr = self.bind_expr(ast, key, scope)?;
3211 partition.push(self.over_aggregate(expr, scope)?);
3212 }
3213 let mut order = Vec::new();
3214 for item in ast.order_list(held.order).to_vec() {
3215 let expr = self.bind_expr(ast, item.expr, scope)?;
3216 let expr = self.over_aggregate(expr, scope)?;
3217 order.push(self.sort_key(expr, item));
3218 }
3219 let frame = WindowFrame {
3220 unit: match held.unit {
3221 ast::WindowUnit::Rows => WindowUnit::Rows,
3222 ast::WindowUnit::Range => WindowUnit::Range,
3223 ast::WindowUnit::Groups => WindowUnit::Groups,
3224 },
3225 start: self.window_bound(ast, held.start, scope)?,
3226 end: self.window_bound(ast, held.end, scope)?,
3227 exclude: match held.exclude {
3228 ast::WindowExclude::NoOthers => WindowExclude::NoOthers,
3229 ast::WindowExclude::CurrentRow => WindowExclude::CurrentRow,
3230 ast::WindowExclude::Group => WindowExclude::Group,
3231 ast::WindowExclude::Ties => WindowExclude::Ties,
3232 },
3233 };
3234 Ok(WindowParts { args: bound, partition, order, inner, frame })
3235 }
3236
3237 /// One end of a frame, with its offset bound where it has one.
3238 fn window_bound(
3239 &mut self,
3240 ast: &Ast,
3241 bound: ast::WindowBound,
3242 scope: &Scope,
3243 ) -> Result<WindowBound> {
3244 let offset = |binder: &mut Self, written| {
3245 let expr = binder.bind_expr(ast, written, scope)?;
3246 binder.over_aggregate(expr, scope)
3247 };
3248 Ok(match bound {
3249 ast::WindowBound::UnboundedPreceding => WindowBound::UnboundedPreceding,
3250 ast::WindowBound::CurrentRow => WindowBound::CurrentRow,
3251 ast::WindowBound::UnboundedFollowing => WindowBound::UnboundedFollowing,
3252 ast::WindowBound::Preceding(written) => WindowBound::Preceding(offset(self, written)?),
3253 ast::WindowBound::Following(written) => WindowBound::Following(offset(self, written)?),
3254 })
3255 }
3256
3257 /// Which of this block's groups is exactly that column, if one of them is.
3258 ///
3259 /// Exactly the column and not an expression over it, because the caller is looking for the same
3260 /// value read from the aggregate instead of from the table underneath it, and `GROUP BY k + 1`
3261 /// carries the sum and not the column.
3262 fn group_of(&self, read: ColumnBinding) -> Option<usize> {
3263 self.aggregation.as_ref()?.groups.iter().position(
3264 |group| matches!(*self.plan.expr(*group), Expr::Column(binding) if binding == read),
3265 )
3266 }
3267
3268 /// The outer column a query still waiting under this grouping correlates to and the grouping
3269 /// does not carry upward, which is the column an error should name.
3270 ///
3271 /// `None` when the binding is not one of those queries, which is every ordinary case of a
3272 /// column read without a group.
3273 fn ungrouped_correlation(&self, binding: ColumnBinding) -> Option<ColumnBinding> {
3274 let pending =
3275 self.scalar_subqueries.iter().find(|pending| pending.index == binding.table)?;
3276 pending.reads.iter().copied().find(|read| self.group_of(*read).is_none())
3277 }
3278
3279 /// Whether a column is the result of a window this block is building.
3280 fn is_window_output(&self, binding: ColumnBinding) -> bool {
3281 self.windows.iter().any(|run| run.index == binding.table)
3282 }
3283
3284 /// Whether a column was resolved in an enclosing query rather than in this one.
3285 ///
3286 /// Every such read is written into the frame of the query being bound as it is resolved, and
3287 /// the frame is only handed up once that query's body is done, so while a select list or a
3288 /// `HAVING` is being bound the frame still holds everything this query read from outside it.
3289 fn is_correlation(&self, binding: ColumnBinding) -> bool {
3290 self.correlations.last().is_some_and(|frame| frame.contains(&binding))
3291 }
3292
3293 /// The name a column is written under, for an error message to say which one it means.
3294 ///
3295 /// A column of an enclosing query is not in this query's scope, so the outer scopes are searched
3296 /// as well. Without that the message names no column at all, which is how `column a column must
3297 /// appear in the GROUP BY clause` came to be a sentence this engine printed.
3298 fn name_of(&self, binding: ColumnBinding, scope: &Scope) -> String {
3299 std::iter::once(scope)
3300 .chain(self.outer_scopes.iter().rev())
3301 .flat_map(|visible| visible.columns.iter())
3302 .find(|column| column.binding == binding)
3303 .map_or_else(|| "a column".to_string(), |column| format!("\"{}\"", column.name))
3304 }
3305
3306 /// Rewrites a bound expression into one the aggregate's output can answer.
3307 ///
3308 /// A subexpression that is one of the group expressions becomes a reference to that group. A
3309 /// column that is neither grouped nor inside an aggregate is the error every SQL user has seen,
3310 /// and it is reported here because this is the first point where it is knowable.
3311 pub(crate) fn over_aggregate(&mut self, expr: ExprRef, scope: &Scope) -> Result<ExprRef> {
3312 let Some(aggregation) = self.aggregation.as_ref() else {
3313 return Ok(expr);
3314 };
3315 let index = aggregation.index;
3316 let groups = aggregation.groups.clone();
3317 for (at, group) in groups.iter().enumerate() {
3318 if self.same_expr(expr, *group) {
3319 let ty = self.plan.expr_type(*group).clone();
3320 return Ok(self.column(index, at, ty));
3321 }
3322 }
3323 let ty = self.plan.expr_type(expr).clone();
3324 match self.plan.expr(expr).clone() {
3325 Expr::Column(binding) if binding.table == index => Ok(expr),
3326 // A window result is not a column of the input and the grouping rule has nothing to say
3327 // about it. It reads the aggregate's output rather than the table's, which is why
3328 // `SELECT sum(count(i)) OVER () FROM t GROUP BY j` binds and `sum(i) OVER ()` over the
3329 // same block does not.
3330 Expr::Column(binding) if self.is_window_output(binding) => Ok(expr),
3331 // The same argument for a query joined in above the grouping. `HAVING sum(x) > (SELECT
3332 // ...)` reads one row out of a query that has nothing to do with the groups, and the
3333 // join that produces it sits on top of the `Aggregate`, so what it produces is not one
3334 // of the grouped table's columns either.
3335 Expr::Column(binding) if self.joined_above.contains(&binding.table) => Ok(expr),
3336 // A column of an enclosing query is one value for the whole of this one, because this
3337 // query is evaluated once per outer row. It is a constant here in the sense the grouping
3338 // rule cares about, so it is allowed wherever a grouped column is and needs no group of
3339 // its own. The grouping rule is about columns of this query's own `FROM`, and a name
3340 // that resolved past it is not one of those. That is #995.
3341 Expr::Column(binding) if self.is_correlation(binding) => Ok(expr),
3342 // A query this block wrote that is still waiting to be joined in underneath the
3343 // grouping lands here as well, and the column the complaint should name is the one that
3344 // query correlates to rather than the column the query produces, which belongs to no
3345 // table anybody wrote. An uncorrelated query and a correlated one whose correlation is
3346 // grouped were both moved over the grouping by [`Self::lift_over_aggregate`] and are
3347 // not here, so what is left correlates to something this block neither grouped nor
3348 // aggregated, and that is an ordinary missing GROUP BY however far inside a query it
3349 // was written. That is #1032.
3350 Expr::Column(binding) => {
3351 let read = self.ungrouped_correlation(binding).unwrap_or(binding);
3352 let name = self.name_of(read, scope);
3353 Err(Error::binder(format!(
3354 "column {name} must appear in the GROUP BY clause or must be part of an aggregate function"
3355 )))
3356 }
3357 Expr::Constant(_)
3358 | Expr::Aggregate { .. }
3359 | Expr::Window { .. }
3360 | Expr::LambdaParam(_) => Ok(expr),
3361 // The body is over the elements and the columns it captures, and a captured column is
3362 // held to the grouping rule like any other, which is the pin's error for
3363 // `list_transform(l, lambda x: x * k) ... GROUP BY l`.
3364 Expr::Lambda { table, params, body } => {
3365 let body = self.over_aggregate(body, scope)?;
3366 Ok(self.plan.add_expr(Expr::Lambda { table, params, body }, ty))
3367 }
3368 Expr::Cast { input, try_cast } => {
3369 let input = self.over_aggregate(input, scope)?;
3370 Ok(self.plan.add_expr(Expr::Cast { input, try_cast }, ty))
3371 }
3372 Expr::Compare { op, left, right } => {
3373 let left = self.over_aggregate(left, scope)?;
3374 let right = self.over_aggregate(right, scope)?;
3375 Ok(self.plan.add_expr(Expr::Compare { op, left, right }, ty))
3376 }
3377 Expr::Conjunction { op, children } => {
3378 let written = self.plan.expr_list(children).to_vec();
3379 let mut rewritten = Vec::with_capacity(written.len());
3380 for child in written {
3381 rewritten.push(self.over_aggregate(child, scope)?);
3382 }
3383 let children = self.plan.add_expr_list(&rewritten);
3384 Ok(self.plan.add_expr(Expr::Conjunction { op, children }, ty))
3385 }
3386 Expr::Function { name, args } => {
3387 let written = self.plan.expr_list(args).to_vec();
3388 let mut rewritten = Vec::with_capacity(written.len());
3389 for arg in written {
3390 rewritten.push(self.over_aggregate(arg, scope)?);
3391 }
3392 let args = self.plan.add_expr_list(&rewritten);
3393 Ok(self.plan.add_expr(Expr::Function { name, args }, ty))
3394 }
3395 Expr::Case { arms, otherwise } => {
3396 let written = self.plan.arm_list(arms).to_vec();
3397 let mut rewritten = Vec::with_capacity(written.len());
3398 for arm in written {
3399 let when = self.over_aggregate(arm.when, scope)?;
3400 let then = self.over_aggregate(arm.then, scope)?;
3401 rewritten.push(rudb_plan::Arm { when, then });
3402 }
3403 let otherwise = match otherwise {
3404 Some(expr) => Some(self.over_aggregate(expr, scope)?),
3405 None => None,
3406 };
3407 let arms = self.plan.add_arms(&rewritten);
3408 Ok(self.plan.add_expr(Expr::Case { arms, otherwise }, ty))
3409 }
3410 }
3411 }
3412
3413 /// Whether two bound expressions are the same expression, by shape rather than by reference.
3414 pub(crate) fn same_expr(&self, left: ExprRef, right: ExprRef) -> bool {
3415 same_expr(&self.plan, left, right)
3416 }
3417}
3418
3419/// The named parameters a table function call was written with.
3420///
3421/// A struct rather than the fields loose, because the seventeen DuckDB has on `read_parquet` and the
3422/// thirty on `read_csv` are all going to want somewhere to go, and because a call with none of them
3423/// written should read as the default of this rather than as a bare false somewhere.
3424///
3425/// The CSV half goes on to the reader and is opened with, here and again in the executor. The
3426/// Parquet half is answered here and nothing downstream sees it, which is what `binary_as_string`
3427/// turning a BLOB column into a VARCHAR one is.
3428#[derive(Debug, Default)]
3429struct Options {
3430 /// `binary_as_string`, which says an unannotated byte array column in a Parquet file holds
3431 /// text. The ClickBench file has twenty eight of those and every query reads them as strings.
3432 binary_as_string: bool,
3433 /// `all_varchar`, which reads every column of a CSV file as text rather than sniffing a type.
3434 all_varchar: bool,
3435 /// `file_row_number`, which adds a column holding each row's ordinal inside its own file.
3436 ///
3437 /// The one Parquet option here that the executor has to act on rather than the binder, since
3438 /// the column is not in the file and has to be counted as the rows come out of it.
3439 file_row_number: bool,
3440 /// `delim`, `sep`, `quote`, `escape` and `header`, which are what the sniffer would decide.
3441 given: Given,
3442}
3443
3444impl Options {
3445 /// What these named parameters add up to.
3446 ///
3447 /// Each one was already checked against the function's list, so a name in here is a name that
3448 /// function takes and the value is already the type it wants. What is left is reading them, and
3449 /// the last one written wins, which is DuckDB's answer to `delim='|', delim=','` and was
3450 /// measured rather than assumed.
3451 fn of(written: &[(&'static str, Value, ExprRef)]) -> Result<Self> {
3452 let mut options = Self::default();
3453 for (parameter, value, _) in written {
3454 match (*parameter, value) {
3455 ("binary_as_string", Value::Boolean(on)) => options.binary_as_string = *on,
3456 ("all_varchar", Value::Boolean(on)) => options.all_varchar = *on,
3457 ("file_row_number", Value::Boolean(on)) => options.file_row_number = *on,
3458 _ => {}
3459 }
3460 }
3461 let named: Vec<(&str, Value)> =
3462 written.iter().map(|(parameter, value, _)| (*parameter, value.clone())).collect();
3463 options.given = csv_given(&named)?;
3464 Ok(options)
3465 }
3466}
3467
3468/// The one file a read names, canonical, with what the file system says about it now, or `None`
3469/// for a read of several files or of something that is not a regular file with a UTF-8 name.
3470fn mirror_target(paths: &[String]) -> Option<(String, FileStamp)> {
3471 let [path] = paths else { return None };
3472 let canonical = std::fs::canonicalize(path).ok()?;
3473 let stamp = FileStamp::of(&canonical)?;
3474 Some((canonical.to_str()?.to_string(), stamp))
3475}
3476
3477/// What was written between the two sides of a set operation.
3478#[derive(Clone, Copy)]
3479struct Operator {
3480 /// `UNION`, `EXCEPT` or `INTERSECT`.
3481 op: SetOp,
3482 /// `ALL`, `DISTINCT`, or neither, which means `DISTINCT` everywhere it is allowed.
3483 quantifier: Quantifier,
3484 /// Whether `BY NAME` was written, which only `UNION` takes.
3485 by_name: bool,
3486}
3487
3488/// One column of the result of a set operation, and where each side keeps it.
3489struct Merged {
3490 /// The name it comes out under, which is the left side's when both sides wrote it.
3491 name: String,
3492 /// What it is, after the two sides' types have met.
3493 ty: LogicalType,
3494 /// Which column of the left side it is, absent when only the right side wrote it.
3495 left: Option<usize>,
3496 /// Which column of the right side it is, absent when only the left side wrote it.
3497 right: Option<usize>,
3498}
3499
3500/// Matches the two sides of an ordinary set operation, which is first column to first column.
3501///
3502/// The names are the left side's, so `SELECT a FROM t UNION SELECT b FROM u` comes out as `a`.
3503fn match_by_position(left: &Scope, right: &Scope) -> Result<Vec<Merged>> {
3504 if left.len() != right.len() {
3505 return Err(Error::binder(format!(
3506 "Set operations can only apply to expressions with the same number of result columns, but left side has {} and right side has {}",
3507 left.len(),
3508 right.len()
3509 )));
3510 }
3511 let mut merged = Vec::with_capacity(left.len());
3512 for (at, (held, other)) in left.columns.iter().zip(&right.columns).enumerate() {
3513 merged.push(Merged {
3514 name: held.name.clone(),
3515 ty: meet(&held.ty, &other.ty)?,
3516 left: Some(at),
3517 right: Some(at),
3518 });
3519 }
3520 Ok(merged)
3521}
3522
3523/// Matches the two sides of a `UNION BY NAME`, which is by column name and not by position.
3524///
3525/// The result has the left side's columns in the order the left side wrote them, then the right
3526/// side's columns the left side did not write, in the order the right side wrote them. A column
3527/// only one side wrote is that side's type and the other side fills it with a null, which is why
3528/// nothing here needs the two sides to be the same width. Names match without regard to case, and
3529/// the spelling that comes out is the left side's, both of which follow the rest of the engine.
3530fn match_by_name(left: &Scope, right: &Scope) -> Result<Vec<Merged>> {
3531 named_once(left)?;
3532 named_once(right)?;
3533 let mut merged = Vec::with_capacity(left.len() + right.len());
3534 for (at, held) in left.columns.iter().enumerate() {
3535 let other = right.columns.iter().position(|column| same_name(&column.name, &held.name));
3536 let ty = match other {
3537 Some(other) => meet(&held.ty, &right.columns[other].ty)?,
3538 None => held.ty.clone(),
3539 };
3540 merged.push(Merged { name: held.name.clone(), ty, left: Some(at), right: other });
3541 }
3542 for (at, held) in right.columns.iter().enumerate() {
3543 if left.columns.iter().any(|column| same_name(&column.name, &held.name)) {
3544 continue;
3545 }
3546 merged.push(Merged {
3547 name: held.name.clone(),
3548 ty: held.ty.clone(),
3549 left: None,
3550 right: Some(at),
3551 });
3552 }
3553 Ok(merged)
3554}
3555
3556/// Refuses a side of a `UNION BY NAME` that wrote one name twice.
3557///
3558/// Matching by name needs the name to say which column, and a side that wrote `a` twice has no
3559/// answer to give. An ordinary union does not care, because there the position says which column.
3560/// The doubled quotes around the name are the reference binary's and not a mistake here.
3561fn named_once(scope: &Scope) -> Result<()> {
3562 for (at, held) in scope.columns.iter().enumerate() {
3563 if scope.columns[..at].iter().any(|column| same_name(&column.name, &held.name)) {
3564 return Err(Error::binder(format!(
3565 "UNION (ALL) BY NAME operation doesn't support duplicate names in the SELECT list - the name \"\"{}\"\" occurs multiple times",
3566 held.name
3567 )));
3568 }
3569 }
3570 Ok(())
3571}
3572
3573/// The one type a column of a set operation comes out as, given what each side wrote.
3574fn meet(left: &LogicalType, right: &LogicalType) -> Result<LogicalType> {
3575 left.promote(right).ok_or_else(|| {
3576 Error::binder(format!(
3577 "Cannot combine a column of type {left} with a column of type {right} in a set operation"
3578 ))
3579 })
3580}
3581
3582/// DuckDB's complaint about a named parameter that was given a null, which is a different sentence
3583/// for almost every parameter.
3584///
3585/// Three of them were measured on `v2.0.0-dev84237` and no two agree: `binary_as_string` is the
3586/// first, `all_varchar` is the second and `header` is the third. They read like three people each
3587/// writing the message in front of them, which is what they are, and a harness that compares error
3588/// text compares all of it. Anything not measured gets the first one, which is the most general of
3589/// the three.
3590fn null_parameter(function: TableFunction, parameter: &str) -> String {
3591 match parameter {
3592 "header" => format!("\"{parameter}\" expects a non-null boolean value (e.g. TRUE or 1)"),
3593 "all_varchar" => format!("{} \"{parameter}\" cannot be NULL", function.name()),
3594 _ => format!("Cannot use NULL as argument to \"{parameter}\""),
3595 }
3596}
3597
3598/// The complaint about a `REPLACE` entry that named a column the star did not stand for.
3599///
3600/// It reads like the complaint about any other name that is not there, down to the list of names
3601/// that are, because from the writer's side it is the same mistake.
3602fn missing_replacement(name: &str, input: &Scope) -> Error {
3603 Error::binder(format!(
3604 "Column \"{name}\" in REPLACE list not found in FROM clause{}",
3605 input.candidates()
3606 ))
3607}
3608
3609/// Whether a type is one `fill` can interpolate over, which is the pin's phrase for it.
3610///
3611/// The pin refuses `fill` with `FILL argument must support subtraction` and its sort key with
3612/// `FILL ordering must support subtraction`, and the two lists are not the same list, which is why
3613/// this takes a flag rather than answering one question. Every number is on both, so are `DATE`,
3614/// `TIME` and the two timestamps, and `TIME WITH TIME ZONE` is a sort key there but not an
3615/// argument. `INTERVAL` is on neither, which is worth saying out loud because an interval does
3616/// subtract: the sentence names subtraction and the rule is narrower than the sentence.
3617fn subtractable(ty: &LogicalType, ordering: bool) -> bool {
3618 if ty.is_numeric() {
3619 return true;
3620 }
3621 match ty {
3622 LogicalType::Date
3623 | LogicalType::Time
3624 | LogicalType::Timestamp
3625 | LogicalType::TimestampS
3626 | LogicalType::TimestampMs
3627 | LogicalType::TimestampNs
3628 | LogicalType::TimestampTz => true,
3629 LogicalType::TimeTz => ordering,
3630 _ => false,
3631 }
3632}
3633
3634/// Refuses a `fill` call the way the pin refuses one, in the pin's order.
3635///
3636/// The order was measured and it is not the order the clauses are written in. A `fill` over a
3637/// `VARCHAR` with no `ORDER BY` at all complains about the argument, so the argument is looked at
3638/// before the sort key is counted, and a `fill` with `DISTINCT` and no `ORDER BY` complains about
3639/// the `ORDER BY`, so the count comes before the clauses. `IGNORE NULLS` is refused here rather
3640/// than being answered as a no-op, since there is nothing for it to skip: `fill` is the one window
3641/// whose whole job is the nulls.
3642fn refuse_fill(
3643 argument: &LogicalType,
3644 order: &[LogicalType],
3645 distinct: bool,
3646 ignore_nulls: bool,
3647) -> Result<()> {
3648 if !subtractable(argument, false) {
3649 return Err(Error::binder("FILL argument must support subtraction"));
3650 }
3651 let [key] = order else {
3652 return Err(Error::binder("FILL functions must have only one ORDER BY expression"));
3653 };
3654 if !subtractable(key, true) {
3655 return Err(Error::binder("FILL ordering must support subtraction"));
3656 }
3657 if distinct {
3658 return Err(Error::binder(
3659 "DISTINCT is not implemented for the window function \"\"fill\"\"",
3660 ));
3661 }
3662 if ignore_nulls {
3663 return Err(Error::binder(
3664 "RESPECT/IGNORE NULLS is not supported for the window function \"fill\"",
3665 ));
3666 }
3667 Ok(())
3668}
3669
3670/// Resolves the call written inside an `OVER`.
3671///
3672/// Every aggregate is also a window, which is why this goes through the same signature table the
3673/// aggregate path uses, and the ranking windows go through it too because they are rows in the same
3674/// table. Everything else is one of three refusals, and all three are the reference binary's: a name
3675/// it knows as a scalar and a name it does not know at all each get their own sentence there.
3676fn window_signature(name: &str, types: &[LogicalType]) -> Result<Resolved> {
3677 match kind_of(name) {
3678 Some(FunctionKind::Aggregate | FunctionKind::Window) => resolve(name, types),
3679 Some(FunctionKind::Scalar) => {
3680 Err(Error::catalog(format!("{name} is not an aggregate function")))
3681 }
3682 None => Err(Error::catalog(format!("Aggregate Function with name {name} does not exist!"))),
3683 }
3684}
3685
3686/// Structural equality over two expressions of one plan.
3687fn same_expr(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
3688 if left == right {
3689 return true;
3690 }
3691 if plan.expr_type(left) != plan.expr_type(right) {
3692 return false;
3693 }
3694 let lists = |left, right| {
3695 let left: &[ExprRef] = plan.expr_list(left);
3696 let right: &[ExprRef] = plan.expr_list(right);
3697 left.len() == right.len()
3698 && left.iter().zip(right).all(|(&left, &right)| same_expr(plan, left, right))
3699 };
3700 match (plan.expr(left), plan.expr(right)) {
3701 (Expr::Column(left), Expr::Column(right)) => left == right,
3702 (Expr::Constant(left), Expr::Constant(right)) => plan.value(*left) == plan.value(*right),
3703 (
3704 Expr::Cast { input: left, try_cast: left_try },
3705 Expr::Cast { input: right, try_cast: right_try },
3706 ) => left_try == right_try && same_expr(plan, *left, *right),
3707 (
3708 Expr::Compare { op: left_op, left: left_a, right: left_b },
3709 Expr::Compare { op: right_op, left: right_a, right: right_b },
3710 ) => {
3711 left_op == right_op
3712 && same_expr(plan, *left_a, *right_a)
3713 && same_expr(plan, *left_b, *right_b)
3714 }
3715 (
3716 Expr::Conjunction { op: left_op, children: left_children },
3717 Expr::Conjunction { op: right_op, children: right_children },
3718 ) => left_op == right_op && lists(*left_children, *right_children),
3719 (
3720 Expr::Function { name: left_name, args: left_args },
3721 Expr::Function { name: right_name, args: right_args },
3722 ) => plan.string(*left_name) == plan.string(*right_name) && lists(*left_args, *right_args),
3723 (
3724 Expr::Aggregate {
3725 name: left_name,
3726 args: left_args,
3727 distinct: left_distinct,
3728 filter: left_filter,
3729 },
3730 Expr::Aggregate {
3731 name: right_name,
3732 args: right_args,
3733 distinct: right_distinct,
3734 filter: right_filter,
3735 },
3736 ) => {
3737 plan.string(*left_name) == plan.string(*right_name)
3738 && left_distinct == right_distinct
3739 && match (left_filter, right_filter) {
3740 (None, None) => true,
3741 (Some(left), Some(right)) => same_expr(plan, *left, *right),
3742 _ => false,
3743 }
3744 && lists(*left_args, *right_args)
3745 }
3746 // The partition, the order and the frame are not compared here and do not need to be. Two
3747 // window calls are only ever asked about when they are already in the same run, which is
3748 // what agreeing on all three means.
3749 (
3750 Expr::Window {
3751 name: left_name,
3752 args: left_args,
3753 distinct: left_distinct,
3754 filter: left_filter,
3755 ignore_nulls: left_nulls,
3756 order: left_order,
3757 },
3758 Expr::Window {
3759 name: right_name,
3760 args: right_args,
3761 distinct: right_distinct,
3762 filter: right_filter,
3763 ignore_nulls: right_nulls,
3764 order: right_order,
3765 },
3766 ) => {
3767 // The keys inside the brackets are compared, unlike the ones in the `OVER`, because two
3768 // calls in the same run can still read their frame in different orders.
3769 let left_keys = plan.sort_key_list(*left_order);
3770 let right_keys = plan.sort_key_list(*right_order);
3771 plan.string(*left_name) == plan.string(*right_name)
3772 && left_distinct == right_distinct
3773 && left_nulls == right_nulls
3774 && left_keys.len() == right_keys.len()
3775 && left_keys.iter().zip(right_keys).all(|(left, right)| {
3776 left.descending == right.descending
3777 && left.nulls_first == right.nulls_first
3778 && same_expr(plan, left.expr, right.expr)
3779 })
3780 && match (left_filter, right_filter) {
3781 (None, None) => true,
3782 (Some(left), Some(right)) => same_expr(plan, *left, *right),
3783 _ => false,
3784 }
3785 && lists(*left_args, *right_args)
3786 }
3787 (
3788 Expr::Case { arms: left_arms, otherwise: left_otherwise },
3789 Expr::Case { arms: right_arms, otherwise: right_otherwise },
3790 ) => {
3791 let left_arms = plan.arm_list(*left_arms);
3792 let right_arms = plan.arm_list(*right_arms);
3793 left_arms.len() == right_arms.len()
3794 && left_arms.iter().zip(right_arms).all(|(left, right)| {
3795 same_expr(plan, left.when, right.when) && same_expr(plan, left.then, right.then)
3796 })
3797 && match (left_otherwise, right_otherwise) {
3798 (None, None) => true,
3799 (Some(left), Some(right)) => same_expr(plan, *left, *right),
3800 _ => false,
3801 }
3802 }
3803 _ => false,
3804 }
3805}