Skip to main content

uqa_sql/binding/
projection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Projection row-type binding and reference validation.
8
9use crate::ast::ColumnType;
10use crate::plan::{ProjectionPlan, QueryBlockPlan, QueryPlan};
11use crate::RowSchema;
12use crate::{SQLError, SQLParam};
13
14use super::production::ControlledBindingContext;
15use super::{BindingContext, QueryFunctionTypeResolver, ScalarExpr, SchemaScope};
16use crate::routines::RoutineResolution;
17use uqa_core::memory::ProductionControl;
18
19#[cfg(test)]
20mod tests;
21
22mod output;
23pub(super) use output::ProjectionOutput;
24
25pub(super) struct ProjectionMetadata {
26    pub ty: Option<uqa_core::memory::Produced<ColumnType>>,
27    pub collation: Option<u32>,
28    pub record: Option<crate::schema::RecordMetadata>,
29}
30
31/// The declared scalar-expression scope and the local relation expanded by a bare wildcard.
32#[derive(Clone, Copy)]
33pub struct ProjectionSchemas<'a> {
34    pub expressions: &'a RowSchema,
35    pub star: &'a RowSchema,
36}
37
38/// Bind a projection against an already-declared input schema. `star_schema` identifies the relation expanded by bare `*`; `expression_schema` may also contain joined sources and hidden lookup aliases used by scalar expressions.
39pub fn bind_projection_output_schema(
40    routines: &dyn RoutineResolution,
41    projections: &[ProjectionPlan],
42    expression_schema: &RowSchema,
43    star_schema: &RowSchema,
44    subqueries: &[QueryPlan],
45    params: &[SQLParam],
46    ctes: &BindingContext,
47) -> Result<RowSchema, SQLError> {
48    let control = ProductionControl::uncontrolled();
49    bind_projection_output_schema_with_control(
50        routines,
51        projections,
52        ProjectionSchemas {
53            expressions: expression_schema,
54            star: star_schema,
55        },
56        subqueries,
57        params,
58        ctes.copy_with_control(&control)?,
59        &control,
60    )
61}
62
63/// Bind projection metadata under the invoking request's allowance.
64pub fn bind_projection_output_schema_with_control(
65    routines: &dyn RoutineResolution,
66    projections: &[ProjectionPlan],
67    schemas: ProjectionSchemas<'_>,
68    subqueries: &[QueryPlan],
69    params: &[SQLParam],
70    ctes: ControlledBindingContext<'_>,
71    control: &ProductionControl<'_>,
72) -> Result<RowSchema, SQLError> {
73    projection_output_schema(
74        SchemaScope::from_context_with_control(ctes, control)?,
75        routines,
76        projections,
77        schemas.expressions,
78        schemas.star,
79        subqueries,
80        params,
81    )
82}
83
84/// Derive and validate a projection's exact output row type without executing it.
85pub fn analyze_projection_output_schema(
86    routines: &dyn RoutineResolution,
87    projections: &[ProjectionPlan],
88    expression_schema: &RowSchema,
89    star_schema: &RowSchema,
90    subqueries: &[QueryPlan],
91    params: &[SQLParam],
92    ctes: &BindingContext,
93) -> Result<RowSchema, SQLError> {
94    let control = ProductionControl::uncontrolled();
95    analyze_projection_output_schema_with_control(
96        routines,
97        projections,
98        ProjectionSchemas {
99            expressions: expression_schema,
100            star: star_schema,
101        },
102        subqueries,
103        params,
104        ctes.copy_with_control(&control)?,
105        &control,
106    )
107}
108
109/// Analyze projection metadata with admission before allocating expressions and row descriptors.
110pub fn analyze_projection_output_schema_with_control(
111    routines: &dyn RoutineResolution,
112    projections: &[ProjectionPlan],
113    schemas: ProjectionSchemas<'_>,
114    subqueries: &[QueryPlan],
115    params: &[SQLParam],
116    ctes: ControlledBindingContext<'_>,
117    control: &ProductionControl<'_>,
118) -> Result<RowSchema, SQLError> {
119    projection_output_schema(
120        SchemaScope::for_analysis_with_control(ctes, control)?,
121        routines,
122        projections,
123        schemas.expressions,
124        schemas.star,
125        subqueries,
126        params,
127    )
128}
129
130fn projection_output_schema(
131    mut scope: SchemaScope,
132    routines: &dyn RoutineResolution,
133    projections: &[ProjectionPlan],
134    expression_schema: &RowSchema,
135    star_schema: &RowSchema,
136    subqueries: &[QueryPlan],
137    params: &[SQLParam],
138) -> Result<RowSchema, SQLError> {
139    let owner = scope.control().capture();
140    let control = owner.control();
141    let labels = crate::semantics::projection_labels_with_control(projections, &[], &control)?;
142    let mut output = ProjectionOutput::new(control);
143    for (label, projection) in labels.iter().zip(projections) {
144        let expansion_schema = match projection.expr {
145            ScalarExpr::QualifiedStar(_) => expression_schema,
146            _ => star_schema,
147        };
148        if output.star(&projection.expr, expansion_schema)? {
149            continue;
150        }
151        let metadata = scope.bind_projection_metadata(
152            routines,
153            &projection.expr,
154            expression_schema,
155            subqueries,
156            params,
157        )?;
158        output.push(label, metadata)?;
159    }
160    for projection in projections {
161        scope.collations.validate_expression(&projection.expr)?;
162    }
163    output.finish()
164}
165
166/// Validate every scalar expression in a query block while the physical input still carries declared SQL types. This must precede polymorphic rewrites such as `pg_typeof`, because an invalid common type is an error, not an `unknown` result.
167pub fn validate_query_block_expression_types(
168    routines: &dyn RoutineResolution,
169    statement: &QueryBlockPlan,
170    schema: &RowSchema,
171    params: &[SQLParam],
172    ctes: &BindingContext,
173) -> Result<(), SQLError> {
174    let control = ProductionControl::uncontrolled();
175    validate_query_block_expression_types_with_control(
176        routines,
177        statement,
178        schema,
179        params,
180        ctes.copy_with_control(&control)?,
181        &control,
182    )
183}
184
185/// Preserve expression and comparison-check order while every inferred type retains its allocation owner.
186pub fn validate_query_block_expression_types_with_control(
187    routines: &dyn RoutineResolution,
188    statement: &QueryBlockPlan,
189    schema: &RowSchema,
190    params: &[SQLParam],
191    ctes: ControlledBindingContext<'_>,
192    control: &ProductionControl<'_>,
193) -> Result<(), SQLError> {
194    control.check()?;
195    let mut scalar_subquery_schemas = crate::production::Buffer::new(control);
196    for plan in &statement.subqueries {
197        scalar_subquery_schemas.push(
198            Some(super::production::bind_query_plan_schema_with_control(
199                routines,
200                plan,
201                params,
202                ctes.copy_with_control(control)?,
203                Some(schema),
204                control,
205            )?),
206            control,
207        )?;
208    }
209    let resolver = QueryFunctionTypeResolver {
210        routines,
211        scalar_subquery_schemas: Some(scalar_subquery_schemas),
212        defer_routine_namespace_errors: true,
213    };
214    let resolve = |expression| {
215        crate::scalar_type_with_resolver_and_control(
216            expression,
217            schema,
218            params,
219            Some(&resolver),
220            control,
221        )
222    };
223    for projection in &statement.projections {
224        resolve(&projection.expr)?;
225    }
226    let mut equality_types = crate::production::Buffer::new(control);
227    for expression in statement
228        .group_by
229        .iter()
230        .chain(statement.grouping_sets.iter().flatten())
231    {
232        equality_types.push(resolve(expression)?, control)?;
233    }
234    let mut ordering_types = crate::production::Buffer::new(control);
235    for order in &statement.order_by {
236        ordering_types.push(resolve(&order.expr)?, control)?;
237    }
238    for expression in &statement.distinct_on {
239        equality_types.push(resolve(expression)?, control)?;
240    }
241    for expression in statement
242        .r#where
243        .iter()
244        .chain(statement.having.iter())
245        .chain(statement.limit.iter())
246        .chain(statement.offset.iter())
247    {
248        resolve(expression)?;
249    }
250    // All expression type errors still precede capability checks. These selections belong only to this invocation's immutable input scope.
251    for ty in equality_types.iter().flatten() {
252        crate::type_resolution::ComparisonSupport::Equality.require_in_catalog(ty, routines)?;
253    }
254    for ty in ordering_types.iter().flatten() {
255        crate::type_resolution::ComparisonSupport::Ordering.require_in_catalog(ty, routines)?;
256    }
257    Ok(())
258}
259
260/// Validate every query-block reference only after the caller has the authoritative source schema. This preserves registered table-function row shapes and checks recursive argument references before definitive routine namespace lookup. `schema` holds the block's columns over `outer`, the scope of the queries that enclose the block.
261pub fn validate_query_block_references(
262    routines: &dyn RoutineResolution,
263    statement: &QueryBlockPlan,
264    schema: &RowSchema,
265    params: &[SQLParam],
266    ctes: &BindingContext,
267    outer: Option<&RowSchema>,
268) -> Result<(), SQLError> {
269    let control = ProductionControl::uncontrolled();
270    validate_query_block_references_with_control(
271        routines,
272        statement,
273        schema,
274        params,
275        ctes.copy_with_control(&control)?,
276        outer,
277        &control,
278    )
279}
280
281/// Validate references with the authoritative source schema and the request's production control.
282pub fn validate_query_block_references_with_control(
283    routines: &dyn RoutineResolution,
284    statement: &QueryBlockPlan,
285    schema: &RowSchema,
286    params: &[SQLParam],
287    ctes: ControlledBindingContext<'_>,
288    outer: Option<&RowSchema>,
289    control: &ProductionControl<'_>,
290) -> Result<(), SQLError> {
291    let output = analyze_projection_output_schema_with_control(
292        routines,
293        &statement.projections,
294        ProjectionSchemas {
295            expressions: schema,
296            star: schema,
297        },
298        &statement.subqueries,
299        params,
300        ctes.copy_with_control(control)?,
301        control,
302    )?;
303    if statement.distinct && statement.distinct_on.is_empty() {
304        for ty in output.column_types().iter().flatten() {
305            crate::type_resolution::ComparisonSupport::Equality.require_in_catalog(ty, routines)?;
306        }
307    }
308    SchemaScope::for_analysis_with_control(ctes, control)?
309        .validate_query_block_clauses(routines, statement, schema, &output, params, outer)
310}
311
312pub(super) fn visit_projection_star_metadata<'a>(
313    expression: &'a ScalarExpr,
314    schema: &'a RowSchema,
315    control: &uqa_core::memory::ProductionControl<'_>,
316    observe: &mut dyn FnMut(crate::semantics::ProjectionStarMetadata<'a>) -> Result<(), SQLError>,
317) -> Result<bool, SQLError> {
318    crate::semantics::visit_bound_projection_star_metadata(
319        expression, schema, schema, control, observe,
320    )
321    .map_err(|error| error.at_position(expression.reference_position()))
322}
323
324pub(super) fn rename_schema(
325    schema: &RowSchema,
326    aliases: &[String],
327    qualifier: Option<&str>,
328) -> RowSchema {
329    rename_schema_with_control(
330        schema,
331        aliases,
332        qualifier,
333        &uqa_core::memory::ProductionControl::uncontrolled(),
334    )
335    .expect("ordinary result renaming")
336}
337
338pub(super) fn rename_schema_with_control(
339    schema: &RowSchema,
340    aliases: &[String],
341    qualifier: Option<&str>,
342    control: &uqa_core::memory::ProductionControl<'_>,
343) -> Result<RowSchema, SQLError> {
344    RowSchema::renamed_with_control(schema, aliases, qualifier, control)
345}