1use std::borrow::Cow;
40use std::cell::RefCell;
41use std::collections::{BTreeMap, BTreeSet};
42use std::convert::{TryFrom, TryInto};
43use std::num::NonZeroU64;
44use std::rc::Rc;
45use std::sync::{Arc, LazyLock};
46use std::{iter, mem};
47
48use itertools::Itertools;
49use mz_expr::func::variadic::{
50 ArrayCreate, ArrayIndex, Coalesce, Greatest, Least, ListCreate, ListIndex, ListSliceLinear,
51 MapBuild, RecordCreate,
52};
53use mz_expr::virtual_syntax::AlgExcept;
54use mz_expr::{
55 Id, LetRecLimit, LocalId, MapFilterProject, MirScalarExpr, REPEAT_ROW_NAME, RowSetFinishing,
56 TableFunc, func as expr_func,
57};
58use mz_ore::collections::CollectionExt;
59use mz_ore::error::ErrorExt;
60use mz_ore::id_gen::IdGen;
61use mz_ore::option::FallibleMapExt;
62use mz_ore::stack::{CheckedRecursion, RecursionGuard};
63use mz_ore::str::StrExt;
64use mz_repr::adt::char::CharLength;
65use mz_repr::adt::numeric::{NUMERIC_DATUM_MAX_PRECISION, NumericMaxScale};
66use mz_repr::adt::timestamp::TimestampPrecision;
67use mz_repr::adt::varchar::VarCharMaxLength;
68use mz_repr::namespaces::MZ_CATALOG_SCHEMA;
69use mz_repr::{
70 CatalogItemId, ColumnIndex, ColumnName, Datum, RelationDesc, RelationVersionSelector,
71 ReprColumnType, Row, RowArena, SqlColumnType, SqlRelationType, SqlScalarType,
72 UNKNOWN_COLUMN_NAME, strconv,
73};
74use mz_sql_parser::ast::display::AstDisplay;
75use mz_sql_parser::ast::visit::Visit;
76use mz_sql_parser::ast::visit_mut::{self, VisitMut};
77use mz_sql_parser::ast::{
78 AsOf, Assignment, AstInfo, CastFailureMode, CreateWebhookSourceBody, CreateWebhookSourceCheck,
79 CreateWebhookSourceHeader, CreateWebhookSourceSecret, CteBlock, DeleteStatement, Distinct,
80 Expr, Function, FunctionArgs, HomogenizingFunction, Ident, InsertSource, IsExprConstruct, Join,
81 JoinConstraint, JoinOperator, Limit, MapEntry, MutRecBlock, MutRecBlockOption,
82 MutRecBlockOptionName, OrderByExpr, Query, Select, SelectItem, SelectOption, SelectOptionName,
83 SetExpr, SetOperator, ShowStatement, SubscriptPosition, TableAlias, TableFactor,
84 TableWithJoins, UnresolvedItemName, UpdateStatement, Value, Values, WindowFrame,
85 WindowFrameBound, WindowFrameUnits, WindowSpec, visit,
86};
87use mz_sql_parser::ident;
88
89use crate::catalog::{CatalogItemType, CatalogType, SessionCatalog};
90use crate::func::{self, Func, FuncSpec, TableFuncImpl};
91use crate::names::{
92 Aug, FullItemName, PartialItemName, ResolvedDataType, ResolvedItemName, SchemaSpecifier,
93};
94use crate::plan::PlanError::InvalidWmrRecursionLimit;
95use crate::plan::error::PlanError;
96use crate::plan::hir::{
97 AbstractColumnType, AbstractExpr, AggregateExpr, AggregateFunc, AggregateWindowExpr,
98 BinaryFunc, CoercibleScalarExpr, CoercibleScalarType, ColumnOrder, ColumnRef, Hir,
99 HirRelationExpr, HirScalarExpr, JoinKind, ScalarWindowExpr, ScalarWindowFunc, UnaryFunc,
100 ValueWindowExpr, ValueWindowFunc, VariadicFunc, WindowExpr, WindowExprType,
101};
102use crate::plan::plan_utils::{self, GroupSizeHints, JoinSide};
103use crate::plan::scope::{Scope, ScopeItem, ScopeUngroupedColumn};
104use crate::plan::statement::{StatementContext, StatementDesc, show};
105use crate::plan::typeconv::{self, CastContext, plan_hypothetical_cast};
106use crate::plan::{
107 Params, PlanContext, QueryWhen, ShowCreatePlan, WebhookValidation, WebhookValidationSecret,
108 literal, transform_ast,
109};
110use crate::session::vars::ENABLE_WITH_ORDINALITY_LEGACY_FALLBACK;
111use crate::session::vars::{self, FeatureFlag};
112use crate::{ORDINALITY_COL_NAME, normalize};
113
114#[derive(Debug)]
115pub struct PlannedRootQuery<E> {
116 pub expr: E,
117 pub desc: RelationDesc,
118 pub finishing: RowSetFinishing<HirScalarExpr, HirScalarExpr>,
119 pub scope: Scope,
120}
121
122#[mz_ore::instrument(target = "compiler", level = "trace", name = "ast_to_hir")]
131pub fn plan_root_query(
132 scx: &StatementContext,
133 mut query: Query<Aug>,
134 lifetime: QueryLifetime,
135) -> Result<PlannedRootQuery<HirRelationExpr>, PlanError> {
136 transform_ast::transform(scx, &mut query)?;
137 let mut qcx = QueryContext::root(scx, lifetime);
138 let PlannedQuery {
139 mut expr,
140 scope,
141 order_by,
142 limit,
143 offset,
144 project,
145 group_size_hints,
146 } = plan_query(&mut qcx, &query)?;
147
148 let mut finishing = RowSetFinishing {
149 limit,
150 offset,
151 project,
152 order_by,
153 };
154
155 try_push_projection_order_by(&mut expr, &mut finishing.project, &mut finishing.order_by);
161
162 if lifetime.is_maintained() {
163 expr.finish_maintained(&mut finishing, group_size_hints);
164 }
165
166 let typ = qcx.relation_type(&expr);
167 let typ = SqlRelationType::new(
168 finishing
169 .project
170 .iter()
171 .map(|i| typ.column_types[*i].clone())
172 .collect(),
173 );
174 let desc = RelationDesc::new(typ, scope.column_names());
175
176 Ok(PlannedRootQuery {
177 expr,
178 desc,
179 finishing,
180 scope,
181 })
182}
183
184fn try_push_projection_order_by(
195 expr: &mut HirRelationExpr,
196 project: &mut Vec<usize>,
197 order_by: &mut Vec<ColumnOrder>,
198) -> bool {
199 let mut unproject = vec![None; expr.arity()];
200 for (out_i, in_i) in project.iter().copied().enumerate() {
201 unproject[in_i] = Some(out_i);
202 }
203 if order_by
204 .iter()
205 .all(|ob| ob.column < unproject.len() && unproject[ob.column].is_some())
206 {
207 let trivial_project = (0..project.len()).collect();
208 *expr = expr.take().project(mem::replace(project, trivial_project));
209 for ob in order_by {
210 ob.column = unproject[ob.column].unwrap();
211 }
212 true
213 } else {
214 false
215 }
216}
217
218pub fn plan_insert_query(
219 scx: &StatementContext,
220 table_name: ResolvedItemName,
221 columns: Vec<Ident>,
222 source: InsertSource<Aug>,
223 returning: Vec<SelectItem<Aug>>,
224) -> Result<
225 (
226 CatalogItemId,
227 HirRelationExpr,
228 PlannedRootQuery<Vec<HirScalarExpr>>,
229 ),
230 PlanError,
231> {
232 let mut qcx = QueryContext::root(scx, QueryLifetime::OneShot);
233 let table = scx.get_item_by_resolved_name(&table_name)?;
234
235 if table.item_type() != CatalogItemType::Table {
237 sql_bail!(
238 "cannot insert into {} '{}'",
239 table.item_type(),
240 table_name.full_name_str()
241 );
242 }
243 let desc = table
244 .relation_desc()
245 .ok_or_else(|| sql_err!("item does not have a relation description"))?;
246 let mut defaults = table
247 .writable_table_details()
248 .ok_or_else(|| {
249 sql_err!(
250 "cannot insert into non-writeable table '{}'",
251 table_name.full_name_str()
252 )
253 })?
254 .to_vec();
255
256 for default in &mut defaults {
257 transform_ast::transform(scx, default)?;
258 }
259
260 if table.id().is_system() {
261 sql_bail!(
262 "cannot insert into system table '{}'",
263 table_name.full_name_str()
264 );
265 }
266
267 let columns: Vec<_> = columns.into_iter().map(normalize::column_name).collect();
268
269 let mut source_types = Vec::with_capacity(columns.len());
271 let mut ordering = Vec::with_capacity(columns.len());
272
273 if columns.is_empty() {
274 source_types.extend(desc.iter_types().map(|x| &x.scalar_type));
277 ordering.extend(0..desc.arity());
278 } else {
279 let column_by_name: BTreeMap<&ColumnName, (usize, &SqlColumnType)> = desc
280 .iter()
281 .enumerate()
282 .map(|(idx, (name, typ))| (name, (idx, typ)))
283 .collect();
284
285 for c in &columns {
286 if let Some((idx, typ)) = column_by_name.get(c) {
287 ordering.push(*idx);
288 source_types.push(&typ.scalar_type);
289 } else {
290 sql_bail!(
291 "column {} of relation {} does not exist",
292 c.quoted(),
293 table_name.full_name_str().quoted()
294 );
295 }
296 }
297 if let Some(dup) = columns.iter().duplicates().next() {
298 sql_bail!("column {} specified more than once", dup.quoted());
299 }
300 };
301
302 let expr = match source {
304 InsertSource::Query(mut query) => {
305 transform_ast::transform(scx, &mut query)?;
306
307 match query {
308 Query {
310 body: SetExpr::Values(Values(values)),
311 ctes,
312 order_by,
313 limit: None,
314 offset: None,
315 } if ctes.is_empty() && order_by.is_empty() => {
316 let names: Vec<_> = ordering.iter().map(|i| desc.get_name(*i)).collect();
317 plan_values_insert(&qcx, &names, &source_types, &values)?
318 }
319 _ => {
320 let (expr, _scope) = plan_nested_query(&mut qcx, &query)?;
321 expr
322 }
323 }
324 }
325 InsertSource::DefaultValues => {
326 HirRelationExpr::constant(vec![vec![]], SqlRelationType::empty())
327 }
328 };
329
330 let expr_arity = expr.arity();
331
332 let max_columns = if columns.is_empty() {
335 desc.arity()
336 } else {
337 columns.len()
338 };
339 if expr_arity > max_columns {
340 sql_bail!("INSERT has more expressions than target columns");
341 }
342 if expr_arity < columns.len() {
344 sql_bail!("INSERT has more target columns than expressions");
345 }
346
347 source_types.truncate(expr_arity);
349 ordering.truncate(expr_arity);
350
351 let expr = cast_relation(&qcx, CastContext::Assignment, expr, source_types).map_err(|e| {
354 sql_err!(
355 "column {} is of type {} but expression is of type {}",
356 desc.get_name(ordering[e.column]).quoted(),
357 qcx.humanize_sql_scalar_type(&e.target_type, false),
358 qcx.humanize_sql_scalar_type(&e.source_type, false),
359 )
360 })?;
361
362 let mut map_exprs = vec![];
364 let mut project_key = Vec::with_capacity(desc.arity());
365
366 let col_to_source: BTreeMap<_, _> = ordering.iter().enumerate().map(|(a, b)| (b, a)).collect();
368
369 let column_details = desc.iter_types().zip_eq(defaults).enumerate();
370 for (col_idx, (col_typ, default)) in column_details {
371 if let Some(src_idx) = col_to_source.get(&col_idx) {
372 project_key.push(*src_idx);
373 } else {
374 let hir = plan_default_expr(scx, &default, &col_typ.scalar_type)?;
375 project_key.push(expr_arity + map_exprs.len());
376 map_exprs.push(hir);
377 }
378 }
379
380 let returning = {
381 let (scope, typ) = if let ResolvedItemName::Item {
382 full_name,
383 version: _,
384 ..
385 } = table_name
386 {
387 let scope = Scope::from_source(Some(full_name.clone().into()), desc.iter_names());
388 let typ = desc.typ().clone();
389 (scope, typ)
390 } else {
391 (Scope::empty(), SqlRelationType::empty())
392 };
393 let ecx = &ExprContext {
394 qcx: &qcx,
395 name: "RETURNING clause",
396 scope: &scope,
397 relation_type: &typ,
398 allow_aggregates: false,
399 allow_subqueries: false,
400 allow_parameters: true,
401 allow_windows: false,
402 };
403 let table_func_names = BTreeMap::new();
404 let mut output_columns = vec![];
405 let mut new_exprs = vec![];
406 let mut new_type = SqlRelationType::empty();
407 for mut si in returning {
408 transform_ast::transform(scx, &mut si)?;
409 for (select_item, column_name) in expand_select_item(ecx, &si, &table_func_names)? {
410 let expr = match &select_item {
411 ExpandedSelectItem::InputOrdinal(i) => HirScalarExpr::column(*i),
412 ExpandedSelectItem::Expr(expr) => plan_expr(ecx, expr)?.type_as_any(ecx)?,
413 };
414 output_columns.push(column_name);
415 let typ = ecx.column_type(&expr);
416 new_type.column_types.push(typ);
417 new_exprs.push(expr);
418 }
419 }
420 let desc = RelationDesc::new(new_type, output_columns);
421 let desc_arity = desc.arity();
422 PlannedRootQuery {
423 expr: new_exprs,
424 desc,
425 finishing: HirRelationExpr::trivial_row_set_finishing_hir(desc_arity),
426 scope,
427 }
428 };
429
430 Ok((
431 table.id(),
432 expr.map(map_exprs).project(project_key),
433 returning,
434 ))
435}
436
437pub fn plan_copy_item(
448 scx: &StatementContext,
449 item_name: ResolvedItemName,
450 columns: Vec<Ident>,
451) -> Result<
452 (
453 CatalogItemId,
454 RelationDesc,
455 Vec<ColumnIndex>,
456 Option<MapFilterProject>,
457 ),
458 PlanError,
459> {
460 let item = scx.get_item_by_resolved_name(&item_name)?;
461 let fullname = scx.catalog.resolve_full_name(item.name());
462 let table_desc = match item.relation_desc() {
463 Some(desc) => desc.into_owned(),
464 None => {
465 return Err(PlanError::InvalidDependency {
466 name: fullname.to_string(),
467 item_type: item.item_type().to_string(),
468 });
469 }
470 };
471 let mut ordering = Vec::with_capacity(columns.len());
472
473 let mfp = if let Some(table_defaults) = item.writable_table_details() {
483 let mut table_defaults = table_defaults.to_vec();
484
485 for default in &mut table_defaults {
486 transform_ast::transform(scx, default)?;
487 }
488
489 let source_column_names: Vec<_> = columns
491 .iter()
492 .cloned()
493 .map(normalize::column_name)
494 .collect();
495
496 let mut default_exprs = Vec::new();
497 let mut project_keys = Vec::with_capacity(table_desc.arity());
498
499 let column_details = table_desc.iter().zip_eq(table_defaults);
502 for ((col_name, col_type), col_default) in column_details {
503 let maybe_src_idx = source_column_names.iter().position(|name| name == col_name);
504 if let Some(src_idx) = maybe_src_idx {
505 project_keys.push(src_idx);
506 } else {
507 let hir = plan_default_expr(scx, &col_default, &col_type.scalar_type)?;
510 let mir = hir.lower_uncorrelated(scx.catalog.system_vars())?;
511 project_keys.push(source_column_names.len() + default_exprs.len());
512 default_exprs.push(mir);
513 }
514 }
515
516 let mfp = MapFilterProject::new(source_column_names.len())
517 .map(default_exprs)
518 .project(project_keys);
519 Some(mfp)
520 } else {
521 None
522 };
523
524 let source_desc = if columns.is_empty() {
526 let indexes = (0..table_desc.arity()).map(ColumnIndex::from_raw);
527 ordering.extend(indexes);
528
529 table_desc
531 } else {
532 let columns: Vec<_> = columns.into_iter().map(normalize::column_name).collect();
533 let column_by_name: BTreeMap<&ColumnName, (ColumnIndex, &SqlColumnType)> = table_desc
534 .iter_all()
535 .map(|(idx, name, typ)| (name, (*idx, typ)))
536 .collect();
537
538 let mut names = Vec::with_capacity(columns.len());
539 let mut source_types = Vec::with_capacity(columns.len());
540
541 for c in &columns {
542 if let Some((idx, typ)) = column_by_name.get(c) {
543 ordering.push(*idx);
544 source_types.push((*typ).clone());
545 names.push(c.clone());
546 } else {
547 sql_bail!(
548 "column {} of relation {} does not exist",
549 c.quoted(),
550 item_name.full_name_str().quoted()
551 );
552 }
553 }
554 if let Some(dup) = columns.iter().duplicates().next() {
555 sql_bail!("column {} specified more than once", dup.quoted());
556 }
557
558 RelationDesc::new(SqlRelationType::new(source_types), names)
560 };
561
562 Ok((item.id(), source_desc, ordering, mfp))
563}
564
565pub fn plan_copy_from(
569 scx: &StatementContext,
570 table_name: ResolvedItemName,
571 columns: Vec<Ident>,
572) -> Result<
573 (
574 CatalogItemId,
575 RelationDesc,
576 Vec<ColumnIndex>,
577 Option<MapFilterProject>,
578 ),
579 PlanError,
580> {
581 let table = scx.get_item_by_resolved_name(&table_name)?;
582
583 if table.item_type() != CatalogItemType::Table {
585 sql_bail!(
586 "cannot insert into {} '{}'",
587 table.item_type(),
588 table_name.full_name_str()
589 );
590 }
591
592 let _ = table.writable_table_details().ok_or_else(|| {
593 sql_err!(
594 "cannot insert into non-writeable table '{}'",
595 table_name.full_name_str()
596 )
597 })?;
598
599 if table.id().is_system() {
600 sql_bail!(
601 "cannot insert into system table '{}'",
602 table_name.full_name_str()
603 );
604 }
605 let (id, desc, ordering, mfp) = plan_copy_item(scx, table_name, columns)?;
606
607 Ok((id, desc, ordering, mfp))
608}
609
610pub fn plan_copy_from_rows(
613 pcx: &PlanContext,
614 catalog: &dyn SessionCatalog,
615 target_id: CatalogItemId,
616 target_name: String,
617 columns: Vec<ColumnIndex>,
618 rows: Vec<mz_repr::Row>,
619) -> Result<HirRelationExpr, PlanError> {
620 let scx = StatementContext::new(Some(pcx), catalog);
621
622 let table = catalog
624 .try_get_item(&target_id)
625 .ok_or_else(|| PlanError::CopyFromTargetTableDropped { target_name })?
626 .at_version(RelationVersionSelector::Latest);
627
628 let mut defaults = table
629 .writable_table_details()
630 .ok_or_else(|| sql_err!("cannot copy into non-writeable table"))?
631 .to_vec();
632
633 for default in &mut defaults {
634 transform_ast::transform(&scx, default)?;
635 }
636
637 let desc = table
638 .relation_desc()
639 .ok_or_else(|| sql_err!("item does not have a relation description"))?;
640 let column_types = columns
641 .iter()
642 .map(|x| desc.get_type(x).clone())
643 .map(|mut x| {
644 x.nullable = true;
647 x
648 })
649 .collect();
650 let typ = SqlRelationType::new(column_types);
651 let expr = HirRelationExpr::Constant {
652 rows,
653 typ: typ.clone(),
654 };
655
656 let default: Vec<_> = (0..desc.arity()).map(ColumnIndex::from_raw).collect();
662 if columns == default {
663 return Ok(expr);
664 }
665
666 let mut map_exprs = vec![];
668 let mut project_key = Vec::with_capacity(desc.arity());
669
670 let col_to_source: BTreeMap<_, _> = columns.iter().enumerate().map(|(a, b)| (b, a)).collect();
672
673 let column_details = desc.iter_all().zip_eq(defaults);
674 for ((col_idx, _col_name, col_typ), default) in column_details {
675 if let Some(src_idx) = col_to_source.get(&col_idx) {
676 project_key.push(*src_idx);
677 } else {
678 let hir = plan_default_expr(&scx, &default, &col_typ.scalar_type)?;
679 project_key.push(typ.arity() + map_exprs.len());
680 map_exprs.push(hir);
681 }
682 }
683
684 Ok(expr.map(map_exprs).project(project_key))
685}
686
687pub struct ReadThenWritePlan {
689 pub id: CatalogItemId,
690 pub selection: HirRelationExpr,
695 pub assignments: BTreeMap<usize, HirScalarExpr>,
697 pub finishing: RowSetFinishing,
698}
699
700pub fn plan_delete_query(
701 scx: &StatementContext,
702 mut delete_stmt: DeleteStatement<Aug>,
703) -> Result<ReadThenWritePlan, PlanError> {
704 transform_ast::transform(scx, &mut delete_stmt)?;
705
706 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
707 plan_mutation_query_inner(
708 qcx,
709 delete_stmt.table_name,
710 delete_stmt.alias,
711 delete_stmt.using,
712 vec![],
713 delete_stmt.selection,
714 )
715}
716
717pub fn plan_update_query(
718 scx: &StatementContext,
719 mut update_stmt: UpdateStatement<Aug>,
720) -> Result<ReadThenWritePlan, PlanError> {
721 transform_ast::transform(scx, &mut update_stmt)?;
722
723 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
724
725 plan_mutation_query_inner(
726 qcx,
727 update_stmt.table_name,
728 update_stmt.alias,
729 vec![],
730 update_stmt.assignments,
731 update_stmt.selection,
732 )
733}
734
735pub fn plan_mutation_query_inner(
736 qcx: QueryContext,
737 table_name: ResolvedItemName,
738 alias: Option<TableAlias>,
739 using: Vec<TableWithJoins<Aug>>,
740 assignments: Vec<Assignment<Aug>>,
741 selection: Option<Expr<Aug>>,
742) -> Result<ReadThenWritePlan, PlanError> {
743 let (id, version) = match table_name {
745 ResolvedItemName::Item { id, version, .. } => (id, version),
746 _ => sql_bail!("cannot mutate non-user table"),
747 };
748
749 let item = qcx.scx.get_item(&id).at_version(version);
751 if item.item_type() != CatalogItemType::Table {
752 sql_bail!(
753 "cannot mutate {} '{}'",
754 item.item_type(),
755 table_name.full_name_str()
756 );
757 }
758 let _ = item.writable_table_details().ok_or_else(|| {
759 sql_err!(
760 "cannot mutate non-writeable table '{}'",
761 table_name.full_name_str()
762 )
763 })?;
764 if id.is_system() {
765 sql_bail!(
766 "cannot mutate system table '{}'",
767 table_name.full_name_str()
768 );
769 }
770
771 let (mut get, scope) = qcx.resolve_table_name(table_name)?;
773 let scope = plan_table_alias(scope, alias.as_ref())?;
774 let desc = item.relation_desc().expect("table has desc");
775 let relation_type = qcx.relation_type(&get);
776
777 if using.is_empty() {
778 if let Some(expr) = selection {
779 let ecx = &ExprContext {
780 qcx: &qcx,
781 name: "WHERE clause",
782 scope: &scope,
783 relation_type: &relation_type,
784 allow_aggregates: false,
785 allow_subqueries: true,
786 allow_parameters: true,
787 allow_windows: false,
788 };
789 let expr = plan_expr(ecx, &expr)?.type_as(ecx, &SqlScalarType::Bool)?;
790 get = get.filter(vec![expr]);
791 }
792 } else {
793 get = handle_mutation_using_clause(&qcx, selection, using, get, scope.clone())?;
794 }
795
796 let mut sets = BTreeMap::new();
797 for Assignment { id, value } in assignments {
798 let name = normalize::column_name(id);
800 match desc.get_by_name(&name) {
801 Some((idx, typ)) => {
802 let ecx = &ExprContext {
803 qcx: &qcx,
804 name: "SET clause",
805 scope: &scope,
806 relation_type: &relation_type,
807 allow_aggregates: false,
808 allow_subqueries: false,
809 allow_parameters: true,
810 allow_windows: false,
811 };
812 let expr = plan_expr(ecx, &value)?.cast_to(
813 ecx,
814 CastContext::Assignment,
815 &typ.scalar_type,
816 )?;
817
818 if sets.insert(idx, expr).is_some() {
819 sql_bail!("column {} set twice", name)
820 }
821 }
822 None => sql_bail!("unknown column {}", name),
823 };
824 }
825
826 let finishing = RowSetFinishing {
827 order_by: vec![],
828 limit: None,
829 offset: 0,
830 project: (0..desc.arity()).collect(),
831 };
832
833 Ok(ReadThenWritePlan {
834 id,
835 selection: get,
836 finishing,
837 assignments: sets,
838 })
839}
840
841fn handle_mutation_using_clause(
853 qcx: &QueryContext,
854 selection: Option<Expr<Aug>>,
855 using: Vec<TableWithJoins<Aug>>,
856 get: HirRelationExpr,
857 outer_scope: Scope,
858) -> Result<HirRelationExpr, PlanError> {
859 let (mut using_rel_expr, using_scope) =
863 using.into_iter().try_fold(plan_join_identity(), |l, twj| {
864 let (left, left_scope) = l;
865 plan_join(
866 qcx,
867 left,
868 left_scope,
869 &Join {
870 relation: TableFactor::NestedJoin {
871 join: Box::new(twj),
872 alias: None,
873 },
874 join_operator: JoinOperator::CrossJoin,
875 },
876 )
877 })?;
878
879 if let Some(expr) = selection {
880 let on = HirScalarExpr::literal_true();
886 let joined = using_rel_expr
887 .clone()
888 .join(get.clone(), on, JoinKind::Inner);
889 let joined_scope = using_scope.product(outer_scope)?;
890 let joined_relation_type = qcx.relation_type(&joined);
891
892 let ecx = &ExprContext {
893 qcx,
894 name: "WHERE clause",
895 scope: &joined_scope,
896 relation_type: &joined_relation_type,
897 allow_aggregates: false,
898 allow_subqueries: true,
899 allow_parameters: true,
900 allow_windows: false,
901 };
902
903 let mut expr = plan_expr(ecx, &expr)?.type_as(ecx, &SqlScalarType::Bool)?;
905
906 let using_rel_arity = qcx.relation_type(&using_rel_expr).arity();
911 #[allow(deprecated)]
912 expr.visit_columns_mut(0, &mut |depth, c| {
913 if c.level == depth && c.column >= using_rel_arity {
914 c.level += 1;
915 c.column -= using_rel_arity;
916 }
917 });
918
919 using_rel_expr = using_rel_expr.filter(vec![expr]);
923 } else {
924 let _joined_scope = using_scope.product(outer_scope)?;
927 }
928 Ok(get.filter(vec![using_rel_expr.exists()]))
939}
940
941#[derive(Debug)]
942pub(crate) struct CastRelationError {
943 pub(crate) column: usize,
944 pub(crate) source_type: SqlScalarType,
945 pub(crate) target_type: SqlScalarType,
946}
947
948pub(crate) fn cast_relation<'a, I>(
952 qcx: &QueryContext,
953 ccx: CastContext,
954 expr: HirRelationExpr,
955 target_types: I,
956) -> Result<HirRelationExpr, CastRelationError>
957where
958 I: IntoIterator<Item = &'a SqlScalarType>,
959{
960 let ecx = &ExprContext {
961 qcx,
962 name: "values",
963 scope: &Scope::empty(),
964 relation_type: &qcx.relation_type(&expr),
965 allow_aggregates: false,
966 allow_subqueries: true,
967 allow_parameters: true,
968 allow_windows: false,
969 };
970 let mut map_exprs = vec![];
971 let mut project_key = vec![];
972 for (i, target_typ) in target_types.into_iter().enumerate() {
973 let expr = HirScalarExpr::column(i);
974 match typeconv::plan_cast(ecx, ccx, expr.clone(), target_typ) {
978 Ok(cast_expr) => {
979 if expr == cast_expr {
980 project_key.push(i);
982 } else {
983 project_key.push(ecx.relation_type.arity() + map_exprs.len());
985 map_exprs.push(cast_expr);
986 }
987 }
988 Err(_) => {
989 return Err(CastRelationError {
990 column: i,
991 source_type: ecx.scalar_type(&expr),
992 target_type: target_typ.clone(),
993 });
994 }
995 }
996 }
997 Ok(expr.map(map_exprs).project(project_key))
998}
999
1000pub fn plan_as_of(
1003 scx: &StatementContext,
1004 as_of: Option<AsOf<Aug>>,
1005) -> Result<QueryWhen, PlanError> {
1006 match as_of {
1007 None => Ok(QueryWhen::Immediately),
1008 Some(as_of) => match as_of {
1009 AsOf::At(expr) => Ok(QueryWhen::AtTimestamp(plan_as_of_or_up_to(scx, expr)?)),
1010 AsOf::AtLeast(expr) => Ok(QueryWhen::AtLeastTimestamp(plan_as_of_or_up_to(scx, expr)?)),
1011 },
1012 }
1013}
1014
1015pub fn plan_as_of_or_up_to(
1025 scx: &StatementContext,
1026 mut expr: Expr<Aug>,
1027) -> Result<mz_repr::Timestamp, PlanError> {
1028 let scope = Scope::empty();
1029 let desc = RelationDesc::empty();
1030 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1033 transform_ast::transform(scx, &mut expr)?;
1034 let ecx = &ExprContext {
1035 qcx: &qcx,
1036 name: "AS OF or UP TO",
1037 scope: &scope,
1038 relation_type: desc.typ(),
1039 allow_aggregates: false,
1040 allow_subqueries: false,
1041 allow_parameters: false,
1042 allow_windows: false,
1043 };
1044 let hir = plan_expr(ecx, &expr)?.cast_to(
1045 ecx,
1046 CastContext::Assignment,
1047 &SqlScalarType::MzTimestamp,
1048 )?;
1049 if hir.contains_unmaterializable() {
1050 bail_unsupported!("calling an unmaterializable function in AS OF or UP TO");
1051 }
1052 let timestamp = hir
1059 .into_literal_mz_timestamp()
1060 .ok_or_else(|| PlanError::InvalidAsOfUpTo)?;
1061 Ok(timestamp)
1062}
1063
1064pub fn plan_secret_as(
1066 scx: &StatementContext,
1067 mut expr: Expr<Aug>,
1068) -> Result<MirScalarExpr, PlanError> {
1069 let scope = Scope::empty();
1070 let desc = RelationDesc::empty();
1071 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1072
1073 transform_ast::transform(scx, &mut expr)?;
1074
1075 let ecx = &ExprContext {
1076 qcx: &qcx,
1077 name: "AS",
1078 scope: &scope,
1079 relation_type: desc.typ(),
1080 allow_aggregates: false,
1081 allow_subqueries: false,
1082 allow_parameters: false,
1083 allow_windows: false,
1084 };
1085 let expr = plan_expr(ecx, &expr)?
1086 .type_as(ecx, &SqlScalarType::Bytes)?
1087 .lower_uncorrelated(scx.catalog.system_vars())?;
1088 Ok(expr)
1089}
1090
1091pub fn plan_webhook_validate_using(
1093 scx: &StatementContext,
1094 validate_using: CreateWebhookSourceCheck<Aug>,
1095) -> Result<WebhookValidation, PlanError> {
1096 let qcx = QueryContext::root(scx, QueryLifetime::Source);
1097
1098 let CreateWebhookSourceCheck {
1099 options,
1100 using: mut expr,
1101 } = validate_using;
1102
1103 let mut column_typs = vec![];
1104 let mut column_names = vec![];
1105
1106 let (bodies, headers, secrets) = options
1107 .map(|o| (o.bodies, o.headers, o.secrets))
1108 .unwrap_or_default();
1109
1110 let mut body_tuples = vec![];
1112 for CreateWebhookSourceBody { alias, use_bytes } in bodies {
1113 let scalar_type = use_bytes
1114 .then_some(SqlScalarType::Bytes)
1115 .unwrap_or(SqlScalarType::String);
1116 let name = alias
1117 .map(|a| a.into_string())
1118 .unwrap_or_else(|| "body".to_string());
1119
1120 column_typs.push(SqlColumnType {
1121 scalar_type,
1122 nullable: false,
1123 });
1124 column_names.push(name);
1125
1126 let column_idx = column_typs.len() - 1;
1128 assert_eq!(
1130 column_idx,
1131 column_names.len() - 1,
1132 "body column names and types don't match"
1133 );
1134 body_tuples.push((column_idx, use_bytes));
1135 }
1136
1137 let mut header_tuples = vec![];
1139
1140 for CreateWebhookSourceHeader { alias, use_bytes } in headers {
1141 let value_type = use_bytes
1142 .then_some(SqlScalarType::Bytes)
1143 .unwrap_or(SqlScalarType::String);
1144 let name = alias
1145 .map(|a| a.into_string())
1146 .unwrap_or_else(|| "headers".to_string());
1147
1148 column_typs.push(SqlColumnType {
1149 scalar_type: SqlScalarType::Map {
1150 value_type: Box::new(value_type),
1151 custom_id: None,
1152 },
1153 nullable: false,
1154 });
1155 column_names.push(name);
1156
1157 let column_idx = column_typs.len() - 1;
1159 assert_eq!(
1161 column_idx,
1162 column_names.len() - 1,
1163 "header column names and types don't match"
1164 );
1165 header_tuples.push((column_idx, use_bytes));
1166 }
1167
1168 let mut validation_secrets = vec![];
1170
1171 for CreateWebhookSourceSecret {
1172 secret,
1173 alias,
1174 use_bytes,
1175 } in secrets
1176 {
1177 let scalar_type = use_bytes
1179 .then_some(SqlScalarType::Bytes)
1180 .unwrap_or(SqlScalarType::String);
1181
1182 column_typs.push(SqlColumnType {
1183 scalar_type,
1184 nullable: false,
1185 });
1186 if let ResolvedItemName::Item { id, .. } = &secret
1191 && id.is_user()
1192 && matches!(
1193 scx.catalog.get_item(id).item_type(),
1194 CatalogItemType::Table
1195 | CatalogItemType::View
1196 | CatalogItemType::MaterializedView
1197 | CatalogItemType::Index
1198 | CatalogItemType::Sink
1199 | CatalogItemType::MetricSink
1200 )
1201 {
1202 return Err(PlanError::InvalidSecret(Box::new(secret)));
1203 }
1204 let ResolvedItemName::Item {
1205 id,
1206 full_name: FullItemName { item, .. },
1207 ..
1208 } = secret
1209 else {
1210 return Err(PlanError::InvalidSecret(Box::new(secret)));
1211 };
1212
1213 let name = if let Some(alias) = alias {
1215 alias.into_string()
1216 } else {
1217 item
1218 };
1219 column_names.push(name);
1220
1221 let column_idx = column_typs.len() - 1;
1224 assert_eq!(
1226 column_idx,
1227 column_names.len() - 1,
1228 "column names and types don't match"
1229 );
1230
1231 validation_secrets.push(WebhookValidationSecret {
1232 id,
1233 column_idx,
1234 use_bytes,
1235 });
1236 }
1237
1238 let relation_typ = SqlRelationType::new(column_typs);
1239 let desc = RelationDesc::new(relation_typ, column_names.clone());
1240 let scope = Scope::from_source(None, column_names);
1241
1242 transform_ast::transform(scx, &mut expr)?;
1243
1244 let ecx = &ExprContext {
1245 qcx: &qcx,
1246 name: "CHECK",
1247 scope: &scope,
1248 relation_type: desc.typ(),
1249 allow_aggregates: false,
1250 allow_subqueries: false,
1251 allow_parameters: false,
1252 allow_windows: false,
1253 };
1254 let expr = plan_expr(ecx, &expr)?
1255 .type_as(ecx, &SqlScalarType::Bool)?
1256 .lower_uncorrelated(scx.catalog.system_vars())?;
1257 let validation = WebhookValidation {
1258 expression: expr,
1259 relation_desc: desc,
1260 bodies: body_tuples,
1261 headers: header_tuples,
1262 secrets: validation_secrets,
1263 };
1264 Ok(validation)
1265}
1266
1267pub fn plan_default_expr(
1268 scx: &StatementContext,
1269 expr: &Expr<Aug>,
1270 target_ty: &SqlScalarType,
1271) -> Result<HirScalarExpr, PlanError> {
1272 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1273 let ecx = &ExprContext {
1274 qcx: &qcx,
1275 name: "DEFAULT expression",
1276 scope: &Scope::empty(),
1277 relation_type: &SqlRelationType::empty(),
1278 allow_aggregates: false,
1279 allow_subqueries: false,
1280 allow_parameters: false,
1281 allow_windows: false,
1282 };
1283 let hir = plan_expr(ecx, expr)?.cast_to(ecx, CastContext::Assignment, target_ty)?;
1284 Ok(hir)
1285}
1286
1287pub fn plan_params<'a>(
1288 scx: &'a StatementContext,
1289 params: Vec<Expr<Aug>>,
1290 desc: &StatementDesc,
1291) -> Result<Params, PlanError> {
1292 if params.len() != desc.param_types.len() {
1293 sql_bail!(
1294 "expected {} params, got {}",
1295 desc.param_types.len(),
1296 params.len()
1297 );
1298 }
1299
1300 let qcx = QueryContext::root(scx, QueryLifetime::OneShot);
1301
1302 let mut datums = Row::default();
1303 let mut packer = datums.packer();
1304 let mut actual_types = Vec::new();
1305 let temp_storage = &RowArena::new();
1306 for (i, (mut expr, expected_ty)) in params.into_iter().zip_eq(&desc.param_types).enumerate() {
1307 transform_ast::transform(scx, &mut expr)?;
1308
1309 let ecx = execute_expr_context(&qcx);
1310 let ex = plan_expr(&ecx, &expr)?.type_as_any(&ecx)?;
1311 let actual_ty = ecx.scalar_type(&ex);
1312 if plan_hypothetical_cast(&ecx, *EXECUTE_CAST_CONTEXT, &actual_ty, expected_ty).is_none() {
1313 return Err(PlanError::WrongParameterType(
1314 i + 1,
1315 ecx.humanize_sql_scalar_type(expected_ty, false),
1316 ecx.humanize_sql_scalar_type(&actual_ty, false),
1317 ));
1318 }
1319 let ex = ex.lower_uncorrelated(scx.catalog.system_vars())?;
1320 let evaled = ex.eval_constant_foldable(temp_storage)?;
1321 packer.push(evaled);
1322 actual_types.push(actual_ty);
1323 }
1324 Ok(Params {
1325 datums,
1326 execute_types: actual_types,
1327 expected_types: desc.param_types.clone(),
1328 })
1329}
1330
1331static EXECUTE_CONTEXT_SCOPE: LazyLock<Scope> = LazyLock::new(Scope::empty);
1332static EXECUTE_CONTEXT_REL_TYPE: LazyLock<SqlRelationType> = LazyLock::new(SqlRelationType::empty);
1333
1334pub(crate) fn execute_expr_context<'a>(qcx: &'a QueryContext<'a>) -> ExprContext<'a> {
1336 ExprContext {
1337 qcx,
1338 name: "EXECUTE",
1339 scope: &EXECUTE_CONTEXT_SCOPE,
1340 relation_type: &EXECUTE_CONTEXT_REL_TYPE,
1341 allow_aggregates: false,
1342 allow_subqueries: false,
1343 allow_parameters: false,
1344 allow_windows: false,
1345 }
1346}
1347
1348pub(crate) static EXECUTE_CAST_CONTEXT: LazyLock<CastContext> =
1353 LazyLock::new(|| CastContext::Assignment);
1354
1355pub fn plan_index_exprs<'a>(
1356 scx: &'a StatementContext,
1357 on_desc: &RelationDesc,
1358 exprs: Vec<Expr<Aug>>,
1359) -> Result<Vec<mz_expr::MirScalarExpr>, PlanError> {
1360 let scope = Scope::from_source(None, on_desc.iter_names());
1361 let qcx = QueryContext::root(scx, QueryLifetime::Index);
1362
1363 let ecx = &ExprContext {
1364 qcx: &qcx,
1365 name: "CREATE INDEX",
1366 scope: &scope,
1367 relation_type: on_desc.typ(),
1368 allow_aggregates: false,
1369 allow_subqueries: false,
1370 allow_parameters: false,
1371 allow_windows: false,
1372 };
1373 let repr_col_types: Vec<ReprColumnType> = on_desc
1374 .typ()
1375 .column_types
1376 .iter()
1377 .map(ReprColumnType::from)
1378 .collect();
1379 let mut out = vec![];
1380 for mut expr in exprs {
1381 transform_ast::transform(scx, &mut expr)?;
1382 let expr = plan_expr_or_col_index(ecx, &expr)?;
1383 let mut expr = expr.lower_uncorrelated(scx.catalog.system_vars())?;
1384 expr.reduce(&repr_col_types);
1385 out.push(expr);
1386 }
1387 Ok(out)
1388}
1389
1390fn plan_expr_or_col_index(ecx: &ExprContext, e: &Expr<Aug>) -> Result<HirScalarExpr, PlanError> {
1391 match check_col_index(ecx.name, e, ecx.relation_type.column_types.len())? {
1392 Some(column) => Ok(HirScalarExpr::column(column)),
1393 _ => plan_expr(ecx, e)?.type_as_any(ecx),
1394 }
1395}
1396
1397fn check_col_index(name: &str, e: &Expr<Aug>, max: usize) -> Result<Option<usize>, PlanError> {
1398 match e {
1399 Expr::Value(Value::Number(n)) => {
1400 let n = n.parse::<usize>().map_err(|e| {
1401 sql_err!("unable to parse column reference in {}: {}: {}", name, n, e)
1402 })?;
1403 if n < 1 || n > max {
1404 sql_bail!(
1405 "column reference {} in {} is out of range (1 - {})",
1406 n,
1407 name,
1408 max
1409 );
1410 }
1411 Ok(Some(n - 1))
1412 }
1413 _ => Ok(None),
1414 }
1415}
1416
1417struct PlannedQuery {
1418 expr: HirRelationExpr,
1419 scope: Scope,
1420 order_by: Vec<ColumnOrder>,
1421 limit: Option<HirScalarExpr>,
1422 offset: HirScalarExpr,
1428 project: Vec<usize>,
1429 group_size_hints: GroupSizeHints,
1430}
1431
1432fn plan_query(qcx: &mut QueryContext, q: &Query<Aug>) -> Result<PlannedQuery, PlanError> {
1433 qcx.checked_recur_mut(|qcx| plan_query_inner(qcx, q))
1434}
1435
1436fn plan_query_inner(qcx: &mut QueryContext, q: &Query<Aug>) -> Result<PlannedQuery, PlanError> {
1437 let cte_bindings = plan_ctes(qcx, q)?;
1440
1441 let limit = match &q.limit {
1442 None => None,
1443 Some(Limit {
1444 quantity,
1445 with_ties: false,
1446 }) => {
1447 let ecx = &ExprContext {
1448 qcx,
1449 name: "LIMIT",
1450 scope: &Scope::empty(),
1451 relation_type: &SqlRelationType::empty(),
1452 allow_aggregates: false,
1453 allow_subqueries: true,
1454 allow_parameters: true,
1455 allow_windows: false,
1456 };
1457 let limit = plan_expr(ecx, quantity)?;
1458 let limit = limit.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?;
1459
1460 let limit = if limit.is_constant() {
1461 let arena = RowArena::new();
1462 let limit = limit.lower_uncorrelated(qcx.scx.catalog.system_vars())?;
1463
1464 match limit.eval_constant_foldable(&arena)? {
1468 d @ Datum::Int64(v) if v >= 0 => {
1469 HirScalarExpr::literal(d, SqlScalarType::Int64)
1470 }
1471 d @ Datum::Null => HirScalarExpr::literal(d, SqlScalarType::Int64),
1472 Datum::Int64(_) => sql_bail!("LIMIT must not be negative"),
1473 _ => sql_bail!("constant LIMIT expression must reduce to an INT or NULL value"),
1474 }
1475 } else {
1476 qcx.scx
1478 .require_feature_flag(&vars::ENABLE_EXPRESSIONS_IN_LIMIT_SYNTAX)?;
1479 limit
1480 };
1481
1482 Some(limit)
1483 }
1484 Some(Limit {
1485 quantity: _,
1486 with_ties: true,
1487 }) => bail_unsupported!("FETCH ... WITH TIES"),
1488 };
1489
1490 let offset = match &q.offset {
1491 None => HirScalarExpr::literal(Datum::Int64(0), SqlScalarType::Int64),
1492 Some(offset) => {
1493 let ecx = &ExprContext {
1494 qcx,
1495 name: "OFFSET",
1496 scope: &Scope::empty(),
1497 relation_type: &SqlRelationType::empty(),
1498 allow_aggregates: false,
1499 allow_subqueries: false,
1500 allow_parameters: true,
1501 allow_windows: false,
1502 };
1503 let offset = plan_expr(ecx, offset)?;
1504 let offset = offset.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?;
1505
1506 let offset = if offset.is_constant() {
1507 let offset_value = offset_into_value(offset)?;
1509 HirScalarExpr::literal(Datum::Int64(offset_value), SqlScalarType::Int64)
1510 } else {
1511 if !offset.contains_parameters() {
1515 return Err(PlanError::InvalidOffset(format!(
1516 "must be simplifiable to a constant, possibly after parameter binding, got {}",
1517 offset
1518 )));
1519 }
1520 offset
1521 };
1522 offset
1523 }
1524 };
1525
1526 let mut planned_query = match &q.body {
1527 SetExpr::Select(s) => {
1528 let select_option_extracted = SelectOptionExtracted::try_from(s.options.clone())?;
1530 let group_size_hints = GroupSizeHints::try_from(select_option_extracted)?;
1531
1532 let plan = plan_select_from_where(qcx, *s.clone(), q.order_by.clone())?;
1533 PlannedQuery {
1534 expr: plan.expr,
1535 scope: plan.scope,
1536 order_by: plan.order_by,
1537 project: plan.project,
1538 limit,
1539 offset,
1540 group_size_hints,
1541 }
1542 }
1543 _ => {
1544 let (expr, scope) = plan_set_expr(qcx, &q.body)?;
1545 let ecx = &ExprContext {
1546 qcx,
1547 name: "ORDER BY clause of a set expression",
1548 scope: &scope,
1549 relation_type: &qcx.relation_type(&expr),
1550 allow_aggregates: false,
1551 allow_subqueries: true,
1552 allow_parameters: true,
1553 allow_windows: false,
1554 };
1555 let output_columns: Vec<_> = scope.column_names().enumerate().collect();
1556 let (order_by, map_exprs) = plan_order_by_exprs(ecx, &q.order_by, &output_columns)?;
1557 let project = (0..ecx.relation_type.arity()).collect();
1558 PlannedQuery {
1559 expr: expr.map(map_exprs),
1560 scope,
1561 order_by,
1562 limit,
1563 project,
1564 offset,
1565 group_size_hints: GroupSizeHints::default(),
1566 }
1567 }
1568 };
1569
1570 match &q.ctes {
1572 CteBlock::Simple(_) => {
1573 for (id, value, shadowed_val) in cte_bindings.into_iter().rev() {
1574 if let Some(cte) = qcx.ctes.remove(&id) {
1575 planned_query.expr = HirRelationExpr::Let {
1576 name: cte.name,
1577 id: id.clone(),
1578 value: Box::new(value),
1579 body: Box::new(planned_query.expr),
1580 };
1581 }
1582 if let Some(shadowed_val) = shadowed_val {
1583 qcx.ctes.insert(id, shadowed_val);
1584 }
1585 }
1586 }
1587 CteBlock::MutuallyRecursive(MutRecBlock { options, ctes: _ }) => {
1588 let MutRecBlockOptionExtracted {
1589 recursion_limit,
1590 return_at_recursion_limit,
1591 error_at_recursion_limit,
1592 seen: _,
1593 } = MutRecBlockOptionExtracted::try_from(options.clone())?;
1594 let limit = match (
1595 recursion_limit,
1596 return_at_recursion_limit,
1597 error_at_recursion_limit,
1598 ) {
1599 (None, None, None) => None,
1600 (Some(max_iters), None, None) => {
1601 Some((max_iters, LetRecLimit::RETURN_AT_LIMIT_DEFAULT))
1602 }
1603 (None, Some(max_iters), None) => Some((max_iters, true)),
1604 (None, None, Some(max_iters)) => Some((max_iters, false)),
1605 _ => {
1606 return Err(InvalidWmrRecursionLimit(
1607 "More than one recursion limit given. \
1608 Please give at most one of RECURSION LIMIT, \
1609 ERROR AT RECURSION LIMIT, \
1610 RETURN AT RECURSION LIMIT."
1611 .to_owned(),
1612 ));
1613 }
1614 }
1615 .try_map(|(max_iters, return_at_limit)| {
1616 Ok::<LetRecLimit, PlanError>(LetRecLimit {
1617 max_iters: NonZeroU64::new(*max_iters).ok_or(InvalidWmrRecursionLimit(
1618 "Recursion limit has to be greater than 0.".to_owned(),
1619 ))?,
1620 return_at_limit: *return_at_limit,
1621 })
1622 })?;
1623
1624 let mut bindings = Vec::new();
1625 for (id, value, shadowed_val) in cte_bindings.into_iter() {
1626 if let Some(cte) = qcx.ctes.remove(&id) {
1627 bindings.push((cte.name, id, value, cte.desc.into_typ()));
1628 }
1629 if let Some(shadowed_val) = shadowed_val {
1630 qcx.ctes.insert(id, shadowed_val);
1631 }
1632 }
1633 if !bindings.is_empty() {
1634 planned_query.expr = HirRelationExpr::LetRec {
1635 limit,
1636 bindings,
1637 body: Box::new(planned_query.expr),
1638 }
1639 }
1640 }
1641 }
1642
1643 Ok(planned_query)
1644}
1645
1646pub(crate) fn offset_into_value(offset: HirScalarExpr) -> Result<i64, PlanError> {
1648 let offset = offset
1649 .try_into_literal_int64()
1650 .map_err(|err| PlanError::InvalidOffset(err.to_string_with_causes()))?;
1651 if offset < 0 {
1652 return Err(negative_offset_error(offset));
1653 }
1654 Ok(offset)
1655}
1656
1657pub(crate) fn negative_offset_error(offset: i64) -> PlanError {
1658 PlanError::InvalidOffset(format!("must not be negative, got {}", offset))
1659}
1660
1661generate_extracted_config!(
1662 MutRecBlockOption,
1663 (RecursionLimit, u64),
1664 (ReturnAtRecursionLimit, u64),
1665 (ErrorAtRecursionLimit, u64)
1666);
1667
1668pub fn plan_ctes(
1673 qcx: &mut QueryContext,
1674 q: &Query<Aug>,
1675) -> Result<Vec<(LocalId, HirRelationExpr, Option<CteDesc>)>, PlanError> {
1676 let mut result = Vec::new();
1678 let mut shadowed_descs = BTreeMap::new();
1681
1682 if let Some(ident) = q.ctes.bound_identifiers().duplicates().next() {
1684 sql_bail!(
1685 "WITH query name {} specified more than once",
1686 normalize::ident_ref(ident).quoted()
1687 )
1688 }
1689
1690 match &q.ctes {
1691 CteBlock::Simple(ctes) => {
1692 for cte in ctes.iter() {
1694 let cte_name = normalize::ident(cte.alias.name.clone());
1695 let (val, scope) = plan_nested_query(qcx, &cte.query)?;
1696 let typ = qcx.relation_type(&val);
1697 let mut desc = RelationDesc::new(typ, scope.column_names());
1698 plan_utils::maybe_rename_columns(
1699 format!("CTE {}", cte.alias.name),
1700 &mut desc,
1701 &cte.alias.columns,
1702 )?;
1703 let shadowed = qcx.ctes.insert(
1705 cte.id,
1706 CteDesc {
1707 name: cte_name,
1708 desc,
1709 },
1710 );
1711
1712 result.push((cte.id, val, shadowed));
1713 }
1714 }
1715 CteBlock::MutuallyRecursive(MutRecBlock { options: _, ctes }) => {
1716 for cte in ctes.iter() {
1718 let cte_name = normalize::ident(cte.name.clone());
1719 let mut desc_columns = Vec::with_capacity(cte.columns.capacity());
1720 for column in cte.columns.iter() {
1721 desc_columns.push((
1722 normalize::column_name(column.name.clone()),
1723 SqlColumnType {
1724 scalar_type: scalar_type_from_sql(qcx.scx, &column.data_type)?,
1725 nullable: true,
1726 },
1727 ));
1728 }
1729 let desc = RelationDesc::from_names_and_types(desc_columns);
1730 let shadowed = qcx.ctes.insert(
1731 cte.id,
1732 CteDesc {
1733 name: cte_name,
1734 desc,
1735 },
1736 );
1737 if let Some(shadowed) = shadowed {
1739 shadowed_descs.insert(cte.id, shadowed);
1740 }
1741 }
1742
1743 for cte in ctes.iter() {
1745 let (val, _scope) = plan_nested_query(qcx, &cte.query)?;
1746
1747 let proposed_typ = qcx.ctes[&cte.id].desc.typ();
1748
1749 if proposed_typ.column_types.iter().any(|c| !c.nullable) {
1750 sql_bail!(
1753 "[internal error]: WMR CTEs do not support NOT NULL constraints on proposed column types"
1754 );
1755 }
1756
1757 if !proposed_typ.keys.is_empty() {
1758 sql_bail!("[internal error]: WMR CTEs do not support keys");
1761 }
1762
1763 let derived_typ = qcx.relation_type(&val);
1765
1766 let type_err = |proposed_typ: &SqlRelationType, derived_typ: SqlRelationType| {
1767 let cte_name = normalize::ident(cte.name.clone());
1768 let proposed_typ = proposed_typ
1769 .column_types
1770 .iter()
1771 .map(|ty| qcx.humanize_sql_scalar_type(&ty.scalar_type, false))
1772 .collect::<Vec<_>>();
1773 let inferred_typ = derived_typ
1774 .column_types
1775 .iter()
1776 .map(|ty| qcx.humanize_sql_scalar_type(&ty.scalar_type, false))
1777 .collect::<Vec<_>>();
1778 Err(PlanError::RecursiveTypeMismatch(
1779 cte_name,
1780 proposed_typ,
1781 inferred_typ,
1782 ))
1783 };
1784
1785 if derived_typ.column_types.len() != proposed_typ.column_types.len() {
1786 return type_err(proposed_typ, derived_typ);
1787 }
1788
1789 let val = match cast_relation(
1791 qcx,
1792 CastContext::Assignment,
1797 val,
1798 proposed_typ.column_types.iter().map(|c| &c.scalar_type),
1799 ) {
1800 Ok(val) => val,
1801 Err(_) => return type_err(proposed_typ, derived_typ),
1802 };
1803
1804 result.push((cte.id, val, shadowed_descs.remove(&cte.id)));
1805 }
1806 }
1807 }
1808
1809 Ok(result)
1810}
1811
1812pub fn plan_nested_query(
1813 qcx: &mut QueryContext,
1814 q: &Query<Aug>,
1815) -> Result<(HirRelationExpr, Scope), PlanError> {
1816 let PlannedQuery {
1817 mut expr,
1818 scope,
1819 order_by,
1820 limit,
1821 offset,
1822 project,
1823 group_size_hints,
1824 } = qcx.checked_recur_mut(|qcx| plan_query(qcx, q))?;
1825 if limit.is_some()
1837 || !offset
1838 .clone()
1839 .try_into_literal_int64()
1840 .is_ok_and(|offset| offset == 0)
1841 {
1842 expr = HirRelationExpr::top_k(
1843 expr,
1844 vec![],
1845 order_by,
1846 limit,
1847 offset,
1848 group_size_hints.limit_input_group_size,
1849 );
1850 }
1851 Ok((expr.project(project), scope))
1852}
1853
1854fn plan_set_expr(
1855 qcx: &mut QueryContext,
1856 q: &SetExpr<Aug>,
1857) -> Result<(HirRelationExpr, Scope), PlanError> {
1858 match q {
1859 SetExpr::Select(select) => {
1860 let order_by_exprs = Vec::new();
1861 let plan = plan_select_from_where(qcx, *select.clone(), order_by_exprs)?;
1862 assert!(plan.order_by.is_empty());
1865 Ok((plan.expr.project(plan.project), plan.scope))
1866 }
1867 SetExpr::SetOperation {
1868 op,
1869 all,
1870 left,
1871 right,
1872 } => {
1873 let (left_expr, left_scope) = qcx.checked_recur_mut(|qcx| plan_set_expr(qcx, left))?;
1875 let (right_expr, right_scope) =
1876 qcx.checked_recur_mut(|qcx| plan_set_expr(qcx, right))?;
1877
1878 let left_type = qcx.relation_type(&left_expr);
1880 let right_type = qcx.relation_type(&right_expr);
1881 if left_type.arity() != right_type.arity() {
1882 sql_bail!(
1883 "each {} query must have the same number of columns: {} vs {}",
1884 op,
1885 left_type.arity(),
1886 right_type.arity(),
1887 );
1888 }
1889
1890 let left_ecx = &ExprContext {
1895 qcx,
1896 name: &op.to_string(),
1897 scope: &left_scope,
1898 relation_type: &left_type,
1899 allow_aggregates: false,
1900 allow_subqueries: false,
1901 allow_parameters: false,
1902 allow_windows: false,
1903 };
1904 let right_ecx = &ExprContext {
1905 qcx,
1906 name: &op.to_string(),
1907 scope: &right_scope,
1908 relation_type: &right_type,
1909 allow_aggregates: false,
1910 allow_subqueries: false,
1911 allow_parameters: false,
1912 allow_windows: false,
1913 };
1914 let mut left_casts = vec![];
1915 let mut right_casts = vec![];
1916 for (i, (left_type, right_type)) in left_type
1917 .column_types
1918 .iter()
1919 .zip_eq(right_type.column_types.iter())
1920 .enumerate()
1921 {
1922 let types = &[
1923 CoercibleScalarType::Coerced(left_type.scalar_type.clone()),
1924 CoercibleScalarType::Coerced(right_type.scalar_type.clone()),
1925 ];
1926 let target =
1927 typeconv::guess_best_common_type(&left_ecx.with_name(&op.to_string()), types)?;
1928 match typeconv::plan_cast(
1929 left_ecx,
1930 CastContext::Implicit,
1931 HirScalarExpr::column(i),
1932 &target,
1933 ) {
1934 Ok(expr) => left_casts.push(expr),
1935 Err(_) => sql_bail!(
1936 "{} types {} and {} cannot be matched",
1937 op,
1938 qcx.humanize_sql_scalar_type(&left_type.scalar_type, false),
1939 qcx.humanize_sql_scalar_type(&target, false),
1940 ),
1941 }
1942 match typeconv::plan_cast(
1943 right_ecx,
1944 CastContext::Implicit,
1945 HirScalarExpr::column(i),
1946 &target,
1947 ) {
1948 Ok(expr) => right_casts.push(expr),
1949 Err(_) => sql_bail!(
1950 "{} types {} and {} cannot be matched",
1951 op,
1952 qcx.humanize_sql_scalar_type(&target, false),
1953 qcx.humanize_sql_scalar_type(&right_type.scalar_type, false),
1954 ),
1955 }
1956 }
1957 let lhs = if left_casts
1958 .iter()
1959 .enumerate()
1960 .any(|(i, e)| e != &HirScalarExpr::column(i))
1961 {
1962 let project_key: Vec<_> = (left_type.arity()..left_type.arity() * 2).collect();
1963 left_expr.map(left_casts).project(project_key)
1964 } else {
1965 left_expr
1966 };
1967 let rhs = if right_casts
1968 .iter()
1969 .enumerate()
1970 .any(|(i, e)| e != &HirScalarExpr::column(i))
1971 {
1972 let project_key: Vec<_> = (right_type.arity()..right_type.arity() * 2).collect();
1973 right_expr.map(right_casts).project(project_key)
1974 } else {
1975 right_expr
1976 };
1977
1978 let relation_expr = match op {
1979 SetOperator::Union => {
1980 if *all {
1981 lhs.union(rhs)
1982 } else {
1983 lhs.union(rhs).distinct()
1984 }
1985 }
1986 SetOperator::Except => Hir::except(all, lhs, rhs),
1987 SetOperator::Intersect => {
1988 let (lhs, rhs) = if lhs.relation_node_count() > rhs.relation_node_count() {
1995 (rhs, lhs)
1996 } else {
1997 (lhs, rhs)
1998 };
1999 let left_clone = lhs.clone();
2007 if *all {
2008 lhs.union(left_clone.union(rhs.negate()).threshold().negate())
2009 } else {
2010 lhs.union(left_clone.union(rhs.negate()).threshold().negate())
2011 .distinct()
2012 }
2013 }
2014 };
2015 let scope = Scope::from_source(
2016 None,
2017 left_scope.column_names(),
2019 );
2020
2021 Ok((relation_expr, scope))
2022 }
2023 SetExpr::Values(Values(values)) => plan_values(qcx, values),
2024 SetExpr::Table(name) => {
2025 let (expr, scope) = qcx.resolve_table_name(name.clone())?;
2026 Ok((expr, scope))
2027 }
2028 SetExpr::Query(query) => {
2029 let (expr, scope) = plan_nested_query(qcx, query)?;
2030 Ok((expr, scope))
2031 }
2032 SetExpr::Show(stmt) => {
2033 if !qcx.lifetime.allow_show() {
2047 return Err(PlanError::ShowCommandInView);
2048 }
2049
2050 fn to_hirscope(
2053 plan: ShowCreatePlan,
2054 desc: StatementDesc,
2055 ) -> Result<(HirRelationExpr, Scope), PlanError> {
2056 let rows = vec![plan.row.iter().collect::<Vec<_>>()];
2057 let desc = desc.relation_desc.ok_or_else(|| {
2058 internal_err!("statement description missing relation descriptor")
2059 })?;
2060 let scope = Scope::from_source(None, desc.iter_names());
2061 let expr = HirRelationExpr::constant(rows, desc.into_typ());
2062 Ok((expr, scope))
2063 }
2064
2065 match stmt.as_ref().clone() {
2066 ShowStatement::ShowColumns(stmt) => {
2067 show::show_columns(qcx.scx, stmt)?.plan_hir(qcx)
2068 }
2069 ShowStatement::ShowCreateConnection(stmt) => to_hirscope(
2070 show::plan_show_create_connection(qcx.scx, stmt.clone())?,
2071 show::describe_show_create_connection(qcx.scx, stmt)?,
2072 ),
2073 ShowStatement::ShowCreateCluster(stmt) => to_hirscope(
2074 show::plan_show_create_cluster(qcx.scx, stmt.clone())?,
2075 show::describe_show_create_cluster(qcx.scx, stmt)?,
2076 ),
2077 ShowStatement::ShowCreateIndex(stmt) => to_hirscope(
2078 show::plan_show_create_index(qcx.scx, stmt.clone())?,
2079 show::describe_show_create_index(qcx.scx, stmt)?,
2080 ),
2081 ShowStatement::ShowCreateSink(stmt) => to_hirscope(
2082 show::plan_show_create_sink(qcx.scx, stmt.clone())?,
2083 show::describe_show_create_sink(qcx.scx, stmt)?,
2084 ),
2085 ShowStatement::ShowCreateMetricSink(stmt) => to_hirscope(
2086 show::plan_show_create_metric_sink(qcx.scx, stmt.clone())?,
2087 show::describe_show_create_metric_sink(qcx.scx, stmt)?,
2088 ),
2089 ShowStatement::ShowCreateSource(stmt) => to_hirscope(
2090 show::plan_show_create_source(qcx.scx, stmt.clone())?,
2091 show::describe_show_create_source(qcx.scx, stmt)?,
2092 ),
2093 ShowStatement::ShowCreateTable(stmt) => to_hirscope(
2094 show::plan_show_create_table(qcx.scx, stmt.clone())?,
2095 show::describe_show_create_table(qcx.scx, stmt)?,
2096 ),
2097 ShowStatement::ShowCreateView(stmt) => to_hirscope(
2098 show::plan_show_create_view(qcx.scx, stmt.clone())?,
2099 show::describe_show_create_view(qcx.scx, stmt)?,
2100 ),
2101 ShowStatement::ShowCreateMaterializedView(stmt) => to_hirscope(
2102 show::plan_show_create_materialized_view(qcx.scx, stmt.clone())?,
2103 show::describe_show_create_materialized_view(qcx.scx, stmt)?,
2104 ),
2105 ShowStatement::ShowCreateType(stmt) => to_hirscope(
2106 show::plan_show_create_type(qcx.scx, stmt.clone())?,
2107 show::describe_show_create_type(qcx.scx, stmt)?,
2108 ),
2109 ShowStatement::ShowObjects(stmt) => {
2110 show::show_objects(qcx.scx, stmt)?.plan_hir(qcx)
2111 }
2112 ShowStatement::ShowVariable(_) => bail_unsupported!("SHOW variable in subqueries"),
2113 ShowStatement::InspectShard(_) => sql_bail!("unsupported INSPECT statement"),
2114 }
2115 }
2116 }
2117}
2118
2119fn plan_values(
2121 qcx: &QueryContext,
2122 values: &[Vec<Expr<Aug>>],
2123) -> Result<(HirRelationExpr, Scope), PlanError> {
2124 assert!(!values.is_empty());
2125
2126 let ecx = &ExprContext {
2127 qcx,
2128 name: "VALUES",
2129 scope: &Scope::empty(),
2130 relation_type: &SqlRelationType::empty(),
2131 allow_aggregates: false,
2132 allow_subqueries: true,
2133 allow_parameters: true,
2134 allow_windows: false,
2135 };
2136
2137 let ncols = values[0].len();
2138 let nrows = values.len();
2139
2140 let mut cols = vec![vec![]; ncols];
2143 for row in values {
2144 if row.len() != ncols {
2145 sql_bail!(
2146 "VALUES expression has varying number of columns: {} vs {}",
2147 row.len(),
2148 ncols
2149 );
2150 }
2151 for (i, v) in row.iter().enumerate() {
2152 cols[i].push(v);
2153 }
2154 }
2155
2156 let mut col_iters = Vec::with_capacity(ncols);
2158 let mut col_types = Vec::with_capacity(ncols);
2159 for col in &cols {
2160 let col = coerce_homogeneous_exprs(ecx, plan_exprs(ecx, col)?, None)?;
2161 let mut col_type = ecx.column_type(&col[0]);
2162 for val in &col[1..] {
2163 col_type = col_type.sql_union(&ecx.column_type(val))?; }
2165 col_types.push(col_type);
2166 col_iters.push(col.into_iter());
2167 }
2168
2169 let mut exprs = vec![];
2171 for _ in 0..nrows {
2172 for i in 0..ncols {
2173 exprs.push(col_iters[i].next().unwrap());
2174 }
2175 }
2176 let out = HirRelationExpr::CallTable {
2177 func: TableFunc::Wrap {
2178 width: ncols,
2179 types: col_types,
2180 },
2181 exprs,
2182 };
2183
2184 let mut scope = Scope::empty();
2186 for i in 0..ncols {
2187 let name = format!("column{}", i + 1);
2188 scope.items.push(ScopeItem::from_column_name(name));
2189 }
2190
2191 Ok((out, scope))
2192}
2193
2194fn plan_values_insert(
2204 qcx: &QueryContext,
2205 target_names: &[&ColumnName],
2206 target_types: &[&SqlScalarType],
2207 values: &[Vec<Expr<Aug>>],
2208) -> Result<HirRelationExpr, PlanError> {
2209 assert!(!values.is_empty());
2210
2211 if !values.iter().map(|row| row.len()).all_equal() {
2212 sql_bail!("VALUES lists must all be the same length");
2213 }
2214
2215 let ecx = &ExprContext {
2216 qcx,
2217 name: "VALUES",
2218 scope: &Scope::empty(),
2219 relation_type: &SqlRelationType::empty(),
2220 allow_aggregates: false,
2221 allow_subqueries: true,
2222 allow_parameters: true,
2223 allow_windows: false,
2224 };
2225
2226 let mut exprs = vec![];
2227 let mut types = vec![];
2228 for row in values {
2229 if row.len() > target_names.len() {
2230 sql_bail!("INSERT has more expressions than target columns");
2231 }
2232 for (column, val) in row.into_iter().enumerate() {
2233 let target_type = &target_types[column];
2234 let val = plan_expr(ecx, val)?;
2235 let val = typeconv::plan_coerce(ecx, val, target_type)?;
2236 let source_type = &ecx.scalar_type(&val);
2237 let val = match typeconv::plan_cast(ecx, CastContext::Assignment, val, target_type) {
2238 Ok(val) => val,
2239 Err(_) => sql_bail!(
2240 "column {} is of type {} but expression is of type {}",
2241 target_names[column].quoted(),
2242 qcx.humanize_sql_scalar_type(target_type, false),
2243 qcx.humanize_sql_scalar_type(source_type, false),
2244 ),
2245 };
2246 if column >= types.len() {
2247 types.push(ecx.column_type(&val));
2248 } else {
2249 types[column] = types[column].sql_union(&ecx.column_type(&val))?; }
2251 exprs.push(val);
2252 }
2253 }
2254
2255 Ok(HirRelationExpr::CallTable {
2256 func: TableFunc::Wrap {
2257 width: values[0].len(),
2258 types,
2259 },
2260 exprs,
2261 })
2262}
2263
2264fn plan_join_identity() -> (HirRelationExpr, Scope) {
2265 let typ = SqlRelationType::new(vec![]);
2266 let expr = HirRelationExpr::constant(vec![vec![]], typ);
2267 let scope = Scope::empty();
2268 (expr, scope)
2269}
2270
2271#[derive(Debug)]
2277struct SelectPlan {
2278 expr: HirRelationExpr,
2279 scope: Scope,
2280 order_by: Vec<ColumnOrder>,
2281 project: Vec<usize>,
2282}
2283
2284generate_extracted_config!(
2285 SelectOption,
2286 (ExpectedGroupSize, u64),
2287 (AggregateInputGroupSize, u64),
2288 (DistinctOnInputGroupSize, u64),
2289 (LimitInputGroupSize, u64)
2290);
2291
2292fn plan_select_from_where(
2310 qcx: &QueryContext,
2311 mut s: Select<Aug>,
2312 mut order_by_exprs: Vec<OrderByExpr<Aug>>,
2313) -> Result<SelectPlan, PlanError> {
2314 let select_option_extracted = SelectOptionExtracted::try_from(s.options.clone())?;
2321 let group_size_hints = GroupSizeHints::try_from(select_option_extracted)?;
2322
2323 let (mut relation_expr, mut from_scope) =
2325 s.from.iter().try_fold(plan_join_identity(), |l, twj| {
2326 let (left, left_scope) = l;
2327 plan_join(
2328 qcx,
2329 left,
2330 left_scope,
2331 &Join {
2332 relation: TableFactor::NestedJoin {
2333 join: Box::new(twj.clone()),
2334 alias: None,
2335 },
2336 join_operator: JoinOperator::CrossJoin,
2337 },
2338 )
2339 })?;
2340
2341 if let Some(selection) = &s.selection {
2343 let ecx = &ExprContext {
2344 qcx,
2345 name: "WHERE clause",
2346 scope: &from_scope,
2347 relation_type: &qcx.relation_type(&relation_expr),
2348 allow_aggregates: false,
2349 allow_subqueries: true,
2350 allow_parameters: true,
2351 allow_windows: false,
2352 };
2353 let expr = plan_expr(ecx, selection)
2354 .map_err(|e| sql_err!("WHERE clause error: {}", e))?
2355 .type_as(ecx, &SqlScalarType::Bool)?;
2356 relation_expr = relation_expr.filter(vec![expr]);
2357 }
2358
2359 let (aggregates, table_funcs) = {
2362 let mut visitor = AggregateTableFuncVisitor::new(qcx.scx);
2363 visitor.visit_select_mut(&mut s);
2364 for o in order_by_exprs.iter_mut() {
2365 visitor.visit_order_by_expr_mut(o);
2366 }
2367 visitor.into_result()?
2368 };
2369 let mut table_func_names: BTreeMap<String, Ident> = BTreeMap::new();
2370 let pre_table_funcs_arity = from_scope.len();
2377 let mut pre_table_funcs_relation = None;
2378 let mut table_funcs_deferred = false;
2379 if !table_funcs.is_empty() {
2380 let (expr, scope) = plan_scalar_table_funcs(
2381 qcx,
2382 &table_funcs,
2383 &mut table_func_names,
2384 &relation_expr,
2385 &from_scope,
2386 )?;
2387 if !aggregates.is_empty() || !s.group_by.is_empty() || s.having.is_some() {
2388 pre_table_funcs_relation = Some(relation_expr.clone());
2389 }
2390 relation_expr = relation_expr.join(expr, HirScalarExpr::literal_true(), JoinKind::Inner);
2391 from_scope = from_scope.product(scope)?;
2392 }
2393
2394 let projection = {
2396 let ecx = &ExprContext {
2397 qcx,
2398 name: "SELECT clause",
2399 scope: &from_scope,
2400 relation_type: &qcx.relation_type(&relation_expr),
2401 allow_aggregates: true,
2402 allow_subqueries: true,
2403 allow_parameters: true,
2404 allow_windows: true,
2405 };
2406 let mut out = vec![];
2407 for si in &s.projection {
2408 if *si == SelectItem::Wildcard && s.from.is_empty() {
2409 sql_bail!("SELECT * with no tables specified is not valid");
2410 }
2411 out.extend(expand_select_item(ecx, si, &table_func_names)?);
2412 }
2413 out
2414 };
2415
2416 let (mut group_scope, select_all_mapping) = {
2420 let ecx = &ExprContext {
2422 qcx,
2423 name: "GROUP BY clause",
2424 scope: &from_scope,
2425 relation_type: &qcx.relation_type(&relation_expr),
2426 allow_aggregates: false,
2427 allow_subqueries: true,
2428 allow_parameters: true,
2429 allow_windows: false,
2430 };
2431 let mut group_key = vec![];
2432 let mut group_exprs: BTreeMap<HirScalarExpr, ScopeItem> = BTreeMap::new();
2433 let mut group_hir_exprs = vec![];
2434 let mut group_scope = Scope::empty();
2435 let mut select_all_mapping = BTreeMap::new();
2436
2437 for group_expr in &s.group_by {
2438 let (group_expr, expr) = plan_group_by_expr(ecx, group_expr, &projection)?;
2439 let new_column = group_key.len();
2440
2441 if let Some(existing_scope_item) = group_exprs.get_mut(&expr) {
2452 if let Some(group_expr) = group_expr {
2456 existing_scope_item.exprs.insert(group_expr.clone());
2457 }
2458 continue;
2459 }
2460
2461 let mut scope_item = if let HirScalarExpr::Column(
2462 ColumnRef {
2463 level: 0,
2464 column: old_column,
2465 },
2466 _name,
2467 ) = &expr
2468 {
2469 select_all_mapping.insert(*old_column, new_column);
2475 let scope_item = ecx.scope.items[*old_column].clone();
2476 scope_item
2477 } else {
2478 ScopeItem::empty()
2479 };
2480
2481 if let Some(group_expr) = group_expr.cloned() {
2482 scope_item.exprs.insert(group_expr);
2483 }
2484
2485 group_key.push(from_scope.len() + group_exprs.len());
2486 group_hir_exprs.push(expr.clone());
2487 group_exprs.insert(expr, scope_item);
2488 }
2489
2490 assert_eq!(group_hir_exprs.len(), group_exprs.len());
2491 for expr in &group_hir_exprs {
2492 if let Some(scope_item) = group_exprs.remove(expr) {
2493 group_scope.items.push(scope_item);
2494 }
2495 }
2496
2497 let ecx = &ExprContext {
2499 qcx,
2500 name: "aggregate function",
2501 scope: &from_scope,
2502 relation_type: &qcx.relation_type(&relation_expr.clone().map(group_hir_exprs.clone())),
2503 allow_aggregates: false,
2504 allow_subqueries: true,
2505 allow_parameters: true,
2506 allow_windows: false,
2507 };
2508 let mut agg_exprs = vec![];
2509 for sql_function in aggregates {
2510 if sql_function.over.is_some() {
2511 unreachable!(
2512 "Window aggregate; AggregateTableFuncVisitor explicitly filters these out"
2513 );
2514 }
2515 agg_exprs.push(plan_aggregate_common(ecx, &sql_function)?);
2516 group_scope
2517 .items
2518 .push(ScopeItem::from_expr(Expr::Function(sql_function.clone())));
2519 }
2520 if !agg_exprs.is_empty() || !group_key.is_empty() || s.having.is_some() {
2521 if let Some(pre_relation_expr) = pre_table_funcs_relation.take() {
2525 let mut references_table_funcs = false;
2526 let mut check = |column: usize| {
2527 if column >= pre_table_funcs_arity {
2528 references_table_funcs = true;
2529 }
2530 };
2531 for expr in &group_hir_exprs {
2532 expr.visit_columns_referring_to_root_level(&mut check);
2533 }
2534 for agg_expr in &agg_exprs {
2535 agg_expr
2536 .expr
2537 .visit_columns_referring_to_root_level(&mut check);
2538 }
2539 if !references_table_funcs {
2540 relation_expr = pre_relation_expr;
2541 for (i, key) in group_key.iter_mut().enumerate() {
2544 *key = pre_table_funcs_arity + i;
2545 }
2546 table_funcs_deferred = true;
2547 }
2548 }
2549
2550 relation_expr = relation_expr.map(group_hir_exprs).reduce(
2552 group_key,
2553 agg_exprs,
2554 group_size_hints.aggregate_input_group_size,
2555 );
2556
2557 let ungrouped_arity = if table_funcs_deferred {
2565 pre_table_funcs_arity
2566 } else {
2567 from_scope.len()
2568 };
2569 for i in 0..ungrouped_arity {
2570 if !select_all_mapping.contains_key(&i) {
2571 let scope_item = &ecx.scope.items[i];
2572 group_scope.ungrouped_columns.push(ScopeUngroupedColumn {
2573 table_name: scope_item.table_name.clone(),
2574 column_name: scope_item.column_name.clone(),
2575 allow_unqualified_references: scope_item.allow_unqualified_references,
2576 });
2577 }
2578 }
2579
2580 (group_scope, select_all_mapping)
2581 } else {
2582 (
2584 from_scope.clone(),
2585 (0..from_scope.len()).map(|i| (i, i)).collect(),
2586 )
2587 }
2588 };
2589
2590 if let Some(ref having) = s.having {
2592 let ecx = &ExprContext {
2593 qcx,
2594 name: "HAVING clause",
2595 scope: &group_scope,
2596 relation_type: &qcx.relation_type(&relation_expr),
2597 allow_aggregates: true,
2598 allow_subqueries: true,
2599 allow_parameters: true,
2600 allow_windows: false,
2601 };
2602 let expr = plan_expr(ecx, having)?.type_as(ecx, &SqlScalarType::Bool)?;
2603 relation_expr = relation_expr.filter(vec![expr]);
2604 }
2605
2606 let window_funcs = {
2619 let mut visitor = WindowFuncCollector::default();
2620 visitor.visit_select(&s);
2624 for o in order_by_exprs.iter() {
2625 visitor.visit_order_by_expr(o);
2626 }
2627 visitor.into_result()
2628 };
2629 for window_func in window_funcs {
2630 let ecx = &ExprContext {
2631 qcx,
2632 name: "window function",
2633 scope: &group_scope,
2634 relation_type: &qcx.relation_type(&relation_expr),
2635 allow_aggregates: true,
2636 allow_subqueries: true,
2637 allow_parameters: true,
2638 allow_windows: true,
2639 };
2640 relation_expr = relation_expr.map(vec![plan_expr(ecx, &window_func)?.type_as_any(ecx)?]);
2641 group_scope.items.push(ScopeItem::from_expr(window_func));
2642 }
2643 if let Some(ref qualify) = s.qualify {
2650 let ecx = &ExprContext {
2651 qcx,
2652 name: "QUALIFY clause",
2653 scope: &group_scope,
2654 relation_type: &qcx.relation_type(&relation_expr),
2655 allow_aggregates: true,
2656 allow_subqueries: true,
2657 allow_parameters: true,
2658 allow_windows: true,
2659 };
2660 let expr = plan_expr(ecx, qualify)?.type_as(ecx, &SqlScalarType::Bool)?;
2661 relation_expr = relation_expr.filter(vec![expr]);
2662 }
2663
2664 if table_funcs_deferred {
2668 let (expr, scope) = plan_scalar_table_funcs(
2669 qcx,
2670 &table_funcs,
2671 &mut table_func_names,
2672 &relation_expr,
2673 &group_scope,
2674 )?;
2675 relation_expr = relation_expr.join(expr, HirScalarExpr::literal_true(), JoinKind::Inner);
2676 let ungrouped_columns = mem::take(&mut group_scope.ungrouped_columns);
2679 group_scope = group_scope.product(scope)?;
2680 group_scope.ungrouped_columns = ungrouped_columns;
2681 }
2682
2683 let output_columns = {
2685 let mut new_exprs = vec![];
2686 let mut new_type = qcx.relation_type(&relation_expr);
2687 let mut output_columns = vec![];
2688 for (select_item, column_name) in &projection {
2689 let ecx = &ExprContext {
2690 qcx,
2691 name: "SELECT clause",
2692 scope: &group_scope,
2693 relation_type: &new_type,
2694 allow_aggregates: true,
2695 allow_subqueries: true,
2696 allow_parameters: true,
2697 allow_windows: true,
2698 };
2699 let expr = match select_item {
2700 ExpandedSelectItem::InputOrdinal(i) => {
2701 if let Some(column) = select_all_mapping.get(i).copied() {
2702 HirScalarExpr::column(column)
2703 } else {
2704 return Err(PlanError::ungrouped_column(&from_scope.items[*i]));
2705 }
2706 }
2707 ExpandedSelectItem::Expr(expr) => plan_expr(ecx, expr)?.type_as_any(ecx)?,
2708 };
2709 if let HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) = expr {
2710 output_columns.push((column, column_name));
2712 } else {
2713 let typ = ecx.column_type(&expr);
2720 new_type.column_types.push(typ);
2721 new_exprs.push(expr);
2722 output_columns.push((group_scope.len(), column_name));
2723 group_scope
2724 .items
2725 .push(ScopeItem::from_expr(select_item.as_expr().cloned()));
2726 }
2727 }
2728 relation_expr = relation_expr.map(new_exprs);
2729 output_columns
2730 };
2731 let mut project_key: Vec<_> = output_columns.iter().map(|(i, _name)| *i).collect();
2732
2733 let order_by = {
2735 let relation_type = qcx.relation_type(&relation_expr);
2736 let (mut order_by, mut map_exprs) = plan_order_by_exprs(
2737 &ExprContext {
2738 qcx,
2739 name: "ORDER BY clause",
2740 scope: &group_scope,
2741 relation_type: &relation_type,
2742 allow_aggregates: true,
2743 allow_subqueries: true,
2744 allow_parameters: true,
2745 allow_windows: true,
2746 },
2747 &order_by_exprs,
2748 &output_columns,
2749 )?;
2750
2751 match s.distinct {
2752 None => relation_expr = relation_expr.map(map_exprs),
2753 Some(Distinct::EntireRow) => {
2754 if relation_type.arity() == 0 {
2755 sql_bail!("SELECT DISTINCT must have at least one column");
2756 }
2757 if !try_push_projection_order_by(
2761 &mut relation_expr,
2762 &mut project_key,
2763 &mut order_by,
2764 ) {
2765 sql_bail!(
2766 "for SELECT DISTINCT, ORDER BY expressions must appear in select list"
2767 );
2768 }
2769 assert!(map_exprs.is_empty());
2770 relation_expr = relation_expr.distinct();
2771 }
2772 Some(Distinct::On(exprs)) => {
2773 if table_funcs_deferred && !order_by_exprs.is_empty() {
2781 bail_unsupported!(
2782 "SELECT list table function with DISTINCT ON and ORDER BY over an aggregation"
2783 );
2784 }
2785
2786 let ecx = &ExprContext {
2787 qcx,
2788 name: "DISTINCT ON clause",
2789 scope: &group_scope,
2790 relation_type: &qcx.relation_type(&relation_expr),
2791 allow_aggregates: true,
2792 allow_subqueries: true,
2793 allow_parameters: true,
2794 allow_windows: true,
2795 };
2796
2797 let mut distinct_exprs = vec![];
2798 for expr in &exprs {
2799 let expr = plan_order_by_or_distinct_expr(ecx, expr, &output_columns)?;
2800 distinct_exprs.push(expr);
2801 }
2802
2803 let mut distinct_key = vec![];
2804
2805 let arity = relation_type.arity();
2815 for ord in order_by.iter().take(distinct_exprs.len()) {
2816 let mut expr = &HirScalarExpr::column(ord.column);
2819 if ord.column >= arity {
2820 expr = &map_exprs[ord.column - arity];
2821 };
2822 match distinct_exprs.iter().position(move |e| e == expr) {
2823 None => sql_bail!(
2824 "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"
2825 ),
2826 Some(pos) => {
2827 distinct_exprs.remove(pos);
2828 }
2829 }
2830 distinct_key.push(ord.column);
2831 }
2832
2833 for expr in distinct_exprs {
2835 let column = match expr {
2838 HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) => column,
2839 _ => {
2840 map_exprs.push(expr);
2841 arity + map_exprs.len() - 1
2842 }
2843 };
2844 distinct_key.push(column);
2845 }
2846
2847 let distinct_len = distinct_key.len();
2852 relation_expr = HirRelationExpr::top_k(
2853 relation_expr.map(map_exprs),
2854 distinct_key,
2855 order_by.iter().skip(distinct_len).cloned().collect(),
2856 Some(HirScalarExpr::literal(
2857 Datum::Int64(1),
2858 SqlScalarType::Int64,
2859 )),
2860 HirScalarExpr::literal(Datum::Int64(0), SqlScalarType::Int64),
2861 group_size_hints.distinct_on_input_group_size,
2862 );
2863 }
2864 }
2865
2866 order_by
2867 };
2868
2869 let scope = Scope::from_source(None, projection.into_iter().map(|(_expr, name)| name));
2874
2875 Ok(SelectPlan {
2876 expr: relation_expr,
2877 scope,
2878 order_by,
2879 project: project_key,
2880 })
2881}
2882
2883fn plan_scalar_table_funcs(
2884 qcx: &QueryContext,
2885 table_funcs: &BTreeMap<Function<Aug>, String>,
2886 table_func_names: &mut BTreeMap<String, Ident>,
2887 relation_expr: &HirRelationExpr,
2888 from_scope: &Scope,
2889) -> Result<(HirRelationExpr, Scope), PlanError> {
2890 let rows_from_qcx = qcx.derived_context(from_scope.clone(), qcx.relation_type(relation_expr));
2891
2892 for (table_func, id) in table_funcs.iter() {
2893 table_func_names.insert(
2894 id.clone(),
2895 Ident::new_unchecked(table_func.name.full_item_name().item.clone()),
2897 );
2898 }
2899 if table_funcs.len() == 1 {
2902 let (table_func, id) = table_funcs.iter().next().unwrap();
2903 let (expr, mut scope) =
2904 plan_solitary_table_function(&rows_from_qcx, table_func, None, false)?;
2905
2906 let num_cols = scope.len();
2908 for i in 0..scope.len() {
2909 scope.items[i].table_name = Some(PartialItemName {
2910 database: None,
2911 schema: None,
2912 item: id.clone(),
2913 });
2914 scope.items[i].from_single_column_function = num_cols == 1;
2915 scope.items[i].allow_unqualified_references = false;
2916 }
2917 return Ok((expr, scope));
2918 }
2919 if table_funcs.keys().any(is_repeat_row) {
2920 bail_unsupported!(format!(
2923 "{} in a SELECT clause with multiple table functions",
2924 REPEAT_ROW_NAME
2925 ));
2926 }
2927 let (expr, mut scope, num_cols) =
2929 plan_rows_from_internal(&rows_from_qcx, table_funcs.keys(), None)?;
2930
2931 let mut i = 0;
2933 for (id, num_cols) in table_funcs.values().zip_eq(num_cols) {
2934 for _ in 0..num_cols {
2935 scope.items[i].table_name = Some(PartialItemName {
2936 database: None,
2937 schema: None,
2938 item: id.clone(),
2939 });
2940 scope.items[i].from_single_column_function = num_cols == 1;
2941 scope.items[i].allow_unqualified_references = false;
2942 i += 1;
2943 }
2944 scope.items[i].table_name = Some(PartialItemName {
2948 database: None,
2949 schema: None,
2950 item: id.clone(),
2951 });
2952 scope.items[i].is_exists_column_for_a_table_function_that_was_in_the_target_list = true;
2953 scope.items[i].allow_unqualified_references = false;
2954 i += 1;
2955 }
2956 scope.items[i].allow_unqualified_references = false;
2958 Ok((expr, scope))
2959}
2960
2961fn plan_group_by_expr<'a>(
2968 ecx: &ExprContext,
2969 group_expr: &'a Expr<Aug>,
2970 projection: &'a [(ExpandedSelectItem, ColumnName)],
2971) -> Result<(Option<&'a Expr<Aug>>, HirScalarExpr), PlanError> {
2972 let plan_projection = |column: usize| match &projection[column].0 {
2973 ExpandedSelectItem::InputOrdinal(column) => Ok((None, HirScalarExpr::column(*column))),
2974 ExpandedSelectItem::Expr(expr) => {
2975 Ok((Some(expr.as_ref()), plan_expr(ecx, expr)?.type_as_any(ecx)?))
2976 }
2977 };
2978
2979 if let Some(column) = check_col_index(ecx.name, group_expr, projection.len())? {
2982 return plan_projection(column);
2983 }
2984
2985 match group_expr {
2989 Expr::Identifier(names) => match plan_identifier(ecx, names) {
2990 Err(PlanError::UnknownColumn {
2991 table: None,
2992 column,
2993 similar,
2994 }) => {
2995 let mut iter = projection.iter().map(|(_expr, name)| name);
2998 if let Some(i) = iter.position(|n| *n == column) {
2999 if iter.any(|n| *n == column) {
3000 Err(PlanError::AmbiguousColumn(column))
3001 } else {
3002 plan_projection(i)
3003 }
3004 } else {
3005 Err(PlanError::UnknownColumn {
3008 table: None,
3009 column,
3010 similar,
3011 })
3012 }
3013 }
3014 res => Ok((Some(group_expr), res?)),
3015 },
3016 _ => Ok((
3017 Some(group_expr),
3018 plan_expr(ecx, group_expr)?.type_as_any(ecx)?,
3019 )),
3020 }
3021}
3022
3023pub(crate) fn plan_order_by_exprs(
3031 ecx: &ExprContext,
3032 order_by_exprs: &[OrderByExpr<Aug>],
3033 output_columns: &[(usize, &ColumnName)],
3034) -> Result<(Vec<ColumnOrder>, Vec<HirScalarExpr>), PlanError> {
3035 let mut order_by = vec![];
3036 let mut map_exprs = vec![];
3037 for obe in order_by_exprs {
3038 let expr = plan_order_by_or_distinct_expr(ecx, &obe.expr, output_columns)?;
3039 let column = match expr {
3042 HirScalarExpr::Column(ColumnRef { level: 0, column }, _name) => column,
3043 _ => {
3044 map_exprs.push(expr);
3045 ecx.relation_type.arity() + map_exprs.len() - 1
3046 }
3047 };
3048 order_by.push(resolve_desc_and_nulls_last(obe, column));
3049 }
3050 Ok((order_by, map_exprs))
3051}
3052
3053fn plan_order_by_or_distinct_expr(
3071 ecx: &ExprContext,
3072 expr: &Expr<Aug>,
3073 output_columns: &[(usize, &ColumnName)],
3074) -> Result<HirScalarExpr, PlanError> {
3075 if let Some(i) = check_col_index(ecx.name, expr, output_columns.len())? {
3076 return Ok(HirScalarExpr::column(output_columns[i].0));
3077 }
3078
3079 if let Expr::Identifier(names) = expr {
3080 if let [name] = &names[..] {
3081 let name = normalize::column_name(name.clone());
3082 let mut iter = output_columns.iter().filter(|(_, n)| **n == name);
3083 if let Some((i, _)) = iter.next() {
3084 match iter.next() {
3085 Some((i2, _)) if i != i2 => return Err(PlanError::AmbiguousColumn(name)),
3089 _ => return Ok(HirScalarExpr::column(*i)),
3090 }
3091 }
3092 }
3093 }
3094
3095 plan_expr(ecx, expr)?.type_as_any(ecx)
3096}
3097
3098fn plan_table_with_joins(
3099 qcx: &QueryContext,
3100 table_with_joins: &TableWithJoins<Aug>,
3101) -> Result<(HirRelationExpr, Scope), PlanError> {
3102 let (mut expr, mut scope) = plan_table_factor(qcx, &table_with_joins.relation)?;
3103 for join in &table_with_joins.joins {
3104 let (new_expr, new_scope) = plan_join(qcx, expr, scope, join)?;
3105 expr = new_expr;
3106 scope = new_scope;
3107 }
3108 Ok((expr, scope))
3109}
3110
3111fn plan_table_factor(
3112 qcx: &QueryContext,
3113 table_factor: &TableFactor<Aug>,
3114) -> Result<(HirRelationExpr, Scope), PlanError> {
3115 match table_factor {
3116 TableFactor::Table { name, alias } => {
3117 let (expr, scope) = qcx.resolve_table_name(name.clone())?;
3118 let scope = plan_table_alias(scope, alias.as_ref())?;
3119 Ok((expr, scope))
3120 }
3121
3122 TableFactor::Function {
3123 function,
3124 alias,
3125 with_ordinality,
3126 } => plan_solitary_table_function(qcx, function, alias.as_ref(), *with_ordinality),
3127
3128 TableFactor::RowsFrom {
3129 functions,
3130 alias,
3131 with_ordinality,
3132 } => plan_rows_from(qcx, functions, alias.as_ref(), *with_ordinality),
3133
3134 TableFactor::Derived {
3135 lateral,
3136 subquery,
3137 alias,
3138 } => {
3139 let mut qcx = (*qcx).clone();
3140 if !lateral {
3141 for scope in &mut qcx.outer_scopes {
3145 if scope.lateral_barrier {
3146 break;
3147 }
3148 scope.items.clear();
3149 }
3150 }
3151 qcx.outer_scopes[0].lateral_barrier = true;
3152 let (expr, scope) = plan_nested_query(&mut qcx, subquery)?;
3153 let scope = plan_table_alias(scope, alias.as_ref())?;
3154 Ok((expr, scope))
3155 }
3156
3157 TableFactor::NestedJoin { join, alias } => {
3158 let (expr, scope) = plan_table_with_joins(qcx, join)?;
3159 let scope = plan_table_alias(scope, alias.as_ref())?;
3160 Ok((expr, scope))
3161 }
3162 }
3163}
3164
3165fn plan_rows_from(
3207 qcx: &QueryContext,
3208 functions: &[Function<Aug>],
3209 alias: Option<&TableAlias>,
3210 with_ordinality: bool,
3211) -> Result<(HirRelationExpr, Scope), PlanError> {
3212 if functions.iter().any(is_repeat_row) {
3214 bail_unsupported!(format!("{} in ROWS FROM", REPEAT_ROW_NAME));
3218 }
3219
3220 if let [function] = functions {
3223 return plan_solitary_table_function(qcx, function, alias, with_ordinality);
3224 }
3225
3226 let (expr, mut scope, num_cols) = plan_rows_from_internal(
3230 qcx,
3231 functions,
3232 Some(functions[0].name.full_item_name().clone()),
3233 )?;
3234
3235 let mut columns = Vec::new();
3237 let mut offset = 0;
3238 for (idx, cols) in num_cols.into_iter().enumerate() {
3240 for i in 0..cols {
3241 columns.push(offset + i);
3242 }
3243 offset += cols + 1;
3244
3245 scope.items.remove(offset - idx - 1);
3248 }
3249
3250 if with_ordinality {
3253 columns.push(offset);
3254 } else {
3255 scope.items.pop();
3256 }
3257
3258 let expr = expr.project(columns);
3259
3260 let scope = plan_table_alias(scope, alias)?;
3261 Ok((expr, scope))
3262}
3263
3264fn is_repeat_row(f: &Function<Aug>) -> bool {
3265 f.name.full_name_str().as_str() == format!("{}.{}", MZ_CATALOG_SCHEMA, REPEAT_ROW_NAME)
3266}
3267
3268fn plan_rows_from_internal<'a>(
3291 qcx: &QueryContext,
3292 functions: impl IntoIterator<Item = &'a Function<Aug>>,
3293 table_name: Option<FullItemName>,
3294) -> Result<(HirRelationExpr, Scope, Vec<usize>), PlanError> {
3295 let mut functions = functions.into_iter();
3296 let mut num_cols = Vec::new();
3297
3298 let (mut left_expr, mut left_scope) =
3302 plan_table_function_internal(qcx, functions.next().unwrap(), true, table_name.clone())?;
3303 num_cols.push(left_scope.len() - 1);
3304 left_expr = left_expr.map(vec![HirScalarExpr::column(left_scope.len() - 1)]);
3306 left_scope
3307 .items
3308 .push(ScopeItem::from_column_name(ORDINALITY_COL_NAME));
3309
3310 for function in functions {
3311 let qcx = qcx.empty_derived_context();
3313 let (right_expr, mut right_scope) =
3314 plan_table_function_internal(&qcx, function, true, table_name.clone())?;
3315 num_cols.push(right_scope.len() - 1);
3316 let left_col = left_scope.len() - 1;
3317 let right_col = left_scope.len() + right_scope.len() - 1;
3318 let on = HirScalarExpr::call_binary(
3319 HirScalarExpr::column(left_col),
3320 HirScalarExpr::column(right_col),
3321 expr_func::Eq,
3322 );
3323 left_expr = left_expr
3324 .join(right_expr, on, JoinKind::FullOuter)
3325 .map(vec![HirScalarExpr::call_variadic(
3326 Coalesce,
3327 vec![
3328 HirScalarExpr::column(left_col),
3329 HirScalarExpr::column(right_col),
3330 ],
3331 )]);
3332
3333 left_expr = left_expr.project(
3336 (0..left_col) .chain(left_col + 1..right_col + 2) .collect(),
3339 );
3340 right_scope.items.push(left_scope.items.pop().unwrap());
3342
3343 left_scope.items.extend(right_scope.items);
3344 }
3345
3346 Ok((left_expr, left_scope, num_cols))
3347}
3348
3349fn plan_solitary_table_function(
3353 qcx: &QueryContext,
3354 function: &Function<Aug>,
3355 alias: Option<&TableAlias>,
3356 with_ordinality: bool,
3357) -> Result<(HirRelationExpr, Scope), PlanError> {
3358 let (expr, mut scope) = plan_table_function_internal(qcx, function, with_ordinality, None)?;
3359
3360 let single_column_function = scope.len() == 1 + if with_ordinality { 1 } else { 0 };
3361 if single_column_function {
3362 let item = &mut scope.items[0];
3363
3364 item.from_single_column_function = true;
3367
3368 if let Some(alias) = alias {
3383 if let ScopeItem {
3384 table_name: Some(table_name),
3385 column_name,
3386 ..
3387 } = item
3388 {
3389 if table_name.item.as_str() == column_name.as_str() {
3390 *column_name = normalize::column_name(alias.name.clone());
3391 }
3392 }
3393 }
3394 }
3395
3396 let scope = plan_table_alias(scope, alias)?;
3397 Ok((expr, scope))
3398}
3399
3400fn plan_table_function_internal(
3405 qcx: &QueryContext,
3406 Function {
3407 name,
3408 args,
3409 filter,
3410 over,
3411 distinct,
3412 }: &Function<Aug>,
3413 with_ordinality: bool,
3414 table_name: Option<FullItemName>,
3415) -> Result<(HirRelationExpr, Scope), PlanError> {
3416 if filter.is_some() {
3421 sql_bail!("FILTER is not allowed for table functions in FROM");
3422 }
3423 if over.is_some() {
3424 sql_bail!("OVER is not allowed for table functions in FROM");
3425 }
3426 if *distinct {
3427 sql_bail!("DISTINCT is not allowed for table functions in FROM");
3428 }
3429
3430 let ecx = &ExprContext {
3431 qcx,
3432 name: "table function arguments",
3433 scope: &Scope::empty(),
3434 relation_type: &SqlRelationType::empty(),
3435 allow_aggregates: false,
3436 allow_subqueries: true,
3437 allow_parameters: true,
3438 allow_windows: false,
3439 };
3440
3441 let scalar_args = match args {
3442 FunctionArgs::Star => sql_bail!("{} does not accept * as an argument", name),
3443 FunctionArgs::Args { args, order_by } => {
3444 if !order_by.is_empty() {
3445 sql_bail!(
3446 "ORDER BY specified, but {} is not an aggregate function",
3447 name
3448 );
3449 }
3450 plan_exprs(ecx, args)?
3451 }
3452 };
3453
3454 let table_name = match table_name {
3455 Some(table_name) => table_name.item,
3456 None => name.full_item_name().item.clone(),
3457 };
3458
3459 let scope_name = Some(PartialItemName {
3460 database: None,
3461 schema: None,
3462 item: table_name,
3463 });
3464
3465 let (expr, mut scope) = match resolve_func(ecx, name, args)? {
3466 Func::Table(impls) => {
3467 let tf = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
3468 let scope = Scope::from_source(scope_name.clone(), tf.column_names);
3469 let expr = match tf.imp {
3470 TableFuncImpl::CallTable { mut func, exprs } => {
3471 if with_ordinality {
3472 func = TableFunc::with_ordinality(func.clone()).ok_or(
3473 PlanError::Unsupported {
3474 feature: format!("WITH ORDINALITY on {}", func),
3475 discussion_no: None,
3476 },
3477 )?;
3478 }
3479 HirRelationExpr::CallTable { func, exprs }
3480 }
3481 TableFuncImpl::Expr(expr) => {
3482 if !with_ordinality {
3483 expr
3484 } else {
3485 if qcx
3489 .scx
3490 .is_feature_flag_enabled(&ENABLE_WITH_ORDINALITY_LEGACY_FALLBACK)
3491 {
3492 tracing::error!(
3496 %name,
3497 "Using the legacy WITH ORDINALITY / ROWS FROM implementation for a table function",
3498 );
3499 expr.map(vec![HirScalarExpr::windowing(WindowExpr {
3500 func: WindowExprType::Scalar(ScalarWindowExpr {
3501 func: ScalarWindowFunc::RowNumber,
3502 order_by: vec![],
3503 }),
3504 partition_by: vec![],
3505 order_by: vec![],
3506 })])
3507 } else {
3508 bail_unsupported!(format!(
3509 "WITH ORDINALITY or ROWS FROM with {}",
3510 name
3511 ));
3512 }
3513 }
3514 }
3515 };
3516 (expr, scope)
3517 }
3518 Func::Scalar(impls) => {
3519 let expr = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
3520 let output = expr.typ(
3521 &qcx.outer_relation_types,
3522 &SqlRelationType::new(vec![]),
3523 &qcx.scx.param_types.borrow(),
3524 );
3525
3526 let relation = SqlRelationType::new(vec![output]);
3527
3528 let function_ident = Ident::new(name.full_item_name().item.clone())?;
3529 let column_name = normalize::column_name(function_ident);
3530 let name = column_name.to_string();
3531
3532 let scope = Scope::from_source(scope_name.clone(), vec![column_name]);
3533
3534 let mut func = TableFunc::TabletizedScalar { relation, name };
3535 if with_ordinality {
3536 func = TableFunc::with_ordinality(func.clone()).ok_or(PlanError::Unsupported {
3537 feature: format!("WITH ORDINALITY on {}", func),
3538 discussion_no: None,
3539 })?;
3540 }
3541 (
3542 HirRelationExpr::CallTable {
3543 func,
3544 exprs: vec![expr],
3545 },
3546 scope,
3547 )
3548 }
3549 o => sql_bail!(
3550 "{} functions are not supported in functions in FROM",
3551 o.class()
3552 ),
3553 };
3554
3555 if with_ordinality {
3556 scope
3557 .items
3558 .push(ScopeItem::from_name(scope_name, "ordinality"));
3559 }
3560
3561 Ok((expr, scope))
3562}
3563
3564fn plan_table_alias(mut scope: Scope, alias: Option<&TableAlias>) -> Result<Scope, PlanError> {
3565 if let Some(TableAlias {
3566 name,
3567 columns,
3568 strict,
3569 }) = alias
3570 {
3571 if (columns.len() > scope.items.len()) || (*strict && columns.len() != scope.items.len()) {
3572 sql_bail!(
3573 "{} has {} columns available but {} columns specified",
3574 name,
3575 scope.items.len(),
3576 columns.len()
3577 );
3578 }
3579
3580 let table_name = normalize::ident(name.to_owned());
3581 for (i, item) in scope.items.iter_mut().enumerate() {
3582 item.table_name = if item.allow_unqualified_references {
3583 Some(PartialItemName {
3584 database: None,
3585 schema: None,
3586 item: table_name.clone(),
3587 })
3588 } else {
3589 None
3623 };
3624 item.column_name = columns
3625 .get(i)
3626 .map(|a| normalize::column_name(a.clone()))
3627 .unwrap_or_else(|| item.column_name.clone());
3628 }
3629 }
3630 Ok(scope)
3631}
3632
3633fn invent_column_name(
3637 ecx: &ExprContext,
3638 expr: &Expr<Aug>,
3639 table_func_names: &BTreeMap<String, Ident>,
3640) -> Result<Option<ColumnName>, PlanError> {
3641 #[derive(Debug)]
3648 enum NameQuality {
3649 Low,
3650 High,
3651 }
3652
3653 fn invent(
3654 ecx: &ExprContext,
3655 expr: &Expr<Aug>,
3656 table_func_names: &BTreeMap<String, Ident>,
3657 ) -> Result<Option<(ColumnName, NameQuality)>, PlanError> {
3658 Ok(match expr {
3659 Expr::Identifier(names) => {
3660 if let [name] = names.as_slice() {
3661 if let Some(table_func_name) = table_func_names.get(name.as_str()) {
3662 return Ok(Some((
3663 normalize::column_name(table_func_name.clone()),
3664 NameQuality::High,
3665 )));
3666 }
3667 }
3668 names
3669 .last()
3670 .map(|n| (normalize::column_name(n.clone()), NameQuality::High))
3671 }
3672 Expr::Value(v) => match v {
3673 Value::Boolean(_) => Some(("bool".into(), NameQuality::High)),
3676 Value::Interval(_) => Some(("interval".into(), NameQuality::High)),
3677 _ => None,
3678 },
3679 Expr::Function(func) => {
3680 let (schema, item) = match &func.name {
3681 ResolvedItemName::Item {
3682 qualifiers,
3683 full_name,
3684 ..
3685 } => (&qualifiers.schema_spec, full_name.item.clone()),
3686 _ => {
3689 bail_internal!("function name did not resolve to an item: {:?}", func.name)
3690 }
3691 };
3692
3693 if schema == &SchemaSpecifier::from(ecx.qcx.scx.catalog.get_mz_internal_schema_id())
3694 || schema
3695 == &SchemaSpecifier::from(ecx.qcx.scx.catalog.get_mz_unsafe_schema_id())
3696 {
3697 None
3698 } else {
3699 Some((item.into(), NameQuality::High))
3700 }
3701 }
3702 Expr::HomogenizingFunction { function, .. } => Some((
3703 function.to_string().to_lowercase().into(),
3704 NameQuality::High,
3705 )),
3706 Expr::NullIf { .. } => Some(("nullif".into(), NameQuality::High)),
3707 Expr::Array { .. } => Some(("array".into(), NameQuality::High)),
3708 Expr::List { .. } => Some(("list".into(), NameQuality::High)),
3709 Expr::Map { .. } | Expr::MapSubquery(_) => Some(("map".into(), NameQuality::High)),
3710 Expr::Cast {
3711 expr, data_type, ..
3712 } => match invent(ecx, expr, table_func_names)? {
3713 Some((name, NameQuality::High)) => Some((name, NameQuality::High)),
3714 _ => Some((data_type.unqualified_item_name().into(), NameQuality::Low)),
3715 },
3716 Expr::Case { else_result, .. } => {
3717 let inner = match else_result.as_ref() {
3718 Some(else_result) => invent(ecx, else_result, table_func_names)?,
3719 None => None,
3720 };
3721 match inner {
3722 Some((name, NameQuality::High)) => Some((name, NameQuality::High)),
3723 _ => Some(("case".into(), NameQuality::Low)),
3724 }
3725 }
3726 Expr::FieldAccess { field, .. } => {
3727 Some((normalize::column_name(field.clone()), NameQuality::High))
3728 }
3729 Expr::Exists { .. } => Some(("exists".into(), NameQuality::High)),
3730 Expr::Subscript { expr, .. } => invent(ecx, expr, table_func_names)?,
3731 Expr::Subquery(query) | Expr::ListSubquery(query) | Expr::ArraySubquery(query) => {
3732 let Ok((_expr, scope)) = plan_nested_query(&mut ecx.derived_query_context(), query)
3740 else {
3741 return Ok(None);
3742 };
3743 scope
3744 .items
3745 .first()
3746 .map(|name| (name.column_name.clone(), NameQuality::High))
3747 }
3748 Expr::Row { .. } => Some(("row".into(), NameQuality::High)),
3749 _ => None,
3750 })
3751 }
3752
3753 Ok(invent(ecx, expr, table_func_names)?.map(|(name, _quality)| name))
3754}
3755
3756#[derive(Debug)]
3757enum ExpandedSelectItem<'a> {
3758 InputOrdinal(usize),
3759 Expr(Cow<'a, Expr<Aug>>),
3760}
3761
3762impl ExpandedSelectItem<'_> {
3763 fn as_expr(&self) -> Option<&Expr<Aug>> {
3764 match self {
3765 ExpandedSelectItem::InputOrdinal(_) => None,
3766 ExpandedSelectItem::Expr(expr) => Some(expr),
3767 }
3768 }
3769}
3770
3771fn expand_select_item<'a>(
3772 ecx: &ExprContext,
3773 s: &'a SelectItem<Aug>,
3774 table_func_names: &BTreeMap<String, Ident>,
3775) -> Result<Vec<(ExpandedSelectItem<'a>, ColumnName)>, PlanError> {
3776 match s {
3777 SelectItem::Expr {
3778 expr: Expr::QualifiedWildcard(table_name),
3779 alias: _,
3780 } => {
3781 *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3782 let table_name =
3783 normalize::unresolved_item_name(UnresolvedItemName(table_name.clone()))?;
3784 let out: Vec<_> = ecx
3785 .scope
3786 .items
3787 .iter()
3788 .enumerate()
3789 .filter(|(_i, item)| item.is_from_table(&table_name))
3790 .map(|(i, item)| {
3791 let name = item.column_name.clone();
3792 (ExpandedSelectItem::InputOrdinal(i), name)
3793 })
3794 .collect();
3795 if out.is_empty() {
3796 sql_bail!("no table named '{}' in scope", table_name);
3797 }
3798 Ok(out)
3799 }
3800 SelectItem::Expr {
3801 expr: Expr::WildcardAccess(sql_expr),
3802 alias: _,
3803 } => {
3804 *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3805 let expr = plan_expr(ecx, sql_expr)?.type_as_any(ecx)?;
3811 let fields = match ecx.scalar_type(&expr) {
3812 SqlScalarType::Record { fields, .. } => fields,
3813 ty => sql_bail!(
3814 "type {} is not composite",
3815 ecx.humanize_sql_scalar_type(&ty, false)
3816 ),
3817 };
3818 let mut skip_cols: BTreeSet<ColumnName> = BTreeSet::new();
3819 if let Expr::Identifier(ident) = sql_expr.as_ref() {
3820 if let [name] = ident.as_slice() {
3821 if let Ok(items) = ecx.scope.items_from_table(
3822 &[],
3823 &PartialItemName {
3824 database: None,
3825 schema: None,
3826 item: name.as_str().to_string(),
3827 },
3828 ) {
3829 for (_, item) in items {
3830 if item
3831 .is_exists_column_for_a_table_function_that_was_in_the_target_list
3832 {
3833 skip_cols.insert(item.column_name.clone());
3834 }
3835 }
3836 }
3837 }
3838 }
3839 let items = fields
3840 .iter()
3841 .filter_map(|(name, _ty)| {
3842 if skip_cols.contains(name) {
3843 None
3844 } else {
3845 let item = ExpandedSelectItem::Expr(Cow::Owned(Expr::FieldAccess {
3846 expr: sql_expr.clone(),
3847 field: normalize::column_name_ident(name),
3848 }));
3849 Some((item, name.clone()))
3850 }
3851 })
3852 .collect();
3853 Ok(items)
3854 }
3855 SelectItem::Wildcard => {
3856 *ecx.qcx.scx.ambiguous_columns.borrow_mut() = true;
3857 let items: Vec<_> = ecx
3858 .scope
3859 .items
3860 .iter()
3861 .enumerate()
3862 .filter(|(_i, item)| item.allow_unqualified_references)
3863 .map(|(i, item)| {
3864 let name = item.column_name.clone();
3865 (ExpandedSelectItem::InputOrdinal(i), name)
3866 })
3867 .collect();
3868
3869 Ok(items)
3870 }
3871 SelectItem::Expr { expr, alias } => {
3872 let name = match alias.clone().map(normalize::column_name) {
3873 Some(name) => name,
3874 None => invent_column_name(ecx, expr, table_func_names)?
3875 .unwrap_or_else(|| UNKNOWN_COLUMN_NAME.into()),
3876 };
3877 Ok(vec![(ExpandedSelectItem::Expr(Cow::Borrowed(expr)), name)])
3878 }
3879 }
3880}
3881
3882fn plan_join(
3883 left_qcx: &QueryContext,
3884 left: HirRelationExpr,
3885 left_scope: Scope,
3886 join: &Join<Aug>,
3887) -> Result<(HirRelationExpr, Scope), PlanError> {
3888 const ON_TRUE: JoinConstraint<Aug> = JoinConstraint::On(Expr::Value(Value::Boolean(true)));
3889 let (kind, constraint) = match &join.join_operator {
3890 JoinOperator::CrossJoin => (JoinKind::Inner, &ON_TRUE),
3891 JoinOperator::Inner(constraint) => (JoinKind::Inner, constraint),
3892 JoinOperator::LeftOuter(constraint) => (JoinKind::LeftOuter, constraint),
3893 JoinOperator::RightOuter(constraint) => (JoinKind::RightOuter, constraint),
3894 JoinOperator::FullOuter(constraint) => (JoinKind::FullOuter, constraint),
3895 };
3896
3897 let mut right_qcx = left_qcx.derived_context(left_scope.clone(), left_qcx.relation_type(&left));
3898 if !kind.can_be_correlated() {
3899 for item in &mut right_qcx.outer_scopes[0].items {
3900 item.error_if_referenced =
3905 Some(|table, column| PlanError::WrongJoinTypeForLateralColumn {
3906 table: table.cloned(),
3907 column: column.clone(),
3908 });
3909 }
3910 }
3911 let (right, right_scope) = plan_table_factor(&right_qcx, &join.relation)?;
3912
3913 let (expr, scope) = match constraint {
3914 JoinConstraint::On(expr) => {
3915 let product_scope = left_scope.product(right_scope)?;
3916 let ecx = &ExprContext {
3917 qcx: left_qcx,
3918 name: "ON clause",
3919 scope: &product_scope,
3920 relation_type: &SqlRelationType::new(
3921 left_qcx
3922 .relation_type(&left)
3923 .column_types
3924 .into_iter()
3925 .chain(right_qcx.relation_type(&right).column_types)
3926 .collect(),
3927 ),
3928 allow_aggregates: false,
3929 allow_subqueries: true,
3930 allow_parameters: true,
3931 allow_windows: false,
3932 };
3933 let on = plan_expr(ecx, expr)?.type_as(ecx, &SqlScalarType::Bool)?;
3934 let joined = left.join(right, on, kind);
3935 (joined, product_scope)
3936 }
3937 JoinConstraint::Using { columns, alias } => {
3938 let column_names = columns
3939 .iter()
3940 .map(|ident| normalize::column_name(ident.clone()))
3941 .collect::<Vec<_>>();
3942
3943 plan_using_constraint(
3944 &column_names,
3945 left_qcx,
3946 left,
3947 left_scope,
3948 &right_qcx,
3949 right,
3950 right_scope,
3951 kind,
3952 alias.as_ref(),
3953 )?
3954 }
3955 JoinConstraint::Natural => {
3956 *left_qcx.scx.ambiguous_columns.borrow_mut() = true;
3959 *right_qcx.scx.ambiguous_columns.borrow_mut() = true;
3960 let left_column_names = left_scope.column_names();
3961 let right_column_names: BTreeSet<_> = right_scope.column_names().collect();
3962 let column_names: Vec<_> = left_column_names
3963 .filter(|col| right_column_names.contains(col))
3964 .cloned()
3965 .collect();
3966 plan_using_constraint(
3967 &column_names,
3968 left_qcx,
3969 left,
3970 left_scope,
3971 &right_qcx,
3972 right,
3973 right_scope,
3974 kind,
3975 None,
3976 )?
3977 }
3978 };
3979 Ok((expr, scope))
3980}
3981
3982#[allow(clippy::too_many_arguments)]
3984fn plan_using_constraint(
3985 column_names: &[ColumnName],
3986 left_qcx: &QueryContext,
3987 left: HirRelationExpr,
3988 left_scope: Scope,
3989 right_qcx: &QueryContext,
3990 right: HirRelationExpr,
3991 right_scope: Scope,
3992 kind: JoinKind,
3993 alias: Option<&Ident>,
3994) -> Result<(HirRelationExpr, Scope), PlanError> {
3995 let mut both_scope = left_scope.clone().product(right_scope.clone())?;
3996
3997 let mut unique_column_names = BTreeSet::new();
4000 for c in column_names {
4001 if !unique_column_names.insert(c) {
4002 return Err(PlanError::Unsupported {
4003 feature: format!(
4004 "column name {} appears more than once in USING clause",
4005 c.quoted()
4006 ),
4007 discussion_no: None,
4008 });
4009 }
4010 }
4011
4012 let alias_item_name = alias.map(|alias| PartialItemName {
4013 database: None,
4014 schema: None,
4015 item: alias.clone().to_string(),
4016 });
4017
4018 if let Some(alias_item_name) = &alias_item_name {
4019 for partial_item_name in both_scope.table_names() {
4020 if partial_item_name.matches(alias_item_name) {
4021 sql_bail!(
4022 "table name \"{}\" specified more than once",
4023 alias_item_name
4024 )
4025 }
4026 }
4027 }
4028
4029 let ecx = &ExprContext {
4030 qcx: right_qcx,
4031 name: "USING clause",
4032 scope: &both_scope,
4033 relation_type: &SqlRelationType::new(
4034 left_qcx
4035 .relation_type(&left)
4036 .column_types
4037 .into_iter()
4038 .chain(right_qcx.relation_type(&right).column_types)
4039 .collect(),
4040 ),
4041 allow_aggregates: false,
4042 allow_subqueries: false,
4043 allow_parameters: false,
4044 allow_windows: false,
4045 };
4046
4047 let mut join_exprs = vec![];
4048 let mut map_exprs = vec![];
4049 let mut new_items = vec![];
4050 let mut join_cols = vec![];
4051 let mut hidden_cols = vec![];
4052
4053 for column_name in column_names {
4054 let (lhs, lhs_name) = left_scope.resolve_using_column(
4056 column_name,
4057 JoinSide::Left,
4058 &mut left_qcx.name_manager.borrow_mut(),
4059 )?;
4060 let (mut rhs, rhs_name) = right_scope.resolve_using_column(
4061 column_name,
4062 JoinSide::Right,
4063 &mut right_qcx.name_manager.borrow_mut(),
4064 )?;
4065
4066 rhs.column += left_scope.len();
4068
4069 let mut exprs = coerce_homogeneous_exprs(
4071 &ecx.with_name(&format!(
4072 "NATURAL/USING join column {}",
4073 column_name.quoted()
4074 )),
4075 vec![
4076 CoercibleScalarExpr::Coerced(HirScalarExpr::named_column(
4077 lhs,
4078 Arc::clone(&lhs_name),
4079 )),
4080 CoercibleScalarExpr::Coerced(HirScalarExpr::named_column(
4081 rhs,
4082 Arc::clone(&rhs_name),
4083 )),
4084 ],
4085 None,
4086 )?;
4087 let (expr1, expr2) = (exprs.remove(0), exprs.remove(0));
4088
4089 match kind {
4090 JoinKind::LeftOuter { .. } | JoinKind::Inner { .. } => {
4091 join_cols.push(lhs.column);
4092 hidden_cols.push(rhs.column);
4093 }
4094 JoinKind::RightOuter => {
4095 join_cols.push(rhs.column);
4096 hidden_cols.push(lhs.column);
4097 }
4098 JoinKind::FullOuter => {
4099 join_cols.push(both_scope.items.len() + map_exprs.len());
4102 hidden_cols.push(lhs.column);
4103 hidden_cols.push(rhs.column);
4104 map_exprs.push(HirScalarExpr::call_variadic(
4105 Coalesce,
4106 vec![expr1.clone(), expr2.clone()],
4107 ));
4108 new_items.push(ScopeItem::from_column_name(column_name));
4109 }
4110 }
4111
4112 if alias_item_name.is_some() {
4117 let new_item_col = both_scope.items.len() + new_items.len();
4118 join_cols.push(new_item_col);
4119 hidden_cols.push(new_item_col);
4120
4121 new_items.push(ScopeItem::from_name(
4122 alias_item_name.clone(),
4123 column_name.clone().to_string(),
4124 ));
4125
4126 let alias_expr = match kind {
4133 JoinKind::LeftOuter { .. } | JoinKind::Inner { .. } => {
4134 HirScalarExpr::named_column(lhs, Arc::clone(&lhs_name))
4135 }
4136 JoinKind::RightOuter => HirScalarExpr::named_column(rhs, Arc::clone(&rhs_name)),
4137 JoinKind::FullOuter => {
4138 HirScalarExpr::call_variadic(Coalesce, vec![expr1.clone(), expr2.clone()])
4139 }
4140 };
4141 map_exprs.push(alias_expr);
4142 }
4143
4144 join_exprs.push(expr1.call_binary(expr2, expr_func::Eq));
4145 }
4146 both_scope.items.extend(new_items);
4147
4148 for c in hidden_cols {
4152 both_scope.items[c].allow_unqualified_references = false;
4153 }
4154
4155 let project_key = join_cols
4157 .into_iter()
4158 .chain(0..both_scope.items.len())
4159 .unique()
4160 .collect::<Vec<_>>();
4161
4162 both_scope = both_scope.project(&project_key);
4163
4164 let on = HirScalarExpr::variadic_and(join_exprs);
4165
4166 let both = left
4167 .join(right, on, kind)
4168 .map(map_exprs)
4169 .project(project_key);
4170 Ok((both, both_scope))
4171}
4172
4173pub fn plan_expr<'a>(
4174 ecx: &'a ExprContext,
4175 e: &Expr<Aug>,
4176) -> Result<CoercibleScalarExpr, PlanError> {
4177 ecx.checked_recur(|ecx| plan_expr_inner(ecx, e))
4178}
4179
4180fn plan_expr_inner<'a>(
4181 ecx: &'a ExprContext,
4182 e: &Expr<Aug>,
4183) -> Result<CoercibleScalarExpr, PlanError> {
4184 if let Some((i, item)) = ecx.scope.resolve_expr(e) {
4185 return Ok(HirScalarExpr::named_column(
4187 i,
4188 ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
4189 )
4190 .into());
4191 }
4192
4193 match e {
4194 Expr::Identifier(names) | Expr::QualifiedWildcard(names) => {
4196 Ok(plan_identifier(ecx, names)?.into())
4197 }
4198
4199 Expr::Value(val) => plan_literal(val),
4201 Expr::Parameter(n) => plan_parameter(ecx, *n),
4202 Expr::Array(exprs) => plan_array(ecx, exprs, None),
4203 Expr::List(exprs) => plan_list(ecx, exprs, None),
4204 Expr::Map(exprs) => plan_map(ecx, exprs, None),
4205 Expr::Row { exprs } => plan_row(ecx, exprs),
4206
4207 Expr::Op { op, expr1, expr2 } => {
4209 Ok(plan_op(ecx, normalize::op(op)?, expr1, expr2.as_deref())?.into())
4210 }
4211 Expr::Cast {
4212 expr,
4213 data_type,
4214 failure_mode,
4215 } => plan_cast(ecx, expr, data_type, *failure_mode),
4216 Expr::Function(func) => Ok(plan_function(ecx, func)?.into()),
4217
4218 Expr::Not { expr } => plan_not(ecx, expr),
4220 Expr::And { left, right } => plan_and(ecx, left, right),
4221 Expr::Or { left, right } => plan_or(ecx, left, right),
4222 Expr::IsExpr {
4223 expr,
4224 construct,
4225 negated,
4226 } => Ok(plan_is_expr(ecx, expr, construct, *negated)?.into()),
4227 Expr::Case {
4228 operand,
4229 conditions,
4230 results,
4231 else_result,
4232 } => Ok(plan_case(ecx, operand, conditions, results, else_result)?.into()),
4233 Expr::HomogenizingFunction { function, exprs } => {
4234 plan_homogenizing_function(ecx, function, exprs)
4235 }
4236 Expr::NullIf { l_expr, r_expr } => Ok(plan_case(
4237 ecx,
4238 &None,
4239 &[l_expr.clone().equals(*r_expr.clone())],
4240 &[Expr::null()],
4241 &Some(Box::new(*l_expr.clone())),
4242 )?
4243 .into()),
4244 Expr::FieldAccess { expr, field } => plan_field_access(ecx, expr, field),
4245 Expr::WildcardAccess(expr) => plan_expr(ecx, expr),
4246 Expr::Subscript { expr, positions } => plan_subscript(ecx, expr, positions),
4247 Expr::Like {
4248 expr,
4249 pattern,
4250 escape,
4251 case_insensitive,
4252 negated,
4253 } => Ok(plan_like(
4254 ecx,
4255 expr,
4256 pattern,
4257 escape.as_deref(),
4258 *case_insensitive,
4259 *negated,
4260 )?
4261 .into()),
4262
4263 Expr::InList {
4264 expr,
4265 list,
4266 negated,
4267 } => plan_in_list(ecx, expr, list, negated),
4268
4269 Expr::Exists(query) => plan_exists(ecx, query),
4271 Expr::Subquery(query) => plan_subquery(ecx, query),
4272 Expr::ListSubquery(query) => plan_list_subquery(ecx, query),
4273 Expr::MapSubquery(query) => plan_map_subquery(ecx, query),
4274 Expr::ArraySubquery(query) => plan_array_subquery(ecx, query),
4275 Expr::Collate { expr, collation } => plan_collate(ecx, expr, collation),
4276 Expr::Nested(_) => bail_internal!("Expr::Nested should have been desugared"),
4277 Expr::InSubquery { .. } => {
4278 bail_internal!("Expr::InSubquery should have been desugared")
4279 }
4280 Expr::AnyExpr { .. } => {
4281 bail_internal!("Expr::AnyExpr should have been desugared")
4282 }
4283 Expr::AllExpr { .. } => {
4284 bail_internal!("Expr::AllExpr should have been desugared")
4285 }
4286 Expr::AnySubquery { .. } => {
4287 bail_internal!("Expr::AnySubquery should have been desugared")
4288 }
4289 Expr::AllSubquery { .. } => {
4290 bail_internal!("Expr::AllSubquery should have been desugared")
4291 }
4292 Expr::Between { .. } => {
4293 bail_internal!("Expr::Between should have been desugared")
4294 }
4295 }
4296}
4297
4298fn plan_parameter(ecx: &ExprContext, n: usize) -> Result<CoercibleScalarExpr, PlanError> {
4299 if !ecx.allow_parameters {
4300 return Err(PlanError::UnknownParameter(n));
4304 }
4305 if n == 0 || n > 65536 {
4306 return Err(PlanError::UnknownParameter(n));
4307 }
4308 if ecx.param_types().borrow().contains_key(&n) {
4309 Ok(HirScalarExpr::parameter(n).into())
4310 } else {
4311 Ok(CoercibleScalarExpr::Parameter(n))
4312 }
4313}
4314
4315fn plan_row(ecx: &ExprContext, exprs: &[Expr<Aug>]) -> Result<CoercibleScalarExpr, PlanError> {
4316 let mut out = vec![];
4317 for e in exprs {
4318 out.push(plan_expr(ecx, e)?);
4319 }
4320 Ok(CoercibleScalarExpr::LiteralRecord(out))
4321}
4322
4323fn plan_cast(
4326 ecx: &ExprContext,
4327 expr: &Expr<Aug>,
4328 data_type: &ResolvedDataType,
4329 failure_mode: CastFailureMode,
4330) -> Result<CoercibleScalarExpr, PlanError> {
4331 let name = match failure_mode {
4332 CastFailureMode::Error => "CAST",
4333 CastFailureMode::NullFallback => {
4334 ecx.qcx.scx.require_feature_flag(&vars::ENABLE_TRY_CAST)?;
4335 "TRY_CAST"
4336 }
4337 };
4338 let to_scalar_type = scalar_type_from_sql(ecx.qcx.scx, data_type)?;
4339 let keeps_hint = |empty: bool| failure_mode == CastFailureMode::Error || empty;
4340 let expr = match expr {
4341 Expr::Array(exprs) if keeps_hint(exprs.is_empty()) => {
4361 plan_array(ecx, exprs, Some(&to_scalar_type))?
4362 }
4363 Expr::List(exprs) if keeps_hint(exprs.is_empty()) => {
4364 plan_list(ecx, exprs, Some(&to_scalar_type))?
4365 }
4366 Expr::Map(exprs) if keeps_hint(exprs.is_empty()) => {
4367 plan_map(ecx, exprs, Some(&to_scalar_type))?
4368 }
4369 Expr::Map(_) => {
4370 bail_unsupported!("non-empty MAP constructor as the argument of TRY_CAST")
4371 }
4372 expr => plan_expr(ecx, expr)?,
4373 };
4374 let ecx = &ecx.with_name(name);
4375 let expr = typeconv::plan_coerce_with_failure_mode(ecx, expr, &to_scalar_type, failure_mode)?;
4378 let expr = typeconv::plan_cast_with_failure_mode(
4379 ecx,
4380 CastContext::Explicit,
4381 failure_mode,
4382 expr,
4383 &to_scalar_type,
4384 )?;
4385 Ok(expr.into())
4386}
4387
4388fn plan_not(ecx: &ExprContext, expr: &Expr<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4389 let ecx = ecx.with_name("NOT argument");
4390 Ok(plan_expr(&ecx, expr)?
4391 .type_as(&ecx, &SqlScalarType::Bool)?
4392 .call_unary(UnaryFunc::Not(expr_func::Not))
4393 .into())
4394}
4395
4396fn plan_and(
4397 ecx: &ExprContext,
4398 left: &Expr<Aug>,
4399 right: &Expr<Aug>,
4400) -> Result<CoercibleScalarExpr, PlanError> {
4401 let ecx = ecx.with_name("AND argument");
4402 Ok(HirScalarExpr::variadic_and(vec![
4403 plan_expr(&ecx, left)?.type_as(&ecx, &SqlScalarType::Bool)?,
4404 plan_expr(&ecx, right)?.type_as(&ecx, &SqlScalarType::Bool)?,
4405 ])
4406 .into())
4407}
4408
4409fn plan_or(
4410 ecx: &ExprContext,
4411 left: &Expr<Aug>,
4412 right: &Expr<Aug>,
4413) -> Result<CoercibleScalarExpr, PlanError> {
4414 let ecx = ecx.with_name("OR argument");
4415 Ok(HirScalarExpr::variadic_or(vec![
4416 plan_expr(&ecx, left)?.type_as(&ecx, &SqlScalarType::Bool)?,
4417 plan_expr(&ecx, right)?.type_as(&ecx, &SqlScalarType::Bool)?,
4418 ])
4419 .into())
4420}
4421
4422fn plan_in_list(
4423 ecx: &ExprContext,
4424 lhs: &Expr<Aug>,
4425 list: &Vec<Expr<Aug>>,
4426 negated: &bool,
4427) -> Result<CoercibleScalarExpr, PlanError> {
4428 let ecx = ecx.with_name("IN list");
4429 let or = HirScalarExpr::variadic_or(
4430 list.into_iter()
4431 .map(|e| {
4432 let eq = lhs.clone().equals(e.clone());
4433 plan_expr(&ecx, &eq)?.type_as(&ecx, &SqlScalarType::Bool)
4434 })
4435 .collect::<Result<Vec<HirScalarExpr>, PlanError>>()?,
4436 );
4437 Ok(if *negated {
4438 or.call_unary(UnaryFunc::Not(expr_func::Not))
4439 } else {
4440 or
4441 }
4442 .into())
4443}
4444
4445fn plan_homogenizing_function(
4446 ecx: &ExprContext,
4447 function: &HomogenizingFunction,
4448 exprs: &[Expr<Aug>],
4449) -> Result<CoercibleScalarExpr, PlanError> {
4450 assert!(!exprs.is_empty()); let expr = HirScalarExpr::call_variadic(
4452 match function {
4453 HomogenizingFunction::Coalesce => VariadicFunc::from(Coalesce),
4454 HomogenizingFunction::Greatest => VariadicFunc::from(Greatest),
4455 HomogenizingFunction::Least => VariadicFunc::from(Least),
4456 },
4457 coerce_homogeneous_exprs(
4458 &ecx.with_name(&function.to_string().to_lowercase()),
4459 plan_exprs(ecx, exprs)?,
4460 None,
4461 )?,
4462 );
4463 Ok(expr.into())
4464}
4465
4466fn plan_field_access(
4467 ecx: &ExprContext,
4468 expr: &Expr<Aug>,
4469 field: &Ident,
4470) -> Result<CoercibleScalarExpr, PlanError> {
4471 let field = normalize::column_name(field.clone());
4472 let expr = plan_expr(ecx, expr)?.type_as_any(ecx)?;
4473 let ty = ecx.scalar_type(&expr);
4474 let i = match &ty {
4475 SqlScalarType::Record { fields, .. } => {
4476 fields.iter().position(|(name, _ty)| *name == field)
4477 }
4478 ty => sql_bail!(
4479 "column notation applied to type {}, which is not a composite type",
4480 ecx.humanize_sql_scalar_type(ty, false)
4481 ),
4482 };
4483 match i {
4484 None => sql_bail!(
4485 "field {} not found in data type {}",
4486 field,
4487 ecx.humanize_sql_scalar_type(&ty, false)
4488 ),
4489 Some(i) => Ok(expr
4490 .call_unary(UnaryFunc::RecordGet(expr_func::RecordGet(i)))
4491 .into()),
4492 }
4493}
4494
4495fn plan_subscript(
4496 ecx: &ExprContext,
4497 expr: &Expr<Aug>,
4498 positions: &[SubscriptPosition<Aug>],
4499) -> Result<CoercibleScalarExpr, PlanError> {
4500 assert!(
4501 !positions.is_empty(),
4502 "subscript expression must contain at least one position"
4503 );
4504
4505 let ecx = &ecx.with_name("subscripting");
4506 let expr = plan_expr(ecx, expr)?.type_as_any(ecx)?;
4507 let ty = ecx.scalar_type(&expr);
4508 match &ty {
4509 SqlScalarType::Array(..) | SqlScalarType::Int2Vector => plan_subscript_array(
4510 ecx,
4511 expr,
4512 positions,
4513 if ty == SqlScalarType::Int2Vector {
4517 1
4518 } else {
4519 0
4520 },
4521 ),
4522 SqlScalarType::Jsonb => plan_subscript_jsonb(ecx, expr, positions),
4523 SqlScalarType::List { element_type, .. } => {
4524 let elem_type_name = ecx.humanize_sql_scalar_type(element_type, false);
4526 let n_layers = ty.unwrap_list_n_layers();
4527 plan_subscript_list(ecx, expr, positions, n_layers, &elem_type_name)
4528 }
4529 ty => sql_bail!(
4530 "cannot subscript type {}",
4531 ecx.humanize_sql_scalar_type(ty, false)
4532 ),
4533 }
4534}
4535
4536fn extract_scalar_subscript_from_positions<'a>(
4540 positions: &'a [SubscriptPosition<Aug>],
4541 expr_type_name: &str,
4542) -> Result<Vec<&'a Expr<Aug>>, PlanError> {
4543 let mut scalar_subscripts = Vec::with_capacity(positions.len());
4544 for p in positions {
4545 if p.explicit_slice {
4546 sql_bail!("{} subscript does not support slices", expr_type_name);
4547 }
4548 assert!(
4549 p.end.is_none(),
4550 "index-appearing subscripts cannot have end value"
4551 );
4552 scalar_subscripts.push(p.start.as_ref().expect("has start if not slice"));
4553 }
4554 Ok(scalar_subscripts)
4555}
4556
4557fn plan_subscript_array(
4558 ecx: &ExprContext,
4559 expr: HirScalarExpr,
4560 positions: &[SubscriptPosition<Aug>],
4561 offset: i64,
4562) -> Result<CoercibleScalarExpr, PlanError> {
4563 let mut exprs = Vec::with_capacity(positions.len() + 1);
4564 exprs.push(expr);
4565
4566 let indexes = extract_scalar_subscript_from_positions(positions, "array")?;
4569
4570 for i in indexes {
4571 exprs.push(plan_expr(ecx, i)?.cast_to(
4572 ecx,
4573 CastContext::Explicit,
4574 &SqlScalarType::Int64,
4575 )?);
4576 }
4577
4578 Ok(HirScalarExpr::call_variadic(ArrayIndex { offset }, exprs).into())
4579}
4580
4581fn plan_subscript_list(
4582 ecx: &ExprContext,
4583 mut expr: HirScalarExpr,
4584 positions: &[SubscriptPosition<Aug>],
4585 mut remaining_layers: usize,
4586 elem_type_name: &str,
4587) -> Result<CoercibleScalarExpr, PlanError> {
4588 let mut i = 0;
4589
4590 while i < positions.len() {
4591 let j = positions[i..]
4593 .iter()
4594 .position(|p| p.explicit_slice)
4595 .unwrap_or(positions.len() - i);
4596 if j != 0 {
4597 let indexes = extract_scalar_subscript_from_positions(&positions[i..i + j], "")?;
4598 let (n, e) = plan_index_list(
4599 ecx,
4600 expr,
4601 indexes.as_slice(),
4602 remaining_layers,
4603 elem_type_name,
4604 )?;
4605 remaining_layers = n;
4606 expr = e;
4607 i += j;
4608 }
4609
4610 let j = positions[i..]
4612 .iter()
4613 .position(|p| !p.explicit_slice)
4614 .unwrap_or(positions.len() - i);
4615 if j != 0 {
4616 expr = plan_slice_list(
4617 ecx,
4618 expr,
4619 &positions[i..i + j],
4620 remaining_layers,
4621 elem_type_name,
4622 )?;
4623 i += j;
4624 }
4625 }
4626
4627 Ok(expr.into())
4628}
4629
4630fn plan_index_list(
4631 ecx: &ExprContext,
4632 expr: HirScalarExpr,
4633 indexes: &[&Expr<Aug>],
4634 n_layers: usize,
4635 elem_type_name: &str,
4636) -> Result<(usize, HirScalarExpr), PlanError> {
4637 let depth = indexes.len();
4638
4639 if depth > n_layers {
4640 if n_layers == 0 {
4641 sql_bail!("cannot subscript type {}", elem_type_name)
4642 } else {
4643 sql_bail!(
4644 "cannot index into {} layers; list only has {} layer{}",
4645 depth,
4646 n_layers,
4647 if n_layers == 1 { "" } else { "s" }
4648 )
4649 }
4650 }
4651
4652 let mut exprs = Vec::with_capacity(depth + 1);
4653 exprs.push(expr);
4654
4655 for i in indexes {
4656 exprs.push(plan_expr(ecx, i)?.cast_to(
4657 ecx,
4658 CastContext::Explicit,
4659 &SqlScalarType::Int64,
4660 )?);
4661 }
4662
4663 Ok((
4664 n_layers - depth,
4665 HirScalarExpr::call_variadic(ListIndex, exprs),
4666 ))
4667}
4668
4669fn plan_slice_list(
4670 ecx: &ExprContext,
4671 expr: HirScalarExpr,
4672 slices: &[SubscriptPosition<Aug>],
4673 n_layers: usize,
4674 elem_type_name: &str,
4675) -> Result<HirScalarExpr, PlanError> {
4676 if n_layers == 0 {
4677 sql_bail!("cannot subscript type {}", elem_type_name)
4678 }
4679
4680 let mut exprs = Vec::with_capacity(slices.len() + 1);
4682 exprs.push(expr);
4683 let extract_position_or_default = |position, default| -> Result<HirScalarExpr, PlanError> {
4685 Ok(match position {
4686 Some(p) => {
4687 plan_expr(ecx, p)?.cast_to(ecx, CastContext::Explicit, &SqlScalarType::Int64)?
4688 }
4689 None => HirScalarExpr::literal(Datum::Int64(default), SqlScalarType::Int64),
4690 })
4691 };
4692 for p in slices {
4693 let start = extract_position_or_default(p.start.as_ref(), 1)?;
4694 let end = extract_position_or_default(p.end.as_ref(), i64::MAX - 1)?;
4695 exprs.push(start);
4696 exprs.push(end);
4697 }
4698
4699 Ok(HirScalarExpr::call_variadic(ListSliceLinear, exprs))
4700}
4701
4702fn plan_like(
4703 ecx: &ExprContext,
4704 expr: &Expr<Aug>,
4705 pattern: &Expr<Aug>,
4706 escape: Option<&Expr<Aug>>,
4707 case_insensitive: bool,
4708 not: bool,
4709) -> Result<HirScalarExpr, PlanError> {
4710 use CastContext::Implicit;
4711 let ecx = ecx.with_name("LIKE argument");
4712 let expr = plan_expr(&ecx, expr)?;
4713 let haystack = match ecx.scalar_type(&expr) {
4714 CoercibleScalarType::Coerced(ref ty @ SqlScalarType::Char { length }) => expr
4715 .type_as(&ecx, ty)?
4716 .call_unary(UnaryFunc::PadChar(expr_func::PadChar { length })),
4717 _ => expr.cast_to(&ecx, Implicit, &SqlScalarType::String)?,
4718 };
4719 let mut pattern = plan_expr(&ecx, pattern)?.cast_to(&ecx, Implicit, &SqlScalarType::String)?;
4720 if let Some(escape) = escape {
4721 pattern = pattern.call_binary(
4722 plan_expr(&ecx, escape)?.cast_to(&ecx, Implicit, &SqlScalarType::String)?,
4723 expr_func::LikeEscape,
4724 );
4725 }
4726 let func: BinaryFunc = if case_insensitive {
4727 expr_func::IsLikeMatchCaseInsensitive.into()
4728 } else {
4729 expr_func::IsLikeMatchCaseSensitive.into()
4730 };
4731 let like = haystack.call_binary(pattern, func);
4732 if not {
4733 Ok(like.call_unary(UnaryFunc::Not(expr_func::Not)))
4734 } else {
4735 Ok(like)
4736 }
4737}
4738
4739fn plan_subscript_jsonb(
4740 ecx: &ExprContext,
4741 expr: HirScalarExpr,
4742 positions: &[SubscriptPosition<Aug>],
4743) -> Result<CoercibleScalarExpr, PlanError> {
4744 use CastContext::Implicit;
4745 use SqlScalarType::{Int64, String};
4746
4747 let subscripts = extract_scalar_subscript_from_positions(positions, "jsonb")?;
4750
4751 let mut exprs = Vec::with_capacity(subscripts.len());
4752 for s in subscripts {
4753 let subscript = plan_expr(ecx, s)?;
4754 let subscript = if let Ok(subscript) = subscript.clone().cast_to(ecx, Implicit, &String) {
4755 subscript
4756 } else if let Ok(subscript) = subscript.cast_to(ecx, Implicit, &Int64) {
4757 typeconv::to_string(ecx, subscript)?
4761 } else {
4762 sql_bail!("jsonb subscript type must be coercible to integer or text");
4763 };
4764 exprs.push(subscript);
4765 }
4766
4767 let expr = expr.call_binary(
4770 HirScalarExpr::call_variadic(
4771 ArrayCreate {
4772 elem_type: SqlScalarType::String,
4773 },
4774 exprs,
4775 ),
4776 expr_func::JsonbGetPath,
4777 );
4778 Ok(expr.into())
4779}
4780
4781fn plan_exists(ecx: &ExprContext, query: &Query<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4782 if !ecx.allow_subqueries {
4783 sql_bail!("{} does not allow subqueries", ecx.name)
4784 }
4785 let mut qcx = ecx.derived_query_context();
4786 let (expr, _scope) = plan_nested_query(&mut qcx, query)?;
4787 Ok(expr.exists().into())
4788}
4789
4790fn plan_subquery(ecx: &ExprContext, query: &Query<Aug>) -> Result<CoercibleScalarExpr, PlanError> {
4791 if !ecx.allow_subqueries {
4792 sql_bail!("{} does not allow subqueries", ecx.name)
4793 }
4794 let mut qcx = ecx.derived_query_context();
4795 let (expr, _scope) = plan_nested_query(&mut qcx, query)?;
4796 let column_types = qcx.relation_type(&expr).column_types;
4797 if column_types.len() != 1 {
4798 sql_bail!(
4799 "Expected subselect to return 1 column, got {} columns",
4800 column_types.len()
4801 );
4802 }
4803 Ok(expr.select().into())
4804}
4805
4806fn plan_list_subquery(
4807 ecx: &ExprContext,
4808 query: &Query<Aug>,
4809) -> Result<CoercibleScalarExpr, PlanError> {
4810 plan_vector_like_subquery(
4811 ecx,
4812 query,
4813 |_| false,
4814 |elem_type| ListCreate { elem_type }.into(),
4815 |order_by| AggregateFunc::ListConcat { order_by },
4816 expr_func::ListListConcat.into(),
4817 |elem_type| {
4818 HirScalarExpr::literal(
4819 Datum::empty_list(),
4820 SqlScalarType::List {
4821 element_type: Box::new(elem_type),
4822 custom_id: None,
4823 },
4824 )
4825 },
4826 "list",
4827 )
4828}
4829
4830fn plan_array_subquery(
4831 ecx: &ExprContext,
4832 query: &Query<Aug>,
4833) -> Result<CoercibleScalarExpr, PlanError> {
4834 plan_vector_like_subquery(
4835 ecx,
4836 query,
4837 |elem_type| {
4838 matches!(
4839 elem_type,
4840 SqlScalarType::Char { .. }
4841 | SqlScalarType::Array { .. }
4842 | SqlScalarType::List { .. }
4843 | SqlScalarType::Map { .. }
4844 )
4845 },
4846 |elem_type| ArrayCreate { elem_type }.into(),
4847 |order_by| AggregateFunc::ArrayConcat { order_by },
4848 expr_func::ArrayArrayConcat.into(),
4849 |elem_type| {
4850 HirScalarExpr::literal(
4851 Datum::empty_array(),
4852 SqlScalarType::Array(Box::new(elem_type)),
4853 )
4854 },
4855 "[]",
4856 )
4857}
4858
4859fn plan_vector_like_subquery<F1, F2, F3, F4>(
4861 ecx: &ExprContext,
4862 query: &Query<Aug>,
4863 is_unsupported_type: F1,
4864 vector_create: F2,
4865 aggregate_concat: F3,
4866 binary_concat: BinaryFunc,
4867 empty_literal: F4,
4868 vector_type_string: &str,
4869) -> Result<CoercibleScalarExpr, PlanError>
4870where
4871 F1: Fn(&SqlScalarType) -> bool,
4872 F2: Fn(SqlScalarType) -> VariadicFunc,
4873 F3: Fn(Vec<ColumnOrder>) -> AggregateFunc,
4874 F4: Fn(SqlScalarType) -> HirScalarExpr,
4875{
4876 if !ecx.allow_subqueries {
4877 sql_bail!("{} does not allow subqueries", ecx.name)
4878 }
4879
4880 let mut qcx = ecx.derived_query_context();
4881 let mut planned_query = plan_query(&mut qcx, query)?;
4882 if planned_query.limit.is_some()
4883 || !planned_query
4884 .offset
4885 .clone()
4886 .try_into_literal_int64()
4887 .is_ok_and(|offset| offset == 0)
4888 {
4889 planned_query.expr = HirRelationExpr::top_k(
4890 planned_query.expr,
4891 vec![],
4892 planned_query.order_by.clone(),
4893 planned_query.limit,
4894 planned_query.offset,
4895 planned_query.group_size_hints.limit_input_group_size,
4896 );
4897 }
4898
4899 if planned_query.project.len() != 1 {
4900 sql_bail!(
4901 "Expected subselect to return 1 column, got {} columns",
4902 planned_query.project.len()
4903 );
4904 }
4905
4906 let project_column = *planned_query.project.get(0).unwrap();
4907 let elem_type = qcx
4908 .relation_type(&planned_query.expr)
4909 .column_types
4910 .get(project_column)
4911 .cloned()
4912 .unwrap()
4913 .scalar_type();
4914
4915 if is_unsupported_type(&elem_type) {
4916 bail_unsupported!(format!(
4917 "cannot build array from subquery because return type {}{}",
4918 ecx.humanize_sql_scalar_type(&elem_type, false),
4919 vector_type_string
4920 ));
4921 }
4922
4923 let aggregation_exprs: Vec<_> = iter::once(HirScalarExpr::call_variadic(
4926 vector_create(elem_type.clone()),
4927 vec![HirScalarExpr::column(project_column)],
4928 ))
4929 .chain(
4930 planned_query
4931 .order_by
4932 .iter()
4933 .map(|co| HirScalarExpr::column(co.column)),
4934 )
4935 .collect();
4936
4937 let aggregation_projection = vec![0];
4941 let aggregation_order_by = planned_query
4942 .order_by
4943 .into_iter()
4944 .enumerate()
4945 .map(|(i, order)| ColumnOrder { column: i, ..order })
4946 .collect();
4947
4948 let reduced_expr = planned_query
4949 .expr
4950 .reduce(
4951 vec![],
4952 vec![AggregateExpr {
4953 func: aggregate_concat(aggregation_order_by),
4954 expr: Box::new(HirScalarExpr::call_variadic(
4955 RecordCreate {
4956 field_names: iter::repeat(ColumnName::from(""))
4957 .take(aggregation_exprs.len())
4958 .collect(),
4959 },
4960 aggregation_exprs,
4961 )),
4962 distinct: false,
4963 }],
4964 None,
4965 )
4966 .project(aggregation_projection);
4967
4968 Ok(reduced_expr
4970 .select()
4971 .call_binary(empty_literal(elem_type), binary_concat)
4972 .into())
4973}
4974
4975fn plan_map_subquery(
4976 ecx: &ExprContext,
4977 query: &Query<Aug>,
4978) -> Result<CoercibleScalarExpr, PlanError> {
4979 if !ecx.allow_subqueries {
4980 sql_bail!("{} does not allow subqueries", ecx.name)
4981 }
4982
4983 let mut qcx = ecx.derived_query_context();
4984 let mut query = plan_query(&mut qcx, query)?;
4985 if query.limit.is_some()
4986 || !query
4987 .offset
4988 .clone()
4989 .try_into_literal_int64()
4990 .is_ok_and(|offset| offset == 0)
4991 {
4992 query.expr = HirRelationExpr::top_k(
4993 query.expr,
4994 vec![],
4995 query.order_by.clone(),
4996 query.limit,
4997 query.offset,
4998 query.group_size_hints.limit_input_group_size,
4999 );
5000 }
5001 if query.project.len() != 2 {
5002 sql_bail!(
5003 "expected map subquery to return 2 columns, got {} columns",
5004 query.project.len()
5005 );
5006 }
5007
5008 let query_types = qcx.relation_type(&query.expr).column_types;
5009 let key_column = query.project[0];
5010 let key_type = query_types[key_column].clone().scalar_type();
5011 let value_column = query.project[1];
5012 let value_type = query_types[value_column].clone().scalar_type();
5013
5014 if key_type != SqlScalarType::String {
5015 sql_bail!("cannot build map from subquery because first column is not of type text");
5016 }
5017
5018 let aggregation_exprs: Vec<_> = iter::once(HirScalarExpr::call_variadic(
5019 RecordCreate {
5020 field_names: vec![ColumnName::from("key"), ColumnName::from("value")],
5021 },
5022 vec![
5023 HirScalarExpr::column(key_column),
5024 HirScalarExpr::column(value_column),
5025 ],
5026 ))
5027 .chain(
5028 query
5029 .order_by
5030 .iter()
5031 .map(|co| HirScalarExpr::column(co.column)),
5032 )
5033 .collect();
5034
5035 let expr = query
5036 .expr
5037 .reduce(
5038 vec![],
5039 vec![AggregateExpr {
5040 func: AggregateFunc::MapAgg {
5041 order_by: query
5042 .order_by
5043 .into_iter()
5044 .enumerate()
5045 .map(|(i, order)| ColumnOrder { column: i, ..order })
5046 .collect(),
5047 value_type: value_type.clone(),
5048 },
5049 expr: Box::new(HirScalarExpr::call_variadic(
5050 RecordCreate {
5051 field_names: iter::repeat(ColumnName::from(""))
5052 .take(aggregation_exprs.len())
5053 .collect(),
5054 },
5055 aggregation_exprs,
5056 )),
5057 distinct: false,
5058 }],
5059 None,
5060 )
5061 .project(vec![0]);
5062
5063 let expr = HirScalarExpr::call_variadic(
5065 Coalesce,
5066 vec![
5067 expr.select(),
5068 HirScalarExpr::literal(
5069 Datum::empty_map(),
5070 SqlScalarType::Map {
5071 value_type: Box::new(value_type),
5072 custom_id: None,
5073 },
5074 ),
5075 ],
5076 );
5077
5078 Ok(expr.into())
5079}
5080
5081pub fn is_supported_collation(collation: &UnresolvedItemName) -> bool {
5084 collation.0.len() == 2
5085 && collation.0[0] == ident!(mz_repr::namespaces::PG_CATALOG_SCHEMA)
5086 && collation.0[1] == ident!("default")
5087}
5088
5089fn plan_collate(
5090 ecx: &ExprContext,
5091 expr: &Expr<Aug>,
5092 collation: &UnresolvedItemName,
5093) -> Result<CoercibleScalarExpr, PlanError> {
5094 if is_supported_collation(collation) {
5095 plan_expr(ecx, expr)
5096 } else {
5097 bail_unsupported!("COLLATE");
5098 }
5099}
5100
5101fn plan_exprs<E>(ecx: &ExprContext, exprs: &[E]) -> Result<Vec<CoercibleScalarExpr>, PlanError>
5108where
5109 E: std::borrow::Borrow<Expr<Aug>>,
5110{
5111 let mut out = vec![];
5112 for expr in exprs {
5113 out.push(plan_expr(ecx, expr.borrow())?);
5114 }
5115 Ok(out)
5116}
5117
5118fn plan_array(
5120 ecx: &ExprContext,
5121 exprs: &[Expr<Aug>],
5122 type_hint: Option<&SqlScalarType>,
5123) -> Result<CoercibleScalarExpr, PlanError> {
5124 let mut out = vec![];
5126 for expr in exprs {
5127 out.push(match expr {
5128 Expr::Array(exprs) => plan_array(ecx, exprs, type_hint.clone())?,
5131 _ => plan_expr(ecx, expr)?,
5132 });
5133 }
5134
5135 let type_hint = match type_hint {
5137 Some(SqlScalarType::Array(elem_type)) => {
5142 let multidimensional = out.iter().any(|e| {
5143 matches!(
5144 ecx.scalar_type(e),
5145 CoercibleScalarType::Coerced(SqlScalarType::Array(_))
5146 )
5147 });
5148 if multidimensional {
5149 type_hint
5150 } else {
5151 Some(&**elem_type)
5152 }
5153 }
5154 Some(_) => None,
5158 None => None,
5160 };
5161
5162 let (elem_type, exprs) = if exprs.is_empty() {
5164 if let Some(elem_type) = type_hint {
5165 (elem_type.clone(), vec![])
5166 } else {
5167 sql_bail!("cannot determine type of empty array");
5168 }
5169 } else {
5170 let out = coerce_homogeneous_exprs(&ecx.with_name("ARRAY"), out, type_hint)?;
5171 (union_scalar_types(ecx, &out)?, out)
5172 };
5173
5174 if matches!(
5180 elem_type,
5181 SqlScalarType::Char { .. } | SqlScalarType::List { .. } | SqlScalarType::Map { .. }
5182 ) {
5183 bail_unsupported!(format!(
5184 "{}[]",
5185 ecx.humanize_sql_scalar_type(&elem_type, false)
5186 ));
5187 }
5188
5189 Ok(HirScalarExpr::call_variadic(ArrayCreate { elem_type }, exprs).into())
5190}
5191
5192fn plan_list(
5193 ecx: &ExprContext,
5194 exprs: &[Expr<Aug>],
5195 type_hint: Option<&SqlScalarType>,
5196) -> Result<CoercibleScalarExpr, PlanError> {
5197 let (elem_type, exprs) = if exprs.is_empty() {
5198 if let Some(SqlScalarType::List { element_type, .. }) = type_hint {
5199 (element_type.without_modifiers(), vec![])
5200 } else {
5201 sql_bail!("cannot determine type of empty list");
5202 }
5203 } else {
5204 let type_hint = match type_hint {
5205 Some(SqlScalarType::List { element_type, .. }) => Some(&**element_type),
5206 _ => None,
5207 };
5208
5209 let mut out = vec![];
5210 for expr in exprs {
5211 out.push(match expr {
5212 Expr::List(exprs) => plan_list(ecx, exprs, type_hint)?,
5215 _ => plan_expr(ecx, expr)?,
5216 });
5217 }
5218 let out = coerce_homogeneous_exprs(&ecx.with_name("LIST"), out, type_hint)?;
5219 (union_scalar_types(ecx, &out)?.without_modifiers(), out)
5220 };
5221
5222 if matches!(elem_type, SqlScalarType::Char { .. }) {
5223 bail_unsupported!("char list");
5224 }
5225
5226 Ok(HirScalarExpr::call_variadic(ListCreate { elem_type }, exprs).into())
5227}
5228
5229fn plan_map(
5230 ecx: &ExprContext,
5231 entries: &[MapEntry<Aug>],
5232 type_hint: Option<&SqlScalarType>,
5233) -> Result<CoercibleScalarExpr, PlanError> {
5234 let (value_type, exprs) = if entries.is_empty() {
5235 if let Some(SqlScalarType::Map { value_type, .. }) = type_hint {
5236 (value_type.without_modifiers(), vec![])
5237 } else {
5238 sql_bail!("cannot determine type of empty map");
5239 }
5240 } else {
5241 let type_hint = match type_hint {
5242 Some(SqlScalarType::Map { value_type, .. }) => Some(&**value_type),
5243 _ => None,
5244 };
5245
5246 let mut keys = vec![];
5247 let mut values = vec![];
5248 for MapEntry { key, value } in entries {
5249 let key = plan_expr(ecx, key)?.type_as(ecx, &SqlScalarType::String)?;
5250 let value = match value {
5251 Expr::Map(entries) => plan_map(ecx, entries, type_hint)?,
5254 _ => plan_expr(ecx, value)?,
5255 };
5256 keys.push(key);
5257 values.push(value);
5258 }
5259 let values = coerce_homogeneous_exprs(&ecx.with_name("MAP"), values, type_hint)?;
5260 let value_type = union_scalar_types(ecx, &values)?.without_modifiers();
5261 let out = itertools::interleave(keys, values).collect();
5262 (value_type, out)
5263 };
5264
5265 if matches!(value_type, SqlScalarType::Char { .. }) {
5266 bail_unsupported!("char map");
5267 }
5268
5269 let expr = HirScalarExpr::call_variadic(MapBuild { value_type }, exprs);
5270 Ok(expr.into())
5271}
5272
5273pub fn coerce_homogeneous_exprs(
5290 ecx: &ExprContext,
5291 exprs: Vec<CoercibleScalarExpr>,
5292 force_type: Option<&SqlScalarType>,
5293) -> Result<Vec<HirScalarExpr>, PlanError> {
5294 assert!(!exprs.is_empty());
5295
5296 let target_holder;
5297 let target = match force_type {
5298 Some(t) => t,
5299 None => {
5300 let types: Vec<_> = exprs.iter().map(|e| ecx.scalar_type(e)).collect();
5301 target_holder = typeconv::guess_best_common_type(ecx, &types)?;
5302 &target_holder
5303 }
5304 };
5305
5306 let mut out = Vec::new();
5308 for expr in exprs {
5309 let arg = typeconv::plan_coerce(ecx, expr, target)?;
5310 let ccx = match force_type {
5311 None => CastContext::Implicit,
5312 Some(_) => CastContext::Explicit,
5313 };
5314 match typeconv::plan_cast(ecx, ccx, arg.clone(), target) {
5315 Ok(expr) => out.push(expr),
5316 Err(_) => sql_bail!(
5317 "{} could not convert type {} to {}",
5318 ecx.name,
5319 ecx.humanize_sql_scalar_type(&ecx.scalar_type(&arg), false),
5320 ecx.humanize_sql_scalar_type(target, false),
5321 ),
5322 }
5323 }
5324 Ok(out)
5325}
5326
5327fn union_scalar_types(
5330 ecx: &ExprContext,
5331 exprs: &[HirScalarExpr],
5332) -> Result<SqlScalarType, PlanError> {
5333 let mut typ = ecx.scalar_type(&exprs[0]);
5334 for expr in &exprs[1..] {
5335 typ = typ.sql_union(&ecx.scalar_type(expr))?;
5336 }
5337 Ok(typ)
5338}
5339
5340pub(crate) fn resolve_desc_and_nulls_last<T: AstInfo>(
5343 obe: &OrderByExpr<T>,
5344 column: usize,
5345) -> ColumnOrder {
5346 let desc = !obe.asc.unwrap_or(true);
5347 ColumnOrder {
5348 column,
5349 desc,
5350 nulls_last: obe.nulls_last.unwrap_or(!desc),
5353 }
5354}
5355
5356fn plan_function_order_by(
5364 ecx: &ExprContext,
5365 order_by: &[OrderByExpr<Aug>],
5366) -> Result<(Vec<HirScalarExpr>, Vec<ColumnOrder>), PlanError> {
5367 let mut order_by_exprs = vec![];
5368 let mut col_orders = vec![];
5369 {
5370 for (i, obe) in order_by.iter().enumerate() {
5371 let expr = plan_expr(ecx, &obe.expr)?.type_as_any(ecx)?;
5375 order_by_exprs.push(expr);
5376 col_orders.push(resolve_desc_and_nulls_last(obe, i));
5377 }
5378 }
5379 Ok((order_by_exprs, col_orders))
5380}
5381
5382fn humanize_or_debug(scx: &StatementContext, name: &ResolvedItemName) -> String {
5387 scx.humanize_resolved_name(name)
5388 .map(|n| n.to_string())
5389 .unwrap_or_else(|_| format!("<error when trying to humanize `{name:?}`>"))
5390}
5391
5392fn plan_aggregate_common(
5394 ecx: &ExprContext,
5395 Function::<Aug> {
5396 name,
5397 args,
5398 filter,
5399 over: _,
5400 distinct,
5401 }: &Function<Aug>,
5402) -> Result<AggregateExpr, PlanError> {
5403 let impls = match resolve_func(ecx, name, args)? {
5418 Func::Aggregate(impls) => impls,
5419 _ => bail_internal!("plan_aggregate_common called on non-aggregate function"),
5420 };
5421
5422 let (args, order_by) = match &args {
5431 FunctionArgs::Star => (vec![], vec![]),
5432 FunctionArgs::Args { args, order_by } => {
5433 if args.is_empty() {
5434 sql_bail!(
5435 "{}(*) must be used to call a parameterless aggregate function",
5436 humanize_or_debug(ecx.qcx.scx, name)
5437 );
5438 }
5439 let args = plan_exprs(ecx, args)?;
5440 (args, order_by.clone())
5441 }
5442 };
5443
5444 let (order_by_exprs, col_orders) = plan_function_order_by(ecx, &order_by)?;
5445
5446 let (mut expr, func) = func::select_impl(ecx, FuncSpec::Func(name), impls, args, col_orders)?;
5447 if let Some(filter) = &filter {
5448 let cond =
5458 plan_expr(&ecx.with_name("FILTER"), filter)?.type_as(ecx, &SqlScalarType::Bool)?;
5459 let expr_typ = ecx.scalar_type(&expr);
5460 expr = HirScalarExpr::if_then_else(
5461 cond,
5462 expr,
5463 HirScalarExpr::literal(func.identity_datum(), expr_typ),
5464 );
5465 }
5466
5467 let mut seen_outer = false;
5468 let mut seen_inner = false;
5469 #[allow(deprecated)]
5470 expr.visit_columns(0, &mut |depth, col| {
5471 if depth == 0 && col.level == 0 {
5472 seen_inner = true;
5473 } else if col.level > depth {
5474 seen_outer = true;
5475 }
5476 });
5477 if seen_outer && !seen_inner {
5478 bail_unsupported!(
5479 3720,
5480 "aggregate functions that refer exclusively to outer columns"
5481 );
5482 }
5483
5484 if func.is_order_sensitive() {
5487 let field_names = iter::repeat(ColumnName::from(""))
5488 .take(1 + order_by_exprs.len())
5489 .collect();
5490 let mut exprs = vec![expr];
5491 exprs.extend(order_by_exprs);
5492 expr = HirScalarExpr::call_variadic(RecordCreate { field_names }, exprs);
5493 }
5494
5495 Ok(AggregateExpr {
5496 func,
5497 expr: Box::new(expr),
5498 distinct: *distinct,
5499 })
5500}
5501
5502fn plan_identifier(ecx: &ExprContext, names: &[Ident]) -> Result<HirScalarExpr, PlanError> {
5503 let mut names = names.to_vec();
5504 let Some(last) = names.pop() else {
5507 bail_internal!("empty identifier");
5508 };
5509 let col_name = normalize::column_name(last);
5510
5511 if !names.is_empty() {
5513 let table_name = normalize::unresolved_item_name(UnresolvedItemName(names))?;
5514 let (i, i_name) = ecx.scope.resolve_table_column(
5515 &ecx.qcx.outer_scopes,
5516 &table_name,
5517 &col_name,
5518 &mut ecx.qcx.name_manager.borrow_mut(),
5519 )?;
5520 return Ok(HirScalarExpr::named_column(i, i_name));
5521 }
5522
5523 let similar_names = match ecx.scope.resolve_column(
5526 &ecx.qcx.outer_scopes,
5527 &col_name,
5528 &mut ecx.qcx.name_manager.borrow_mut(),
5529 ) {
5530 Ok((i, i_name)) => {
5531 return Ok(HirScalarExpr::named_column(i, i_name));
5532 }
5533 Err(PlanError::UnknownColumn { similar, .. }) => similar,
5534 Err(e) => return Err(e),
5535 };
5536
5537 let items = ecx.scope.items_from_table(
5540 &ecx.qcx.outer_scopes,
5541 &PartialItemName {
5542 database: None,
5543 schema: None,
5544 item: col_name.as_str().to_owned(),
5545 },
5546 )?;
5547 match items.as_slice() {
5548 [] => Err(PlanError::UnknownColumn {
5550 table: None,
5551 column: col_name,
5552 similar: similar_names,
5553 }),
5554 [(column, item)] if item.from_single_column_function => Ok(HirScalarExpr::named_column(
5559 *column,
5560 ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
5561 )),
5562 _ => {
5565 let mut has_exists_column = None;
5566 let (exprs, field_names): (Vec<_>, Vec<_>) = items
5567 .into_iter()
5568 .filter_map(|(column, item)| {
5569 if item.is_exists_column_for_a_table_function_that_was_in_the_target_list {
5570 has_exists_column = Some(column);
5571 None
5572 } else {
5573 let expr = HirScalarExpr::named_column(
5574 column,
5575 ecx.qcx.name_manager.borrow_mut().intern_scope_item(item),
5576 );
5577 let name = item.column_name.clone();
5578 Some((expr, name))
5579 }
5580 })
5581 .unzip();
5582 let expr = if exprs.len() == 1 && has_exists_column.is_some() {
5584 exprs.into_element()
5585 } else {
5586 HirScalarExpr::call_variadic(RecordCreate { field_names }, exprs)
5587 };
5588 if let Some(has_exists_column) = has_exists_column {
5589 Ok(HirScalarExpr::if_then_else(
5590 HirScalarExpr::unnamed_column(has_exists_column)
5591 .call_unary(UnaryFunc::IsNull(mz_expr::func::IsNull)),
5592 HirScalarExpr::literal_null(ecx.scalar_type(&expr)),
5593 expr,
5594 ))
5595 } else {
5596 Ok(expr)
5597 }
5598 }
5599 }
5600}
5601
5602fn plan_op(
5603 ecx: &ExprContext,
5604 op: &str,
5605 expr1: &Expr<Aug>,
5606 expr2: Option<&Expr<Aug>>,
5607) -> Result<HirScalarExpr, PlanError> {
5608 let impls = func::resolve_op(op)?;
5609 let args = match expr2 {
5610 None => plan_exprs(ecx, &[expr1])?,
5611 Some(expr2) => plan_exprs(ecx, &[expr1, expr2])?,
5612 };
5613 func::select_impl(ecx, FuncSpec::Op(op), impls, args, vec![])
5614}
5615
5616fn plan_function<'a>(
5617 ecx: &ExprContext,
5618 f @ Function {
5619 name,
5620 args,
5621 filter,
5622 over,
5623 distinct,
5624 }: &'a Function<Aug>,
5625) -> Result<HirScalarExpr, PlanError> {
5626 let impls = match resolve_func(ecx, name, args)? {
5627 Func::Table(_) => {
5628 sql_bail!(
5629 "table functions are not allowed in {} (function {})",
5630 ecx.name,
5631 name
5632 );
5633 }
5634 Func::Scalar(impls) => {
5635 if over.is_some() {
5636 sql_bail!(
5637 "OVER clause not allowed on {name}. The OVER clause can only be used with window functions (including aggregations)."
5638 );
5639 }
5640 impls
5641 }
5642 Func::ScalarWindow(impls) => {
5643 let (
5644 ignore_nulls,
5645 order_by_exprs,
5646 col_orders,
5647 _window_frame,
5648 partition_by,
5649 scalar_args,
5650 ) = plan_window_function_non_aggr(ecx, f)?;
5651
5652 if !scalar_args.is_empty() {
5656 if let ResolvedItemName::Item {
5657 full_name: FullItemName { item, .. },
5658 ..
5659 } = name
5660 {
5661 sql_bail!(
5662 "function {} has 0 parameters, but was called with {}",
5663 item,
5664 scalar_args.len()
5665 );
5666 }
5667 }
5668
5669 let func = func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])?;
5674
5675 if ignore_nulls {
5676 bail_unsupported!(IGNORE_NULLS_ERROR_MSG);
5679 }
5680
5681 return Ok(HirScalarExpr::windowing(WindowExpr {
5682 func: WindowExprType::Scalar(ScalarWindowExpr {
5683 func,
5684 order_by: col_orders,
5685 }),
5686 partition_by,
5687 order_by: order_by_exprs,
5688 }));
5689 }
5690 Func::ValueWindow(impls) => {
5691 let window_plan = plan_window_function_non_aggr(ecx, f)?;
5692 let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition_by, win_args) =
5693 window_plan;
5694
5695 let (args_encoded, func) =
5696 func::select_impl(ecx, FuncSpec::Func(name), impls, win_args, vec![])?;
5697
5698 if ignore_nulls {
5699 match func {
5700 ValueWindowFunc::Lag | ValueWindowFunc::Lead => {}
5701 _ => bail_unsupported!(IGNORE_NULLS_ERROR_MSG),
5702 }
5703 }
5704
5705 return Ok(HirScalarExpr::windowing(WindowExpr {
5706 func: WindowExprType::Value(ValueWindowExpr {
5707 func,
5708 args: Box::new(args_encoded),
5709 order_by: col_orders,
5710 window_frame,
5711 ignore_nulls, }),
5713 partition_by,
5714 order_by: order_by_exprs,
5715 }));
5716 }
5717 Func::Aggregate(_) => {
5718 if f.over.is_none() {
5719 if ecx.allow_aggregates {
5721 sql_bail!(
5724 "Internal error: encountered unplanned non-windowed aggregate function: {:?}",
5725 name,
5726 );
5727 } else {
5728 sql_bail!(
5731 "aggregate functions are not allowed in {} (function {})",
5732 ecx.name,
5733 name
5734 );
5735 }
5736 } else {
5737 let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition_by) =
5738 plan_window_function_common(ecx, &f.name, f.over.as_deref())?;
5739
5740 match (&window_frame.start_bound, &window_frame.end_bound) {
5742 (
5743 mz_expr::WindowFrameBound::UnboundedPreceding,
5744 mz_expr::WindowFrameBound::OffsetPreceding(..),
5745 )
5746 | (
5747 mz_expr::WindowFrameBound::UnboundedPreceding,
5748 mz_expr::WindowFrameBound::OffsetFollowing(..),
5749 )
5750 | (
5751 mz_expr::WindowFrameBound::OffsetPreceding(..),
5752 mz_expr::WindowFrameBound::UnboundedFollowing,
5753 )
5754 | (
5755 mz_expr::WindowFrameBound::OffsetFollowing(..),
5756 mz_expr::WindowFrameBound::UnboundedFollowing,
5757 ) => bail_unsupported!("mixed unbounded - offset frames"),
5758 (_, _) => {} }
5760
5761 if ignore_nulls {
5762 bail_unsupported!(IGNORE_NULLS_ERROR_MSG);
5766 }
5767
5768 let aggregate_expr = plan_aggregate_common(ecx, f)?;
5769
5770 if aggregate_expr.distinct {
5771 bail_unsupported!("DISTINCT in window aggregates");
5773 }
5774
5775 return Ok(HirScalarExpr::windowing(WindowExpr {
5776 func: WindowExprType::Aggregate(AggregateWindowExpr {
5777 aggregate_expr,
5778 order_by: col_orders,
5779 window_frame,
5780 }),
5781 partition_by,
5782 order_by: order_by_exprs,
5783 }));
5784 }
5785 }
5786 };
5787
5788 if over.is_some() {
5789 bail_internal!("OVER clause should have been handled by the window function path above");
5790 }
5791
5792 if *distinct {
5793 sql_bail!(
5794 "DISTINCT specified, but {} is not an aggregate function",
5795 humanize_or_debug(ecx.qcx.scx, name)
5796 );
5797 }
5798 if filter.is_some() {
5799 sql_bail!(
5800 "FILTER specified, but {} is not an aggregate function",
5801 humanize_or_debug(ecx.qcx.scx, name)
5802 );
5803 }
5804
5805 let scalar_args = match &args {
5806 FunctionArgs::Star => {
5807 sql_bail!(
5808 "* argument is invalid with non-aggregate function {}",
5809 humanize_or_debug(ecx.qcx.scx, name)
5810 )
5811 }
5812 FunctionArgs::Args { args, order_by } => {
5813 if !order_by.is_empty() {
5814 sql_bail!(
5815 "ORDER BY specified, but {} is not an aggregate function",
5816 humanize_or_debug(ecx.qcx.scx, name)
5817 );
5818 }
5819 plan_exprs(ecx, args)?
5820 }
5821 };
5822
5823 func::select_impl(ecx, FuncSpec::Func(name), impls, scalar_args, vec![])
5824}
5825
5826pub const IGNORE_NULLS_ERROR_MSG: &str =
5827 "IGNORE NULLS and RESPECT NULLS options for functions other than LAG and LEAD";
5828
5829pub fn resolve_func(
5833 ecx: &ExprContext,
5834 name: &ResolvedItemName,
5835 args: &mz_sql_parser::ast::FunctionArgs<Aug>,
5836) -> Result<&'static Func, PlanError> {
5837 if let Ok(i) = ecx.qcx.scx.get_item_by_resolved_name(name) {
5838 if let Ok(f) = i.func() {
5839 return Ok(f);
5840 }
5841 }
5842
5843 let cexprs = match args {
5846 mz_sql_parser::ast::FunctionArgs::Star => vec![],
5847 mz_sql_parser::ast::FunctionArgs::Args { args, order_by } => {
5848 if !order_by.is_empty() {
5849 sql_bail!(
5850 "ORDER BY specified, but {} is not an aggregate function",
5851 name
5852 );
5853 }
5854 plan_exprs(ecx, args)?
5855 }
5856 };
5857
5858 let arg_types: Vec<_> = cexprs
5859 .into_iter()
5860 .map(|ty| match ecx.scalar_type(&ty) {
5861 CoercibleScalarType::Coerced(ty) => ecx.humanize_sql_scalar_type(&ty, false),
5862 CoercibleScalarType::Record(_) => "record".to_string(),
5863 CoercibleScalarType::Uncoerced => "unknown".to_string(),
5864 })
5865 .collect();
5866
5867 Err(PlanError::UnknownFunction {
5868 name: name.to_string(),
5869 arg_types,
5870 })
5871}
5872
5873fn plan_is_expr<'a>(
5874 ecx: &ExprContext,
5875 expr: &'a Expr<Aug>,
5876 construct: &IsExprConstruct<Aug>,
5877 not: bool,
5878) -> Result<HirScalarExpr, PlanError> {
5879 let expr_hir = plan_expr(ecx, expr)?;
5880
5881 let mut result = match construct {
5882 IsExprConstruct::Null => {
5883 expr_hir.type_as_any(ecx)?.call_is_null()
5888 }
5889 IsExprConstruct::Unknown => expr_hir.type_as(ecx, &SqlScalarType::Bool)?.call_is_null(),
5890 IsExprConstruct::True => expr_hir
5891 .type_as(ecx, &SqlScalarType::Bool)?
5892 .call_unary(UnaryFunc::IsTrue(expr_func::IsTrue)),
5893 IsExprConstruct::False => expr_hir
5894 .type_as(ecx, &SqlScalarType::Bool)?
5895 .call_unary(UnaryFunc::IsFalse(expr_func::IsFalse)),
5896 IsExprConstruct::DistinctFrom(expr2) => {
5897 let ne_ast = expr.clone().not_equals(expr2.as_ref().clone());
5908 let ne_hir = plan_expr(ecx, &ne_ast)?.type_as_any(ecx)?;
5909
5910 let expr1_hir = expr_hir.type_as_any(ecx)?;
5911 let expr2_hir = plan_expr(ecx, expr2)?.type_as_any(ecx)?;
5912
5913 let term1 = HirScalarExpr::variadic_or(vec![
5914 ne_hir,
5915 expr1_hir.clone().call_is_null(),
5916 expr2_hir.clone().call_is_null(),
5917 ]);
5918 let term2 = HirScalarExpr::variadic_or(vec![
5919 expr1_hir.call_is_null().not(),
5920 expr2_hir.call_is_null().not(),
5921 ]);
5922 term1.and(term2)
5923 }
5924 };
5925 if not {
5926 result = result.not();
5927 }
5928 Ok(result)
5929}
5930
5931fn plan_case<'a>(
5932 ecx: &ExprContext,
5933 operand: &'a Option<Box<Expr<Aug>>>,
5934 conditions: &'a [Expr<Aug>],
5935 results: &'a [Expr<Aug>],
5936 else_result: &'a Option<Box<Expr<Aug>>>,
5937) -> Result<HirScalarExpr, PlanError> {
5938 let mut cond_exprs = Vec::new();
5939 let mut result_exprs = Vec::new();
5940 for (c, r) in conditions.iter().zip_eq(results) {
5941 let c = match operand {
5942 Some(operand) => operand.clone().equals(c.clone()),
5943 None => c.clone(),
5944 };
5945 let cexpr = plan_expr(ecx, &c)?.type_as(ecx, &SqlScalarType::Bool)?;
5946 cond_exprs.push(cexpr);
5947 result_exprs.push(r);
5948 }
5949 result_exprs.push(match else_result {
5950 Some(else_result) => else_result,
5951 None => &Expr::Value(Value::Null),
5952 });
5953 let mut result_exprs = coerce_homogeneous_exprs(
5954 &ecx.with_name("CASE"),
5955 plan_exprs(ecx, &result_exprs)?,
5956 None,
5957 )?;
5958 let mut expr = result_exprs.pop().unwrap();
5959 assert_eq!(cond_exprs.len(), result_exprs.len());
5960 for (cexpr, rexpr) in cond_exprs
5961 .into_iter()
5962 .rev()
5963 .zip_eq(result_exprs.into_iter().rev())
5964 {
5965 expr = HirScalarExpr::if_then_else(cexpr, rexpr, expr);
5966 }
5967 Ok(expr)
5968}
5969
5970fn plan_literal<'a>(l: &'a Value) -> Result<CoercibleScalarExpr, PlanError> {
5971 let (datum, scalar_type) = match l {
5972 Value::Number(s) => {
5973 let d = strconv::parse_numeric(s.as_str())?;
5974 if !s.contains(&['E', '.'][..]) {
5975 if let Ok(n) = d.0.try_into() {
5977 (Datum::Int32(n), SqlScalarType::Int32)
5978 } else if let Ok(n) = d.0.try_into() {
5979 (Datum::Int64(n), SqlScalarType::Int64)
5980 } else {
5981 (
5982 Datum::Numeric(d),
5983 SqlScalarType::Numeric { max_scale: None },
5984 )
5985 }
5986 } else {
5987 (
5988 Datum::Numeric(d),
5989 SqlScalarType::Numeric { max_scale: None },
5990 )
5991 }
5992 }
5993 Value::HexString(_) => bail_unsupported!("hex string literals"),
5994 Value::Boolean(b) => match b {
5995 false => (Datum::False, SqlScalarType::Bool),
5996 true => (Datum::True, SqlScalarType::Bool),
5997 },
5998 Value::Interval(i) => {
5999 let i = literal::plan_interval(i)?;
6000 (Datum::Interval(i), SqlScalarType::Interval)
6001 }
6002 Value::String(s) => return Ok(CoercibleScalarExpr::LiteralString(s.clone())),
6003 Value::Null => return Ok(CoercibleScalarExpr::LiteralNull),
6004 };
6005 let expr = HirScalarExpr::literal(datum, scalar_type);
6006 Ok(expr.into())
6007}
6008
6009fn plan_window_function_non_aggr<'a>(
6012 ecx: &ExprContext,
6013 Function {
6014 name,
6015 args,
6016 filter,
6017 over,
6018 distinct,
6019 }: &'a Function<Aug>,
6020) -> Result<
6021 (
6022 bool,
6023 Vec<HirScalarExpr>,
6024 Vec<ColumnOrder>,
6025 mz_expr::WindowFrame,
6026 Vec<HirScalarExpr>,
6027 Vec<CoercibleScalarExpr>,
6028 ),
6029 PlanError,
6030> {
6031 let (ignore_nulls, order_by_exprs, col_orders, window_frame, partition) =
6032 plan_window_function_common(ecx, name, over.as_deref())?;
6033
6034 if *distinct {
6035 sql_bail!(
6036 "DISTINCT specified, but {} is not an aggregate function",
6037 name
6038 );
6039 }
6040
6041 if filter.is_some() {
6042 bail_unsupported!("FILTER in non-aggregate window functions");
6043 }
6044
6045 let scalar_args = match &args {
6046 FunctionArgs::Star => {
6047 sql_bail!("* argument is invalid with non-aggregate function {}", name)
6048 }
6049 FunctionArgs::Args { args, order_by } => {
6050 if !order_by.is_empty() {
6051 sql_bail!(
6052 "ORDER BY specified, but {} is not an aggregate function",
6053 name
6054 );
6055 }
6056 plan_exprs(ecx, args)?
6057 }
6058 };
6059
6060 Ok((
6061 ignore_nulls,
6062 order_by_exprs,
6063 col_orders,
6064 window_frame,
6065 partition,
6066 scalar_args,
6067 ))
6068}
6069
6070fn plan_window_function_common(
6072 ecx: &ExprContext,
6073 name: &<Aug as AstInfo>::ItemName,
6074 over: Option<&WindowSpec<Aug>>,
6075) -> Result<
6076 (
6077 bool,
6078 Vec<HirScalarExpr>,
6079 Vec<ColumnOrder>,
6080 mz_expr::WindowFrame,
6081 Vec<HirScalarExpr>,
6082 ),
6083 PlanError,
6084> {
6085 if !ecx.allow_windows {
6086 sql_bail!(
6087 "window functions are not allowed in {} (function {})",
6088 ecx.name,
6089 name
6090 );
6091 }
6092
6093 let window_spec = match over {
6094 Some(over) => over,
6095 None => sql_bail!("window function {} requires an OVER clause", name),
6096 };
6097 if window_spec.ignore_nulls && window_spec.respect_nulls {
6098 sql_bail!("Both IGNORE NULLS and RESPECT NULLS were given.");
6099 }
6100 let window_frame = match window_spec.window_frame.as_ref() {
6101 Some(frame) => plan_window_frame(frame)?,
6102 None => mz_expr::WindowFrame::default(),
6103 };
6104 let mut partition = Vec::new();
6105 for expr in &window_spec.partition_by {
6106 partition.push(plan_expr(ecx, expr)?.type_as_any(ecx)?);
6107 }
6108
6109 let (order_by_exprs, col_orders) = plan_function_order_by(ecx, &window_spec.order_by)?;
6110
6111 Ok((
6112 window_spec.ignore_nulls,
6113 order_by_exprs,
6114 col_orders,
6115 window_frame,
6116 partition,
6117 ))
6118}
6119
6120fn plan_window_frame(
6121 WindowFrame {
6122 units,
6123 start_bound,
6124 end_bound,
6125 }: &WindowFrame,
6126) -> Result<mz_expr::WindowFrame, PlanError> {
6127 use mz_expr::WindowFrameBound::*;
6128 let units = window_frame_unit_ast_to_expr(units)?;
6129 let start_bound = window_frame_bound_ast_to_expr(start_bound);
6130 let end_bound = end_bound
6131 .as_ref()
6132 .map(window_frame_bound_ast_to_expr)
6133 .unwrap_or(CurrentRow);
6134
6135 match (&start_bound, &end_bound) {
6137 (UnboundedFollowing, _) => {
6139 sql_bail!("frame start cannot be UNBOUNDED FOLLOWING")
6140 }
6141 (_, UnboundedPreceding) => {
6143 sql_bail!("frame end cannot be UNBOUNDED PRECEDING")
6144 }
6145 (CurrentRow, OffsetPreceding(_)) => {
6147 sql_bail!("frame starting from current row cannot have preceding rows")
6148 }
6149 (OffsetFollowing(_), OffsetPreceding(_) | CurrentRow) => {
6150 sql_bail!("frame starting from following row cannot have preceding rows")
6151 }
6152 (OffsetPreceding(o1), OffsetFollowing(o2)) => {
6155 if *o1 > 1000000 || *o2 > 1000000 {
6159 sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6160 }
6161 }
6162 (OffsetPreceding(o1), OffsetPreceding(o2)) => {
6163 if *o1 > 1000000 || *o2 > 1000000 {
6164 sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6165 }
6166 }
6167 (OffsetFollowing(o1), OffsetFollowing(o2)) => {
6168 if *o1 > 1000000 || *o2 > 1000000 {
6169 sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6170 }
6171 }
6172 (OffsetPreceding(o), CurrentRow) => {
6173 if *o > 1000000 {
6174 sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6175 }
6176 }
6177 (CurrentRow, OffsetFollowing(o)) => {
6178 if *o > 1000000 {
6179 sql_bail!("Window frame offsets greater than 1000000 are currently not supported")
6180 }
6181 }
6182 (_, _) => (),
6184 }
6185
6186 if units == mz_expr::WindowFrameUnits::Range
6189 && (start_bound != UnboundedPreceding || end_bound != CurrentRow)
6190 {
6191 bail_unsupported!("RANGE in non-default window frames")
6192 }
6193
6194 let frame = mz_expr::WindowFrame {
6195 units,
6196 start_bound,
6197 end_bound,
6198 };
6199 Ok(frame)
6200}
6201
6202fn window_frame_unit_ast_to_expr(
6203 unit: &WindowFrameUnits,
6204) -> Result<mz_expr::WindowFrameUnits, PlanError> {
6205 match unit {
6206 WindowFrameUnits::Rows => Ok(mz_expr::WindowFrameUnits::Rows),
6207 WindowFrameUnits::Range => Ok(mz_expr::WindowFrameUnits::Range),
6208 WindowFrameUnits::Groups => bail_unsupported!("GROUPS in window frames"),
6209 }
6210}
6211
6212fn window_frame_bound_ast_to_expr(bound: &WindowFrameBound) -> mz_expr::WindowFrameBound {
6213 match bound {
6214 WindowFrameBound::CurrentRow => mz_expr::WindowFrameBound::CurrentRow,
6215 WindowFrameBound::Preceding(None) => mz_expr::WindowFrameBound::UnboundedPreceding,
6216 WindowFrameBound::Preceding(Some(offset)) => {
6217 mz_expr::WindowFrameBound::OffsetPreceding(*offset)
6218 }
6219 WindowFrameBound::Following(None) => mz_expr::WindowFrameBound::UnboundedFollowing,
6220 WindowFrameBound::Following(Some(offset)) => {
6221 mz_expr::WindowFrameBound::OffsetFollowing(*offset)
6222 }
6223 }
6224}
6225
6226pub fn scalar_type_from_sql(
6227 scx: &StatementContext,
6228 data_type: &ResolvedDataType,
6229) -> Result<SqlScalarType, PlanError> {
6230 match data_type {
6231 ResolvedDataType::AnonymousList(elem_type) => {
6232 let elem_type = scalar_type_from_sql(scx, elem_type)?;
6233 if matches!(elem_type, SqlScalarType::Char { .. }) {
6234 bail_unsupported!("char list");
6235 }
6236 Ok(SqlScalarType::List {
6237 element_type: Box::new(elem_type),
6238 custom_id: None,
6239 })
6240 }
6241 ResolvedDataType::AnonymousMap {
6242 key_type,
6243 value_type,
6244 } => {
6245 match scalar_type_from_sql(scx, key_type)? {
6246 SqlScalarType::String => {}
6247 other => sql_bail!(
6248 "map key type must be {}, got {}",
6249 scx.humanize_sql_scalar_type(&SqlScalarType::String, false),
6250 scx.humanize_sql_scalar_type(&other, false)
6251 ),
6252 }
6253 Ok(SqlScalarType::Map {
6254 value_type: Box::new(scalar_type_from_sql(scx, value_type)?),
6255 custom_id: None,
6256 })
6257 }
6258 ResolvedDataType::Named { id, modifiers, .. } => {
6259 scalar_type_from_catalog(scx.catalog, *id, modifiers)
6260 }
6261 ResolvedDataType::Error => bail_internal!("should have been caught in name resolution"),
6262 }
6263}
6264
6265const MAX_TYPE_NESTING_DEPTH: usize = 128;
6269
6270const MAX_TYPE_RESOLUTION_NODES: usize = 100_000;
6276
6277pub fn scalar_type_from_catalog(
6278 catalog: &dyn SessionCatalog,
6279 id: CatalogItemId,
6280 modifiers: &[i64],
6281) -> Result<SqlScalarType, PlanError> {
6282 let (depth_limit, mut budget) = type_resolution_limits(catalog);
6283 scalar_type_from_catalog_inner(catalog, id, modifiers, 0, depth_limit, &mut budget)
6284}
6285
6286fn type_resolution_limits(catalog: &dyn SessionCatalog) -> (usize, usize) {
6300 if catalog
6301 .system_vars()
6302 .unsafe_enable_unbounded_custom_type_resolution()
6303 {
6304 (usize::MAX, usize::MAX)
6305 } else {
6306 (MAX_TYPE_NESTING_DEPTH, MAX_TYPE_RESOLUTION_NODES)
6307 }
6308}
6309
6310pub struct TypeResolutionBudget {
6323 remaining: usize,
6326 depth_limit: usize,
6329}
6330
6331impl TypeResolutionBudget {
6332 pub fn for_root(catalog: &dyn SessionCatalog) -> TypeResolutionBudget {
6338 let (depth_limit, budget) = type_resolution_limits(catalog);
6339 TypeResolutionBudget {
6340 remaining: budget.saturating_sub(1),
6342 depth_limit,
6343 }
6344 }
6345
6346 pub fn resolve_child(
6350 &mut self,
6351 catalog: &dyn SessionCatalog,
6352 id: CatalogItemId,
6353 modifiers: &[i64],
6354 ) -> Result<SqlScalarType, PlanError> {
6355 scalar_type_from_catalog_inner(
6356 catalog,
6357 id,
6358 modifiers,
6359 1,
6360 self.depth_limit,
6361 &mut self.remaining,
6362 )
6363 }
6364}
6365
6366fn scalar_type_from_catalog_inner(
6367 catalog: &dyn SessionCatalog,
6368 id: CatalogItemId,
6369 modifiers: &[i64],
6370 depth: usize,
6371 depth_limit: usize,
6372 budget: &mut usize,
6373) -> Result<SqlScalarType, PlanError> {
6374 if depth > depth_limit {
6375 sql_bail!("custom type nesting depth exceeds limit of {}", depth_limit);
6376 }
6377 *budget = match budget.checked_sub(1) {
6378 Some(remaining) => remaining,
6379 None => sql_bail!("custom type is too complex to resolve"),
6380 };
6381 let entry = catalog.get_item(&id);
6382 let type_details = match entry.type_details() {
6383 Some(type_details) => type_details,
6384 None => {
6385 sql_bail!(
6388 "internal error: {} does not refer to a type",
6389 catalog.resolve_full_name(entry.name()).to_string().quoted()
6390 );
6391 }
6392 };
6393 match &type_details.typ {
6394 CatalogType::Numeric => {
6395 let mut modifiers = modifiers.iter().fuse();
6396 let precision = match modifiers.next() {
6397 Some(p) if *p < 1 || *p > i64::from(NUMERIC_DATUM_MAX_PRECISION) => {
6398 sql_bail!(
6399 "precision for type numeric must be between 1 and {}",
6400 NUMERIC_DATUM_MAX_PRECISION,
6401 );
6402 }
6403 Some(p) => Some(*p),
6404 None => None,
6405 };
6406 let scale = match modifiers.next() {
6407 Some(scale) => {
6408 if let Some(precision) = precision {
6409 if *scale > precision {
6410 sql_bail!(
6411 "scale for type numeric must be between 0 and precision {}",
6412 precision
6413 );
6414 }
6415 }
6416 Some(NumericMaxScale::try_from(*scale)?)
6417 }
6418 None => None,
6419 };
6420 if modifiers.next().is_some() {
6421 sql_bail!("type numeric supports at most two type modifiers");
6422 }
6423 Ok(SqlScalarType::Numeric { max_scale: scale })
6424 }
6425 CatalogType::Char => {
6426 let mut modifiers = modifiers.iter().fuse();
6427 let length = match modifiers.next() {
6428 Some(l) => Some(CharLength::try_from(*l)?),
6429 None => Some(CharLength::ONE),
6430 };
6431 if modifiers.next().is_some() {
6432 sql_bail!("type character supports at most one type modifier");
6433 }
6434 Ok(SqlScalarType::Char { length })
6435 }
6436 CatalogType::VarChar => {
6437 let mut modifiers = modifiers.iter().fuse();
6438 let length = match modifiers.next() {
6439 Some(l) => Some(VarCharMaxLength::try_from(*l)?),
6440 None => None,
6441 };
6442 if modifiers.next().is_some() {
6443 sql_bail!("type character varying supports at most one type modifier");
6444 }
6445 Ok(SqlScalarType::VarChar { max_length: length })
6446 }
6447 CatalogType::Timestamp => {
6448 let mut modifiers = modifiers.iter().fuse();
6449 let precision = match modifiers.next() {
6450 Some(p) => Some(TimestampPrecision::try_from(*p)?),
6451 None => None,
6452 };
6453 if modifiers.next().is_some() {
6454 sql_bail!("type timestamp supports at most one type modifier");
6455 }
6456 Ok(SqlScalarType::Timestamp { precision })
6457 }
6458 CatalogType::TimestampTz => {
6459 let mut modifiers = modifiers.iter().fuse();
6460 let precision = match modifiers.next() {
6461 Some(p) => Some(TimestampPrecision::try_from(*p)?),
6462 None => None,
6463 };
6464 if modifiers.next().is_some() {
6465 sql_bail!("type timestamp with time zone supports at most one type modifier");
6466 }
6467 Ok(SqlScalarType::TimestampTz { precision })
6468 }
6469 t => {
6470 if !modifiers.is_empty() {
6471 sql_bail!(
6472 "{} does not support type modifiers",
6473 catalog.resolve_full_name(entry.name()).to_string()
6474 );
6475 }
6476 match t {
6477 CatalogType::Array {
6478 element_reference: element_id,
6479 } => Ok(SqlScalarType::Array(Box::new(
6480 scalar_type_from_catalog_inner(
6481 catalog,
6482 *element_id,
6483 modifiers,
6484 depth + 1,
6485 depth_limit,
6486 budget,
6487 )?,
6488 ))),
6489 CatalogType::List {
6490 element_reference: element_id,
6491 element_modifiers,
6492 } => Ok(SqlScalarType::List {
6493 element_type: Box::new(scalar_type_from_catalog_inner(
6494 catalog,
6495 *element_id,
6496 element_modifiers,
6497 depth + 1,
6498 depth_limit,
6499 budget,
6500 )?),
6501 custom_id: Some(id),
6502 }),
6503 CatalogType::Map {
6504 key_reference: _,
6505 key_modifiers: _,
6506 value_reference: value_id,
6507 value_modifiers,
6508 } => Ok(SqlScalarType::Map {
6509 value_type: Box::new(scalar_type_from_catalog_inner(
6510 catalog,
6511 *value_id,
6512 value_modifiers,
6513 depth + 1,
6514 depth_limit,
6515 budget,
6516 )?),
6517 custom_id: Some(id),
6518 }),
6519 CatalogType::Range {
6520 element_reference: element_id,
6521 } => Ok(SqlScalarType::Range {
6522 element_type: Box::new(scalar_type_from_catalog_inner(
6523 catalog,
6524 *element_id,
6525 &[],
6526 depth + 1,
6527 depth_limit,
6528 budget,
6529 )?),
6530 }),
6531 CatalogType::Record { fields } => {
6532 let scalars: Box<[(ColumnName, SqlColumnType)]> = fields
6533 .iter()
6534 .map(|f| {
6535 let scalar_type = scalar_type_from_catalog_inner(
6536 catalog,
6537 f.type_reference,
6538 &f.type_modifiers,
6539 depth + 1,
6540 depth_limit,
6541 budget,
6542 )?;
6543 Ok((
6544 f.name.clone(),
6545 SqlColumnType {
6546 scalar_type,
6547 nullable: true,
6548 },
6549 ))
6550 })
6551 .collect::<Result<Box<_>, PlanError>>()?;
6552 Ok(SqlScalarType::Record {
6553 fields: scalars,
6554 custom_id: Some(id),
6555 })
6556 }
6557 CatalogType::AclItem => Ok(SqlScalarType::AclItem),
6558 CatalogType::Bool => Ok(SqlScalarType::Bool),
6559 CatalogType::Bytes => Ok(SqlScalarType::Bytes),
6560 CatalogType::Date => Ok(SqlScalarType::Date),
6561 CatalogType::Float32 => Ok(SqlScalarType::Float32),
6562 CatalogType::Float64 => Ok(SqlScalarType::Float64),
6563 CatalogType::Int16 => Ok(SqlScalarType::Int16),
6564 CatalogType::Int32 => Ok(SqlScalarType::Int32),
6565 CatalogType::Int64 => Ok(SqlScalarType::Int64),
6566 CatalogType::UInt16 => Ok(SqlScalarType::UInt16),
6567 CatalogType::UInt32 => Ok(SqlScalarType::UInt32),
6568 CatalogType::UInt64 => Ok(SqlScalarType::UInt64),
6569 CatalogType::MzTimestamp => Ok(SqlScalarType::MzTimestamp),
6570 CatalogType::Interval => Ok(SqlScalarType::Interval),
6571 CatalogType::Jsonb => Ok(SqlScalarType::Jsonb),
6572 CatalogType::Oid => Ok(SqlScalarType::Oid),
6573 CatalogType::PgLegacyChar => Ok(SqlScalarType::PgLegacyChar),
6574 CatalogType::PgLegacyName => Ok(SqlScalarType::PgLegacyName),
6575 CatalogType::Pseudo => {
6576 sql_bail!(
6577 "cannot reference pseudo type {}",
6578 catalog.resolve_full_name(entry.name()).to_string()
6579 )
6580 }
6581 CatalogType::RegClass => Ok(SqlScalarType::RegClass),
6582 CatalogType::RegProc => Ok(SqlScalarType::RegProc),
6583 CatalogType::RegType => Ok(SqlScalarType::RegType),
6584 CatalogType::String => Ok(SqlScalarType::String),
6585 CatalogType::Time => Ok(SqlScalarType::Time),
6586 CatalogType::Uuid => Ok(SqlScalarType::Uuid),
6587 CatalogType::Int2Vector => Ok(SqlScalarType::Int2Vector),
6588 CatalogType::MzAclItem => Ok(SqlScalarType::MzAclItem),
6589 CatalogType::Numeric => unreachable!("handled above"),
6590 CatalogType::Char => unreachable!("handled above"),
6591 CatalogType::VarChar => unreachable!("handled above"),
6592 CatalogType::Timestamp => unreachable!("handled above"),
6593 CatalogType::TimestampTz => unreachable!("handled above"),
6594 }
6595 }
6596 }
6597}
6598
6599struct AggregateTableFuncVisitor<'a> {
6602 scx: &'a StatementContext<'a>,
6603 aggs: Vec<Function<Aug>>,
6604 within_aggregate: bool,
6605 tables: BTreeMap<Function<Aug>, String>,
6606 table_disallowed_context: Vec<&'static str>,
6607 in_select_item: bool,
6608 id_gen: IdGen,
6609 err: Option<PlanError>,
6610}
6611
6612impl<'a> AggregateTableFuncVisitor<'a> {
6613 fn new(scx: &'a StatementContext<'a>) -> AggregateTableFuncVisitor<'a> {
6614 AggregateTableFuncVisitor {
6615 scx,
6616 aggs: Vec::new(),
6617 within_aggregate: false,
6618 tables: BTreeMap::new(),
6619 table_disallowed_context: Vec::new(),
6620 in_select_item: false,
6621 id_gen: Default::default(),
6622 err: None,
6623 }
6624 }
6625
6626 fn into_result(
6627 self,
6628 ) -> Result<(Vec<Function<Aug>>, BTreeMap<Function<Aug>, String>), PlanError> {
6629 match self.err {
6630 Some(err) => Err(err),
6631 None => {
6632 let mut seen = BTreeSet::new();
6635 let aggs = self
6636 .aggs
6637 .into_iter()
6638 .filter(move |agg| seen.insert(agg.clone()))
6639 .collect();
6640 Ok((aggs, self.tables))
6641 }
6642 }
6643 }
6644}
6645
6646impl<'a> VisitMut<'_, Aug> for AggregateTableFuncVisitor<'a> {
6647 fn visit_function_mut(&mut self, func: &mut Function<Aug>) {
6648 let item = match self.scx.get_item_by_resolved_name(&func.name) {
6649 Ok(i) => i,
6650 Err(_) => return,
6652 };
6653
6654 match item.func() {
6655 Ok(Func::Aggregate { .. }) if func.over.is_none() => {
6658 if self.within_aggregate {
6659 self.err = Some(sql_err!("nested aggregate functions are not allowed",));
6660 return;
6661 }
6662 self.aggs.push(func.clone());
6663 let Function {
6664 name: _,
6665 args,
6666 filter,
6667 over: _,
6668 distinct: _,
6669 } = func;
6670 if let Some(filter) = filter {
6671 self.visit_expr_mut(filter);
6672 }
6673 let old_within_aggregate = self.within_aggregate;
6674 self.within_aggregate = true;
6675 self.table_disallowed_context
6676 .push("aggregate function calls");
6677
6678 self.visit_function_args_mut(args);
6679
6680 self.within_aggregate = old_within_aggregate;
6681 self.table_disallowed_context.pop();
6682 }
6683 Ok(Func::Table { .. }) => {
6684 self.table_disallowed_context.push("other table functions");
6685 visit_mut::visit_function_mut(self, func);
6686 self.table_disallowed_context.pop();
6687 }
6688 _ => visit_mut::visit_function_mut(self, func),
6689 }
6690 }
6691
6692 fn visit_query_mut(&mut self, _query: &mut Query<Aug>) {
6693 }
6695
6696 fn visit_expr_mut(&mut self, expr: &mut Expr<Aug>) {
6697 let (disallowed_context, func) = match expr {
6698 Expr::Case { .. } => (Some("CASE"), None),
6699 Expr::HomogenizingFunction {
6700 function: HomogenizingFunction::Coalesce,
6701 ..
6702 } => (Some("COALESCE"), None),
6703 Expr::Function(func) if self.in_select_item => {
6704 let mut table_func = None;
6707 if let Ok(item) = self.scx.get_item_by_resolved_name(&func.name) {
6708 if let Ok(Func::Table { .. }) = item.func() {
6709 if let Some(context) = self.table_disallowed_context.last() {
6710 self.err = Some(sql_err!(
6711 "table functions are not allowed in {} (function {})",
6712 context,
6713 func.name
6714 ));
6715 return;
6716 }
6717 table_func = Some(func.clone());
6718 }
6719 }
6720 (None, table_func)
6723 }
6724 _ => (None, None),
6725 };
6726 if let Some(func) = func {
6727 visit_mut::visit_expr_mut(self, expr);
6729 if let Function {
6731 name: _,
6732 args: _,
6733 filter: None,
6734 over: None,
6735 distinct: false,
6736 } = &func
6737 {
6738 let unique_id = self.id_gen.allocate_id();
6740 let id = self
6741 .tables
6742 .entry(func)
6743 .or_insert_with(|| format!("table_func_{unique_id}"));
6744 *expr = Expr::Identifier(vec![Ident::new_unchecked(id.clone())]);
6747 }
6748 }
6749 if let Some(context) = disallowed_context {
6750 self.table_disallowed_context.push(context);
6751 }
6752
6753 visit_mut::visit_expr_mut(self, expr);
6754
6755 if disallowed_context.is_some() {
6756 self.table_disallowed_context.pop();
6757 }
6758 }
6759
6760 fn visit_select_item_mut(&mut self, si: &mut SelectItem<Aug>) {
6761 let old = self.in_select_item;
6762 self.in_select_item = true;
6763 visit_mut::visit_select_item_mut(self, si);
6764 self.in_select_item = old;
6765 }
6766}
6767
6768#[derive(Default)]
6769struct WindowFuncCollector {
6770 window_funcs: Vec<Expr<Aug>>,
6771}
6772
6773impl WindowFuncCollector {
6774 fn into_result(self) -> Vec<Expr<Aug>> {
6775 let mut seen = BTreeSet::new();
6777 let window_funcs_dedupped = self
6778 .window_funcs
6779 .into_iter()
6780 .filter(move |expr| seen.insert(expr.clone()))
6781 .rev()
6784 .collect();
6785 window_funcs_dedupped
6786 }
6787}
6788
6789impl Visit<'_, Aug> for WindowFuncCollector {
6790 fn visit_expr(&mut self, expr: &Expr<Aug>) {
6791 match expr {
6792 Expr::Function(func) => {
6793 if func.over.is_some() {
6794 self.window_funcs.push(expr.clone());
6795 }
6796 }
6797 _ => (),
6798 }
6799 visit::visit_expr(self, expr);
6800 }
6801
6802 fn visit_query(&mut self, _query: &Query<Aug>) {
6803 }
6805}
6806
6807#[derive(Debug, Eq, PartialEq, Copy, Clone)]
6809pub enum QueryLifetime {
6810 OneShot,
6812 Index,
6814 MaterializedView,
6816 Subscribe,
6818 View,
6820 Source,
6822}
6823
6824impl QueryLifetime {
6825 pub fn is_one_shot(&self) -> bool {
6829 let result = match self {
6830 QueryLifetime::OneShot => true,
6831 QueryLifetime::Index => false,
6832 QueryLifetime::MaterializedView => false,
6833 QueryLifetime::Subscribe => false,
6834 QueryLifetime::View => false,
6835 QueryLifetime::Source => false,
6836 };
6837 assert_eq!(!result, self.is_maintained());
6838 result
6839 }
6840
6841 pub fn is_maintained(&self) -> bool {
6844 match self {
6845 QueryLifetime::OneShot => false,
6846 QueryLifetime::Index => true,
6847 QueryLifetime::MaterializedView => true,
6848 QueryLifetime::Subscribe => true,
6849 QueryLifetime::View => true,
6850 QueryLifetime::Source => true,
6851 }
6852 }
6853
6854 pub fn allow_show(&self) -> bool {
6856 match self {
6857 QueryLifetime::OneShot => true,
6858 QueryLifetime::Index => false,
6859 QueryLifetime::MaterializedView => false,
6860 QueryLifetime::Subscribe => true, QueryLifetime::View => false,
6862 QueryLifetime::Source => false,
6863 }
6864 }
6865}
6866
6867#[derive(Debug, Clone)]
6869pub struct CteDesc {
6870 pub name: String,
6871 pub desc: RelationDesc,
6872}
6873
6874#[derive(Debug, Clone)]
6876pub struct QueryContext<'a> {
6877 pub scx: &'a StatementContext<'a>,
6879 pub lifetime: QueryLifetime,
6881 pub outer_scopes: Vec<Scope>,
6883 pub outer_relation_types: Vec<SqlRelationType>,
6885 pub ctes: BTreeMap<LocalId, CteDesc>,
6887 pub name_manager: Rc<RefCell<NameManager>>,
6889 pub recursion_guard: RecursionGuard,
6890}
6891
6892impl CheckedRecursion for QueryContext<'_> {
6893 fn recursion_guard(&self) -> &RecursionGuard {
6894 &self.recursion_guard
6895 }
6896}
6897
6898impl<'a> QueryContext<'a> {
6899 pub fn root(scx: &'a StatementContext, lifetime: QueryLifetime) -> QueryContext<'a> {
6900 QueryContext {
6901 scx,
6902 lifetime,
6903 outer_scopes: vec![],
6904 outer_relation_types: vec![],
6905 ctes: BTreeMap::new(),
6906 name_manager: Rc::new(RefCell::new(NameManager::new())),
6907 recursion_guard: RecursionGuard::with_limit(1024), }
6909 }
6910
6911 fn relation_type(&self, expr: &HirRelationExpr) -> SqlRelationType {
6912 expr.typ(&self.outer_relation_types, &self.scx.param_types.borrow())
6913 }
6914
6915 fn derived_context(&self, scope: Scope, relation_type: SqlRelationType) -> QueryContext<'a> {
6918 let ctes = self.ctes.clone();
6919 let outer_scopes = iter::once(scope).chain(self.outer_scopes.clone()).collect();
6920 let outer_relation_types = iter::once(relation_type)
6921 .chain(self.outer_relation_types.clone())
6922 .collect();
6923 let name_manager = Rc::clone(&self.name_manager);
6925
6926 QueryContext {
6927 scx: self.scx,
6928 lifetime: self.lifetime,
6929 outer_scopes,
6930 outer_relation_types,
6931 ctes,
6932 name_manager,
6933 recursion_guard: self.recursion_guard.clone(),
6934 }
6935 }
6936
6937 fn empty_derived_context(&self) -> QueryContext<'a> {
6939 let scope = Scope::empty();
6940 let ty = SqlRelationType::empty();
6941 self.derived_context(scope, ty)
6942 }
6943
6944 pub fn resolve_table_name(
6947 &self,
6948 object: ResolvedItemName,
6949 ) -> Result<(HirRelationExpr, Scope), PlanError> {
6950 match object {
6951 ResolvedItemName::Item {
6952 id,
6953 full_name,
6954 version,
6955 ..
6956 } => {
6957 let item = self.scx.get_item(&id).at_version(version);
6958 let desc = match item.relation_desc() {
6959 Some(desc) => desc.clone(),
6960 None => {
6961 return Err(PlanError::InvalidDependency {
6962 name: full_name.to_string(),
6963 item_type: item.item_type().to_string(),
6964 });
6965 }
6966 };
6967 let expr = HirRelationExpr::Get {
6968 id: Id::Global(item.global_id()),
6969 typ: desc.typ().clone(),
6970 };
6971
6972 let name = full_name.into();
6973 let scope = Scope::from_source(Some(name), desc.iter_names().cloned());
6974
6975 Ok((expr, scope))
6976 }
6977 ResolvedItemName::Cte { id, name } => {
6978 let name = name.into();
6979 let cte = self.ctes.get(&id).unwrap();
6980 let expr = HirRelationExpr::Get {
6981 id: Id::Local(id),
6982 typ: cte.desc.typ().clone(),
6983 };
6984
6985 let scope = Scope::from_source(Some(name), cte.desc.iter_names());
6986
6987 Ok((expr, scope))
6988 }
6989 ResolvedItemName::Error => bail_internal!("should have been caught in name resolution"),
6990 }
6991 }
6992
6993 pub fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
6996 self.scx.humanize_sql_scalar_type(typ, postgres_compat)
6997 }
6998}
6999
7000#[derive(Debug, Clone)]
7002pub struct ExprContext<'a> {
7003 pub qcx: &'a QueryContext<'a>,
7004 pub name: &'a str,
7006 pub scope: &'a Scope,
7009 pub relation_type: &'a SqlRelationType,
7012 pub allow_aggregates: bool,
7014 pub allow_subqueries: bool,
7016 pub allow_parameters: bool,
7018 pub allow_windows: bool,
7020}
7021
7022impl CheckedRecursion for ExprContext<'_> {
7023 fn recursion_guard(&self) -> &RecursionGuard {
7024 &self.qcx.recursion_guard
7025 }
7026}
7027
7028impl<'a> ExprContext<'a> {
7029 pub fn catalog(&self) -> &dyn SessionCatalog {
7030 self.qcx.scx.catalog
7031 }
7032
7033 pub fn with_name(&self, name: &'a str) -> ExprContext<'a> {
7034 let mut ecx = self.clone();
7035 ecx.name = name;
7036 ecx
7037 }
7038
7039 pub fn column_type<E>(&self, expr: &E) -> E::Type
7040 where
7041 E: AbstractExpr,
7042 {
7043 expr.typ(
7044 &self.qcx.outer_relation_types,
7045 self.relation_type,
7046 &self.qcx.scx.param_types.borrow(),
7047 )
7048 }
7049
7050 pub fn scalar_type<E>(&self, expr: &E) -> <E::Type as AbstractColumnType>::AbstractScalarType
7051 where
7052 E: AbstractExpr,
7053 {
7054 self.column_type(expr).scalar_type()
7055 }
7056
7057 fn derived_query_context(&self) -> QueryContext<'_> {
7058 let mut scope = self.scope.clone();
7059 scope.lateral_barrier = true;
7060 self.qcx.derived_context(scope, self.relation_type.clone())
7061 }
7062
7063 pub fn require_feature_flag(&self, flag: &'static FeatureFlag) -> Result<(), PlanError> {
7064 self.qcx.scx.require_feature_flag(flag)
7065 }
7066
7067 pub fn param_types(&self) -> &RefCell<BTreeMap<usize, SqlScalarType>> {
7068 &self.qcx.scx.param_types
7069 }
7070
7071 pub fn humanize_sql_scalar_type(&self, typ: &SqlScalarType, postgres_compat: bool) -> String {
7074 self.qcx.scx.humanize_sql_scalar_type(typ, postgres_compat)
7075 }
7076
7077 pub fn intern(&self, item: &ScopeItem) -> Arc<str> {
7078 self.qcx.name_manager.borrow_mut().intern_scope_item(item)
7079 }
7080}
7081
7082#[derive(Debug, Clone)]
7088pub struct NameManager(BTreeSet<Arc<str>>);
7089
7090impl NameManager {
7091 pub fn new() -> Self {
7093 Self(BTreeSet::new())
7094 }
7095
7096 fn intern<S: AsRef<str>>(&mut self, s: S) -> Arc<str> {
7099 let s = s.as_ref();
7100 if let Some(interned) = self.0.get(s) {
7101 Arc::clone(interned)
7102 } else {
7103 let interned: Arc<str> = Arc::from(s);
7104 self.0.insert(Arc::clone(&interned));
7105 interned
7106 }
7107 }
7108
7109 pub fn intern_scope_item(&mut self, item: &ScopeItem) -> Arc<str> {
7112 self.intern(item.column_name.as_str())
7128 }
7129}
7130
7131#[cfg(test)]
7132mod test {
7133 use super::*;
7134
7135 #[mz_ore::test]
7140 pub fn test_name_manager_string_interning() {
7141 let mut nm = NameManager::new();
7142
7143 let orig_hi = "hi";
7144 let hi = nm.intern(orig_hi);
7145 let hello = nm.intern("hello");
7146
7147 assert_ne!(hi.as_ptr(), hello.as_ptr());
7148
7149 let hi2 = nm.intern("hi");
7151 assert_eq!(hi.as_ptr(), hi2.as_ptr());
7152
7153 let s = format!(
7155 "{}{}",
7156 hi.chars().nth(0).unwrap(),
7157 hi2.chars().nth(1).unwrap()
7158 );
7159 assert_ne!(orig_hi.as_ptr(), s.as_ptr());
7161
7162 let hi3 = nm.intern(s);
7163 assert_eq!(hi.as_ptr(), hi3.as_ptr());
7164 }
7165}