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 pub(crate) index: u32,
181}
182
183#[derive(Debug)]
185pub(crate) struct Binder<'a> {
186 catalog: &'a Catalog,
187 pub(crate) parameters: &'a Parameters,
189 pub(crate) session: &'a Session,
191 pub(crate) semantics: Semantics,
193 plan: Plan,
194 next_index: u32,
195 pub(crate) current_span: Span,
197 pub(crate) aggregation: Option<Aggregation>,
199 pub(crate) in_aggregate: bool,
201 pub(crate) in_filter: bool,
203 pub(crate) windows: Vec<WindowRun>,
205 pub(crate) in_window: bool,
207 pub(crate) scalar_subqueries: Vec<PendingSubquery>,
209 pub(crate) joined_above: Vec<u32>,
215 pub(crate) outer_scopes: Vec<Scope>,
216 pub(crate) lateral_scopes: Vec<usize>,
223 pub(crate) correlations: Vec<Vec<ColumnBinding>>,
224 pub(crate) clause: &'static str,
226 expanding: Vec<String>,
228 materialized: Vec<Materialized>,
234 next_cte: u32,
236 started: Option<i64>,
238}
239
240impl<'a> Binder<'a> {
241 pub(crate) fn with(
242 catalog: &'a Catalog,
243 parameters: &'a Parameters,
244 session: &'a Session,
245 ) -> Self {
246 Self {
247 catalog,
248 parameters,
249 session,
250 semantics: session.semantics(),
251 plan: Plan::new(),
252 next_index: 0,
253 current_span: Span::new(0, 0),
254 aggregation: None,
255 in_aggregate: false,
256 in_filter: false,
257 windows: Vec::new(),
258 in_window: false,
259 scalar_subqueries: Vec::new(),
260 joined_above: Vec::new(),
261 outer_scopes: Vec::new(),
262 lateral_scopes: Vec::new(),
263 correlations: Vec::new(),
264 clause: "SELECT clause",
265 expanding: Vec::new(),
266 materialized: Vec::new(),
267 next_cte: 0,
268 started: None,
269 }
270 }
271
272 pub(crate) fn catalog(&self) -> &Catalog {
273 self.catalog
274 }
275
276 pub(crate) fn instant(&mut self) -> i64 {
283 *self.started.get_or_insert_with(crate::context::micros_now)
284 }
285
286 pub(crate) fn plan(&self) -> &Plan {
287 &self.plan
288 }
289
290 pub(crate) fn plan_mut(&mut self) -> &mut Plan {
291 &mut self.plan
292 }
293
294 pub(crate) fn add_expr(&mut self, expr: Expr, ty: LogicalType) -> ExprRef {
295 self.plan.add_expr_at(expr, ty, self.current_span)
296 }
297
298 pub(crate) fn add_constant(&mut self, value: Value) -> ExprRef {
299 let ty = value.logical_type();
300 let reference = self.plan.add_value(value);
301 self.plan.add_expr_at(Expr::Constant(reference), ty, self.current_span)
302 }
303
304 pub(crate) fn add_node(&mut self, node: Node) -> NodeRef {
305 self.plan.add_node_at(node, self.current_span)
306 }
307
308 pub(crate) fn into_plan(self) -> Plan {
309 self.plan
310 }
311
312 pub(crate) fn fresh_index(&mut self) -> u32 {
314 let index = self.next_index;
315 self.next_index += 1;
316 index
317 }
318
319 fn column(&mut self, index: u32, position: usize, ty: LogicalType) -> ExprRef {
321 let binding = ColumnBinding::new(index, position as u32);
322 self.plan.add_expr(Expr::Column(binding), ty)
323 }
324
325 fn attach_scalar_subqueries(&mut self, mut input: NodeRef) -> NodeRef {
327 let subqueries = std::mem::take(&mut self.scalar_subqueries);
328 for pending in subqueries {
329 let PendingSubquery { node: mut right, kind, conditions, dependent, index: _ } =
330 pending;
331 if kind == JoinKind::Single && !self.semantics.scalar_subquery_error_on_multiple_rows()
332 {
333 right = self.add_node(Node::Limit { input: right, count: Some(1), offset: 0 });
334 }
335 let conditions = self.plan.add_expr_list(&conditions);
336 input = if dependent {
337 self.add_node(Node::DependentJoin { left: input, right, kind, conditions })
338 } else {
339 self.add_node(Node::Join {
340 left: input,
341 right,
342 kind,
343 conditions,
344 build: BuildSide::default(),
345 })
346 };
347 }
348 input
349 }
350
351 pub(crate) fn bind_query(
354 &mut self,
355 ast: &Ast,
356 query: ast::QueryRef,
357 ) -> Result<(NodeRef, Scope)> {
358 let span = ast.query_span(query);
359 let outer = std::mem::replace(&mut self.current_span, span);
360 let result =
361 self.bind_query_inner(ast, query).map_err(|error| error.with_fallback_span(span));
362 self.current_span = outer;
363 result
364 }
365
366 fn bind_query_inner(&mut self, ast: &Ast, query: ast::QueryRef) -> Result<(NodeRef, Scope)> {
367 let written = ast.query(query);
368 if written.ctes.is_empty() {
369 return self.bind_body(ast, &written);
370 }
371 let depth = self.materialized.len();
375 let result = self.bind_materialized(ast, &written);
376 self.materialized.truncate(depth);
377 result
378 }
379
380 fn bind_materialized(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
386 let depth = self.materialized.len();
387 let held = ast.cte_list(written.ctes).to_vec();
388 let mut definitions = Vec::with_capacity(held.len());
389 for &index in &held {
390 definitions.push(self.bind_definition(ast, index)?);
391 }
392 let (mut node, scope) = self.bind_body(ast, written)?;
393 for (at, definition) in definitions.into_iter().enumerate().rev() {
394 let entry = &self.materialized[depth + at];
395 let cte = entry.cte;
396 let name = entry.name.clone();
397 let fields = entry.fields.clone();
398 let name = self.plan.intern(&name);
399 let columns = self.plan.add_fields(&fields);
400 node =
401 self.add_node(Node::MaterializedCte { definition, body: node, name, cte, columns });
402 }
403 Ok((node, scope))
404 }
405
406 fn bind_definition(&mut self, ast: &Ast, index: u32) -> Result<NodeRef> {
416 let held = ast.cte(index);
417 let name = ast.string(held.name).to_string();
418 let (node, mut scope) = self.bind_query(ast, held.query)?;
419 if !held.columns.is_empty() {
420 let names: Vec<&str> = ast.name(held.columns).collect();
421 scope.rename_prefix(&names);
422 }
423 let table = self.fresh_index();
424 let mut exprs = Vec::with_capacity(scope.len());
425 let mut names = Vec::with_capacity(scope.len());
426 for column in &scope.columns {
427 exprs.push(self.plan.add_expr(Expr::Column(column.binding), column.ty.clone()));
428 names.push(self.plan.intern(&column.name));
429 }
430 let exprs = self.plan.add_expr_list(&exprs);
431 let names = self.plan.add_name_list(&names);
432 let node = self.add_node(Node::Project { input: node, index: table, exprs, names });
433 let cte = self.next_cte;
434 self.next_cte += 1;
435 self.materialized.push(Materialized { written: index, cte, name, fields: scope.fields() });
436 Ok(node)
437 }
438
439 fn bind_body(&mut self, ast: &Ast, written: &ast::Query) -> Result<(NodeRef, Scope)> {
440 match written.body {
441 ast::QueryBody::Select(select) => self.bind_select(ast, select, written),
442 ast::QueryBody::SetOp { op, quantifier, by_name, left, right } => {
443 if by_name {
444 return Err(Error::not_implemented("UNION BY NAME"));
445 }
446 self.bind_set_op(ast, written, op, quantifier, left, right)
447 }
448 ast::QueryBody::Values(rows) => self.bind_values(ast, written, rows),
449 ast::QueryBody::Describe(inner) => self.bind_describe(ast, written, inner),
450 ast::QueryBody::Show { name, relation } => self.bind_show(ast, written, name, relation),
451 }
452 }
453
454 fn bind_show(
456 &mut self,
457 ast: &Ast,
458 query: &ast::Query,
459 name: ast::Slice,
460 relation: ast::QueryRef,
461 ) -> Result<(NodeRef, Scope)> {
462 let text = ast.name_text(name);
463 let parts: Vec<&str> = ast.name(name).collect();
464 let table_exists = self.catalog.resolve(&parts).is_ok();
465 let as_table = match self.semantics.show_behavior() {
466 ShowBehavior::Auto => table_exists,
467 ShowBehavior::Setting => false,
468 ShowBehavior::Table => true,
469 };
470 if as_table {
471 return self.bind_describe(ast, query, relation);
472 }
473 let Some((_, value)) =
474 self.session.iter().find(|(name, _)| name.eq_ignore_ascii_case(&text))
475 else {
476 return Err(Error::catalog(format!("Setting with name \"{text}\" does not exist")));
477 };
478 let field = Field::new(text, LogicalType::Varchar);
479 let expr = self.plan.add_constant(Value::Varchar(value.to_string()));
480 let row = self.plan.add_expr_list(&[expr]);
481 let rows = self.plan.add_rows(&[row]);
482 let columns = self.plan.add_fields(std::slice::from_ref(&field));
483 let index = self.fresh_index();
484 let node = self.add_node(Node::Values { index, columns, rows });
485 let mut scope = Scope::empty();
486 scope.push(Visible {
487 table: String::new(),
488 name: field.name,
489 binding: ColumnBinding::new(index, 0),
490 ty: LogicalType::Varchar,
491 not_null: false,
492 });
493 Ok((node, scope))
494 }
495
496 fn bind_describe(
512 &mut self,
513 ast: &Ast,
514 query: &ast::Query,
515 inner: ast::QueryRef,
516 ) -> Result<(NodeRef, Scope)> {
517 let (_, described) = self.bind_query(ast, inner)?;
518 let fields: Vec<Field> = ["column_name", "column_type", "null", "key", "default", "extra"]
519 .iter()
520 .map(|name| Field::new(*name, LogicalType::Varchar))
521 .collect();
522 let mut slices = Vec::with_capacity(described.columns.len());
523 for column in described.columns.clone() {
524 let written = [
527 column.name.clone(),
528 column.ty.to_string(),
529 if column.not_null { "NO" } else { "YES" }.to_owned(),
530 ];
531 let mut items: Vec<ExprRef> = written
532 .into_iter()
533 .map(|text| self.plan.add_constant(Value::Varchar(text)))
534 .collect();
535 for _ in 0..3 {
536 let empty = self.plan.add_constant(Value::Null);
537 items.push(self.cast_to(empty, &LogicalType::Varchar));
538 }
539 slices.push(self.plan.add_expr_list(&items));
540 }
541 let rows = self.plan.add_rows(&slices);
542 let columns = self.plan.add_fields(&fields);
543 let index = self.fresh_index();
544 let mut node = self.add_node(Node::Values { index, columns, rows });
545 let mut scope = Scope::empty();
546 for (at, field) in fields.iter().enumerate() {
547 scope.push(Visible {
548 table: String::new(),
549 name: field.name.clone(),
550 binding: ColumnBinding::new(index, at as u32),
551 ty: field.ty.clone(),
552 not_null: false,
553 });
554 }
555 let keys = self.sort_keys(ast, query, &scope, &[])?;
556 if !keys.is_empty() {
557 let keys = self.plan.add_sort_keys(&keys);
558 node = self.add_node(Node::Sort { input: node, keys });
559 }
560 node = self.apply_limit(ast, query, node)?;
561 Ok((node, scope))
562 }
563
564 fn passes_through(&self, expr: ExprRef, input: &Scope) -> bool {
570 let Expr::Column(binding) = *self.plan.expr(expr) else { return false };
571 input.columns.iter().any(|column| column.binding == binding && column.not_null)
572 }
573
574 fn bind_values(
581 &mut self,
582 ast: &Ast,
583 query: &ast::Query,
584 rows: ast::Slice,
585 ) -> Result<(NodeRef, Scope)> {
586 let written = ast.rows(rows).to_vec();
587 let Some(first) = written.first() else {
588 return Err(Error::binder("VALUES needs at least one row"));
589 };
590 let width = first.len as usize;
591 for (at, row) in written.iter().enumerate() {
592 if row.len as usize != width {
593 return Err(Error::binder(format!(
594 "VALUES lists must all be the same length, expected {width} columns but row {} has {}",
595 at + 1,
596 row.len
597 )));
598 }
599 }
600 let empty = Scope::empty();
602 let previous = std::mem::replace(&mut self.clause, "VALUES clause");
603 let mut bound: Vec<Vec<ExprRef>> = Vec::with_capacity(written.len());
604 for row in &written {
605 let mut items = Vec::with_capacity(width);
606 for &expr in ast.expr_list(*row) {
607 items.push(self.bind_expr(ast, expr, &empty)?);
608 }
609 bound.push(items);
610 }
611 self.clause = previous;
612 let mut types = Vec::with_capacity(width);
613 for at in 0..width {
614 let mut ty = self.plan.expr_type(bound[0][at]).clone();
615 for row in &bound[1..] {
616 let other = self.plan.expr_type(row[at]).clone();
617 ty = ty.promote(&other).ok_or_else(|| {
618 Error::binder(format!(
619 "Cannot combine a value of type {ty} with a value of type {other} in column {} of a VALUES",
620 at + 1
621 ))
622 })?;
623 }
624 types.push(ty);
625 }
626 let mut slices = Vec::with_capacity(bound.len());
627 for row in &bound {
628 let items: Vec<ExprRef> = row
629 .iter()
630 .zip(&types)
631 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
632 .collect::<Result<_>>()?;
633 slices.push(self.plan.add_expr_list(&items));
634 }
635 let rows = self.plan.add_rows(&slices);
636 let fields: Vec<Field> = types
637 .iter()
638 .enumerate()
639 .map(|(at, ty)| Field::new(format!("col{at}"), ty.clone()))
640 .collect();
641 let columns = self.plan.add_fields(&fields);
642 let index = self.fresh_index();
643 let mut node = self.add_node(Node::Values { index, columns, rows });
644 let mut scope = Scope::empty();
645 for (at, field) in fields.iter().enumerate() {
646 scope.push(Visible {
647 table: String::new(),
648 name: field.name.clone(),
649 binding: ColumnBinding::new(index, at as u32),
650 ty: field.ty.clone(),
651 not_null: false,
652 });
653 }
654 let keys = self.sort_keys(ast, query, &scope, &[])?;
655 if !keys.is_empty() {
656 let keys = self.plan.add_sort_keys(&keys);
657 node = self.add_node(Node::Sort { input: node, keys });
658 }
659 node = self.apply_limit(ast, query, node)?;
660 Ok((node, scope))
661 }
662
663 fn bind_set_op(
664 &mut self,
665 ast: &Ast,
666 query: &ast::Query,
667 op: SetOp,
668 quantifier: Quantifier,
669 left: ast::QueryRef,
670 right: ast::QueryRef,
671 ) -> Result<(NodeRef, Scope)> {
672 let (left_node, left_scope) = self.bind_query(ast, left)?;
673 let (right_node, right_scope) = self.bind_query(ast, right)?;
674 if left_scope.len() != right_scope.len() {
675 return Err(Error::binder(format!(
676 "Set operations can only apply to expressions with the same number of result columns, but left side has {} and right side has {}",
677 left_scope.len(),
678 right_scope.len()
679 )));
680 }
681 let mut types = Vec::with_capacity(left_scope.len());
683 for (left, right) in left_scope.columns.iter().zip(&right_scope.columns) {
684 let common = left.ty.promote(&right.ty).ok_or_else(|| {
685 Error::binder(format!(
686 "Cannot combine a column of type {} with a column of type {} in a set operation",
687 left.ty, right.ty
688 ))
689 })?;
690 types.push(common);
691 }
692 let left_node = self.conform(left_node, &left_scope, &types)?;
693 let right_node = self.conform(right_node, &right_scope, &types)?;
694 let index = self.fresh_index();
695 let kind = match op {
696 SetOp::Union => SetOpKind::Union,
697 SetOp::Except => SetOpKind::Except,
698 SetOp::Intersect => SetOpKind::Intersect,
699 };
700 let all = quantifier == Quantifier::All;
703 let mut node =
704 self.add_node(Node::SetOp { left: left_node, right: right_node, kind, all, index });
705 let mut scope = Scope::empty();
706 for (at, (column, ty)) in left_scope.columns.iter().zip(&types).enumerate() {
707 scope.push(Visible {
708 table: String::new(),
709 name: column.name.clone(),
710 binding: ColumnBinding::new(index, at as u32),
711 ty: ty.clone(),
712 not_null: false,
715 });
716 }
717 let keys = self.sort_keys(ast, query, &scope, &[])?;
721 if !keys.is_empty() {
722 let keys = self.plan.add_sort_keys(&keys);
723 node = self.add_node(Node::Sort { input: node, keys });
724 }
725 node = self.apply_limit(ast, query, node)?;
726 Ok((node, scope))
727 }
728
729 fn conform(&mut self, node: NodeRef, scope: &Scope, types: &[LogicalType]) -> Result<NodeRef> {
731 if scope.columns.iter().zip(types).all(|(column, ty)| &column.ty == ty) {
732 return Ok(node);
733 }
734 let index = self.fresh_index();
735 let mut exprs = Vec::with_capacity(types.len());
736 let mut names = Vec::with_capacity(types.len());
737 for (column, ty) in scope.columns.iter().zip(types) {
738 let expr = self.plan.add_expr(Expr::Column(column.binding), column.ty.clone());
739 exprs.push(self.checked_cast_to(expr, ty, false)?);
740 names.push(self.plan.intern(&column.name));
741 }
742 let exprs = self.plan.add_expr_list(&exprs);
743 let names = self.plan.add_name_list(&names);
744 Ok(self.add_node(Node::Project { input: node, index, exprs, names }))
745 }
746
747 fn bind_select(
750 &mut self,
751 ast: &Ast,
752 select: ast::SelectRef,
753 query: &ast::Query,
754 ) -> Result<(NodeRef, Scope)> {
755 let written = ast.select(select);
756 let outer_windows = std::mem::take(&mut self.windows);
760 let (mut node, input) = self.bind_from(ast, written.from)?;
761 node = self.attach_scalar_subqueries(node);
762
763 if written.filter != NONE {
764 self.clause = "WHERE clause";
765 let predicate = self.bind_expr(ast, written.filter, &input)?;
766 let predicate = self.as_boolean(predicate, "WHERE")?;
767 node = self.attach_scalar_subqueries(node);
768 node = self.add_node(Node::Filter { input: node, predicate });
769 }
770
771 let targets = ast.target_list(written.targets).to_vec();
772 if targets.is_empty() {
773 return Err(Error::binder("a SELECT needs at least one expression to select"));
774 }
775
776 let group_items = self.group_items(ast, &written, &targets)?;
777 let aggregating = !group_items.is_empty()
778 || written.having != NONE
779 || targets.iter().any(|target| has_aggregate(ast, target.expr));
780 if aggregating {
781 self.clause = "GROUP BY clause";
782 let mut groups = Vec::with_capacity(group_items.len());
783 for item in &group_items {
784 groups.push(self.bind_expr(ast, *item, &input)?);
785 }
786 let index = self.fresh_index();
787 self.aggregation = Some(Aggregation { index, groups, aggregates: Vec::new() });
788 }
789
790 self.clause = "SELECT clause";
791 let (mut exprs, mut names) = self.bind_targets(ast, &targets, &input)?;
792 let visible = exprs.len();
793
794 let mut having = None;
795 let mut above = Vec::new();
802 if written.having != NONE {
803 self.clause = "HAVING clause";
804 let before = self.scalar_subqueries.len();
805 let predicate = self.bind_expr(ast, written.having, &input)?;
806 for pending in self.scalar_subqueries.split_off(before) {
809 if pending.dependent {
810 self.scalar_subqueries.push(pending);
811 } else {
812 above.push(pending);
813 }
814 }
815 self.joined_above = above.iter().map(|pending| pending.index).collect();
816 let predicate = self.over_aggregate(predicate, &input)?;
817 let mut rewritten = Vec::with_capacity(above.len());
820 for mut pending in above {
821 let conditions = std::mem::take(&mut pending.conditions);
822 let mut over = Vec::with_capacity(conditions.len());
823 for condition in conditions {
824 over.push(self.over_aggregate(condition, &input)?);
825 }
826 pending.conditions = over;
827 rewritten.push(pending);
828 }
829 above = rewritten;
830 self.joined_above.clear();
831 having = Some(self.as_boolean(predicate, "HAVING")?);
832 }
833
834 let project = self.fresh_index();
837 let mut output = Scope::empty();
838 for (at, (expr, name)) in exprs.iter().zip(&names).enumerate() {
839 output.push(Visible {
840 table: String::new(),
841 name: name.clone(),
842 binding: ColumnBinding::new(project, at as u32),
843 ty: self.plan.expr_type(*expr).clone(),
844 not_null: self.passes_through(*expr, &input),
845 });
846 }
847
848 self.clause = "ORDER BY clause";
849 let mut extra = Vec::new();
850 let keys = self.select_sort_keys(
851 ast, query, &input, &output, project, &mut exprs, &mut names, &mut extra,
852 )?;
853 if !extra.is_empty() && written.distinct != Distinct::No {
854 return Err(Error::binder(
855 "For SELECT DISTINCT, ORDER BY expressions must appear in the select list",
856 ));
857 }
858 let on = self.distinct_on(ast, written.distinct, &output)?;
859
860 node = self.attach_scalar_subqueries(node);
861
862 if let Some(aggregation) = self.aggregation.take() {
863 let index = aggregation.index;
864 let groups = self.plan.add_expr_list(&aggregation.groups);
865 let aggregates = self.plan.add_expr_list(&aggregation.aggregates);
866 node = self.add_node(Node::Aggregate { input: node, index, groups, aggregates });
867 }
868 if !above.is_empty() {
869 debug_assert!(self.scalar_subqueries.is_empty(), "a query is waiting to be joined");
870 self.scalar_subqueries = above;
871 node = self.attach_scalar_subqueries(node);
872 }
873 if let Some(predicate) = having {
874 node = self.add_node(Node::Filter { input: node, predicate });
875 }
876
877 for run in std::mem::replace(&mut self.windows, outer_windows) {
881 let partition = self.plan.add_expr_list(&run.partition);
882 let order = self.plan.add_sort_keys(&run.order);
883 let expressions = self.plan.add_expr_list(&run.calls);
884 node = self.add_node(Node::Window {
885 input: node,
886 index: run.index,
887 partition,
888 order,
889 frame: run.frame,
890 expressions,
891 });
892 }
893
894 let interned: Vec<u32> = names.iter().map(|name| self.plan.intern(name)).collect();
895 let exprs_slice = self.plan.add_expr_list(&exprs);
896 let names_slice = self.plan.add_name_list(&interned);
897 node = self.add_node(Node::Project {
898 input: node,
899 index: project,
900 exprs: exprs_slice,
901 names: names_slice,
902 });
903
904 if written.distinct != Distinct::No {
905 let on = self.plan.add_expr_list(&on);
906 node = self.add_node(Node::Distinct { input: node, on });
907 }
908 if !keys.is_empty() {
909 let keys = self.plan.add_sort_keys(&keys);
910 node = self.add_node(Node::Sort { input: node, keys });
911 }
912 node = self.apply_limit(ast, query, node)?;
913
914 if extra.is_empty() {
915 output.columns.truncate(visible);
916 return Ok((node, output));
917 }
918 let index = self.fresh_index();
921 let mut kept = Vec::with_capacity(visible);
922 let mut kept_names = Vec::with_capacity(visible);
923 let mut scope = Scope::empty();
924 for (at, name) in names.iter().enumerate().take(visible) {
925 let ty = output.columns[at].ty.clone();
926 kept.push(self.column(project, at, ty.clone()));
927 kept_names.push(self.plan.intern(name));
928 scope.push(Visible {
929 table: String::new(),
930 name: name.clone(),
931 binding: ColumnBinding::new(index, at as u32),
932 ty,
933 not_null: output.columns[at].not_null,
934 });
935 }
936 let exprs = self.plan.add_expr_list(&kept);
937 let names = self.plan.add_name_list(&kept_names);
938 node = self.add_node(Node::Project { input: node, index, exprs, names });
939 Ok((node, scope))
940 }
941
942 fn bind_targets(
944 &mut self,
945 ast: &Ast,
946 targets: &[ast::Target],
947 input: &Scope,
948 ) -> Result<(Vec<ExprRef>, Vec<String>)> {
949 let mut exprs = Vec::with_capacity(targets.len());
950 let mut names = Vec::with_capacity(targets.len());
951 for target in targets {
952 if let ast::Expr::Star { qualifier, replacements } = ast.expr(target.expr) {
953 let table = ast.name(qualifier).last().map(str::to_string);
954 let expanded: Vec<Visible> =
955 input.star(table.as_deref())?.into_iter().cloned().collect();
956 let replacements = ast.target_list(replacements).to_vec();
957 let mut used = vec![false; replacements.len()];
958 for column in expanded {
959 let found = replacements.iter().zip(&mut used).find(|(replacement, _)| {
960 same_name(ast.string(replacement.alias), &column.name)
961 });
962 let (expr, name) = match found {
967 Some((replacement, used)) => {
968 *used = true;
969 let expr = self.bind_expr(ast, replacement.expr, input)?;
970 (expr, ast.string(replacement.alias).to_string())
971 }
972 None => (
973 self.plan.add_expr(Expr::Column(column.binding), column.ty),
974 column.name,
975 ),
976 };
977 exprs.push(self.over_aggregate(expr, input)?);
978 names.push(name);
979 }
980 if let Some((replacement, _)) =
984 replacements.iter().zip(&used).find(|(_, used)| !**used)
985 {
986 return Err(missing_replacement(ast.string(replacement.alias), input));
987 }
988 continue;
989 }
990 let expr = self.bind_expr(ast, target.expr, input)?;
991 exprs.push(self.over_aggregate(expr, input)?);
992 names.push(if target.alias == NONE {
993 self.output_name(ast, target.expr, input)
994 } else {
995 ast.string(target.alias).to_string()
996 });
997 }
998 Ok((exprs, names))
999 }
1000
1001 fn output_name(&self, ast: &Ast, target: ast::ExprRef, input: &Scope) -> String {
1007 if let ast::Expr::Column { name } = ast.expr(target) {
1008 let parts: Vec<&str> = ast.name(name).collect();
1009 if let Ok(found) = input.resolve(&parts) {
1010 return found.name.clone();
1011 }
1012 }
1013 describe(ast, target, self.semantics)
1014 }
1015
1016 fn group_items(
1018 &self,
1019 ast: &Ast,
1020 select: &ast::Select,
1021 targets: &[ast::Target],
1022 ) -> Result<Vec<ast::ExprRef>> {
1023 if select.group_by_all {
1024 return Ok(targets
1027 .iter()
1028 .filter(|target| !has_aggregate(ast, target.expr))
1029 .map(|target| target.expr)
1030 .collect());
1031 }
1032 let mut items = Vec::new();
1033 for &item in ast.expr_list(select.group_by) {
1034 items.push(self.output_reference(ast, item, targets, "GROUP BY")?.unwrap_or(item));
1035 }
1036 Ok(items)
1037 }
1038
1039 fn output_reference(
1041 &self,
1042 ast: &Ast,
1043 item: ast::ExprRef,
1044 targets: &[ast::Target],
1045 clause: &str,
1046 ) -> Result<Option<ast::ExprRef>> {
1047 match ast.expr(item) {
1048 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1049 let written = ast.string(text);
1050 let position: usize = written.parse().map_err(|_| {
1051 Error::binder(format!("{clause} term {written} is not a column"))
1052 })?;
1053 if position == 0 || position > targets.len() {
1054 return Err(Error::binder(format!(
1055 "{clause} term out of range - should be between 1 and {}",
1056 targets.len()
1057 )));
1058 }
1059 Ok(Some(targets[position - 1].expr))
1060 }
1061 ast::Expr::Column { name } => {
1062 let parts: Vec<&str> = ast.name(name).collect();
1063 let [written] = parts.as_slice() else { return Ok(None) };
1064 let mut found = None;
1065 for target in targets {
1066 if target.alias != NONE && same_name(ast.string(target.alias), written) {
1067 if found.is_some() {
1068 return Ok(None);
1069 }
1070 found = Some(target.expr);
1071 }
1072 }
1073 Ok(found)
1074 }
1075 _ => Ok(None),
1076 }
1077 }
1078
1079 #[allow(clippy::too_many_arguments)]
1083 fn select_sort_keys(
1084 &mut self,
1085 ast: &Ast,
1086 query: &ast::Query,
1087 input: &Scope,
1088 output: &Scope,
1089 project: u32,
1090 exprs: &mut Vec<ExprRef>,
1091 names: &mut Vec<String>,
1092 extra: &mut Vec<usize>,
1093 ) -> Result<Vec<SortKey>> {
1094 if query.order_by_all {
1095 return Ok(self.every_column(output));
1096 }
1097 let items = ast.order_list(query.order_by).to_vec();
1098 let mut keys = Vec::with_capacity(items.len());
1099 for item in items {
1100 self.check_order_literal(ast, item.expr)?;
1101 let position = match self.output_position(ast, item.expr, output)? {
1102 Some(position) => position,
1103 None => {
1104 let bound = self.bind_expr(ast, item.expr, input)?;
1105 let bound = self.over_aggregate(bound, input)?;
1106 match exprs.iter().position(|&held| self.same_expr(held, bound)) {
1107 Some(position) => position,
1108 None => {
1109 exprs.push(bound);
1110 names.push(describe(ast, item.expr, self.semantics));
1111 extra.push(exprs.len() - 1);
1112 exprs.len() - 1
1113 }
1114 }
1115 }
1116 };
1117 let ty = self.plan.expr_type(exprs[position]).clone();
1118 let expr = self.column(project, position, ty);
1119 keys.push(self.sort_key(expr, item));
1120 }
1121 Ok(keys)
1122 }
1123
1124 fn sort_keys(
1126 &mut self,
1127 ast: &Ast,
1128 query: &ast::Query,
1129 output: &Scope,
1130 targets: &[ast::Target],
1131 ) -> Result<Vec<SortKey>> {
1132 if query.order_by_all {
1133 return Ok(self.every_column(output));
1134 }
1135 let items = ast.order_list(query.order_by).to_vec();
1136 let mut keys = Vec::with_capacity(items.len());
1137 for item in items {
1138 self.check_order_literal(ast, item.expr)?;
1139 let expr = match self.output_position(ast, item.expr, output)? {
1140 Some(position) => {
1141 let column = &output.columns[position];
1142 let (binding, ty) = (column.binding, column.ty.clone());
1143 self.plan.add_expr(Expr::Column(binding), ty)
1144 }
1145 None => {
1146 let _ = targets;
1147 self.bind_expr(ast, item.expr, output)?
1148 }
1149 };
1150 keys.push(self.sort_key(expr, item));
1151 }
1152 Ok(keys)
1153 }
1154
1155 fn every_column(&mut self, output: &Scope) -> Vec<SortKey> {
1156 let columns: Vec<(ColumnBinding, LogicalType)> =
1157 output.columns.iter().map(|column| (column.binding, column.ty.clone())).collect();
1158 columns
1159 .into_iter()
1160 .map(|(binding, ty)| {
1161 let expr = self.plan.add_expr(Expr::Column(binding), ty);
1162 let descending = self.semantics.default_descending();
1163 SortKey { expr, descending, nulls_first: self.semantics.nulls_first(descending) }
1164 })
1165 .collect()
1166 }
1167
1168 fn sort_key(&self, expr: ExprRef, item: ast::OrderItem) -> SortKey {
1170 let descending = match item.order {
1171 Order::Unstated => self.semantics.default_descending(),
1172 Order::Ascending => false,
1173 Order::Descending => true,
1174 };
1175 let nulls_first = match item.nulls {
1176 Nulls::First => true,
1177 Nulls::Last => false,
1178 Nulls::Unstated => self.semantics.nulls_first(descending),
1179 };
1180 SortKey { expr, descending, nulls_first }
1181 }
1182
1183 fn output_position(
1185 &self,
1186 ast: &Ast,
1187 item: ast::ExprRef,
1188 output: &Scope,
1189 ) -> Result<Option<usize>> {
1190 match ast.expr(item) {
1191 ast::Expr::Literal { kind: LiteralKind::Number, text } => {
1192 let written = ast.string(text);
1193 if written.contains(['.', 'e', 'E']) {
1194 return Ok(None);
1195 }
1196 let position: usize = written.parse().map_err(|_| {
1197 Error::binder(format!("ORDER BY term {written} is not a column"))
1198 })?;
1199 if position == 0 || position > output.len() {
1200 return Err(Error::binder(format!(
1201 "ORDER BY term out of range - should be between 1 and {}",
1202 output.len()
1203 )));
1204 }
1205 Ok(Some(position - 1))
1206 }
1207 ast::Expr::Column { name } => {
1208 let parts: Vec<&str> = ast.name(name).collect();
1209 let [written] = parts.as_slice() else { return Ok(None) };
1210 Ok(output.position_of(None, written))
1211 }
1212 _ => Ok(None),
1213 }
1214 }
1215
1216 fn check_order_literal(&self, ast: &Ast, item: ast::ExprRef) -> Result<()> {
1218 if !self.semantics.order_by_non_integer_literal()
1219 && matches!(
1220 ast.expr(item),
1221 ast::Expr::Literal { kind, text }
1222 if kind != LiteralKind::Number
1223 || ast.string(text).contains(['.', 'e', 'E'])
1224 )
1225 {
1226 return Err(Error::binder(
1227 "ORDER BY non-integer literal has no effect.\n* SET order_by_non_integer_literal=true to allow this behavior.",
1228 ));
1229 }
1230 Ok(())
1231 }
1232
1233 fn distinct_on(
1235 &mut self,
1236 ast: &Ast,
1237 distinct: Distinct,
1238 output: &Scope,
1239 ) -> Result<Vec<ExprRef>> {
1240 let Distinct::On(items) = distinct else {
1241 return Ok(Vec::new());
1242 };
1243 let items = ast.expr_list(items).to_vec();
1244 let mut on = Vec::with_capacity(items.len());
1245 for item in items {
1246 let Some(position) = self.output_position(ast, item, output)? else {
1247 return Err(Error::not_implemented(
1248 "DISTINCT ON an expression that is not in the select list",
1249 ));
1250 };
1251 let column = &output.columns[position];
1252 let (binding, ty) = (column.binding, column.ty.clone());
1253 on.push(self.plan.add_expr(Expr::Column(binding), ty));
1254 }
1255 Ok(on)
1256 }
1257
1258 fn apply_limit(&mut self, ast: &Ast, query: &ast::Query, input: NodeRef) -> Result<NodeRef> {
1259 if query.limit_percent {
1260 return Err(Error::not_implemented("LIMIT with a percentage"));
1261 }
1262 let count = self.constant_count(ast, query.limit, "LIMIT")?;
1263 let offset = self.constant_count(ast, query.offset, "OFFSET")?.unwrap_or(0);
1264 if count.is_none() && offset == 0 {
1265 return Ok(input);
1266 }
1267 Ok(self.add_node(Node::Limit { input, count, offset }))
1268 }
1269
1270 fn constant_count(
1272 &mut self,
1273 ast: &Ast,
1274 written: ast::ExprRef,
1275 clause: &str,
1276 ) -> Result<Option<u64>> {
1277 if written == NONE {
1278 return Ok(None);
1279 }
1280 self.clause = "LIMIT clause";
1281 let scope = Scope::empty();
1282 let bound = self.bind_expr(ast, written, &scope)?;
1283 let Expr::Constant(value) = *self.plan.expr(bound) else {
1284 return Err(Error::not_implemented(format!("a {clause} that is not a constant")));
1285 };
1286 let count = match self.plan.value(value) {
1287 Value::Null => return Ok(None),
1288 Value::TinyInt(count) => i128::from(*count),
1289 Value::SmallInt(count) => i128::from(*count),
1290 Value::Integer(count) => i128::from(*count),
1291 Value::BigInt(count) => i128::from(*count),
1292 Value::HugeInt(count) => *count,
1293 other => {
1294 return Err(Error::binder(format!(
1295 "{clause} takes a whole number of rows, not a value of type {}",
1296 other.logical_type()
1297 )));
1298 }
1299 };
1300 u64::try_from(count)
1301 .map(Some)
1302 .map_err(|_| Error::binder(format!("{clause} must not be negative")))
1303 }
1304
1305 fn bind_from(&mut self, ast: &Ast, from: ast::Slice) -> Result<(NodeRef, Scope)> {
1308 let sources = ast.source_list(from).to_vec();
1309 let Some((first, rest)) = sources.split_first() else {
1310 return Ok((self.add_node(Node::Dummy), Scope::empty()));
1313 };
1314 let (mut node, mut scope) = self.bind_source(ast, *first)?;
1315 for source in rest {
1316 let (right, right_scope, correlations) = self.bind_lateral(ast, *source, &scope)?;
1317 node = if correlations.is_empty() {
1318 self.add_node(Node::CrossProduct { left: node, right })
1319 } else {
1320 let conditions = self.plan.add_expr_list(&[]);
1321 self.add_node(Node::DependentJoin {
1322 left: node,
1323 right,
1324 kind: JoinKind::Inner,
1325 conditions,
1326 })
1327 };
1328 scope = scope.concat(right_scope);
1329 }
1330 Ok((node, scope))
1331 }
1332
1333 fn bind_lateral(
1345 &mut self,
1346 ast: &Ast,
1347 source: ast::SourceRef,
1348 left: &Scope,
1349 ) -> Result<(NodeRef, Scope, Vec<ColumnBinding>)> {
1350 self.lateral_scopes.push(self.outer_scopes.len());
1351 self.outer_scopes.push(left.clone());
1352 self.correlations.push(Vec::new());
1353 let bound = self.bind_source(ast, source);
1354 let read = self.correlations.pop().expect("correlation frame");
1355 self.outer_scopes.pop();
1356 self.lateral_scopes.pop();
1357 let (node, scope) = bound?;
1358
1359 let mut here = Vec::new();
1360 for binding in read {
1361 if left.columns.iter().any(|column| column.binding == binding) {
1362 here.push(binding);
1363 } else if let Some(enclosing) = self.correlations.last_mut() {
1364 if !enclosing.contains(&binding) {
1365 enclosing.push(binding);
1366 }
1367 }
1368 }
1369 if !here.is_empty() && matches!(ast.source(source), ast::Source::Function { .. }) {
1375 return Err(Error::not_implemented("a table function reading a LATERAL column"));
1376 }
1377 Ok((node, scope, here))
1378 }
1379
1380 fn bind_source(&mut self, ast: &Ast, source: ast::SourceRef) -> Result<(NodeRef, Scope)> {
1381 match ast.source(source) {
1382 ast::Source::Table { name, alias, columns } => {
1383 self.bind_table(ast, name, alias, columns)
1384 }
1385 ast::Source::Function { name, args, alias, columns, pragma } => {
1386 self.bind_table_function(ast, name, args, alias, columns, pragma)
1387 }
1388 ast::Source::Subquery { query, alias, columns } => {
1389 let (node, mut scope) = self.bind_query(ast, query)?;
1390 let label = if alias == NONE {
1391 "unnamed_subquery".to_string()
1392 } else {
1393 ast.string(alias).to_string()
1394 };
1395 scope.relabel(&label);
1396 if !columns.is_empty() {
1397 let names: Vec<&str> = ast.name(columns).collect();
1398 scope.rename(&names, &label)?;
1399 }
1400 Ok((node, scope))
1401 }
1402 ast::Source::Values { rows, alias, columns } => {
1403 let bare = ast::Query::bare(ast::QueryBody::Values(rows));
1404 let (node, mut scope) = self.bind_values(ast, &bare, rows)?;
1405 let label =
1406 if alias == NONE { String::new() } else { ast.string(alias).to_string() };
1407 scope.relabel(&label);
1408 if !columns.is_empty() {
1409 let names: Vec<&str> = ast.name(columns).collect();
1410 scope.rename(&names, &label)?;
1411 }
1412 Ok((node, scope))
1413 }
1414 ast::Source::Cte { cte, alias, columns } => {
1415 self.bind_cte_scan(ast, cte, alias, columns)
1416 }
1417 ast::Source::Join { left, right, kind, natural, on, using } => {
1418 self.bind_join(ast, left, right, kind, natural, on, using)
1419 }
1420 }
1421 }
1422
1423 fn bind_cte_scan(
1430 &mut self,
1431 ast: &Ast,
1432 written: u32,
1433 alias: ast::StrRef,
1434 columns: ast::Slice,
1435 ) -> Result<(NodeRef, Scope)> {
1436 let Some(held) = self.materialized.iter().rev().find(|held| held.written == written) else {
1437 let name = ast.string(ast.cte(written).name);
1438 return Err(Error::binder(format!("Table with name {name} does not exist!")));
1439 };
1440 let cte = held.cte;
1441 let fields = held.fields.clone();
1442 let text = held.name.clone();
1443 let label = if alias == NONE { text.clone() } else { ast.string(alias).to_string() };
1444 let name = self.plan.intern(&text);
1445 let index = self.fresh_index();
1446 let mut scope = Scope::empty();
1447 for (at, field) in fields.iter().enumerate() {
1448 scope.push(Visible {
1449 table: label.clone(),
1450 name: field.name.clone(),
1451 binding: ColumnBinding::new(index, at as u32),
1452 ty: field.ty.clone(),
1453 not_null: field.not_null,
1454 });
1455 }
1456 if !columns.is_empty() {
1457 let names: Vec<&str> = ast.name(columns).collect();
1458 scope.rename(&names, &label)?;
1459 }
1460 let columns = self.plan.add_fields(&fields);
1461 let node = self.add_node(Node::CteScan { index, cte, name, columns });
1462 Ok((node, scope))
1463 }
1464
1465 fn bind_table(
1466 &mut self,
1467 ast: &Ast,
1468 name: ast::Slice,
1469 alias: ast::StrRef,
1470 columns: ast::Slice,
1471 ) -> Result<(NodeRef, Scope)> {
1472 let parts: Vec<&str> = ast.name(name).collect();
1473 let catalog = self.catalog;
1474 let resolved = match catalog.resolve(&parts) {
1477 Ok(resolved) => resolved,
1478 Err(missing) => {
1479 return self.bind_replacement_scan(ast, &parts, alias, columns, missing);
1480 }
1481 };
1482 if catalog.entry(&resolved)? == Entry::View {
1483 return self.bind_view(ast, &resolved, alias, columns);
1484 }
1485 let table = catalog.table(&resolved)?;
1486 let fields: Vec<Field> = table.columns().to_vec();
1487 let label =
1488 if alias == NONE { resolved.table.clone() } else { ast.string(alias).to_string() };
1489 let index = self.fresh_index();
1490 let mut scope = Scope::empty();
1491 for (at, field) in fields.iter().enumerate() {
1492 scope.push(Visible {
1493 table: label.clone(),
1494 name: field.name.clone(),
1495 binding: ColumnBinding::new(index, at as u32),
1496 ty: field.ty.clone(),
1497 not_null: field.not_null,
1498 });
1499 }
1500 if !columns.is_empty() {
1501 let names: Vec<&str> = ast.name(columns).collect();
1502 scope.rename(&names, &label)?;
1503 }
1504 let catalog_name = self.plan.intern(&resolved.catalog);
1505 let schema = self.plan.intern(&resolved.schema);
1506 let table_name = self.plan.intern(&resolved.table);
1507 let alias = self.plan.intern(&label);
1508 let columns = self.plan.add_fields(&fields);
1509 let node = self.add_node(Node::Get {
1510 catalog: catalog_name,
1511 schema,
1512 table: table_name,
1513 alias,
1514 index,
1515 columns,
1516 });
1517 Ok((node, scope))
1518 }
1519
1520 fn bind_view(
1532 &mut self,
1533 ast: &Ast,
1534 name: &QualifiedName,
1535 alias: ast::StrRef,
1536 columns: ast::Slice,
1537 ) -> Result<(NodeRef, Scope)> {
1538 let view = self.catalog.view(name)?;
1539 let full = name.to_string();
1540 if self.expanding.contains(&full) {
1541 return Err(Error::binder(format!(
1545 "infinite recursion detected: attempting to recursively bind view \"\"{}\"\"",
1546 name.table
1547 )));
1548 }
1549 let body = parse_ast_with_case(view.sql(), self.semantics.identifier_case())?;
1550 let query = match body.statements.as_slice() {
1551 [ast::Statement::Query(query)] => *query,
1552 _ => return Err(Error::binder(format!("view \"{}\" is not a query", name.table))),
1555 };
1556 self.expanding.push(full);
1557 let bound = self.bind_query(&body, query);
1558 self.expanding.pop();
1559 let (node, mut scope) = bound?;
1560
1561 let aliases: Vec<&str> = view.aliases().iter().map(String::as_str).collect();
1562 if !aliases.is_empty() {
1563 scope.rename(&aliases, "unnamed_subquery")?;
1564 }
1565 view.remember(scope.fields());
1572 let label = if alias == NONE { name.table.clone() } else { ast.string(alias).to_string() };
1573 scope.relabel(&label);
1574 if !columns.is_empty() {
1575 let names: Vec<&str> = ast.name(columns).collect();
1576 scope.rename(&names, &label)?;
1577 }
1578 Ok((node, scope))
1579 }
1580
1581 fn bind_table_function(
1589 &mut self,
1590 ast: &Ast,
1591 name: ast::Slice,
1592 args: ast::Slice,
1593 alias: ast::StrRef,
1594 columns: ast::Slice,
1595 pragma: bool,
1596 ) -> Result<(NodeRef, Scope)> {
1597 let parts: Vec<&str> = ast.name(name).collect();
1598 let function_name = *parts.last().unwrap_or(&"");
1602 if let Some(schema) = parts.iter().rev().nth(1) {
1603 if !schema.eq_ignore_ascii_case("main") && !schema.eq_ignore_ascii_case("system") {
1604 return Err(Error::catalog(format!(
1605 "Table Function with name {} does not exist!",
1606 parts.join(".")
1607 )));
1608 }
1609 }
1610 let Some(called) = TableFunction::lookup(function_name) else {
1614 if pragma {
1615 if args.is_empty() && self.catalog.resolve(&parts).is_ok() {
1621 return self.bind_table(ast, name, alias, columns);
1622 }
1623 let spelled = function_name.strip_prefix("pragma_").unwrap_or(function_name);
1624 return Err(Error::catalog(format!(
1625 "Pragma Function with name {spelled} does not exist!"
1626 )));
1627 }
1628 return Err(Error::catalog(format!(
1629 "Table Function with name {function_name} does not exist!"
1630 )));
1631 };
1632 let written = ast.target_list(args).to_vec();
1633 let empty = Scope::empty();
1634 let previous = std::mem::replace(&mut self.clause, "table function arguments");
1635 let mut bound = Vec::new();
1636 let mut written_options = Vec::new();
1637 for argument in written {
1638 let expr = self.bind_expr(ast, argument.expr, &empty)?;
1639 if argument.alias == NONE {
1640 bound.push(expr);
1641 } else {
1642 let name = ast.string(argument.alias).to_string();
1643 let (parameter, value) = self.named_argument(called, &name, expr)?;
1644 written_options.push((parameter, value, expr));
1645 }
1646 }
1647 self.clause = previous;
1648 let options = Options::of(&written_options)?;
1649
1650 let given: Vec<LogicalType> =
1653 bound.iter().map(|&expr| self.plan.expr_type(expr).clone()).collect();
1654 let resolved = if pragma {
1655 resolve_pragma(function_name, &given)?
1656 } else {
1657 resolve_table(function_name, &given)?
1658 };
1659 let mut cast: Vec<ExprRef> = bound
1660 .iter()
1661 .zip(&resolved.arguments)
1662 .map(|(&expr, ty)| self.checked_cast_to(expr, ty, false))
1663 .collect::<Result<_>>()?;
1664
1665 if resolved.function.takes_a_name() {
1666 let Columns::Fixed(fields) = resolved.columns else {
1667 return Err(Error::internal("a pragma that resolved to a file"));
1668 };
1669 let [argument] = cast[..] else {
1670 return Err(Error::internal("a pragma that resolved to more than one name"));
1671 };
1672 return self.bind_pragma(ast, resolved.function, &fields, argument, alias, columns);
1673 }
1674 let fields = match resolved.columns {
1675 Columns::Fixed(fields) => fields,
1676 columns => {
1677 let paths = self.file_paths(cast[0], resolved.function.name())?;
1682 let first = paths.first().map_or("", String::as_str);
1683 let mut fields = match columns {
1684 Columns::Csv => csv_fields(&paths, options.given)?,
1687 _ => parquet_fields(first)?,
1688 };
1689 if options.all_varchar {
1690 for field in &mut fields {
1695 field.ty = LogicalType::Varchar;
1696 }
1697 }
1698 if options.binary_as_string {
1699 for field in &mut fields {
1704 if field.ty == LogicalType::Blob {
1705 field.ty = LogicalType::Varchar;
1706 }
1707 }
1708 }
1709 if options.file_row_number {
1710 if fields.iter().any(|field| field.name == FILE_ROW_NUMBER) {
1716 return Err(Error::binder(format!(
1717 "Duplicate column name \"{FILE_ROW_NUMBER}\": the file already has a \
1718 column of that name, so file_row_number cannot add one"
1719 )));
1720 }
1721 fields.push(Field::required(FILE_ROW_NUMBER.to_string(), LogicalType::BigInt));
1722 }
1723 cast = paths.iter().map(|path| self.path_constant(path)).collect();
1724 fields
1725 }
1726 };
1727 let label = if alias == NONE {
1728 resolved.function.name().to_string()
1729 } else {
1730 ast.string(alias).to_string()
1731 };
1732 let names: Vec<&str> = ast.name(columns).collect();
1733 self.table_function_source(
1734 resolved.function,
1735 &cast,
1736 &written_options,
1737 fields,
1738 &label,
1739 &names,
1740 )
1741 }
1742
1743 fn bind_pragma(
1756 &mut self,
1757 ast: &Ast,
1758 function: TableFunction,
1759 fields: &[Field],
1760 argument: ExprRef,
1761 alias: ast::StrRef,
1762 columns: ast::Slice,
1763 ) -> Result<(NodeRef, Scope)> {
1764 let written = self.pragma_name(argument, function)?;
1765 let parts = identifier_parts(&written);
1766 let spelled: Vec<&str> = parts.iter().map(String::as_str).collect();
1767 let name = self.catalog.resolve(&spelled)?;
1768 let described = self.described(ast, &name)?;
1769 let mut rows = Vec::with_capacity(described.len());
1770 for (at, field) in described.iter().enumerate() {
1771 let items = if matches!(function, TableFunction::PragmaShow) {
1772 self.describing(field)
1773 } else {
1774 self.table_info(at, field)
1775 };
1776 rows.push(self.plan.add_expr_list(&items));
1777 }
1778 let rows = self.plan.add_rows(&rows);
1779 let held = self.plan.add_fields(fields);
1780 let index = self.fresh_index();
1781 let node = self.add_node(Node::Values { index, columns: held, rows });
1782 let label =
1783 if alias == NONE { function.name().to_string() } else { ast.string(alias).to_string() };
1784 let mut scope = Scope::empty();
1785 for (at, field) in fields.iter().enumerate() {
1786 scope.push(Visible {
1787 table: label.clone(),
1788 name: field.name.clone(),
1789 binding: ColumnBinding::new(index, at as u32),
1790 ty: field.ty.clone(),
1791 not_null: false,
1792 });
1793 }
1794 if !columns.is_empty() {
1795 let names: Vec<&str> = ast.name(columns).collect();
1796 scope.rename(&names, &label)?;
1797 }
1798 Ok((node, scope))
1799 }
1800
1801 fn pragma_name(&self, argument: ExprRef, function: TableFunction) -> Result<String> {
1811 let Expr::Constant(reference) = *self.plan.expr(argument) else {
1812 return Err(Error::not_implemented(format!(
1813 "{}() given a name that is not a constant",
1814 function.name()
1815 )));
1816 };
1817 match self.plan.value(reference) {
1818 Value::Varchar(name) => Ok(name.clone()),
1819 Value::Null => Ok("NULL".to_string()),
1820 other => {
1821 Err(Error::internal(format!("a pragma name bound as VARCHAR arrived as {other}")))
1822 }
1823 }
1824 }
1825
1826 fn described(&mut self, ast: &Ast, name: &QualifiedName) -> Result<Vec<Field>> {
1837 if self.catalog.entry(name)? == Entry::Table {
1838 return Ok(self.catalog.table(name)?.columns().to_vec());
1839 }
1840 let (_, scope) = self.bind_view(ast, name, NONE, ast::Slice::default())?;
1841 Ok(scope.fields())
1842 }
1843
1844 fn describing(&mut self, field: &Field) -> Vec<ExprRef> {
1846 let written = [
1847 field.name.clone(),
1848 field.ty.to_string(),
1849 if field.not_null { "NO" } else { "YES" }.to_owned(),
1850 ];
1851 let mut items: Vec<ExprRef> =
1852 written.into_iter().map(|text| self.plan.add_constant(Value::Varchar(text))).collect();
1853 for _ in 0..3 {
1854 let empty = self.plan.add_constant(Value::Null);
1855 items.push(self.cast_to(empty, &LogicalType::Varchar));
1856 }
1857 items
1858 }
1859
1860 fn table_info(&mut self, at: usize, field: &Field) -> Vec<ExprRef> {
1866 let cid = self.plan.add_constant(Value::Integer(i32::try_from(at).unwrap_or(i32::MAX)));
1867 let name = self.plan.add_constant(Value::Varchar(field.name.clone()));
1868 let ty = self.plan.add_constant(Value::Varchar(field.ty.to_string()));
1869 let not_null = self.plan.add_constant(Value::Boolean(field.not_null));
1870 let default = self.plan.add_constant(Value::Null);
1871 let default = self.cast_to(default, &LogicalType::Varchar);
1872 let key = self.plan.add_constant(Value::Boolean(false));
1873 vec![cid, name, ty, not_null, default, key]
1874 }
1875
1876 fn named_argument(
1890 &mut self,
1891 function: TableFunction,
1892 name: &str,
1893 expr: ExprRef,
1894 ) -> Result<(&'static str, Value)> {
1895 let known = function
1896 .parameters()
1897 .iter()
1898 .find(|(parameter, _)| parameter.eq_ignore_ascii_case(name));
1899 let Some((parameter, wanted)) = known else {
1900 let candidates: Vec<String> = function
1901 .parameters()
1902 .iter()
1903 .map(|(parameter, ty)| format!(" {parameter} {ty}"))
1904 .collect();
1905 return Err(Error::binder(format!(
1906 "Invalid named parameter \"{name}\" for function {}\nCandidates:\n{}\n",
1907 function.name(),
1908 candidates.join("\n")
1909 )));
1910 };
1911 let Expr::Constant(reference) = *self.plan.expr(expr) else {
1912 return Err(Error::not_implemented(format!(
1913 "the named parameter {parameter} with a value that is not a constant"
1914 )));
1915 };
1916 let value = self.plan.value(reference).clone();
1917 if value == Value::Null {
1918 return Err(Error::binder(null_parameter(function, parameter)));
1919 }
1920 let given = self.plan.expr_type(expr).clone();
1921 if given != *wanted {
1922 return Err(Error::not_implemented(format!(
1923 "the named parameter {parameter} given a {given} where a {wanted} was wanted"
1924 )));
1925 }
1926 Ok((parameter, value))
1927 }
1928
1929 fn bind_replacement_scan(
1940 &mut self,
1941 ast: &Ast,
1942 parts: &[&str],
1943 alias: ast::StrRef,
1944 columns: ast::Slice,
1945 missing: Error,
1946 ) -> Result<(NodeRef, Scope)> {
1947 let [path] = parts else { return Err(missing) };
1948 let path = *path;
1949 let extension = path.rsplit_once('.').map(|(_, after)| after).unwrap_or_default();
1950 let Some(function) = Self::reader_for(extension) else {
1951 if is_file(path) {
1952 return Err(Error::binder(format!(
1957 "No extension found that is capable of reading the file \"{path}\"\n* If this \
1958 file is a supported file format you can explicitly use the reader functions, \
1959 such as read_csv, read_json or read_parquet"
1960 )));
1961 }
1962 return Err(missing);
1963 };
1964 let paths = files(path)?;
1969 let first = paths.first().map_or("", String::as_str);
1970 let fields = match function {
1971 TableFunction::ReadParquet => parquet_fields(first)?,
1972 _ => csv_fields(&paths, Given::default())?,
1973 };
1974 let label = if alias == NONE {
1980 if is_pattern(path) {
1981 path.to_string()
1982 } else {
1983 let file = path.rsplit_once('/').map_or(path, |(_, file)| file);
1984 file.rsplit_once('.').map_or(file, |(stem, _)| stem).to_string()
1985 }
1986 } else {
1987 ast.string(alias).to_string()
1988 };
1989 let arguments: Vec<ExprRef> = paths.iter().map(|path| self.path_constant(path)).collect();
1990 let names: Vec<&str> = ast.name(columns).collect();
1991 self.table_function_source(function, &arguments, &[], fields, &label, &names)
1992 }
1993
1994 fn path_constant(&mut self, path: &str) -> ExprRef {
1996 let value = self.plan.add_value(Value::Varchar(path.to_string()));
1997 self.plan.add_expr(Expr::Constant(value), LogicalType::Varchar)
1998 }
1999
2000 fn reader_for(extension: &str) -> Option<TableFunction> {
2007 if extension.eq_ignore_ascii_case("parquet") {
2008 return Some(TableFunction::ReadParquet);
2009 }
2010 if extension.eq_ignore_ascii_case("csv") || extension.eq_ignore_ascii_case("tsv") {
2011 return Some(TableFunction::ReadCsv);
2012 }
2013 None
2014 }
2015
2016 fn table_function_source(
2021 &mut self,
2022 function: TableFunction,
2023 args: &[ExprRef],
2024 written: &[(&'static str, Value, ExprRef)],
2025 fields: Vec<Field>,
2026 label: &str,
2027 names: &[&str],
2028 ) -> Result<(NodeRef, Scope)> {
2029 let index = self.fresh_index();
2030 let mut scope = Scope::empty();
2031 for (at, field) in fields.iter().enumerate() {
2032 scope.push(Visible {
2033 table: label.to_string(),
2034 name: field.name.clone(),
2035 binding: ColumnBinding::new(index, at as u32),
2036 ty: field.ty.clone(),
2037 not_null: false,
2040 });
2041 }
2042 if !names.is_empty() {
2043 scope.rename(names, label)?;
2044 }
2045 let function = self.plan.intern(function.name());
2046 let args = self.plan.add_expr_list(args);
2047 let named: Vec<u32> =
2048 written.iter().map(|(parameter, _, _)| self.plan.intern(parameter)).collect();
2049 let settings: Vec<ExprRef> = written.iter().map(|(_, _, expr)| *expr).collect();
2050 let options = self.plan.add_name_list(&named);
2051 let settings = self.plan.add_expr_list(&settings);
2052 let columns = self.plan.add_fields(&fields);
2053 let node = self.add_node(Node::TableFunction {
2054 index,
2055 function,
2056 args,
2057 options,
2058 settings,
2059 columns,
2060 });
2061 Ok((node, scope))
2062 }
2063
2064 fn file_paths(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2071 let mut paths = Vec::new();
2072 for pattern in self.file_patterns(expr, name)? {
2073 paths.extend(files(&pattern)?);
2074 }
2075 Ok(paths)
2076 }
2077
2078 fn file_patterns(&self, expr: ExprRef, name: &str) -> Result<Vec<String>> {
2090 let Expr::Constant(reference) = *self.plan.expr(expr) else {
2091 return Err(Error::not_implemented(
2092 "a table function file name that is not a constant",
2093 ));
2094 };
2095 match self.plan.value(reference) {
2096 Value::Varchar(path) => Ok(vec![path.clone()]),
2097 Value::Null => Err(Error::parser(format!("{name} cannot take NULL list as parameter"))),
2099 Value::List { values, .. } => values
2100 .iter()
2101 .map(|value| match value {
2102 Value::Varchar(path) => Ok(path.clone()),
2103 _ => Err(Error::parser(format!(
2104 "{name} reader cannot take NULL input as parameter"
2105 ))),
2106 })
2107 .collect(),
2108 other => {
2109 Err(Error::internal(format!("a file name bound as VARCHAR arrived as {other}")))
2110 }
2111 }
2112 }
2113
2114 #[allow(clippy::too_many_arguments)]
2115 fn bind_join(
2116 &mut self,
2117 ast: &Ast,
2118 left: ast::SourceRef,
2119 right: ast::SourceRef,
2120 kind: ast::JoinKind,
2121 natural: bool,
2122 on: ast::ExprRef,
2123 using: ast::Slice,
2124 ) -> Result<(NodeRef, Scope)> {
2125 let (left_node, left_scope) = self.bind_source(ast, left)?;
2126 let (right_node, right_scope, correlated) = self.bind_lateral(ast, right, &left_scope)?;
2127 if !correlated.is_empty()
2131 && !matches!(kind, ast::JoinKind::Inner | ast::JoinKind::Cross | ast::JoinKind::Left)
2132 {
2133 return Err(Error::binder(
2134 "The combining JOIN type must be INNER or LEFT for a LATERAL reference",
2135 ));
2136 }
2137 let split = left_scope.len();
2138 let mut scope = left_scope.concat(right_scope);
2139
2140 let merged: Vec<String> = if natural {
2143 let mut names = Vec::new();
2144 for (at, column) in scope.columns.iter().enumerate().take(split) {
2145 if scope.columns[split..].iter().any(|right| same_name(&right.name, &column.name))
2146 && !names.iter().any(|held: &String| same_name(held, &column.name))
2147 {
2148 let _ = at;
2149 names.push(column.name.clone());
2150 }
2151 }
2152 names
2153 } else {
2154 let mut names: Vec<String> = Vec::new();
2160 for name in ast.name(using) {
2161 if !names.iter().any(|held| same_name(held, name)) {
2162 names.push(name.to_string());
2163 }
2164 }
2165 names
2166 };
2167
2168 let mut conditions = Vec::new();
2169 let mut dropped = Vec::new();
2170 for name in &merged {
2171 let left_at = scope.columns[..split]
2172 .iter()
2173 .position(|column| same_name(&column.name, name))
2174 .ok_or_else(|| {
2175 Error::binder(format!(
2176 "column \"{name}\" specified in USING clause does not exist in left table"
2177 ))
2178 })?;
2179 let right_at = scope.columns[split..]
2180 .iter()
2181 .position(|column| same_name(&column.name, name))
2182 .map(|at| at + split)
2183 .ok_or_else(|| {
2184 Error::binder(format!(
2185 "column \"{name}\" specified in USING clause does not exist in right table"
2186 ))
2187 })?;
2188 let left_column = &scope.columns[left_at];
2189 let (left_binding, left_type) = (left_column.binding, left_column.ty.clone());
2190 let right_column = &scope.columns[right_at];
2191 let (right_binding, right_type) = (right_column.binding, right_column.ty.clone());
2192 let left_expr = self.plan.add_expr(Expr::Column(left_binding), left_type);
2193 let right_expr = self.plan.add_expr(Expr::Column(right_binding), right_type);
2194 conditions.push(self.compare(rudb_plan::CompareOp::Equal, left_expr, right_expr)?);
2195 dropped.push(right_at);
2196 }
2197 dropped.sort_unstable();
2200 for at in dropped.into_iter().rev() {
2201 scope.remove(at);
2202 }
2203
2204 if on != NONE {
2205 if !merged.is_empty() {
2206 return Err(Error::binder("a join cannot have both ON and USING"));
2207 }
2208 self.clause = "JOIN condition";
2209 let predicate = self.bind_expr(ast, on, &scope)?;
2210 conditions.push(self.as_boolean(predicate, "JOIN")?);
2211 }
2212
2213 if kind == ast::JoinKind::Cross && !conditions.is_empty() {
2214 return Err(Error::binder("a CROSS JOIN cannot have a condition"));
2215 }
2216 if correlated.is_empty()
2220 && conditions.is_empty()
2221 && matches!(kind, ast::JoinKind::Cross | ast::JoinKind::Inner)
2222 {
2223 let node = self.add_node(Node::CrossProduct { left: left_node, right: right_node });
2224 return Ok((node, scope));
2225 }
2226 let kind = match kind {
2227 ast::JoinKind::Inner | ast::JoinKind::Cross => JoinKind::Inner,
2228 ast::JoinKind::Left => JoinKind::Left,
2229 ast::JoinKind::Right => JoinKind::Right,
2230 ast::JoinKind::Full => JoinKind::Full,
2231 ast::JoinKind::Semi => JoinKind::Semi,
2232 ast::JoinKind::Anti => JoinKind::Anti,
2233 ast::JoinKind::Positional => JoinKind::Positional,
2234 };
2235 let conditions = self.plan.add_expr_list(&conditions);
2236 let node = if correlated.is_empty() {
2237 self.add_node(Node::Join {
2238 left: left_node,
2239 right: right_node,
2240 kind,
2241 conditions,
2242 build: BuildSide::default(),
2243 })
2244 } else {
2245 self.add_node(Node::DependentJoin {
2246 left: left_node,
2247 right: right_node,
2248 kind,
2249 conditions,
2250 })
2251 };
2252 Ok((node, scope))
2253 }
2254
2255 fn bind_filter(
2263 &mut self,
2264 ast: &Ast,
2265 filter: ast::ExprRef,
2266 scope: &Scope,
2267 ) -> Result<Option<ExprRef>> {
2268 if filter == NONE {
2269 return Ok(None);
2270 }
2271 let bound = self.bind_expr(ast, filter, scope)?;
2272 Ok(Some(self.checked_cast_to(bound, &LogicalType::Boolean, false)?))
2273 }
2274
2275 pub(crate) fn bind_aggregate(
2277 &mut self,
2278 ast: &Ast,
2279 name: &str,
2280 args: &[ast::ExprRef],
2281 distinct: bool,
2282 filter: ast::ExprRef,
2283 scope: &Scope,
2284 ) -> Result<ExprRef> {
2285 if self.in_filter {
2286 return Err(Error::binder("aggregate functions are not allowed in FILTER"));
2287 }
2288 if self.in_aggregate {
2289 return Err(Error::binder(format!(
2290 "aggregate function calls cannot be nested, and {name}() is inside one"
2291 )));
2292 }
2293 if self.aggregation.is_none() {
2294 return Err(Error::binder(format!(
2295 "aggregate function calls cannot be used in the {}",
2296 self.clause
2297 )));
2298 }
2299 self.in_aggregate = true;
2304 self.in_filter = true;
2305 let filter = self.bind_filter(ast, filter, scope);
2306 self.in_filter = false;
2307 self.in_aggregate = false;
2308 let filter = filter?;
2309
2310 self.in_aggregate = true;
2311 let mut bound = Vec::with_capacity(args.len());
2312 let mut failure = None;
2313 for &arg in args {
2314 match self.bind_expr(ast, arg, scope) {
2315 Ok(expr) => bound.push(expr),
2316 Err(error) => {
2317 failure = Some(error);
2318 break;
2319 }
2320 }
2321 }
2322 self.in_aggregate = false;
2323 if let Some(error) = failure {
2324 return Err(error);
2325 }
2326
2327 let types: Vec<LogicalType> =
2328 bound.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2329 let resolved = resolve(name, &types)?;
2330 let mut cast = Vec::with_capacity(bound.len());
2331 for (arg, wanted) in bound.iter().zip(&resolved.arguments) {
2332 cast.push(self.checked_cast_to(*arg, wanted, false)?);
2333 }
2334 let args = self.plan.add_expr_list(&cast);
2335 let name = self.plan.intern(resolved.name);
2336 let ty = resolved.returns;
2337 let call = self.plan.add_expr(Expr::Aggregate { name, args, distinct, filter }, ty.clone());
2338
2339 let existing = self.aggregation.as_ref().map(|held| held.aggregates.clone());
2342 let existing = existing.unwrap_or_default();
2343 let at = match existing.iter().position(|&held| self.same_expr(held, call)) {
2344 Some(at) => at,
2345 None => {
2346 let aggregation = self.aggregation.as_mut().expect("checked above");
2347 aggregation.aggregates.push(call);
2348 aggregation.aggregates.len() - 1
2349 }
2350 };
2351 let aggregation = self.aggregation.as_ref().expect("checked above");
2352 let (index, groups) = (aggregation.index, aggregation.groups.len());
2353 Ok(self.column(index, groups + at, ty))
2354 }
2355
2356 pub(crate) fn bind_window(
2364 &mut self,
2365 ast: &Ast,
2366 written: &WindowCall<'_>,
2367 scope: &Scope,
2368 ) -> Result<ExprRef> {
2369 let WindowCall { name, args, distinct, filter, ignore_nulls, spec } = *written;
2370 if self.in_aggregate {
2371 return Err(Error::binder(
2372 "aggregate function calls cannot contain window function calls",
2373 ));
2374 }
2375 if self.in_window {
2376 return Err(Error::binder("window function calls cannot be nested"));
2377 }
2378 let clause = if self.clause == "JOIN condition" { "WHERE clause" } else { self.clause };
2382 if clause != "SELECT clause" && clause != "ORDER BY clause" {
2383 return Err(Error::binder(format!("{clause} cannot contain window functions!")));
2384 }
2385
2386 let starred = args.iter().any(|&arg| {
2390 matches!(ast.expr(arg), ast::Expr::Star { qualifier, replacements }
2391 if qualifier.is_empty() && replacements.is_empty())
2392 });
2393 let (name, args): (&str, &[ast::ExprRef]) = if starred {
2394 if !same_name(name, "count") || args.len() != 1 {
2395 return Err(Error::binder(format!("* is not allowed in {name}()")));
2396 }
2397 ("count_star", &[])
2398 } else if same_name(name, "count") && args.is_empty() {
2399 ("count_star", &[])
2402 } else {
2403 (name, args)
2404 };
2405
2406 let held = ast.window(spec);
2407 self.in_window = true;
2408 let parts = self.window_parts(ast, args, held, scope);
2409 let filter = if parts.is_ok() { self.bind_filter(ast, filter, scope) } else { Ok(None) };
2414 self.in_window = false;
2415 let parts = parts?;
2416 let filter = filter?;
2417 let offsets = [parts.frame.start, parts.frame.end]
2420 .iter()
2421 .any(|end| matches!(end, WindowBound::Preceding(_) | WindowBound::Following(_)));
2422 if parts.frame.unit == WindowUnit::Range && offsets && parts.order.len() != 1 {
2423 return Err(Error::binder("RANGE frames must have only one ORDER BY expression"));
2424 }
2425
2426 let types: Vec<LogicalType> =
2427 parts.args.iter().map(|&arg| self.plan.expr_type(arg).clone()).collect();
2428 let resolved = window_signature(name, &types)?;
2429 if resolved.name == "fill" {
2432 let keys: Vec<LogicalType> =
2433 parts.order.iter().map(|key| self.plan.expr_type(key.expr).clone()).collect();
2434 refuse_fill(&types[0], &keys, distinct, ignore_nulls)?;
2435 }
2436 if distinct && kind_of(resolved.name) == Some(FunctionKind::Window) {
2440 return Err(Error::binder(format!(
2441 "DISTINCT is not implemented for the window function \"\"{name}\"\""
2442 )));
2443 }
2444 if filter.is_some() && kind_of(resolved.name) == Some(FunctionKind::Window) {
2447 return Err(Error::binder(format!(
2448 "FILTER is not implemented for the window function \"\"{name}\"\""
2449 )));
2450 }
2451 let mut cast = Vec::with_capacity(parts.args.len());
2452 for (arg, wanted) in parts.args.iter().zip(&resolved.arguments) {
2453 cast.push(self.checked_cast_to(*arg, wanted, false)?);
2454 }
2455 let args = self.plan.add_expr_list(&cast);
2456 let name = self.plan.intern(resolved.name);
2457 let ty = resolved.returns;
2458 let call = self
2459 .plan
2460 .add_expr(Expr::Window { name, args, distinct, filter, ignore_nulls }, ty.clone());
2461
2462 let at = self.window_run(parts.partition, parts.order, parts.frame, call);
2463 let index = self.windows.last().expect("the run was just filed").index;
2464 Ok(self.column(index, at, ty))
2465 }
2466
2467 fn window_run(
2474 &mut self,
2475 partition: Vec<ExprRef>,
2476 order: Vec<SortKey>,
2477 frame: WindowFrame,
2478 call: ExprRef,
2479 ) -> usize {
2480 let matches = self.windows.last().is_some_and(|run| {
2481 run.frame == frame
2482 && run.partition.len() == partition.len()
2483 && run.order.len() == order.len()
2484 && run.partition.iter().zip(&partition).all(|(&l, &r)| self.same_expr(l, r))
2485 && run.order.iter().zip(&order).all(|(l, r)| {
2486 l.descending == r.descending
2487 && l.nulls_first == r.nulls_first
2488 && self.same_expr(l.expr, r.expr)
2489 })
2490 });
2491 if !matches {
2492 let index = self.fresh_index();
2493 self.windows.push(WindowRun { index, partition, order, frame, calls: Vec::new() });
2494 }
2495 let calls = self.windows.last().expect("a run is open").calls.clone();
2498 if let Some(at) = calls.iter().position(|&held| self.same_expr(held, call)) {
2499 return at;
2500 }
2501 let run = self.windows.last_mut().expect("a run is open");
2502 run.calls.push(call);
2503 run.calls.len() - 1
2504 }
2505
2506 fn window_parts(
2512 &mut self,
2513 ast: &Ast,
2514 args: &[ast::ExprRef],
2515 held: ast::WindowSpec,
2516 scope: &Scope,
2517 ) -> Result<WindowParts> {
2518 let mut bound = Vec::with_capacity(args.len());
2519 for &arg in args {
2520 let expr = self.bind_expr(ast, arg, scope)?;
2521 bound.push(self.over_aggregate(expr, scope)?);
2522 }
2523 let mut partition = Vec::new();
2524 for &key in ast.expr_list(held.partition) {
2525 let expr = self.bind_expr(ast, key, scope)?;
2526 partition.push(self.over_aggregate(expr, scope)?);
2527 }
2528 let mut order = Vec::new();
2529 for item in ast.order_list(held.order).to_vec() {
2530 let expr = self.bind_expr(ast, item.expr, scope)?;
2531 let expr = self.over_aggregate(expr, scope)?;
2532 order.push(self.sort_key(expr, item));
2533 }
2534 let frame = WindowFrame {
2535 unit: match held.unit {
2536 ast::WindowUnit::Rows => WindowUnit::Rows,
2537 ast::WindowUnit::Range => WindowUnit::Range,
2538 ast::WindowUnit::Groups => WindowUnit::Groups,
2539 },
2540 start: self.window_bound(ast, held.start, scope)?,
2541 end: self.window_bound(ast, held.end, scope)?,
2542 exclude: match held.exclude {
2543 ast::WindowExclude::NoOthers => WindowExclude::NoOthers,
2544 ast::WindowExclude::CurrentRow => WindowExclude::CurrentRow,
2545 ast::WindowExclude::Group => WindowExclude::Group,
2546 ast::WindowExclude::Ties => WindowExclude::Ties,
2547 },
2548 };
2549 Ok(WindowParts { args: bound, partition, order, frame })
2550 }
2551
2552 fn window_bound(
2554 &mut self,
2555 ast: &Ast,
2556 bound: ast::WindowBound,
2557 scope: &Scope,
2558 ) -> Result<WindowBound> {
2559 let offset = |binder: &mut Self, written| {
2560 let expr = binder.bind_expr(ast, written, scope)?;
2561 binder.over_aggregate(expr, scope)
2562 };
2563 Ok(match bound {
2564 ast::WindowBound::UnboundedPreceding => WindowBound::UnboundedPreceding,
2565 ast::WindowBound::CurrentRow => WindowBound::CurrentRow,
2566 ast::WindowBound::UnboundedFollowing => WindowBound::UnboundedFollowing,
2567 ast::WindowBound::Preceding(written) => WindowBound::Preceding(offset(self, written)?),
2568 ast::WindowBound::Following(written) => WindowBound::Following(offset(self, written)?),
2569 })
2570 }
2571
2572 fn is_window_output(&self, binding: ColumnBinding) -> bool {
2574 self.windows.iter().any(|run| run.index == binding.table)
2575 }
2576
2577 pub(crate) fn over_aggregate(&mut self, expr: ExprRef, scope: &Scope) -> Result<ExprRef> {
2583 let Some(aggregation) = self.aggregation.as_ref() else {
2584 return Ok(expr);
2585 };
2586 let index = aggregation.index;
2587 let groups = aggregation.groups.clone();
2588 for (at, group) in groups.iter().enumerate() {
2589 if self.same_expr(expr, *group) {
2590 let ty = self.plan.expr_type(*group).clone();
2591 return Ok(self.column(index, at, ty));
2592 }
2593 }
2594 let ty = self.plan.expr_type(expr).clone();
2595 match self.plan.expr(expr).clone() {
2596 Expr::Column(binding) if binding.table == index => Ok(expr),
2597 Expr::Column(binding) if self.is_window_output(binding) => Ok(expr),
2602 Expr::Column(binding) if self.joined_above.contains(&binding.table) => Ok(expr),
2607 Expr::Column(binding) => {
2608 let name =
2609 scope.columns.iter().find(|column| column.binding == binding).map_or_else(
2610 || "a column".to_string(),
2611 |column| format!("\"{}\"", column.name),
2612 );
2613 Err(Error::binder(format!(
2614 "column {name} must appear in the GROUP BY clause or must be part of an aggregate function"
2615 )))
2616 }
2617 Expr::Constant(_) | Expr::Aggregate { .. } | Expr::Window { .. } => Ok(expr),
2618 Expr::Cast { input, try_cast } => {
2619 let input = self.over_aggregate(input, scope)?;
2620 Ok(self.plan.add_expr(Expr::Cast { input, try_cast }, ty))
2621 }
2622 Expr::Compare { op, left, right } => {
2623 let left = self.over_aggregate(left, scope)?;
2624 let right = self.over_aggregate(right, scope)?;
2625 Ok(self.plan.add_expr(Expr::Compare { op, left, right }, ty))
2626 }
2627 Expr::Conjunction { op, children } => {
2628 let written = self.plan.expr_list(children).to_vec();
2629 let mut rewritten = Vec::with_capacity(written.len());
2630 for child in written {
2631 rewritten.push(self.over_aggregate(child, scope)?);
2632 }
2633 let children = self.plan.add_expr_list(&rewritten);
2634 Ok(self.plan.add_expr(Expr::Conjunction { op, children }, ty))
2635 }
2636 Expr::Function { name, args } => {
2637 let written = self.plan.expr_list(args).to_vec();
2638 let mut rewritten = Vec::with_capacity(written.len());
2639 for arg in written {
2640 rewritten.push(self.over_aggregate(arg, scope)?);
2641 }
2642 let args = self.plan.add_expr_list(&rewritten);
2643 Ok(self.plan.add_expr(Expr::Function { name, args }, ty))
2644 }
2645 Expr::Case { arms, otherwise } => {
2646 let written = self.plan.arm_list(arms).to_vec();
2647 let mut rewritten = Vec::with_capacity(written.len());
2648 for arm in written {
2649 let when = self.over_aggregate(arm.when, scope)?;
2650 let then = self.over_aggregate(arm.then, scope)?;
2651 rewritten.push(rudb_plan::Arm { when, then });
2652 }
2653 let otherwise = match otherwise {
2654 Some(expr) => Some(self.over_aggregate(expr, scope)?),
2655 None => None,
2656 };
2657 let arms = self.plan.add_arms(&rewritten);
2658 Ok(self.plan.add_expr(Expr::Case { arms, otherwise }, ty))
2659 }
2660 }
2661 }
2662
2663 pub(crate) fn same_expr(&self, left: ExprRef, right: ExprRef) -> bool {
2665 same_expr(&self.plan, left, right)
2666 }
2667}
2668
2669#[derive(Debug, Default)]
2679struct Options {
2680 binary_as_string: bool,
2683 all_varchar: bool,
2685 file_row_number: bool,
2690 given: Given,
2692}
2693
2694impl Options {
2695 fn of(written: &[(&'static str, Value, ExprRef)]) -> Result<Self> {
2702 let mut options = Self::default();
2703 for (parameter, value, _) in written {
2704 match (*parameter, value) {
2705 ("binary_as_string", Value::Boolean(on)) => options.binary_as_string = *on,
2706 ("all_varchar", Value::Boolean(on)) => options.all_varchar = *on,
2707 ("file_row_number", Value::Boolean(on)) => options.file_row_number = *on,
2708 _ => {}
2709 }
2710 }
2711 let named: Vec<(&str, Value)> =
2712 written.iter().map(|(parameter, value, _)| (*parameter, value.clone())).collect();
2713 options.given = csv_given(&named)?;
2714 Ok(options)
2715 }
2716}
2717
2718fn null_parameter(function: TableFunction, parameter: &str) -> String {
2727 match parameter {
2728 "header" => format!("\"{parameter}\" expects a non-null boolean value (e.g. TRUE or 1)"),
2729 "all_varchar" => format!("{} \"{parameter}\" cannot be NULL", function.name()),
2730 _ => format!("Cannot use NULL as argument to \"{parameter}\""),
2731 }
2732}
2733
2734fn missing_replacement(name: &str, input: &Scope) -> Error {
2739 Error::binder(format!(
2740 "Column \"{name}\" in REPLACE list not found in FROM clause{}",
2741 input.candidates()
2742 ))
2743}
2744
2745fn subtractable(ty: &LogicalType, ordering: bool) -> bool {
2754 if ty.is_numeric() {
2755 return true;
2756 }
2757 match ty {
2758 LogicalType::Date
2759 | LogicalType::Time
2760 | LogicalType::Timestamp
2761 | LogicalType::TimestampS
2762 | LogicalType::TimestampMs
2763 | LogicalType::TimestampNs
2764 | LogicalType::TimestampTz => true,
2765 LogicalType::TimeTz => ordering,
2766 _ => false,
2767 }
2768}
2769
2770fn refuse_fill(
2779 argument: &LogicalType,
2780 order: &[LogicalType],
2781 distinct: bool,
2782 ignore_nulls: bool,
2783) -> Result<()> {
2784 if !subtractable(argument, false) {
2785 return Err(Error::binder("FILL argument must support subtraction"));
2786 }
2787 let [key] = order else {
2788 return Err(Error::binder("FILL functions must have only one ORDER BY expression"));
2789 };
2790 if !subtractable(key, true) {
2791 return Err(Error::binder("FILL ordering must support subtraction"));
2792 }
2793 if distinct {
2794 return Err(Error::binder(
2795 "DISTINCT is not implemented for the window function \"\"fill\"\"",
2796 ));
2797 }
2798 if ignore_nulls {
2799 return Err(Error::binder(
2800 "RESPECT/IGNORE NULLS is not supported for the window function \"fill\"",
2801 ));
2802 }
2803 Ok(())
2804}
2805
2806fn window_signature(name: &str, types: &[LogicalType]) -> Result<Resolved> {
2813 match kind_of(name) {
2814 Some(FunctionKind::Aggregate | FunctionKind::Window) => resolve(name, types),
2815 Some(FunctionKind::Scalar) => {
2816 Err(Error::catalog(format!("{name} is not an aggregate function")))
2817 }
2818 None => Err(Error::catalog(format!("Aggregate Function with name {name} does not exist!"))),
2819 }
2820}
2821
2822fn same_expr(plan: &Plan, left: ExprRef, right: ExprRef) -> bool {
2824 if left == right {
2825 return true;
2826 }
2827 if plan.expr_type(left) != plan.expr_type(right) {
2828 return false;
2829 }
2830 let lists = |left, right| {
2831 let left: &[ExprRef] = plan.expr_list(left);
2832 let right: &[ExprRef] = plan.expr_list(right);
2833 left.len() == right.len()
2834 && left.iter().zip(right).all(|(&left, &right)| same_expr(plan, left, right))
2835 };
2836 match (plan.expr(left), plan.expr(right)) {
2837 (Expr::Column(left), Expr::Column(right)) => left == right,
2838 (Expr::Constant(left), Expr::Constant(right)) => plan.value(*left) == plan.value(*right),
2839 (
2840 Expr::Cast { input: left, try_cast: left_try },
2841 Expr::Cast { input: right, try_cast: right_try },
2842 ) => left_try == right_try && same_expr(plan, *left, *right),
2843 (
2844 Expr::Compare { op: left_op, left: left_a, right: left_b },
2845 Expr::Compare { op: right_op, left: right_a, right: right_b },
2846 ) => {
2847 left_op == right_op
2848 && same_expr(plan, *left_a, *right_a)
2849 && same_expr(plan, *left_b, *right_b)
2850 }
2851 (
2852 Expr::Conjunction { op: left_op, children: left_children },
2853 Expr::Conjunction { op: right_op, children: right_children },
2854 ) => left_op == right_op && lists(*left_children, *right_children),
2855 (
2856 Expr::Function { name: left_name, args: left_args },
2857 Expr::Function { name: right_name, args: right_args },
2858 ) => plan.string(*left_name) == plan.string(*right_name) && lists(*left_args, *right_args),
2859 (
2860 Expr::Aggregate {
2861 name: left_name,
2862 args: left_args,
2863 distinct: left_distinct,
2864 filter: left_filter,
2865 },
2866 Expr::Aggregate {
2867 name: right_name,
2868 args: right_args,
2869 distinct: right_distinct,
2870 filter: right_filter,
2871 },
2872 ) => {
2873 plan.string(*left_name) == plan.string(*right_name)
2874 && left_distinct == right_distinct
2875 && match (left_filter, right_filter) {
2876 (None, None) => true,
2877 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2878 _ => false,
2879 }
2880 && lists(*left_args, *right_args)
2881 }
2882 (
2886 Expr::Window {
2887 name: left_name,
2888 args: left_args,
2889 distinct: left_distinct,
2890 filter: left_filter,
2891 ignore_nulls: left_nulls,
2892 },
2893 Expr::Window {
2894 name: right_name,
2895 args: right_args,
2896 distinct: right_distinct,
2897 filter: right_filter,
2898 ignore_nulls: right_nulls,
2899 },
2900 ) => {
2901 plan.string(*left_name) == plan.string(*right_name)
2902 && left_distinct == right_distinct
2903 && left_nulls == right_nulls
2904 && match (left_filter, right_filter) {
2905 (None, None) => true,
2906 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2907 _ => false,
2908 }
2909 && lists(*left_args, *right_args)
2910 }
2911 (
2912 Expr::Case { arms: left_arms, otherwise: left_otherwise },
2913 Expr::Case { arms: right_arms, otherwise: right_otherwise },
2914 ) => {
2915 let left_arms = plan.arm_list(*left_arms);
2916 let right_arms = plan.arm_list(*right_arms);
2917 left_arms.len() == right_arms.len()
2918 && left_arms.iter().zip(right_arms).all(|(left, right)| {
2919 same_expr(plan, left.when, right.when) && same_expr(plan, left.then, right.then)
2920 })
2921 && match (left_otherwise, right_otherwise) {
2922 (None, None) => true,
2923 (Some(left), Some(right)) => same_expr(plan, *left, *right),
2924 _ => false,
2925 }
2926 }
2927 _ => false,
2928 }
2929}