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::{
15    bind_query_plan_schema, projection_columns, BindingContext, QueryFunctionTypeResolver,
16    ScalarExpr, SchemaScope,
17};
18use crate::routines::RoutineResolution;
19
20type ProjectionStarColumn = (String, Option<ColumnType>, Option<u32>);
21
22#[cfg(test)]
23mod tests;
24
25pub(super) struct ProjectionMetadata {
26    pub ty: Option<ColumnType>,
27    pub collation: Option<u32>,
28    pub record: Option<crate::schema::RecordMetadata>,
29}
30
31/// Keep only selections that differ from their output type's default while the output schema is being assembled.
32#[derive(Default)]
33pub(super) struct OutputCollations(Vec<(usize, u32)>);
34
35impl OutputCollations {
36    pub(super) fn push(&mut self, position: usize, ty: Option<&ColumnType>, oid: Option<u32>) {
37        if let Some((ty, oid)) = ty.zip(oid) {
38            if crate::schema::composites::type_is_collatable(ty)
39                && crate::catalog::type_metadata::pg_type_collation_oid(ty) != i64::from(oid)
40            {
41                self.0.push((position, oid));
42            }
43        }
44    }
45
46    pub(super) fn apply(self, mut schema: RowSchema) -> RowSchema {
47        for (position, oid) in self.0 {
48            schema = schema
49                .with_collation_override(crate::schema::CollationBinding::Column(position), oid)
50                .expect("selected collation belongs to its typed output");
51        }
52        schema
53    }
54}
55
56/// 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.
57pub fn bind_projection_output_schema(
58    routines: &dyn RoutineResolution,
59    projections: &[ProjectionPlan],
60    expression_schema: &RowSchema,
61    star_schema: &RowSchema,
62    subqueries: &[QueryPlan],
63    params: &[SQLParam],
64    ctes: &BindingContext,
65) -> Result<RowSchema, SQLError> {
66    projection_output_schema(
67        SchemaScope::from_context(ctes)?,
68        routines,
69        projections,
70        expression_schema,
71        star_schema,
72        subqueries,
73        params,
74    )
75}
76
77/// Derive and validate a projection's exact output row type without executing it.
78pub fn analyze_projection_output_schema(
79    routines: &dyn RoutineResolution,
80    projections: &[ProjectionPlan],
81    expression_schema: &RowSchema,
82    star_schema: &RowSchema,
83    subqueries: &[QueryPlan],
84    params: &[SQLParam],
85    ctes: &BindingContext,
86) -> Result<RowSchema, SQLError> {
87    projection_output_schema(
88        SchemaScope::for_analysis(ctes)?,
89        routines,
90        projections,
91        expression_schema,
92        star_schema,
93        subqueries,
94        params,
95    )
96}
97
98fn projection_output_schema(
99    mut scope: SchemaScope,
100    routines: &dyn RoutineResolution,
101    projections: &[ProjectionPlan],
102    expression_schema: &RowSchema,
103    star_schema: &RowSchema,
104    subqueries: &[QueryPlan],
105    params: &[SQLParam],
106) -> Result<RowSchema, SQLError> {
107    let labels = projection_columns(projections);
108    let mut columns = Vec::new();
109    let mut types = Vec::new();
110    let mut records = Vec::new();
111    let mut collations = OutputCollations::default();
112    for (position, projection) in projections.iter().enumerate() {
113        let expansion_schema = match projection.expr {
114            ScalarExpr::QualifiedStar(_) => expression_schema,
115            _ => star_schema,
116        };
117        if let Some(star_columns) = projection_star_columns(&projection.expr, expansion_schema)? {
118            records.extend(
119                super::record_fields::star_metadata(&projection.expr, expansion_schema)
120                    .unwrap_or_default(),
121            );
122            for (column, ty, collation) in star_columns {
123                collations.push(types.len(), ty.as_ref(), collation);
124                columns.push(column);
125                types.push(ty);
126            }
127            continue;
128        }
129        columns.push(labels[position].clone());
130        let metadata = scope.bind_projection_metadata(
131            routines,
132            &projection.expr,
133            expression_schema,
134            subqueries,
135            params,
136        )?;
137        collations.push(types.len(), metadata.ty.as_ref(), metadata.collation);
138        types.push(metadata.ty);
139        records.push(metadata.record);
140    }
141    for projection in projections {
142        scope.collations.validate_expression(&projection.expr)?;
143    }
144    Ok(collations
145        .apply(RowSchema::with_types(columns, types))
146        .with_record_metadata(
147            records
148                .into_iter()
149                .enumerate()
150                .filter_map(|(index, fields)| fields.map(|fields| (index, fields))),
151        ))
152}
153
154/// 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.
155pub fn validate_query_block_expression_types(
156    routines: &dyn RoutineResolution,
157    statement: &QueryBlockPlan,
158    schema: &RowSchema,
159    params: &[SQLParam],
160    ctes: &BindingContext,
161) -> Result<(), SQLError> {
162    let scalar_subquery_schemas = statement
163        .subqueries
164        .iter()
165        .map(|plan| bind_query_plan_schema(routines, plan, params, ctes, Some(schema)).map(Some))
166        .collect::<Result<Vec<_>, _>>()?;
167    let resolver = QueryFunctionTypeResolver {
168        routines,
169        scalar_subquery_schemas: Some(scalar_subquery_schemas),
170        defer_routine_namespace_errors: true,
171    };
172    let resolve =
173        |expression| crate::scalar_type_with_resolver(expression, schema, params, &resolver);
174    for projection in &statement.projections {
175        resolve(&projection.expr)?;
176    }
177    let mut equality_types = statement
178        .group_by
179        .iter()
180        .chain(statement.grouping_sets.iter().flatten())
181        .map(resolve)
182        .collect::<Result<Vec<_>, _>>()?;
183    let ordering_types = statement
184        .order_by
185        .iter()
186        .map(|order| resolve(&order.expr))
187        .collect::<Result<Vec<_>, _>>()?;
188    for expression in &statement.distinct_on {
189        equality_types.push(resolve(expression)?);
190    }
191    for expression in statement
192        .r#where
193        .iter()
194        .chain(statement.having.iter())
195        .chain(statement.limit.iter())
196        .chain(statement.offset.iter())
197    {
198        resolve(expression)?;
199    }
200    // All expression type errors still precede capability checks. These selections belong only to this invocation's immutable input scope.
201    for ty in equality_types.iter().flatten() {
202        crate::type_resolution::ComparisonSupport::Equality.require_in_catalog(ty, routines)?;
203    }
204    for ty in ordering_types.iter().flatten() {
205        crate::type_resolution::ComparisonSupport::Ordering.require_in_catalog(ty, routines)?;
206    }
207    Ok(())
208}
209
210/// 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.
211pub fn validate_query_block_references(
212    routines: &dyn RoutineResolution,
213    statement: &QueryBlockPlan,
214    schema: &RowSchema,
215    params: &[SQLParam],
216    ctes: &BindingContext,
217    outer: Option<&RowSchema>,
218) -> Result<(), SQLError> {
219    let output = analyze_projection_output_schema(
220        routines,
221        &statement.projections,
222        schema,
223        schema,
224        &statement.subqueries,
225        params,
226        ctes,
227    )?;
228    if statement.distinct && statement.distinct_on.is_empty() {
229        for ty in output.column_types().iter().flatten() {
230            crate::type_resolution::ComparisonSupport::Equality.require_in_catalog(ty, routines)?;
231        }
232    }
233    SchemaScope::for_analysis(ctes)?
234        .validate_query_block_clauses(routines, statement, schema, &output, params, outer)
235}
236
237pub(super) fn projection_star_columns(
238    expression: &ScalarExpr,
239    schema: &RowSchema,
240) -> Result<Option<Vec<ProjectionStarColumn>>, SQLError> {
241    match expression {
242        ScalarExpr::Star => Ok(Some(
243            schema
244                .columns()
245                .iter()
246                .enumerate()
247                .map(|(position, column)| {
248                    (
249                        schema.public_name(position).unwrap_or(column).to_string(),
250                        schema.column_type(position).cloned(),
251                        schema.column_collation(position),
252                    )
253                })
254                .collect(),
255        )),
256        ScalarExpr::QualifiedStar(qualifier) => {
257            let columns = schema
258                .qualified_star_position_layout(qualifier)
259                .into_iter()
260                .map(|(column, logical, _, ty)| {
261                    let collation = logical.map_or_else(
262                        || schema.qualified_collation(qualifier, &column),
263                        |position| schema.column_collation(position),
264                    );
265                    (column, ty, collation)
266                })
267                .collect::<Vec<_>>();
268            if columns.is_empty() {
269                return Err(SQLError::UnknownTable(qualifier.clone()));
270            }
271            Ok(Some(columns))
272        }
273        _ => Ok(None),
274    }
275}
276
277pub(super) fn rename_schema(
278    schema: &RowSchema,
279    aliases: &[String],
280    qualifier: Option<&str>,
281) -> RowSchema {
282    let columns = schema
283        .columns()
284        .iter()
285        .enumerate()
286        .map(|(position, column)| {
287            aliases
288                .get(position)
289                .cloned()
290                .unwrap_or_else(|| schema.public_name(position).unwrap_or(column).to_string())
291        })
292        .collect();
293    let renamed = match qualifier {
294        Some(qualifier) => {
295            RowSchema::with_qualified_types(qualifier, columns, schema.column_types().to_vec())
296        }
297        None => RowSchema::with_types(columns, schema.column_types().to_vec()),
298    };
299    let renamed = renamed
300        .with_column_collations((0..schema.len()).map(|position| schema.column_collation(position)))
301        .with_record_fields_from(schema);
302    let renamed = if schema.columns_are_open(None) {
303        RowSchema::with_open_columns(&renamed, qualifier)
304    } else {
305        renamed
306    };
307    let mut hidden = Vec::new();
308    let mut conflicting = Vec::new();
309    for (identity, ty) in schema.typed_virtual_identities() {
310        let conflicts = match identity.qualifier() {
311            Some(source) => schema.qualified_column_is_ambiguous(source, identity.column()),
312            None => schema.column_is_ambiguous(identity.column()),
313        };
314        let mapped = qualifier.map_or_else(
315            || vec![identity.clone()],
316            |qualifier| {
317                vec![
318                    crate::ColumnIdentity::unqualified(identity.column()),
319                    crate::ColumnIdentity::qualified(qualifier, identity.column()),
320                ]
321            },
322        );
323        for identity in mapped {
324            if conflicts {
325                conflicting.push((identity, ty.cloned()));
326            } else {
327                hidden.push((identity, ty.cloned()));
328            }
329        }
330    }
331    let renamed = RowSchema::with_typed_virtual_identities(&renamed, &hidden);
332    RowSchema::with_typed_conflicting_virtual_identities(&renamed, &conflicting)
333}