Skip to main content

uqa_sql/semantics/
sets.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Set-returning expression binding, validation, and dependency rewriting.
8
9use crate::ast::FunctionBinding;
10use crate::plan::{AggregateClassifier, ProjectionTarget, QueryBlockPlan};
11use crate::routines::RoutineResolution;
12use crate::{RowSchema, SQLError, SQLParam, ScalarExpr};
13
14/// Routine metadata and aggregate classification required by set-returning expression analysis.
15pub trait SetFunctionCatalog: RoutineResolution + AggregateClassifier {}
16impl<T: RoutineResolution + AggregateClassifier + ?Sized> SetFunctionCatalog for T {}
17
18pub type PhysicalProjection = (ProjectionTarget, ScalarExpr);
19
20pub mod placement;
21pub mod placement_scope;
22pub mod rewrite;
23pub mod validation;
24use rewrite::rewrite_set_calls;
25
26#[derive(Clone)]
27pub struct SetFunctionCall {
28    pub placeholder: crate::ast::InternalColumnRef,
29    pub name: String,
30    pub binding: Option<FunctionBinding>,
31    pub args: Vec<ScalarExpr>,
32    pub level: usize,
33}
34
35pub struct SetProjectionPlan {
36    pub projections: Vec<PhysicalProjection>,
37    pub calls: Vec<SetFunctionCall>,
38}
39
40pub struct AggregateOutputProjectionPlan {
41    pub statement: QueryBlockPlan,
42    pub projections: Vec<PhysicalProjection>,
43}
44
45pub struct GroupSetProjectionPlan {
46    pub statement: QueryBlockPlan,
47    pub projections: Vec<PhysicalProjection>,
48}
49
50impl SetProjectionPlan {
51    pub fn new(
52        engine: &dyn SetFunctionCatalog,
53        resolver: &dyn crate::FunctionTypeResolver,
54        projections: Vec<PhysicalProjection>,
55        schema: &RowSchema,
56        params: &[SQLParam],
57    ) -> Result<Self, SQLError> {
58        let mut calls = Vec::new();
59        let call_relation = crate::ast::InternalRelationId::allocate();
60        let projections = projections
61            .into_iter()
62            .map(|(target, expression)| {
63                Ok((
64                    target,
65                    rewrite_set_calls(
66                        engine,
67                        resolver,
68                        expression,
69                        &mut calls,
70                        call_relation,
71                        schema,
72                        params,
73                    )?,
74                ))
75            })
76            .collect::<Result<Vec<_>, SQLError>>()?;
77        debug_assert!(!calls.is_empty());
78        Ok(Self { projections, calls })
79    }
80}
81
82pub mod static_setness;
83
84#[cfg(test)]
85mod tests;