1use rudb_catalog::{Catalog, Entry, QualifiedName, same_name};
16use rudb_common::{
17 Error, Field, LogicalType, Result, Semantics, Session, ShowBehavior, Span, Value,
18};
19use rudb_functions::{
20 Columns, FILE_ROW_NUMBER, FunctionKind, Given, Resolved, TableFunction, csv_fields, csv_given,
21 files, is_file, is_pattern, kind_of, parquet_fields, resolve, resolve_pragma, resolve_table,
22};
23use rudb_parse::ast::{self, Ast, Distinct, LiteralKind, Nulls, Order, Quantifier, SetOp};
24use rudb_parse::{NONE, identifier_parts, parse_ast_with_case};
25use rudb_plan::{
26 BuildSide, ColumnBinding, Expr, ExprRef, JoinKind, Node, NodeRef, Plan, SetOpKind, SortKey,
27 WindowBound, WindowExclude, WindowFrame, WindowUnit,
28};
29
30use crate::expr::{describe, has_aggregate};
31use crate::parameters::Parameters;
32use crate::scope::{Scope, Visible};
33
34pub fn bind(ast: &Ast, catalog: &Catalog) -> Result<Plan> {
41 bind_with(ast, catalog, &Parameters::new(), &Session::new())
42}
43
44pub fn bind_with(
53 ast: &Ast,
54 catalog: &Catalog,
55 parameters: &Parameters,
56 session: &Session,
57) -> Result<Plan> {
58 let query = match ast.statements.as_slice() {
59 [ast::Statement::Query(query)] => *query,
60 [] => return Err(Error::binder("no statement to bind")),
61 [_] => return Err(Error::not_implemented("a statement that is not a query")),
64 _ => return Err(Error::not_implemented("a script of more than one statement")),
65 };
66 let mut binder = Binder::with(catalog, parameters, session);
67 let (root, _) = binder.bind_query(ast, query)?;
68 let mut plan = binder.into_plan();
69 plan.set_root(root);
70 plan.validate()?;
71 Ok(plan)
72}
73
74pub fn bind_sql(query: &str, catalog: &Catalog) -> Result<Plan> {
80 bind_sql_with(query, catalog, &Session::new())
81}
82
83pub fn bind_sql_with(query: &str, catalog: &Catalog, session: &Session) -> Result<Plan> {
89 let ast = parse_ast_with_case(query, session.semantics().identifier_case())?;
90 bind_with(&ast, catalog, &Parameters::new(), session)
91}
92
93#[derive(Debug)]
95pub(crate) struct Aggregation {
96 pub(crate) index: u32,
98 pub(crate) groups: Vec<ExprRef>,
100 pub(crate) aggregates: Vec<ExprRef>,
102}
103
104#[derive(Debug)]
112pub(crate) struct WindowRun {
113 index: u32,
115 partition: Vec<ExprRef>,
117 order: Vec<SortKey>,
119 frame: WindowFrame,
121 calls: Vec<ExprRef>,
123}
124
125pub(crate) struct WindowCall<'a> {
130 pub(crate) name: &'a str,
132 pub(crate) args: &'a [ast::ExprRef],
134 pub(crate) distinct: bool,
136 pub(crate) filter: ast::ExprRef,
138 pub(crate) ignore_nulls: bool,
140 pub(crate) spec: ast::WindowRef,
142}
143
144struct WindowParts {
146 args: Vec<ExprRef>,
148 partition: Vec<ExprRef>,
150 order: Vec<SortKey>,
152 frame: WindowFrame,
154}
155
156#[derive(Debug)]
158struct Materialized {
159 written: u32,
161 cte: u32,
163 name: String,
165 fields: Vec<Field>,
167}
168
169#[derive(Debug)]
170pub(crate) struct PendingSubquery {
171 pub(crate) node: NodeRef,
172 pub(crate) kind: JoinKind,
173 pub(crate) conditions: Vec<ExprRef>,
174 pub(crate) dependent: bool,
175}
176
177#[derive(Debug)]
179pub(crate) struct Binder<'a> {
180 catalog: &'a Catalog,
181 pub(crate) parameters: &'a Parameters,
183 pub(crate) session: &'a Session,
185 pub(crate) semantics: Semantics,
187 plan: Plan,
188 next_index: u32,
189 pub(crate) current_span: Span,
191 pub(crate) aggregation: Option<Aggregation>,
193 pub(crate) in_aggregate: bool,
195 pub(crate) in_filter: bool,
197 pub(crate) windows: Vec<WindowRun>,
199 pub(crate) in_window: bool,
201 pub(crate) scalar_subqueries: Vec<PendingSubquery>,
203 pub(crate) outer_scopes: Vec<Scope>,
204 pub(crate) lateral_scopes: Vec<usize>,
211 pub(crate) correlations: Vec<Vec<ColumnBinding>>,
212 pub(crate) clause: &'static str,
214 expanding: Vec<String>,
216 materialized: Vec<Materialized>,
222 next_cte: u32,
224 started: Option<i64>,
226}
227
228impl<'a> Binder<'a> {
229 pub(crate) fn with(
230 catalog: &'a Catalog,
231 parameters: &'a Parameters,
232 session: &'a Session,
233 ) -> Self {
234 Self {
235 catalog,
236 parameters,
237 session,
238 semantics: session.semantics(),
239 plan: Plan::new(),
240 next_index: 0,
241 current_span: Span::new(0, 0),
242 aggregation: None,
243 in_aggregate: false,
244 in_filter: false,
245 windows: Vec::new(),
246 in_window: false,
247 scalar_subqueries: Vec::new(),
248 outer_scopes: Vec::new(),
249 lateral_scopes: Vec::new(),
250 correlations: Vec::new(),
251 clause: "SELECT clause",
252 expanding: Vec::new(),
253 materialized: Vec::new(),
254 next_cte: 0,
255 started: None,
256 }
257 }
258
259 pub(crate) fn catalog(&self) -> &Catalog {
260 self.catalog
261 }
262
263 pub(crate) fn instant(&mut self) -> i64 {
270 *self.started.get_or_insert_with(crate::context::micros_now)
271 }
272
273 pub(crate) fn plan(&self) -> &Plan {
274 &self.plan
275 }
276
277 pub(crate) fn plan_mut(&mut self) -> &mut Plan {
278 &mut self.plan
279 }
280
281 pub(crate) fn add_expr(&mut self, expr: Expr, ty: LogicalType) -> ExprRef {
282 self.plan.add_expr_at(expr, ty, self.current_span)
283 }
284
285 pub(crate) fn add_constant(&mut self, value: Value) -> ExprRef {
286 let ty = value.logical_type();
287 let reference = self.plan.add_value(value);
288 self.plan.add_expr_at(Expr::Constant(reference), ty, self.current_span)
289 }
290
291 pub(crate) fn add_node(&mut self, node: Node) -> NodeRef {
292 self.plan.add_node_at(node, self.current_span)
293 }
294
295 pub(crate) fn into_plan(self) -> Plan {
296 self.plan
297 }
298
299 pub(crate) fn fresh_index(&mut self) -> u32 {
301 let index = self.next_index;
302 self.next_index += 1;
303 index
304 }
305
306 fn column(&mut self, index: u32, position: usize, ty: LogicalType) -> ExprRef {
308 let binding = ColumnBinding::new(index, position as u32);
309 self.plan.add_expr(Expr::Column(binding), ty)
310 }
311
312 fn attach_scalar_subqueries(&mut self, mut input: NodeRef) -> NodeRef {
314 let subqueries = std::mem::take(&mut self.scalar_subqueries);
315 for pending in subqueries {
316 let PendingSubquery { node: mut right, kind, conditions, dependent } = pending;
317 if kind == JoinKind::Single && !self.semantics.scalar_subquery_error_on_multiple_rows()
318 {
319 right = self.add_node(Node::Limit { input: right, count: Some(1), offset: 0 });
320 }
321 let conditions = self.plan.add_expr_list(&conditions);
322 input = if dependent {
323 self.add_node(Node::DependentJoin { left: input, right, kind, conditions })
324 } else {
325 self.add_node(Node::Join {
326 left: input,
327 right,
328 kind,
329 conditions,
330 build: BuildSide::default(),
331 })
332 };
333 }
334 input
335 }
336
337 pub(crate) fn bind_query(
340 &mut self,
341 ast: &Ast,
342 query: ast::QueryRef,
343 ) -> Result<(NodeRef, Scope)> {
344 let span = ast.query_span(query);
345 let outer = std::mem::replace(&mut self.current_span, span);
346 let result =
347 self.bind_query_inner(ast, query).map_err(|error| error.with_fallback_span(span));
348 self.current_span = outer;
349 result
350 }
351
352 fn bind_query_inner(&mut self, ast: &Ast, query: ast::QueryRef) -> Result<(NodeRef, Scope)> {
353 let written = ast.query(query);
354 if written.ctes.is_empty() {
355 return self.bind_body(ast, &written);
356 }
357 let depth = self.materialized.len();
361 let result = self.bind_materialized(ast, &written);
362 self.materialized.truncate(depth);
363 result
364 }
365
366 fn bind_materialized(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
372 let depth = self.materialized.len();
373 let held = ast.cte_list(written.ctes).to_vec();
374 let mut definitions = Vec::with_capacity(held.len());
375 for &index in &held {
376 definitions.push(self.bind_definition(ast, index)?);
377 }
378 let (mut node, scope) = self.bind_body(ast, written)?;
379 for (at, definition) in definitions.into_iter().enumerate().rev() {
380 let entry = &self.materialized[depth + at];
381 let cte = entry.cte;
382 let name = entry.name.clone();
383 let fields = entry.fields.clone();
384 let name = self.plan.intern(&name);
385 let columns = self.plan.add_fields(&fields);
386 node =
387 self.add_node(Node::MaterializedCte { definition, body: node, name, cte, columns });
388 }
389 Ok((node, scope))
390 }
391
392 fn bind_definition(&mut self, ast: &Ast, index: u32) -> Result<NodeRef> {
402 let held = ast.cte(index);
403 let name = ast.string(held.name).to_string();
404 let (node, mut scope) = self.bind_query(ast, held.query)?;
405 if !held.columns.is_empty() {
406 let names: Vec<&str> = ast.name(held.columns).collect();
407 scope.rename_prefix(&names);
408 }
409 let table = self.fresh_index();
410 let mut exprs = Vec::with_capacity(scope.len());
411 let mut names = Vec::with_capacity(scope.len());
412 for column in &scope.columns {
413 exprs.push(self.plan.add_expr(Expr::Column(column.binding), column.ty.clone()));
414 names.push(self.plan.intern(&column.name));
415 }
416 let exprs = self.plan.add_expr_list(&exprs);
417 let names = self.plan.add_name_list(&names);
418 let node = self.add_node(Node::Project { input: node, index: table, exprs, names });
419 let cte = self.next_cte;
420 self.next_cte += 1;
421 self.materialized.push(Materialized { written: index, cte, name, fields: scope.fields() });
422 Ok(node)
423 }
424
425 fn bind_body(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
426 match written.body {
427 ast::QueryBody::Select(select) => self.bind_select(ast, select, written),
428 ast::QueryBody::SetOp { op, quantifier, by_name, left, right } => {
429 if by_name {
430 return Err(Error::not_implemented("UNION BY NAME"));
431 }
432 self.bind_set_op(ast, written, op, quantifier, left, right)
433 }
434 ast::QueryBody::Values(rows) => self.bind_values(ast, written, rows),
435 ast::QueryBody::Describe(inner) => self.bind_describe(ast, written, inner),
436 ast::QueryBody::Show { name, relation } => self.bind_show(ast, written, name, relation),
437 }
438 }
439
440 fn bind_show(
442 &mut self,
443 ast: &Ast,
444 query: &ast::Query,
445 name: ast::Slice,
446 relation: ast::QueryRef,
447 ) -> Result<(NodeRef, Scope)> {
448 let text = ast.name_text(name);
449 let parts: Vec<&str> = ast.name(name).collect();
450 let table_exists = self.catalog.resolve(&parts).is_ok();
451 let as_table = match self.semantics.show_behavior() {
452 ShowBehavior::Auto => table_exists,
453 ShowBehavior::Setting => false,
454 ShowBehavior::Table => true,
455 };
456 if as_table {
457 return self.bind_describe(ast, query, relation);
458 }
459 let Some((_, value)) =
460 self.session.iter().find(|(name, _)| name.eq_ignore_ascii_case(&text))
461 else {
462 return Err(Error::catalog(format!("Setting with name \"{text}\" does not exist")));
463 };
464 let field = Field::new(text, LogicalType::Varchar);
465 let expr = self.plan.add_constant(Value::Varchar(value.to_string()));
466 let row = self.plan.add_expr_list(&[expr]);
467 let rows = self.plan.add_rows(&[row]);
468 let columns = self.plan.add_fields(std::slice::from_ref(&field));
469 let index = self.fresh_index();
470 let node = self.add_node(Node::Values { index, columns, rows });
471 let mut scope = Scope::empty();
472 scope.push(Visible {
473 table: String::new(),
474 name: field.name,
475 binding: ColumnBinding::new(index, 0),
476 ty: LogicalType::Varchar,
477 not_null: false,
478 });
479 Ok((node, scope))
480 }
481
482 fn bind_describe(
498 &mut self,
499 ast: &Ast,
500 query: &ast::Query,
501 inner: ast::QueryRef,
502 ) -> Result<(NodeRef, Scope)> {
503 let (_, described) = self.bind_query(ast, inner)?;
504 let fields: Vec<Field> = ["column_name", "column_type", "null", "key", "default", "extra"]
505 .iter()
506 .map(|name| Field::new(*name, LogicalType::Varchar))
507 .collect();
508 let mut slices = Vec::with_capacity(described.columns.len());
509 for column in described.columns.clone() {
510 let written = [
513 column.name.clone(),
514 column.ty.to_string(),
515 if column.not_null { "NO" } else { "YES" }.to_owned(),
516 ];
517 let mut items: Vec<ExprRef> = written
518 .into_iter()
519 .map(|text| self.plan.add_constant(Value::Varchar(text)))
520 .collect();
521 for _ in 0..3 {
522 let empty = self.plan.add_constant(Value::Null);
523 items.push(self.cast_to(empty, &LogicalType::Varchar));
524 }
525 slices.push(self.plan.add_expr_list(&items));
526 }
527 let rows = self.plan.add_rows(&slices);
528 let columns = self.plan.add_fields(&fields);
529 let index = self.fresh_index();
530 let mut node = self.add_node(Node::Values { index, columns, rows });
531 let mut scope = Scope::empty();
532 for (at, field) in fields.iter().enumerate() {
533 scope.push(Visible {
534 table: String::new(),
535 name: field.name.clone(),
536 binding: ColumnBinding::new(index, at as u32),
537 ty: field.ty.clone(),
538 not_null: false,
539 });
540 }
541 let keys = self.sort_keys(ast, query, &scope, &[])?;
542 if !keys.is_empty() {
543 let keys = self.plan.add_sort_keys(&keys);
544 node = self.add_node(Node::Sort { input: node, keys });
545 }
546 node = self.apply_limit(ast, query, node)?;
547 Ok((node, scope))
548 }
549
550 fn passes_through(&self, expr: ExprRef, input: &Scope) -> bool {
556 let Expr::Column(binding) = *self.plan.expr(expr) else { return false };
557 input.columns.iter().any(|column| column.binding == binding && column.not_null)
558 }
559
560 fn bind_values(
567 &mut self,
568 ast: &Ast,
569 query: &ast::Query,
570 rows: ast::Slice,
571 ) -> Result<(NodeRef, Scope)> {
572 let written = ast.rows(rows).to_vec();
573 let Some(first) = written.first() else {
574 return Err(Error::binder("VALUES needs at least one row"));
575 };
576 let width = first.len as usize;
577 for (at, row) in written.iter().enumerate() {
578 if row.len as usize != width {
579 return Err(Error::binder(format!(
580 "VALUES lists must all be the same length, expected {width} columns but row {} has {}",
581 at + 1,
582 row.len
583 )));
584 }
585 }
586 let empty = Scope::empty();
588 let previous = std::mem::replace(&mut self.clause, "VALUES clause");
589 let mut bound: Vec<Vec<ExprRef>> = Vec::with_capacity(written.len());
590 for row in &written {
591 let mut items = Vec::with_capacity(width);
592 for &expr in ast.expr_list(*row) {
593 items.push(self.bind_expr(ast, expr, &empty)?);
594 }
595 bound.push(items);
596 }
597 self.clause = previous;
598 let mut types = Vec::with_capacity(width);
599 for at in 0..width {
600 let mut ty = self.plan.expr_type(bound[0][at]).clone();
601 for row in &bound[1..] {
602 let other = self.plan.expr_type(row[at]).clone();
603 ty = ty.promote(&other).ok_or_else(|| {
604 Error::binder(format!(
605 "Cannot combine a value of type {ty} with a value of type {other} in column {} of a VALUES",
606 at + 1
607 ))
608 })?;
609 }
610 types.push(ty);
611 }
612 let mut slices = Vec::with_capacity(bound.len());
613 for row in &bound {
614 let items: Vec<ExprRef> = row
615 .iter()
616 .zip(&types)
617 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
618 .collect::<Result<_>>()?;
619 slices.push(self.plan.add_expr_list(&items));
620 }
621 let rows = self.plan.add_rows(&slices);
622 let fields: Vec<Field> = types
623 .iter()
624 .enumerate()
625 .map(|(at, ty)| Field::new(format!("col{at}"), ty.clone()))
626 .collect();
627 let columns = self.plan.add_fields(&fields);
628 let index = self.fresh_index();
629 let mut node = self.add_node(Node::Values { index, columns, rows });
630 let mut scope = Scope::empty();
631 for (at, field) in fields.iter().enumerate() {
632 scope.push(Visible {
633 table: String::new(),
634 name: field.name.clone(),
635 binding: ColumnBinding::new(index, at as u32),
636 ty: field.ty.clone(),
637 not_null: false,
638 });
639 }
640 let keys = self.sort_keys(ast, query, &scope, &[])?;
641 if !keys.is_empty() {
642 let keys = self.plan.add_sort_keys(&keys);
643 node = self.add_node(Node::Sort { input: node, keys });
644 }
645 node = self.apply_limit(ast, query, node)?;
646 Ok((node, scope))
647 }
648
649 fn bind_set_op(
650 &mut self,
651 ast: &Ast,
652 query: &ast::Query,
653 op: SetOp,
654 quantifier: Quantifier,
655 left: ast::QueryRef,
656 right: ast::QueryRef,
657 ) -> Result<(NodeRef, Scope)> {
658 let (left_node, left_scope) = self.bind_query(ast, left)?;
659 let (right_node, right_scope) = self.bind_query(ast, right)?;
660 if left_scope.len() != right_scope.len() {
661 return Err(Error::binder(format!(
662 "Set operations can only apply to expressions with the same number of result columns, but left side has {} and right side has {}",
663 left_scope.len(),
664 right_scope.len()
665 )));
666 }
667 let mut types = Vec::with_capacity(left_scope.len());
669 for (left, right) in left_scope.columns.iter().zip(&right_scope.columns) {
670 let common = left.ty.promote(&right.ty).ok_or_else(|| {
671 Error::binder(format!(
672 "Cannot combine a column of type {} with a column of type {} in a set operation",
673 left.ty, right.ty
674 ))
675 })?;
676 types.push(common);
677 }
678 let left_node = self.conform(left_node, &left_scope, &types)?;
679 let right_node = self.conform(right_node, &right_scope, &types)?;
680 let index = self.fresh_index();
681 let kind = match op {
682 SetOp::Union => SetOpKind::Union,
683 SetOp::Except => SetOpKind::Except,
684 SetOp::Intersect => SetOpKind::Intersect,
685 };
686 let all = quantifier == Quantifier::All;
689 let mut node =
690 self.add_node(Node::SetOp { left: left_node, right: right_node, kind, all, index });
691 let mut scope = Scope::empty();
692 for (at, (column, ty)) in left_scope.columns.iter().zip(&types).enumerate() {
693 scope.push(Visible {
694 table: String::new(),
695 name: column.name.clone(),
696 binding: ColumnBinding::new(index, at as u32),
697 ty: ty.clone(),
698 not_null: false,
701 });
702 }
703 let keys = self.sort_keys(ast, query, &scope, &[])?;
707 if !keys.is_empty() {
708 let keys = self.plan.add_sort_keys(&keys);
709 node = self.add_node(Node::Sort { input: node, keys });
710 }
711 node = self.apply_limit(ast, query, node)?;
712 Ok((node, scope))
713 }
714
715 fn conform(&mut self, node: NodeRef, scope: &Scope, types: &[LogicalType]) -> Result<NodeRef> {
717 if scope.columns.iter().zip(types).all(|(column, ty)| &column.ty == ty) {
718 return Ok(node);
719 }
720 let index = self.fresh_index();
721 let mut exprs = Vec::with_capacity(types.len());
722 let mut names = Vec::with_capacity(types.len());
723 for (column, ty) in scope.columns.iter().zip(types) {
724 let expr = self.plan.add_expr(Expr::Column(column.binding), column.ty.clone());
725 exprs.push(self.checked_cast_to(expr, ty, false)?);
726 names.push(self.plan.intern(&column.name));
727 }
728 let exprs = self.plan.add_expr_list(&exprs);
729 let names = self.plan.add_name_list(&names);
730 Ok(self.add_node(Node::Project { input: node, index, exprs, names }))
731 }
732
733 fn bind_select(
736 &mut self,
737 ast: &Ast,
738 select: ast::SelectRef,
739 query: &ast::Query,
740 ) -> Result<(NodeRef, Scope)> {
741 let written = ast.select(select);
742 let outer_windows = std::mem::take(&mut self.windows);
746 let (mut node, input) = self.bind_from(ast, written.from)?;
747 node = self.attach_scalar_subqueries(node);
748
749 if written.filter != NONE {
750 self.clause = "WHERE clause";
751 let predicate = self.bind_expr(ast, written.filter, &input)?;
752 let predicate = self.as_boolean(predicate, "WHERE")?;
753 node = self.attach_scalar_subqueries(node);
754 node = self.add_node(Node::Filter { input: node, predicate });
755 }
756
757 let targets = ast.target_list(written.targets).to_vec();
758 if targets.is_empty() {
759 return Err(Error::binder("a SELECT needs at least one expression to select"));
760 }
761
762 let group_items = self.group_items(ast, &written, &targets)?;
763 let aggregating = !group_items.is_empty()
764 || written.having != NONE
765 || targets.iter().any(|target| has_aggregate(ast, target.expr));
766 if aggregating {
767 self.clause = "GROUP BY clause";
768 let mut groups = Vec::with_capacity(group_items.len());
769 for item in &group_items {
770 groups.push(self.bind_expr(ast, *item, &input)?);
771 }
772 let index = self.fresh_index();
773 self.aggregation = Some(Aggregation { index, groups, aggregates: Vec::new() });
774 }
775
776 self.clause = "SELECT clause";
777 let (mut exprs, mut names) = self.bind_targets(ast, &targets, &input)?;
778 let visible = exprs.len();
779
780 let mut having = None;
781 if written.having != NONE {
782 self.clause = "HAVING clause";
783 let predicate = self.bind_expr(ast, written.having, &input)?;
784 let predicate = self.over_aggregate(predicate, &input)?;
785 having = Some(self.as_boolean(predicate, "HAVING")?);
786 }
787
788 let project = self.fresh_index();
791 let mut output = Scope::empty();
792 for (at, (expr, name)) in exprs.iter().zip(&names).enumerate() {
793 output.push(Visible {
794 table: String::new(),
795 name: name.clone(),
796 binding: ColumnBinding::new(project, at as u32),
797 ty: self.plan.expr_type(*expr).clone(),
798 not_null: self.passes_through(*expr, &input),
799 });
800 }
801
802 self.clause = "ORDER BY clause";
803 let mut extra = Vec::new();
804 let keys = self.select_sort_keys(
805 ast, query, &input, &output, project, &mut exprs, &mut names, &mut extra,
806 )?;
807 if !extra.is_empty() && written.distinct != Distinct::No {
808 return Err(Error::binder(
809 "For SELECT DISTINCT, ORDER BY expressions must appear in the select list",
810 ));
811 }
812 let on = self.distinct_on(ast, written.distinct, &output)?;
813
814 node = self.attach_scalar_subqueries(node);
815
816 if let Some(aggregation) = self.aggregation.take() {
817 let index = aggregation.index;
818 let groups = self.plan.add_expr_list(&aggregation.groups);
819 let aggregates = self.plan.add_expr_list(&aggregation.aggregates);
820 node = self.add_node(Node::Aggregate { input: node, index, groups, aggregates });
821 }
822 if let Some(predicate) = having {
823 node = self.add_node(Node::Filter { input: node, predicate });
824 }
825
826 for run in std::mem::replace(&mut self.windows, outer_windows) {
830 let partition = self.plan.add_expr_list(&run.partition);
831 let order = self.plan.add_sort_keys(&run.order);
832 let expressions = self.plan.add_expr_list(&run.calls);
833 node = self.add_node(Node::Window {
834 input: node,
835 index: run.index,
836 partition,
837 order,
838 frame: run.frame,
839 expressions,
840 });
841 }
842
843 let interned: Vec<u32> = names.iter().map(|name| self.plan.intern(name)).collect();
844 let exprs_slice = self.plan.add_expr_list(&exprs);
845 let names_slice = self.plan.add_name_list(&interned);
846 node = self.add_node(Node::Project {
847 input: node,
848 index: project,
849 exprs: exprs_slice,
850 names: names_slice,
851 });
852
853 if written.distinct != Distinct::No {
854 let on = self.plan.add_expr_list(&on);
855 node = self.add_node(Node::Distinct { input: node, on });
856 }
857 if !keys.is_empty() {
858 let keys = self.plan.add_sort_keys(&keys);
859 node = self.add_node(Node::Sort { input: node, keys });
860 }
861 node = self.apply_limit(ast, query, node)?;
862
863 if extra.is_empty() {
864 output.columns.truncate(visible);
865 return Ok((node, output));
866 }
867 let index = self.fresh_index();
870 let mut kept = Vec::with_capacity(visible);
871 let mut kept_names = Vec::with_capacity(visible);
872 let mut scope = Scope::empty();
873 for (at, name) in names.iter().enumerate().take(visible) {
874 let ty = output.columns[at].ty.clone();
875 kept.push(self.column(project, at, ty.clone()));
876 kept_names.push(self.plan.intern(name));
877 scope.push(Visible {
878 table: String::new(),
879 name: name.clone(),
880 binding: ColumnBinding::new(index, at as u32),
881 ty,
882 not_null: output.columns[at].not_null,
883 });
884 }
885 let exprs = self.plan.add_expr_list(&kept);
886 let names = self.plan.add_name_list(&kept_names);
887 node = self.add_node(Node::Project { input: node, index, exprs, names });
888 Ok((node, scope))
889 }
890
891 fn bind_targets(
893 &mut self,
894 ast: &Ast,
895 targets: &[ast::Target],
896 input: &Scope,
897 ) -> Result<(Vec<ExprRef>, Vec<String>)> {
898 let mut exprs = Vec::with_capacity(targets.len());
899 let mut names = Vec::with_capacity(targets.len());
900 for target in targets {
901 if let ast::Expr::Star { qualifier, replacements } = ast.expr(target.expr) {
902 let table = ast.name(qualifier).last().map(str::to_string);
903 let expanded: Vec<Visible> =
904 input.star(table.as_deref())?.into_iter().cloned().collect();
905 let replacements = ast.target_list(replacements).to_vec();
906 let mut used = vec![false; replacements.len()];
907 for column in expanded {
908 let found = replacements.iter().zip(&mut used).find(|(replacement, _)| {
909 same_name(ast.string(replacement.alias), &column.name)
910 });
911 let (expr, name) = match found {
916 Some((replacement, used)) => {
917 *used = true;
918 let expr = self.bind_expr(ast, replacement.expr, input)?;
919 (expr, ast.string(replacement.alias).to_string())
920 }
921 None => (
922 self.plan.add_expr(Expr::Column(column.binding), column.ty),
923 column.name,
924 ),
925 };
926 exprs.push(self.over_aggregate(expr, input)?);
927 names.push(name);
928 }
929 if let Some((replacement, _)) =
933 replacements.iter().zip(&used).find(|(_, used)| !**used)
934 {
935 return Err(missing_replacement(ast.string(replacement.alias), input));
936 }
937 continue;
938 }
939 let expr = self.bind_expr(ast, target.expr, input)?;
940 exprs.push(self.over_aggregate(expr, input)?);
941 names.push(if target.alias == NONE {
942 self.output_name(ast, target.expr, input)
943 } else {
944 ast.string(target.alias).to_string()
945 });
946 }
947 Ok((exprs, names))
948 }
949
950 fn output_name(&self, ast: &Ast, target: ast::ExprRef, input: &Scope) -> String {
956 if let ast::Expr::Column { name } = ast.expr(target) {
957 let parts: Vec<&str> = ast.name(name).collect();
958 if let Ok(found) = input.resolve(&parts) {
959 return found.name.clone();
960 }
961 }
962 describe(ast, target, self.semantics)
963 }
964
965 fn group_items(
967 &self,
968 ast: &Ast,
969 select: &ast::Select,
970 targets: &[ast::Target],
971 ) -> Result<Vec<ast::ExprRef>> {
972 if select.group_by_all {
973 return Ok(targets
976 .iter()
977 .filter(|target| !has_aggregate(ast, target.expr))
978 .map(|target| target.expr)
979 .collect());
980 }
981 let mut items = Vec::new();
982 for &item in ast.expr_list(select.group_by) {
983 items.push(self.output_reference(ast, item, targets, "GROUP BY")?.unwrap_or(item));
984 }
985 Ok(items)
986 }
987
988 fn output_reference(
990 &self,
991 ast: &Ast,
992 item: ast::ExprRef,
993 targets: &[ast::Target],
994 clause: &str,
995 ) -> Result<Option<ast::ExprRef>> {
996 match ast.expr(item) {
997 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
998 let written = ast.string(text);
999 let position: usize = written.parse().map_err(|_| {
1000 Error::binder(format!("{clause} term {written} is not a column"))
1001 })?;
1002 if position == 0 || position > targets.len() {
1003 return Err(Error::binder(format!(
1004 "{clause} term out of range - should be between 1 and {}",
1005 targets.len()
1006 )));
1007 }
1008 Ok(Some(targets[position - 1].expr))
1009 }
1010 ast::Expr::Column { name } => {
1011 let parts: Vec<&str> = ast.name(name).collect();
1012 let [written] = parts.as_slice() else { return Ok(None) };
1013 let mut found = None;
1014 for target in targets {
1015 if target.alias != NONE && same_name(ast.string(target.alias), written) {
1016 if found.is_some() {
1017 return Ok(None);
1018 }
1019 found = Some(target.expr);
1020 }
1021 }
1022 Ok(found)
1023 }
1024 _ => Ok(None),
1025 }
1026 }
1027
1028 #[allow(clippy::too_many_arguments)]
1032 fn select_sort_keys(
1033 &mut self,
1034 ast: &Ast,
1035 query: &ast::Query,
1036 input: &Scope,
1037 output: &Scope,
1038 project: u32,
1039 exprs: &mut Vec<ExprRef>,
1040 names: &mut Vec<String>,
1041 extra: &mut Vec<usize>,
1042 ) -> Result<Vec<SortKey>> {
1043 if query.order_by_all {
1044 return Ok(self.every_column(output));
1045 }
1046 let items = ast.order_list(query.order_by).to_vec();
1047 let mut keys = Vec::with_capacity(items.len());
1048 for item in items {
1049 self.check_order_literal(ast, item.expr)?;
1050 let position = match self.output_position(ast, item.expr, output)? {
1051 Some(position) => position,
1052 None => {
1053 let bound = self.bind_expr(ast, item.expr, input)?;
1054 let bound = self.over_aggregate(bound, input)?;
1055 match exprs.iter().position(|&held| self.same_expr(held, bound)) {
1056 Some(position) => position,
1057 None => {
1058 exprs.push(bound);
1059 names.push(describe(ast, item.expr, self.semantics));
1060 extra.push(exprs.len() - 1);
1061 exprs.len() - 1
1062 }
1063 }
1064 }
1065 };
1066 let ty = self.plan.expr_type(exprs[position]).clone();
1067 let expr = self.column(project, position, ty);
1068 keys.push(self.sort_key(expr, item));
1069 }
1070 Ok(keys)
1071 }
1072
1073 fn sort_keys(
1075 &mut self,
1076 ast: &Ast,
1077 query: &ast::Query,
1078 output: &Scope,
1079 targets: &[ast::Target],
1080 ) -> Result<Vec<SortKey>> {
1081 if query.order_by_all {
1082 return Ok(self.every_column(output));
1083 }
1084 let items = ast.order_list(query.order_by).to_vec();
1085 let mut keys = Vec::with_capacity(items.len());
1086 for item in items {
1087 self.check_order_literal(ast, item.expr)?;
1088 let expr = match self.output_position(ast, item.expr, output)? {
1089 Some(position) => {
1090 let column = &output.columns[position];
1091 let (binding, ty) = (column.binding, column.ty.clone());
1092 self.plan.add_expr(Expr::Column(binding), ty)
1093 }
1094 None => {
1095 let _ = targets;
1096 self.bind_expr(ast, item.expr, output)?
1097 }
1098 };
1099 keys.push(self.sort_key(expr, item));
1100 }
1101 Ok(keys)
1102 }
1103
1104 fn every_column(&mut self, output: &Scope) -> Vec<SortKey> {
1105 let columns: Vec<(ColumnBinding, LogicalType)> =
1106 output.columns.iter().map(|column| (column.binding, column.ty.clone())).collect();
1107 columns
1108 .into_iter()
1109 .map(|(binding, ty)| {
1110 let expr = self.plan.add_expr(Expr::Column(binding), ty);
1111 let descending = self.semantics.default_descending();
1112 SortKey { expr, descending, nulls_first: self.semantics.nulls_first(descending) }
1113 })
1114 .collect()
1115 }
1116
1117 fn sort_key(&self, expr: ExprRef, item: ast::OrderItem) -> SortKey {
1119 let descending = match item.order {
1120 Order::Unstated => self.semantics.default_descending(),
1121 Order::Ascending => false,
1122 Order::Descending => true,
1123 };
1124 let nulls_first = match item.nulls {
1125 Nulls::First => true,
1126 Nulls::Last => false,
1127 Nulls::Unstated => self.semantics.nulls_first(descending),
1128 };
1129 SortKey { expr, descending, nulls_first }
1130 }
1131
1132 fn output_position(
1134 &self,
1135 ast: &Ast,
1136 item: ast::ExprRef,
1137 output: &Scope,
1138 ) -> Result<Option<usize>> {
1139 match ast.expr(item) {
1140 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1141 let written = ast.string(text);
1142 if written.contains(['.', 'e', 'E']) {
1143 return Ok(None);
1144 }
1145 let position: usize = written.parse().map_err(|_| {
1146 Error::binder(format!("ORDER BY term {written} is not a column"))
1147 })?;
1148 if position == 0 || position > output.len() {
1149 return Err(Error::binder(format!(
1150 "ORDER BY term out of range - should be between 1 and {}",
1151 output.len()
1152 )));
1153 }
1154 Ok(Some(position - 1))
1155 }
1156 ast::Expr::Column { name } => {
1157 let parts: Vec<&str> = ast.name(name).collect();
1158 let [written] = parts.as_slice() else { return Ok(None) };
1159 Ok(output.position_of(None, written))
1160 }
1161 _ => Ok(None),
1162 }
1163 }
1164
1165 fn check_order_literal(&self, ast: &Ast, item: ast::ExprRef) -> Result<()> {
1167 if !self.semantics.order_by_non_integer_literal()
1168 && matches!(
1169 ast.expr(item),
1170 ast::Expr::Literal { kind, text }
1171 if kind != LiteralKind::Number
1172 || ast.string(text).contains(['.', 'e', 'E'])
1173 )
1174 {
1175 return Err(Error::binder(
1176 "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to allow this behavior.",
1177 ));
1178 }
1179 Ok(())
1180 }
1181
1182 fn distinct_on(
1184 &mut self,
1185 ast: &Ast,
1186 distinct: Distinct,
1187 output: &Scope,
1188 ) -> Result<Vec<ExprRef>> {
1189 let Distinct::On(items) = distinct else {
1190 return Ok(Vec::new());
1191 };
1192 let items = ast.expr_list(items).to_vec();
1193 let mut on = Vec::with_capacity(items.len());
1194 for item in items {
1195 let Some(position) = self.output_position(ast, item, output)? else {
1196 return Err(Error::not_implemented(
1197 "DISTINCT ON an expression that is not in the select list",
1198 ));
1199 };
1200 let column = &output.columns[position];
1201 let (binding, ty) = (column.binding, column.ty.clone());
1202 on.push(self.plan.add_expr(Expr::Column(binding), ty));
1203 }
1204 Ok(on)
1205 }
1206
1207 fn apply_limit(&mut self, ast: &Ast, query: &ast::Query, input: NodeRef) -> Result<NodeRef> {
1208 if query.limit_percent {
1209 return Err(Error::not_implemented("LIMIT with a percentage"));
1210 }
1211 let count = self.constant_count(ast, query.limit, "LIMIT")?;
1212 let offset = self.constant_count(ast, query.offset, "OFFSET")?.unwrap_or(0);
1213 if count.is_none() && offset == 0 {
1214 return Ok(input);
1215 }
1216 Ok(self.add_node(Node::Limit { input, count, offset }))
1217 }
1218
1219 fn constant_count(
1221 &mut self,
1222 ast: &Ast,
1223 written: ast::ExprRef,
1224 clause: &str,
1225 ) -> Result<Option<u64>> {
1226 if written == NONE {
1227 return Ok(None);
1228 }
1229 self.clause = "LIMIT clause";
1230 let scope = Scope::empty();
1231 let bound = self.bind_expr(ast, written, &scope)?;
1232 let Expr::Constant(value) = *self.plan.expr(bound) else {
1233 return Err(Error::not_implemented(format!("a {clause} that is not a constant")));
1234 };
1235 let count = match self.plan.value(value) {
1236 Value::Null => return Ok(None),
1237 Value::TinyInt(count) => i128::from(*count),
1238 Value::SmallInt(count) => i128::from(*count),
1239 Value::Integer(count) => i128::from(*count),
1240 Value::BigInt(count) => i128::from(*count),
1241 Value::HugeInt(count) => *count,
1242 other => {
1243 return Err(Error::binder(format!(
1244 "{clause} takes a whole number of rows, not a value of type {}",
1245 other.logical_type()
1246 )));
1247 }
1248 };
1249 u64::try_from(count)
1250 .map(Some)
1251 .map_err(|_| Error::binder(format!("{clause} must not be negative")))
1252 }
1253
1254 fn bind_from(&mut self, ast: &Ast, from: ast::Slice) -> Result<(NodeRef, Scope)> {
1257 let sources = ast.source_list(from).to_vec();
1258 let Some((first, rest)) = sources.split_first() else {
1259 return Ok((self.add_node(Node::Dummy), Scope::empty()));
1262 };
1263 let (mut node, mut scope) = self.bind_source(ast, *first)?;
1264 for source in rest {
1265 let (right, right_scope, correlations) = self.bind_lateral(ast, *source, &scope)?;
1266 node = if correlations.is_empty() {
1267 self.add_node(Node::CrossProduct { left: node, right })
1268 } else {
1269 let conditions = self.plan.add_expr_list(&[]);
1270 self.add_node(Node::DependentJoin {
1271 left: node,
1272 right,
1273 kind: JoinKind::Inner,
1274 conditions,
1275 })
1276 };
1277 scope = scope.concat(right_scope);
1278 }
1279 Ok((node, scope))
1280 }
1281
1282 fn bind_lateral(
1294 &mut self,
1295 ast: &Ast,
1296 source: ast::SourceRef,
1297 left: &Scope,
1298 ) -> Result<(NodeRef, Scope, Vec<ColumnBinding>)> {
1299 self.lateral_scopes.push(self.outer_scopes.len());
1300 self.outer_scopes.push(left.clone());
1301 self.correlations.push(Vec::new());
1302 let bound = self.bind_source(ast, source);
1303 let read = self.correlations.pop().expect("correlation frame");
1304 self.outer_scopes.pop();
1305 self.lateral_scopes.pop();
1306 let (node, scope) = bound?;
1307
1308 let mut here = Vec::new();
1309 for binding in read {
1310 if left.columns.iter().any(|column| column.binding == binding) {
1311 here.push(binding);
1312 } else if let Some(enclosing) = self.correlations.last_mut() {
1313 if !enclosing.contains(&binding) {
1314 enclosing.push(binding);
1315 }
1316 }
1317 }
1318 if !here.is_empty() && matches!(ast.source(source), ast::Source::Function { .. }) {
1324 return Err(Error::not_implemented("a table function reading a LATERAL column"));
1325 }
1326 Ok((node, scope, here))
1327 }
1328
1329 fn bind_source(&mut self, ast: &Ast, source: ast::SourceRef) -> Result<(NodeRef, Scope)> {
1330 match ast.source(source) {
1331 ast::Source::Table { name, alias, columns } => {
1332 self.bind_table(ast, name, alias, columns)
1333 }
1334 ast::Source::Function { name, args, alias, columns, pragma } => {
1335 self.bind_table_function(ast, name, args, alias, columns, pragma)
1336 }
1337 ast::Source::Subquery { query, alias, columns } => {
1338 let (node, mut scope) = self.bind_query(ast, query)?;
1339 let label = if alias == NONE {
1340 "unnamed_subquery".to_string()
1341 } else {
1342 ast.string(alias).to_string()
1343 };
1344 scope.relabel(&label);
1345 if !columns.is_empty() {
1346 let names: Vec<&str> = ast.name(columns).collect();
1347 scope.rename(&names, &label)?;
1348 }
1349 Ok((node, scope))
1350 }
1351 ast::Source::Values { rows, alias, columns } => {
1352 let bare = ast::Query::bare(ast::QueryBody::Values(rows));
1353 let (node, mut scope) = self.bind_values(ast, &bare, rows)?;
1354 let label =
1355 if alias == NONE { String::new() } else { ast.string(alias).to_string() };
1356 scope.relabel(&label);
1357 if !columns.is_empty() {
1358 let names: Vec<&str> = ast.name(columns).collect();
1359 scope.rename(&names, &label)?;
1360 }
1361 Ok((node, scope))
1362 }
1363 ast::Source::Cte { cte, alias, columns } => {
1364 self.bind_cte_scan(ast, cte, alias, columns)
1365 }
1366 ast::Source::Join { left, right, kind, natural, on, using } => {
1367 self.bind_join(ast, left, right, kind, natural, on, using)
1368 }
1369 }
1370 }
1371
1372 fn bind_cte_scan(
1379 &mut self,
1380 ast: &Ast,
1381 written: u32,
1382 alias: ast::StrRef,
1383 columns: ast::Slice,
1384 ) -> Result<(NodeRef, Scope)> {
1385 let Some(held) = self.materialized.iter().rev().find(|held| held.written == written) else {
1386 let name = ast.string(ast.cte(written).name);
1387 return Err(Error::binder(format!("Table with name {name} does not exist!")));
1388 };
1389 let cte = held.cte;
1390 let fields = held.fields.clone();
1391 let text = held.name.clone();
1392 let label = if alias == NONE { text.clone() } else { ast.string(alias).to_string() };
1393 let name = self.plan.intern(&text);
1394 let index = self.fresh_index();
1395 let mut scope = Scope::empty();
1396 for (at, field) in fields.iter().enumerate() {
1397 scope.push(Visible {
1398 table: label.clone(),
1399 name: field.name.clone(),
1400 binding: ColumnBinding::new(index, at as u32),
1401 ty: field.ty.clone(),
1402 not_null: field.not_null,
1403 });
1404 }
1405 if !columns.is_empty() {
1406 let names: Vec<&str> = ast.name(columns).collect();
1407 scope.rename(&names, &label)?;
1408 }
1409 let columns = self.plan.add_fields(&fields);
1410 let node = self.add_node(Node::CteScan { index, cte, name, columns });
1411 Ok((node, scope))
1412 }
1413
1414 fn bind_table(
1415 &mut self,
1416 ast: &Ast,
1417 name: ast::Slice,
1418 alias: ast::StrRef,
1419 columns: ast::Slice,
1420 ) -> Result<(NodeRef, Scope)> {
1421 let parts: Vec<&str> = ast.name(name).collect();
1422 let catalog = self.catalog;
1423 let resolved = match catalog.resolve(&parts) {
1426 Ok(resolved) => resolved,
1427 Err(missing) => {
1428 return self.bind_replacement_scan(ast, &parts, alias, columns, missing);
1429 }
1430 };
1431 if catalog.entry(&resolved)? == Entry::View {
1432 return self.bind_view(ast, &resolved, alias, columns);
1433 }
1434 let table = catalog.table(&resolved)?;
1435 let fields: Vec<Field> = table.columns().to_vec();
1436 let label =
1437 if alias == NONE { resolved.table.clone() } else { ast.string(alias).to_string() };
1438 let index = self.fresh_index();
1439 let mut scope = Scope::empty();
1440 for (at, field) in fields.iter().enumerate() {
1441 scope.push(Visible {
1442 table: label.clone(),
1443 name: field.name.clone(),
1444 binding: ColumnBinding::new(index, at as u32),
1445 ty: field.ty.clone(),
1446 not_null: field.not_null,
1447 });
1448 }
1449 if !columns.is_empty() {
1450 let names: Vec<&str> = ast.name(columns).collect();
1451 scope.rename(&names, &label)?;
1452 }
1453 let catalog_name = self.plan.intern(&resolved.catalog);
1454 let schema = self.plan.intern(&resolved.schema);
1455 let table_name = self.plan.intern(&resolved.table);
1456 let alias = self.plan.intern(&label);
1457 let columns = self.plan.add_fields(&fields);
1458 let node = self.add_node(Node::Get {
1459 catalog: catalog_name,
1460 schema,
1461 table: table_name,
1462 alias,
1463 index,
1464 columns,
1465 });
1466 Ok((node, scope))
1467 }
1468
1469 fn bind_view(
1481 &mut self,
1482 ast: &Ast,
1483 name: &QualifiedName,
1484 alias: ast::StrRef,
1485 columns: ast::Slice,
1486 ) -> Result<(NodeRef, Scope)> {
1487 let view = self.catalog.view(name)?;
1488 let full = name.to_string();
1489 if self.expanding.contains(&full) {
1490 return Err(Error::binder(format!(
1494 "infinite recursion detected: attempting to recursively bind view \"\"{}\"\"",
1495 name.table
1496 )));
1497 }
1498 let body = parse_ast_with_case(view.sql(), self.semantics.identifier_case())?;
1499 let query = match body.statements.as_slice() {
1500 [ast::Statement::Query(query)] => *query,
1501 _ => return Err(Error::binder(format!("view \"{}\" is not a query", name.table))),
1504 };
1505 self.expanding.push(full);
1506 let bound = self.bind_query(&body, query);
1507 self.expanding.pop();
1508 let (node, mut scope) = bound?;
1509
1510 let aliases: Vec<&str> = view.aliases().iter().map(String::as_str).collect();
1511 if !aliases.is_empty() {
1512 scope.rename(&aliases, "unnamed_subquery")?;
1513 }
1514 view.remember(scope.fields());
1521 let label = if alias == NONE { name.table.clone() } else { ast.string(alias).to_string() };
1522 scope.relabel(&label);
1523 if !columns.is_empty() {
1524 let names: Vec<&str> = ast.name(columns).collect();
1525 scope.rename(&names, &label)?;
1526 }
1527 Ok((node, scope))
1528 }
1529
1530 fn bind_table_function(
1538 &mut self,
1539 ast: &Ast,
1540 name: ast::Slice,
1541 args: ast::Slice,
1542 alias: ast::StrRef,
1543 columns: ast::Slice,
1544 pragma: bool,
1545 ) -> Result<(NodeRef, Scope)> {
1546 let parts: Vec<&str> = ast.name(name).collect();
1547 let function_name = *parts.last().unwrap_or(&"");
1551 if let Some(schema) = parts.iter().rev().nth(1) {
1552 if !schema.eq_ignore_ascii_case("main") && !schema.eq_ignore_ascii_case("system") {
1553 return Err(Error::catalog(format!(
1554 "Table Function with name {} does not exist!",
1555 parts.join(".")
1556 )));
1557 }
1558 }
1559 let Some(called) = TableFunction::lookup(function_name) else {
1563 if pragma {
1564 if args.is_empty() && self.catalog.resolve(&parts).is_ok() {
1570 return self.bind_table(ast, name, alias, columns);
1571 }
1572 let spelled = function_name.strip_prefix("pragma_").unwrap_or(function_name);
1573 return Err(Error::catalog(format!(
1574 "Pragma Function with name {spelled} does not exist!"
1575 )));
1576 }
1577 return Err(Error::catalog(format!(
1578 "Table Function with name {function_name} does not exist!"
1579 )));
1580 };
1581 let written = ast.target_list(args).to_vec();
1582 let empty = Scope::empty();
1583 let previous = std::mem::replace(&mut self.clause, "table function arguments");
1584 let mut bound = Vec::new();
1585 let mut written_options = Vec::new();
1586 for argument in written {
1587 let expr = self.bind_expr(ast, argument.expr, &empty)?;
1588 if argument.alias == NONE {
1589 bound.push(expr);
1590 } else {
1591 let name = ast.string(argument.alias).to_string();
1592 let (parameter, value) = self.named_argument(called, &name, expr)?;
1593 written_options.push((parameter, value, expr));
1594 }
1595 }
1596 self.clause = previous;
1597 let options = Options::of(&written_options)?;
1598
1599 let given: Vec<LogicalType> =
1602 bound.iter().map(|&expr| self.plan.expr_type(expr).clone()).collect();
1603 let resolved = if pragma {
1604 resolve_pragma(function_name, &given)?
1605 } else {
1606 resolve_table(function_name, &given)?
1607 };
1608 let mut cast: Vec<ExprRef> = bound
1609 .iter()
1610 .zip(&resolved.arguments)
1611 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
1612 .collect::<Result<_>>()?;
1613
1614 if resolved.function.takes_a_name() {
1615 let Columns::Fixed(fields) = resolved.columns else {
1616 return Err(Error::internal("a pragma that resolved to a file"));
1617 };
1618 let [argument] = cast[..] else {
1619 return Err(Error::internal("a pragma that resolved to more than one name"));
1620 };
1621 return self.bind_pragma(ast, resolved.function, &fields, argument, alias, columns);
1622 }
1623 let fields = match resolved.columns {
1624 Columns::Fixed(fields) => fields,
1625 columns => {
1626 let paths = self.file_paths(cast[0], resolved.function.name())?;
1631 let first = paths.first().map_or("", String::as_str);
1632 let mut fields = match columns {
1633 Columns::Csv => csv_fields(&paths, options.given)?,
1636 _ => parquet_fields(first)?,
1637 };
1638 if options.all_varchar {
1639 for field in &mut fields {
1644 field.ty = LogicalType::Varchar;
1645 }
1646 }
1647 if options.binary_as_string {
1648 for field in &mut fields {
1653 if field.ty == LogicalType::Blob {
1654 field.ty = LogicalType::Varchar;
1655 }
1656 }
1657 }
1658 if options.file_row_number {
1659 if fields.iter().any(|field| field.name == FILE_ROW_NUMBER) {
1665 return Err(Error::binder(format!(
1666 "Duplicate column name \"{FILE_ROW_NUMBER}\": the file already has a \
1667 column of that name, so file_row_number cannot add one"
1668 )));
1669 }
1670 fields.push(Field::required(FILE_ROW_NUMBER.to_string(), LogicalType::BigInt));
1671 }
1672 cast = paths.iter().map(|path| self.path_constant(path)).collect();
1673 fields
1674 }
1675 };
1676 let label = if alias == NONE {
1677 resolved.function.name().to_string()
1678 } else {
1679 ast.string(alias).to_string()
1680 };
1681 let names: Vec<&str> = ast.name(columns).collect();
1682 self.table_function_source(
1683 resolved.function,
1684 &cast,
1685 &written_options,
1686 fields,
1687 &label,
1688 &names,
1689 )
1690 }
1691
1692 fn bind_pragma(
1705 &mut self,
1706 ast: &Ast,
1707 function: TableFunction,
1708 fields: &[Field],
1709 argument: ExprRef,
1710 alias: ast::StrRef,
1711 columns: ast::Slice,
1712 ) -> Result<(NodeRef, Scope)> {
1713 let written = self.pragma_name(argument, function)?;
1714 let parts = identifier_parts(&written);
1715 let spelled: Vec<&str> = parts.iter().map(String::as_str).collect();
1716 let name = self.catalog.resolve(&spelled)?;
1717 let described = self.described(ast, &name)?;
1718 let mut rows = Vec::with_capacity(described.len());
1719 for (at, field) in described.iter().enumerate() {
1720 let items = if matches!(function, TableFunction::PragmaShow) {
1721 self.describing(field)
1722 } else {
1723 self.table_info(at, field)
1724 };
1725 rows.push(self.plan.add_expr_list(&items));
1726 }
1727 let rows = self.plan.add_rows(&rows);
1728 let held = self.plan.add_fields(fields);
1729 let index = self.fresh_index();
1730 let node = self.add_node(Node::Values { index, columns: held, rows });
1731 let label =
1732 if alias == NONE { function.name().to_string() } else { ast.string(alias).to_string() };
1733 let mut scope = Scope::empty();
1734 for (at, field) in fields.iter().enumerate() {
1735 scope.push(Visible {
1736 table: label.clone(),
1737 name: field.name.clone(),
1738 binding: ColumnBinding::new(index, at as u32),
1739 ty: field.ty.clone(),
1740 not_null: false,
1741 });
1742 }
1743 if !columns.is_empty() {
1744 let names: Vec<&str> = ast.name(columns).collect();
1745 scope.rename(&names, &label)?;
1746 }
1747 Ok((node, scope))
1748 }
1749
1750 fn pragma_name(&self, argument: ExprRef, function: TableFunction) -> Result<String> {
1760 let Expr::Constant(reference) = *self.plan.expr(argument) else {
1761 return Err(Error::not_implemented(format!(
1762 "{}() given a name that is not a constant",
1763 function.name()
1764 )));
1765 };
1766 match self.plan.value(reference) {
1767 Value::Varchar(name) => Ok(name.clone()),
1768 Value::Null => Ok("NULL".to_string()),
1769 other => {
1770 Err(Error::internal(format!("a pragma name bound as VARCHAR arrived as {other}")))
1771 }
1772 }
1773 }
1774
1775 fn described(&mut self, ast: &Ast, name: &QualifiedName) -> Result<Vec<Field>> {
1786 if self.catalog.entry(name)? == Entry::Table {
1787 return Ok(self.catalog.table(name)?.columns().to_vec());
1788 }
1789 let (_, scope) = self.bind_view(ast, name, NONE, ast::Slice::default())?;
1790 Ok(scope.fields())
1791 }
1792
1793 fn describing(&mut self, field: &Field) -> Vec<ExprRef> {
1795 let written = [
1796 field.name.clone(),
1797 field.ty.to_string(),
1798 if field.not_null { "NO" } else { "YES" }.to_owned(),
1799 ];
1800 let mut items: Vec<ExprRef> =
1801 written.into_iter().map(|text| self.plan.add_constant(Value::Varchar(text))).collect();
1802 for _ in 0..3 {
1803 let empty = self.plan.add_constant(Value::Null);
1804 items.push(self.cast_to(empty, &LogicalType::Varchar));
1805 }
1806 items
1807 }
1808
1809 fn table_info(&mut self, at: usize, field: &Field) -> Vec<ExprRef> {
1815 let cid = self.plan.add_constant(Value::Integer(i32::try_from(at).unwrap_or(i32::MAX)));
1816 let name = self.plan.add_constant(Value::Varchar(field.name.clone()));
1817 let ty = self.plan.add_constant(Value::Varchar(field.ty.to_string()));
1818 let not_null = self.plan.add_constant(Value::Boolean(field.not_null));
1819 let default = self.plan.add_constant(Value::Null);
1820 let default = self.cast_to(default, &LogicalType::Varchar);
1821 let key = self.plan.add_constant(Value::Boolean(false));
1822 vec![cid, name, ty, not_null, default, key]
1823 }
1824
1825 fn named_argument(
1839 &mut self,
1840 function: TableFunction,
1841 name: &str,
1842 expr: ExprRef,
1843 ) -> Result<(&'static str, Value)> {
1844 let known = function
1845 .parameters()
1846 .iter()
1847 .find(|(parameter, _)| parameter.eq_ignore_ascii_case(name));
1848 let Some((parameter, wanted)) = known else {
1849 let candidates: Vec<String> = function
1850 .parameters()
1851 .iter()
1852 .map(|(parameter, ty)| format!(" {parameter} {ty}"))
1853 .collect();
1854 return Err(Error::binder(format!(
1855 "Invalid named parameter \"{name}\" for function {}\nCandidates:\n{}\n",
1856 function.name(),
1857 candidates.join("\n")
1858 )));
1859 };
1860 let Expr::Constant(reference) = *self.plan.expr(expr) else {
1861 return Err(Error::not_implemented(format!(
1862 "the named parameter {parameter} with a value that is not a constant"
1863 )));
1864 };
1865 let value = self.plan.value(reference).clone();
1866 if value == Value::Null {
1867 return Err(Error::binder(null_parameter(function, parameter)));
1868 }
1869 let given = self.plan.expr_type(expr).clone();
1870 if given != *wanted {
1871 return Err(Error::not_implemented(format!(
1872 "the named parameter {parameter} given a {given} where a {wanted} was wanted"
1873 )));
1874 }
1875 Ok((parameter, value))
1876 }
1877
1878 fn bind_replacement_scan(
1889 &mut self,
1890 ast: &Ast,
1891 parts: &[&str],
1892 alias: ast::StrRef,
1893 columns: ast::Slice,
1894 missing: Error,
1895 ) -> Result<(NodeRef, Scope)> {
1896 let [path] = parts else { return Err(missing) };
1897 let path = *path;
1898 let extension = path.rsplit_once('.').map(|(_, after)| after).unwrap_or_default();
1899 let Some(function) = Self::reader_for(extension) else {
1900 if is_file(path) {
1901 return Err(Error::binder(format!(
1906 "No extension found that is capable of reading the file \"{path}\"\n* If this \
1907 file is a supported file format you can explicitly use the reader functions, \
1908 such as read_csv, read_json or read_parquet"
1909 )));
1910 }
1911 return Err(missing);
1912 };
1913 let paths = files(path)?;
1918 let first = paths.first().map_or("", String::as_str);
1919 let fields = match function {
1920 TableFunction::ReadParquet => parquet_fields(first)?,
1921 _ => csv_fields(&paths, Given::default())?,
1922 };
1923 let label = if alias == NONE {
1929 if is_pattern(path) {
1930 path.to_string()
1931 } else {
1932 let file = path.rsplit_once('/').map_or(path, |(_, file)| file);
1933 file.rsplit_once('.').map_or(file, |(stem, _)| stem).to_string()
1934 }
1935 } else {
1936 ast.string(alias).to_string()
1937 };
1938 let arguments: Vec<ExprRef> = paths.iter().map(|path| self.path_constant(path)).collect();
1939 let names: Vec<&str> = ast.name(columns).collect();
1940 self.table_function_source(function, &arguments, &[], fields, &label, &names)
1941 }
1942
1943 fn path_constant(&mut self, path: &str) -> ExprRef {
1945 let value = self.plan.add_value(Value::Varchar(path.to_string()));
1946 self.plan.add_expr(Expr::Constant(value), LogicalType::Varchar)
1947 }
1948
1949 fn reader_for(extension: &str) -> Option<TableFunction> {
1956 if extension.eq_ignore_ascii_case("parquet") {
1957 return Some(TableFunction::ReadParquet);
1958 }
1959 if extension.eq_ignore_ascii_case("csv") || extension.eq_ignore_ascii_case("tsv") {
1960 return Some(TableFunction::ReadCsv);
1961 }
1962 None
1963 }
1964
1965 fn table_function_source(
1970 &mut self,
1971 function: TableFunction,
1972 args: &[ExprRef],
1973 written: &[(&'static str, Value, ExprRef)],
1974 fields: Vec<Field>,
1975 label: &str,
1976 names: &[&str],
1977 ) -> Result<(NodeRef, Scope)> {
1978 let index = self.fresh_index();
1979 let mut scope = Scope::empty();
1980 for (at, field) in fields.iter().enumerate() {
1981 scope.push(Visible {
1982 table: label.to_string(),
1983 name: field.name.clone(),
1984 binding: ColumnBinding::new(index, at as u32),
1985 ty: field.ty.clone(),
1986 not_null: false,
1989 });
1990 }
1991 if !names.is_empty() {
1992 scope.rename(names, label)?;
1993 }
1994 let function = self.plan.intern(function.name());
1995 let args = self.plan.add_expr_list(args);
1996 let named: Vec<u32> =
1997 written.iter().map(|(parameter, _, _)| self.plan.intern(parameter)).collect();
1998 let settings: Vec<ExprRef> = written.iter().map(|(_, _, expr)| *expr).collect();
1999 let options = self.plan.add_name_list(&named);
2000 let settings = self.plan.add_expr_list(&settings);
2001 let columns = self.plan.add_fields(&fields);
2002 let node = self.add_node(Node::TableFunction {
2003 index,
2004 function,
2005 args,
2006 options,
2007 settings,
2008 columns,
2009 });
2010 Ok((node, scope))
2011 }
2012
2013 fn file_paths(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2020 let mut paths = Vec::new();
2021 for pattern in self.file_patterns(expr, name)? {
2022 paths.extend(files(&pattern)?);
2023 }
2024 Ok(paths)
2025 }
2026
2027 fn file_patterns(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2039 let Expr::Constant(reference) = *self.plan.expr(expr) else {
2040 return Err(Error::not_implemented(
2041 "a table function file name that is not a constant",
2042 ));
2043 };
2044 match self.plan.value(reference) {
2045 Value::Varchar(path) => Ok(vec![path.clone()]),
2046 Value::Null => Err(Error::parser(format!("{name} cannot take NULL list as parameter"))),
2048 Value::List { values, .. } => values
2049 .iter()
2050 .map(|value| match value {
2051 Value::Varchar(path) => Ok(path.clone()),
2052 _ => Err(Error::parser(format!(
2053 "{name} reader cannot take NULL input as parameter"
2054 ))),
2055 })
2056 .collect(),
2057 other => {
2058 Err(Error::internal(format!("a file name bound as VARCHAR arrived as {other}")))
2059 }
2060 }
2061 }
2062
2063 #[allow(clippy::too_many_arguments)]
2064 fn bind_join(
2065 &mut self,
2066 ast: &Ast,
2067 left: ast::SourceRef,
2068 right: ast::SourceRef,
2069 kind: ast::JoinKind,
2070 natural: bool,
2071 on: ast::ExprRef,
2072 using: ast::Slice,
2073 ) -> Result<(NodeRef, Scope)> {
2074 let (left_node, left_scope) = self.bind_source(ast, left)?;
2075 let (right_node, right_scope, correlated) = self.bind_lateral(ast, right, &left_scope)?;
2076 if !correlated.is_empty()
2080 && !matches!(kind, ast::JoinKind::Inner | ast::JoinKind::Cross | ast::JoinKind::Left)
2081 {
2082 return Err(Error::binder(
2083 "The combining JOIN type must be INNER or LEFT for a LATERAL reference",
2084 ));
2085 }
2086 let split = left_scope.len();
2087 let mut scope = left_scope.concat(right_scope);
2088
2089 let merged: Vec<String> = if natural {
2092 let mut names = Vec::new();
2093 for (at, column) in scope.columns.iter().enumerate().take(split) {
2094 if scope.columns[split..].iter().any(|right| same_name(&right.name, &column.name))
2095 && !names.iter().any(|held: &String| same_name(held, &column.name))
2096 {
2097 let _ = at;
2098 names.push(column.name.clone());
2099 }
2100 }
2101 names
2102 } else {
2103 let mut names: Vec<String> = Vec::new();
2109 for name in ast.name(using) {
2110 if !names.iter().any(|held| same_name(held, name)) {
2111 names.push(name.to_string());
2112 }
2113 }
2114 names
2115 };
2116
2117 let mut conditions = Vec::new();
2118 let mut dropped = Vec::new();
2119 for name in &merged {
2120 let left_at = scope.columns[..split]
2121 .iter()
2122 .position(|column| same_name(&column.name, name))
2123 .ok_or_else(|| {
2124 Error::binder(format!(
2125 "column \"{name}\" specified in USING clause does not exist in left table"
2126 ))
2127 })?;
2128 let right_at = scope.columns[split..]
2129 .iter()
2130 .position(|column| same_name(&column.name, name))
2131 .map(|at| at + split)
2132 .ok_or_else(|| {
2133 Error::binder(format!(
2134 "column \"{name}\" specified in USING clause does not exist in right table"
2135 ))
2136 })?;
2137 let left_column = &scope.columns[left_at];
2138 let (left_binding, left_type) = (left_column.binding, left_column.ty.clone());
2139 let right_column = &scope.columns[right_at];
2140 let (right_binding, right_type) = (right_column.binding, right_column.ty.clone());
2141 let left_expr = self.plan.add_expr(Expr::Column(left_binding), left_type);
2142 let right_expr = self.plan.add_expr(Expr::Column(right_binding), right_type);
2143 conditions.push(self.compare(rudb_plan::CompareOp::Equal, left_expr, right_expr)?);
2144 dropped.push(right_at);
2145 }
2146 dropped.sort_unstable();
2149 for at in dropped.into_iter().rev() {
2150 scope.remove(at);
2151 }
2152
2153 if on != NONE {
2154 if !merged.is_empty() {
2155 return Err(Error::binder("a join cannot have both ON and USING"));
2156 }
2157 self.clause = "JOIN condition";
2158 let predicate = self.bind_expr(ast, on, &scope)?;
2159 conditions.push(self.as_boolean(predicate, "JOIN")?);
2160 }
2161
2162 if kind == ast::JoinKind::Cross && !conditions.is_empty() {
2163 return Err(Error::binder("a CROSS JOIN cannot have a condition"));
2164 }
2165 if correlated.is_empty()
2169 && conditions.is_empty()
2170 && matches!(kind, ast::JoinKind::Cross | ast::JoinKind::Inner)
2171 {
2172 let node = self.add_node(Node::CrossProduct { left: left_node, right: right_node });
2173 return Ok((node, scope));
2174 }
2175 let kind = match kind {
2176 ast::JoinKind::Inner | ast::JoinKind::Cross => JoinKind::Inner,
2177 ast::JoinKind::Left => JoinKind::Left,
2178 ast::JoinKind::Right => JoinKind::Right,
2179 ast::JoinKind::Full => JoinKind::Full,
2180 ast::JoinKind::Semi => JoinKind::Semi,
2181 ast::JoinKind::Anti => JoinKind::Anti,
2182 ast::JoinKind::Positional => JoinKind::Positional,
2183 };
2184 let conditions = self.plan.add_expr_list(&conditions);
2185 let node = if correlated.is_empty() {
2186 self.add_node(Node::Join {
2187 left: left_node,
2188 right: right_node,
2189 kind,
2190 conditions,
2191 build: BuildSide::default(),
2192 })
2193 } else {
2194 self.add_node(Node::DependentJoin {
2195 left: left_node,
2196 right: right_node,
2197 kind,
2198 conditions,
2199 })
2200 };
2201 Ok((node, scope))
2202 }
2203
2204 fn bind_filter(
2212 &mut self,
2213 ast: &Ast,
2214 filter: ast::ExprRef,
2215 scope: &Scope,
2216 ) -> Result<Option<ExprRef>> {
2217 if filter == NONE {
2218 return Ok(None);
2219 }
2220 let bound = self.bind_expr(ast, filter, scope)?;
2221 Ok(Some(self.checked_cast_to(bound, &LogicalType::Boolean, false)?))
2222 }
2223
2224 pub(crate) fn bind_aggregate(
2226 &mut self,
2227 ast: &Ast,
2228 name: &str,
2229 args: &[ast::ExprRef],
2230 distinct: bool,
2231 filter: ast::ExprRef,
2232 scope: &Scope,
2233 ) -> Result<ExprRef> {
2234 if self.in_filter {
2235 return Err(Error::binder("aggregate functions are not allowed in FILTER"));
2236 }
2237 if self.in_aggregate {
2238 return Err(Error::binder(format!(
2239 "aggregate function calls cannot be nested, and {name}() is inside one"
2240 )));
2241 }
2242 if self.aggregation.is_none() {
2243 return Err(Error::binder(format!(
2244 "aggregate function calls cannot be used in the {}",
2245 self.clause
2246 )));
2247 }
2248 self.in_aggregate = true;
2253 self.in_filter = true;
2254 let filter = self.bind_filter(ast, filter, scope);
2255 self.in_filter = false;
2256 self.in_aggregate = false;
2257 let filter = filter?;
2258
2259 self.in_aggregate = true;
2260 let mut bound = Vec::with_capacity(args.len());
2261 let mut failure = None;
2262 for &arg in args {
2263 match self.bind_expr(ast, arg, scope) {
2264 Ok(expr) => bound.push(expr),
2265 Err(error) => {
2266 failure = Some(error);
2267 break;
2268 }
2269 }
2270 }
2271 self.in_aggregate = false;
2272 if let Some(error) = failure {
2273 return Err(error);
2274 }
2275
2276 let types: Vec<LogicalType> =
2277 bound.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2278 let resolved = resolve(name, &types)?;
2279 let mut cast = Vec::with_capacity(bound.len());
2280 for (arg, wanted) in bound.iter().zip(&resolved.arguments) {
2281 cast.push(self.checked_cast_to(*arg, wanted, false)?);
2282 }
2283 let args = self.plan.add_expr_list(&cast);
2284 let name = self.plan.intern(resolved.name);
2285 let ty = resolved.returns;
2286 let call = self.plan.add_expr(Expr::Aggregate { name, args, distinct, filter }, ty.clone());
2287
2288 let existing = self.aggregation.as_ref().map(|held| held.aggregates.clone());
2291 let existing = existing.unwrap_or_default();
2292 let at = match existing.iter().position(|&held| self.same_expr(held, call)) {
2293 Some(at) => at,
2294 None => {
2295 let aggregation = self.aggregation.as_mut().expect("checked above");
2296 aggregation.aggregates.push(call);
2297 aggregation.aggregates.len() - 1
2298 }
2299 };
2300 let aggregation = self.aggregation.as_ref().expect("checked above");
2301 let (index, groups) = (aggregation.index, aggregation.groups.len());
2302 Ok(self.column(index, groups + at, ty))
2303 }
2304
2305 pub(crate) fn bind_window(
2313 &mut self,
2314 ast: &Ast,
2315 written: &WindowCall<'_>,
2316 scope: &Scope,
2317 ) -> Result<ExprRef> {
2318 let WindowCall { name, args, distinct, filter, ignore_nulls, spec } = *written;
2319 if self.in_aggregate {
2320 return Err(Error::binder(
2321 "aggregate function calls cannot contain window function calls",
2322 ));
2323 }
2324 if self.in_window {
2325 return Err(Error::binder("window function calls cannot be nested"));
2326 }
2327 let clause = if self.clause == "JOIN condition" { "WHERE clause" } else { self.clause };
2331 if clause != "SELECT clause" && clause != "ORDER BY clause" {
2332 return Err(Error::binder(format!("{clause} cannot contain window functions!")));
2333 }
2334
2335 let starred = args.iter().any(|&arg| {
2339 matches!(ast.expr(arg), ast::Expr::Star { qualifier, replacements }
2340 if qualifier.is_empty() && replacements.is_empty())
2341 });
2342 let (name, args): (&str, &[ast::ExprRef]) = if starred {
2343 if !same_name(name, "count") || args.len() != 1 {
2344 return Err(Error::binder(format!("* is not allowed in {name}()")));
2345 }
2346 ("count_star", &[])
2347 } else if same_name(name, "count") && args.is_empty() {
2348 ("count_star", &[])
2351 } else {
2352 (name, args)
2353 };
2354
2355 let held = ast.window(spec);
2356 self.in_window = true;
2357 let parts = self.window_parts(ast, args, held, scope);
2358 let filter = if parts.is_ok() { self.bind_filter(ast, filter, scope) } else { Ok(None) };
2363 self.in_window = false;
2364 let parts = parts?;
2365 let filter = filter?;
2366 let offsets = [parts.frame.start, parts.frame.end]
2369 .iter()
2370 .any(|end| matches!(end, WindowBound::Preceding(_) | WindowBound::Following(_)));
2371 if parts.frame.unit == WindowUnit::Range && offsets && parts.order.len() != 1 {
2372 return Err(Error::binder("RANGE frames must have only one ORDER BY expression"));
2373 }
2374
2375 let types: Vec<LogicalType> =
2376 parts.args.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2377 let resolved = window_signature(name, &types)?;
2378 if resolved.name == "fill" {
2381 let keys: Vec<LogicalType> =
2382 parts.order.iter().map(|key| self.plan.expr_type(key.expr).clone()).collect();
2383 refuse_fill(&types[0], &keys, distinct, ignore_nulls)?;
2384 }
2385 if distinct && kind_of(resolved.name) == Some(FunctionKind::Window) {
2389 return Err(Error::binder(format!(
2390 "DISTINCT is not implemented for the window function \"\"{name}\"\""
2391 )));
2392 }
2393 if filter.is_some() && kind_of(resolved.name) == Some(FunctionKind::Window) {
2396 return Err(Error::binder(format!(
2397 "FILTER is not implemented for the window function \"\"{name}\"\""
2398 )));
2399 }
2400 let mut cast = Vec::with_capacity(parts.args.len());
2401 for (arg, wanted) in parts.args.iter().zip(&resolved.arguments) {
2402 cast.push(self.checked_cast_to(*arg, wanted, false)?);
2403 }
2404 let args = self.plan.add_expr_list(&cast);
2405 let name = self.plan.intern(resolved.name);
2406 let ty = resolved.returns;
2407 let call = self
2408 .plan
2409 .add_expr(Expr::Window { name, args, distinct, filter, ignore_nulls }, ty.clone());
2410
2411 let at = self.window_run(parts.partition, parts.order, parts.frame, call);
2412 let index = self.windows.last().expect("the run was just filed").index;
2413 Ok(self.column(index, at, ty))
2414 }
2415
2416 fn window_run(
2423 &mut self,
2424 partition: Vec<ExprRef>,
2425 order: Vec<SortKey>,
2426 frame: WindowFrame,
2427 call: ExprRef,
2428 ) -> usize {
2429 let matches = self.windows.last().is_some_and(|run| {
2430 run.frame == frame
2431 && run.partition.len() == partition.len()
2432 && run.order.len() == order.len()
2433 && run.partition.iter().zip(&partition).all(|(&l, &r)| self.same_expr(l, r))
2434 && run.order.iter().zip(&order).all(|(l, r)| {
2435 l.descending == r.descending
2436 && l.nulls_first == r.nulls_first
2437 && self.same_expr(l.expr, r.expr)
2438 })
2439 });
2440 if !matches {
2441 let index = self.fresh_index();
2442 self.windows.push(WindowRun { index, partition, order, frame, calls: Vec::new() });
2443 }
2444 let calls = self.windows.last().expect("a run is open").calls.clone();
2447 if let Some(at) = calls.iter().position(|&held| self.same_expr(held, call)) {
2448 return at;
2449 }
2450 let run = self.windows.last_mut().expect("a run is open");
2451 run.calls.push(call);
2452 run.calls.len() - 1
2453 }
2454
2455 fn window_parts(
2461 &mut self,
2462 ast: &Ast,
2463 args: &[ast::ExprRef],
2464 held: ast::WindowSpec,
2465 scope: &Scope,
2466 ) -> Result<WindowParts> {
2467 let mut bound = Vec::with_capacity(args.len());
2468 for &arg in args {
2469 let expr = self.bind_expr(ast, arg, scope)?;
2470 bound.push(self.over_aggregate(expr, scope)?);
2471 }
2472 let mut partition = Vec::new();
2473 for &key in ast.expr_list(held.partition) {
2474 let expr = self.bind_expr(ast, key, scope)?;
2475 partition.push(self.over_aggregate(expr, scope)?);
2476 }
2477 let mut order = Vec::new();
2478 for item in ast.order_list(held.order).to_vec() {
2479 let expr = self.bind_expr(ast, item.expr, scope)?;
2480 let expr = self.over_aggregate(expr, scope)?;
2481 order.push(self.sort_key(expr, item));
2482 }
2483 let frame = WindowFrame {
2484 unit: match held.unit {
2485 ast::WindowUnit::Rows => WindowUnit::Rows,
2486 ast::WindowUnit::Range => WindowUnit::Range,
2487 ast::WindowUnit::Groups => WindowUnit::Groups,
2488 },
2489 start: self.window_bound(ast, held.start, scope)?,
2490 end: self.window_bound(ast, held.end, scope)?,
2491 exclude: match held.exclude {
2492 ast::WindowExclude::NoOthers => WindowExclude::NoOthers,
2493 ast::WindowExclude::CurrentRow => WindowExclude::CurrentRow,
2494 ast::WindowExclude::Group => WindowExclude::Group,
2495 ast::WindowExclude::Ties => WindowExclude::Ties,
2496 },
2497 };
2498 Ok(WindowParts { args: bound, partition, order, frame })
2499 }
2500
2501 fn window_bound(
2503 &mut self,
2504 ast: &Ast,
2505 bound: ast::WindowBound,
2506 scope: &Scope,
2507 ) -> Result<WindowBound> {
2508 let offset = |binder: &mut Self, written| {
2509 let expr = binder.bind_expr(ast, written, scope)?;
2510 binder.over_aggregate(expr, scope)
2511 };
2512 Ok(match bound {
2513 ast::WindowBound::UnboundedPreceding => WindowBound::UnboundedPreceding,
2514 ast::WindowBound::CurrentRow => WindowBound::CurrentRow,
2515 ast::WindowBound::UnboundedFollowing => WindowBound::UnboundedFollowing,
2516 ast::WindowBound::Preceding(written) => WindowBound::Preceding(offset(self, written)?),
2517 ast::WindowBound::Following(written) => WindowBound::Following(offset(self, written)?),
2518 })
2519 }
2520
2521 fn is_window_output(&self, binding: ColumnBinding) -> bool {
2523 self.windows.iter().any(|run| run.index == binding.table)
2524 }
2525
2526 pub(crate) fn over_aggregate(&mut self, expr: ExprRef, scope: &Scope) -> Result<ExprRef> {
2532 let Some(aggregation) = self.aggregation.as_ref() else {
2533 return Ok(expr);
2534 };
2535 let index = aggregation.index;
2536 let groups = aggregation.groups.clone();
2537 for (at, group) in groups.iter().enumerate() {
2538 if self.same_expr(expr, *group) {
2539 let ty = self.plan.expr_type(*group).clone();
2540 return Ok(self.column(index, at, ty));
2541 }
2542 }
2543 let ty = self.plan.expr_type(expr).clone();
2544 match self.plan.expr(expr).clone() {
2545 Expr::Column(binding) if binding.table == index => Ok(expr),
2546 Expr::Column(binding) if self.is_window_output(binding) => Ok(expr),
2551 Expr::Column(binding) => {
2552 let name =
2553 scope.columns.iter().find(|column| column.binding == binding).map_or_else(
2554 || "a column".to_string(),
2555 |column| format!("\"{}\"", column.name),
2556 );
2557 Err(Error::binder(format!(
2558 "column {name} must appear in the GROUP BY clause or must be part of an aggregate function"
2559 )))
2560 }
2561 Expr::Constant(_) | Expr::Aggregate { .. } | Expr::Window { .. } => Ok(expr),
2562 Expr::Cast { input, try_cast } => {
2563 let input = self.over_aggregate(input, scope)?;
2564 Ok(self.plan.add_expr(Expr::Cast { input, try_cast }, ty))
2565 }
2566 Expr::Compare { op, left, right } => {
2567 let left = self.over_aggregate(left, scope)?;
2568 let right = self.over_aggregate(right, scope)?;
2569 Ok(self.plan.add_expr(Expr::Compare { op, left, right }, ty))
2570 }
2571 Expr::Conjunction { op, children } => {
2572 let written = self.plan.expr_list(children).to_vec();
2573 let mut rewritten = Vec::with_capacity(written.len());
2574 for child in written {
2575 rewritten.push(self.over_aggregate(child, scope)?);
2576 }
2577 let children = self.plan.add_expr_list(&rewritten);
2578 Ok(self.plan.add_expr(Expr::Conjunction { op, children }, ty))
2579 }
2580 Expr::Function { name, args } => {
2581 let written = self.plan.expr_list(args).to_vec();
2582 let mut rewritten = Vec::with_capacity(written.len());
2583 for arg in written {
2584 rewritten.push(self.over_aggregate(arg, scope)?);
2585 }
2586 let args = self.plan.add_expr_list(&rewritten);
2587 Ok(self.plan.add_expr(Expr::Function { name, args }, ty))
2588 }
2589 Expr::Case { arms, otherwise } => {
2590 let written = self.plan.arm_list(arms).to_vec();
2591 let mut rewritten = Vec::with_capacity(written.len());
2592 for arm in written {
2593 let when = self.over_aggregate(arm.when, scope)?;
2594 let then = self.over_aggregate(arm.then, scope)?;
2595 rewritten.push(rudb_plan::Arm { when, then });
2596 }
2597 let otherwise = match otherwise {
2598 Some(expr) => Some(self.over_aggregate(expr, scope)?),
2599 None => None,
2600 };
2601 let arms = self.plan.add_arms(&rewritten);
2602 Ok(self.plan.add_expr(Expr::Case { arms, otherwise }, ty))
2603 }
2604 }
2605 }
2606
2607 pub(crate) fn same_expr(&self, left: ExprRef, right: ExprRef) -> bool {
2609 same_expr(&self.plan, left, right)
2610 }
2611}
2612
2613#[derive(Debug, Default)]
2623struct Options {
2624 binary_as_string: bool,
2627 all_varchar: bool,
2629 file_row_number: bool,
2634 given: Given,
2636}
2637
2638impl Options {
2639 fn of(written: &[(&'static str, Value, ExprRef)]) -> Result<Self> {
2646 let mut options = Self::default();
2647 for (parameter, value, _) in written {
2648 match (*parameter, value) {
2649 ("binary_as_string", Value::Boolean(on)) => options.binary_as_string = *on,
2650 ("all_varchar", Value::Boolean(on)) => options.all_varchar = *on,
2651 ("file_row_number", Value::Boolean(on)) => options.file_row_number = *on,
2652 _ => {}
2653 }
2654 }
2655 let named: Vec<(&str, Value)> =
2656 written.iter().map(|(parameter, value, _)| (*parameter, value.clone())).collect();
2657 options.given = csv_given(&named)?;
2658 Ok(options)
2659 }
2660}
2661
2662fn null_parameter(function: TableFunction, parameter: &str) -> String {
2671 match parameter {
2672 "header" => format!("\"{parameter}\" expects a non-null boolean value (e.g. TRUE or 1)"),
2673 "all_varchar" => format!("{} \"{parameter}\" cannot be NULL", function.name()),
2674 _ => format!("Cannot use NULL as argument to \"{parameter}\""),
2675 }
2676}
2677
2678fn missing_replacement(name: &str, input: &Scope) -> Error {
2683 Error::binder(format!(
2684 "Column \"{name}\" in REPLACE list not found in FROM clause{}",
2685 input.candidates()
2686 ))
2687}
2688
2689fn subtractable(ty: &LogicalType, ordering: bool) -> bool {
2698 if ty.is_numeric() {
2699 return true;
2700 }
2701 match ty {
2702 LogicalType::Date
2703 | LogicalType::Time
2704 | LogicalType::Timestamp
2705 | LogicalType::TimestampS
2706 | LogicalType::TimestampMs
2707 | LogicalType::TimestampNs
2708 | LogicalType::TimestampTz => true,
2709 LogicalType::TimeTz => ordering,
2710 _ => false,
2711 }
2712}
2713
2714fn refuse_fill(
2723 argument: &LogicalType,
2724 order: &[LogicalType],
2725 distinct: bool,
2726 ignore_nulls: bool,
2727) -> Result<()> {
2728 if !subtractable(argument, false) {
2729 return Err(Error::binder("FILL argument must support subtraction"));
2730 }
2731 let [key] = order else {
2732 return Err(Error::binder("FILL functions must have only one ORDER BY expression"));
2733 };
2734 if !subtractable(key, true) {
2735 return Err(Error::binder("FILL ordering must support subtraction"));
2736 }
2737 if distinct {
2738 return Err(Error::binder(
2739 "DISTINCT is not implemented for the window function \"\"fill\"\"",
2740 ));
2741 }
2742 if ignore_nulls {
2743 return Err(Error::binder(
2744 "RESPECT/IGNORE NULLS is not supported for the window function \"fill\"",
2745 ));
2746 }
2747 Ok(())
2748}
2749
2750fn window_signature(name: &str, types: &[LogicalType]) -> Result<Resolved> {
2757 match kind_of(name) {
2758 Some(FunctionKind::Aggregate | FunctionKind::Window) => resolve(name, types),
2759 Some(FunctionKind::Scalar) => {
2760 Err(Error::catalog(format!("{name} is not an aggregate function")))
2761 }
2762 None => Err(Error::catalog(format!("Aggregate Function with name {name} does not exist!"))),
2763 }
2764}
2765
2766fn same_expr(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
2768 if left == right {
2769 return true;
2770 }
2771 if plan.expr_type(left) != plan.expr_type(right) {
2772 return false;
2773 }
2774 let lists = |left, right| {
2775 let left: &[ExprRef] = plan.expr_list(left);
2776 let right: &[ExprRef] = plan.expr_list(right);
2777 left.len() == right.len()
2778 && left.iter().zip(right).all(|(&left, &right)| same_expr(plan, left, right))
2779 };
2780 match (plan.expr(left), plan.expr(right)) {
2781 (Expr::Column(left), Expr::Column(right)) => left == right,
2782 (Expr::Constant(left), Expr::Constant(right)) => plan.value(*left) == plan.value(*right),
2783 (
2784 Expr::Cast { input: left, try_cast: left_try },
2785 Expr::Cast { input: right, try_cast: right_try },
2786 ) => left_try == right_try && same_expr(plan, *left, *right),
2787 (
2788 Expr::Compare { op: left_op, left: left_a, right: left_b },
2789 Expr::Compare { op: right_op, left: right_a, right: right_b },
2790 ) => {
2791 left_op == right_op
2792 && same_expr(plan, *left_a, *right_a)
2793 && same_expr(plan, *left_b, *right_b)
2794 }
2795 (
2796 Expr::Conjunction { op: left_op, children: left_children },
2797 Expr::Conjunction { op: right_op, children: right_children },
2798 ) => left_op == right_op && lists(*left_children, *right_children),
2799 (
2800 Expr::Function { name: left_name, args: left_args },
2801 Expr::Function { name: right_name, args: right_args },
2802 ) => plan.string(*left_name) == plan.string(*right_name) && lists(*left_args, *right_args),
2803 (
2804 Expr::Aggregate {
2805 name: left_name,
2806 args: left_args,
2807 distinct: left_distinct,
2808 filter: left_filter,
2809 },
2810 Expr::Aggregate {
2811 name: right_name,
2812 args: right_args,
2813 distinct: right_distinct,
2814 filter: right_filter,
2815 },
2816 ) => {
2817 plan.string(*left_name) == plan.string(*right_name)
2818 && left_distinct == right_distinct
2819 && match (left_filter, right_filter) {
2820 (None, None) => true,
2821 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2822 _ => false,
2823 }
2824 && lists(*left_args, *right_args)
2825 }
2826 (
2830 Expr::Window {
2831 name: left_name,
2832 args: left_args,
2833 distinct: left_distinct,
2834 filter: left_filter,
2835 ignore_nulls: left_nulls,
2836 },
2837 Expr::Window {
2838 name: right_name,
2839 args: right_args,
2840 distinct: right_distinct,
2841 filter: right_filter,
2842 ignore_nulls: right_nulls,
2843 },
2844 ) => {
2845 plan.string(*left_name) == plan.string(*right_name)
2846 && left_distinct == right_distinct
2847 && left_nulls == right_nulls
2848 && match (left_filter, right_filter) {
2849 (None, None) => true,
2850 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2851 _ => false,
2852 }
2853 && lists(*left_args, *right_args)
2854 }
2855 (
2856 Expr::Case { arms: left_arms, otherwise: left_otherwise },
2857 Expr::Case { arms: right_arms, otherwise: right_otherwise },
2858 ) => {
2859 let left_arms = plan.arm_list(*left_arms);
2860 let right_arms = plan.arm_list(*right_arms);
2861 left_arms.len() == right_arms.len()
2862 && left_arms.iter().zip(right_arms).all(|(left, right)| {
2863 same_expr(plan, left.when, right.when) && same_expr(plan, left.then, right.then)
2864 })
2865 && match (left_otherwise, right_otherwise) {
2866 (None, None) => true,
2867 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2868 _ => false,
2869 }
2870 }
2871 _ => false,
2872 }
2873}