Skip to main content

uqa_sql/semantics/
projection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Projection labels, star expansion, and DML row-image schemas.
8
9use super::{DOC_ID_COLUMN, TABLE_OID_COLUMN};
10use crate::ast::ReturningAliases;
11use crate::plan::ProjectionPlan;
12use crate::{ColumnIdentity, RowSchema, SQLError, ScalarExpr};
13
14mod labels;
15mod mutation;
16mod stars;
17pub(crate) use labels::{field_selection_label, rule_function_label};
18pub use labels::{
19    function_projection_label, projection_label_at, projection_labels_with_control,
20    visit_query_output_columns, with_projection_label, ProjectionLabels,
21};
22pub use mutation::{mutation_clause_schema_with_control, returning_expression_schema_with_control};
23pub(crate) use stars::row_star_fields_with_control;
24pub use stars::{
25    bound_projection_expression_with_control, visit_bound_projection_star_fields,
26    ProjectionFieldVisitor,
27};
28pub use stars::{visit_bound_projection_star_metadata, ProjectionStarMetadata};
29
30pub fn projection_columns(projections: &[ProjectionPlan]) -> Vec<String> {
31    projections.iter().map(projection_label_at).collect()
32}
33
34/// Resolve an SQL92 output ordinal against the expanded SELECT list before using its type or physical expression.
35pub fn query_output_position(position: i64, width: usize, clause: &str) -> Result<usize, SQLError> {
36    usize::try_from(position)
37        .ok()
38        .and_then(|position| position.checked_sub(1))
39        .filter(|position| *position < width)
40        .ok_or_else(|| output_position_error(clause, position))
41}
42
43pub fn output_position_error(clause: &str, position: i64) -> SQLError {
44    SQLError::Routine {
45        sqlstate: "42P10".into(),
46        message: format!("{clause} position {position} is not in select list"),
47    }
48}
49
50pub fn expand_from_star_columns(
51    columns: Vec<String>,
52    projections: &[ProjectionPlan],
53    source_schema: &RowSchema,
54) -> Result<Vec<String>, SQLError> {
55    let mut output = Vec::new();
56    for (position, projection) in projections.iter().enumerate() {
57        match &projection.expr {
58            ScalarExpr::Star => {
59                output.extend(
60                    source_schema
61                        .columns()
62                        .iter()
63                        .enumerate()
64                        .filter(|(position, _)| {
65                            visible_projection_source_position(source_schema, *position)
66                        })
67                        .map(|(source_position, column)| {
68                            source_schema
69                                .public_name(source_position)
70                                .unwrap_or(column)
71                                .to_string()
72                        }),
73                );
74            }
75            ScalarExpr::QualifiedStar(qualifier) => {
76                let qualified_columns = source_schema
77                    .qualified_star_position_layout(qualifier)
78                    .into_iter()
79                    .filter(|(_, logical, _, _)| {
80                        logical.is_none_or(|position| {
81                            visible_projection_source_position(source_schema, position)
82                        })
83                    })
84                    .map(|(column, _, _, _)| column)
85                    .collect::<Vec<_>>();
86                if qualified_columns.is_empty() && !source_schema.has_qualifier(qualifier) {
87                    return Err(SQLError::UnknownTable(qualifier.to_string()));
88                }
89                output.extend(qualified_columns);
90            }
91            _ => output.push(columns[position].clone()),
92        }
93    }
94    Ok(output)
95}
96
97pub fn bound_projection_expression(schema: &RowSchema, position: usize) -> ScalarExpr {
98    let control = uqa_core::memory::ProductionControl::uncontrolled();
99    bound_projection_expression_with_control(schema, position, &control)
100        .expect("ordinary projection reference")
101        .finish(&control)
102        .expect("ordinary reference completion")
103        .into_uncontrolled()
104        .expect("ordinary reference ownership")
105}
106
107pub fn expand_bound_projection_stars(
108    projections: &[ProjectionPlan],
109    schema: &RowSchema,
110) -> Result<Vec<ProjectionPlan>, SQLError> {
111    expand_bound_projection_stars_in_scope(projections, schema, schema)
112}
113
114/// Bare stars expand the local FROM output, while qualified stars can select an admitted enclosing namespace.
115pub fn expand_bound_projection_stars_in_scope(
116    projections: &[ProjectionPlan],
117    schema: &RowSchema,
118    expression_schema: &RowSchema,
119) -> Result<Vec<ProjectionPlan>, SQLError> {
120    let mut expanded = Vec::new();
121    for projection in projections {
122        let star = visit_bound_projection_star_fields(
123            &projection.expr,
124            schema,
125            expression_schema,
126            &uqa_core::memory::ProductionControl::uncontrolled(),
127            &mut |column, position, qualifier| {
128                let selected = if qualifier.is_some() {
129                    expression_schema
130                } else {
131                    schema
132                };
133                expanded.push(ProjectionPlan {
134                    expr: position.map_or_else(
135                        || {
136                            ScalarExpr::qualified_column(
137                                qualifier.expect("hidden qualified field"),
138                                column,
139                            )
140                        },
141                        |position| bound_projection_expression(selected, position),
142                    ),
143                    alias: Some(column.to_string()),
144                });
145                Ok(())
146            },
147        )?;
148        if !star {
149            expanded.push(projection.clone());
150        }
151    }
152    Ok(expanded)
153}
154
155pub fn visible_projection_source_position(schema: &RowSchema, position: usize) -> bool {
156    schema.wildcard_position_visible(position)
157}
158
159pub fn returning_context_schema(
160    columns: &[String],
161    types: &[Option<crate::ast::ColumnType>],
162    composite_width: usize,
163    target_qualifier: &str,
164    aliases: &ReturningAliases,
165) -> RowSchema {
166    let target =
167        RowSchema::with_qualified_types(target_qualifier, columns.to_vec(), types.to_vec());
168    returning_schema_for_target(target, composite_width, aliases)
169}
170
171/// Add OLD/NEW image bindings to an already-qualified, positional target schema. Each image retains the target column's selected collation even when the image's value is NULL.
172pub fn returning_schema_for_target(
173    target: RowSchema,
174    composite_width: usize,
175    aliases: &ReturningAliases,
176) -> RowSchema {
177    let width = target.len();
178    assert_eq!(
179        target.physical_width(),
180        width,
181        "RETURNING target must be positional"
182    );
183    assert!(
184        composite_width <= width,
185        "RETURNING user columns must belong to the target"
186    );
187    debug_assert!((0..width).all(|position| target.slot(position) == Some(position)));
188    let target = RowSchema::with_wildcard_hidden_positions(&target, composite_width..width);
189    let types = target.column_types();
190    let hidden_types = types
191        .iter()
192        .cloned()
193        .chain(types.iter().cloned())
194        .collect::<Vec<_>>();
195    let schema = RowSchema::append_hidden_typed(&target, &hidden_types);
196    let identity_aliases = target
197        .columns()
198        .iter()
199        .enumerate()
200        .flat_map(|(position, column)| {
201            [
202                (
203                    ColumnIdentity::qualified(&aliases.old, column),
204                    width + position,
205                    types[position].clone(),
206                ),
207                (
208                    ColumnIdentity::qualified(&aliases.new, column),
209                    width * 2 + position,
210                    types[position].clone(),
211                ),
212            ]
213        })
214        .collect::<Vec<_>>();
215    let mut schema = RowSchema::with_physical_identity_aliases(&schema, &identity_aliases);
216    for (binding, oid) in target.collation_overrides() {
217        let crate::schema::CollationBinding::Column(position) = binding else {
218            continue;
219        };
220        for qualifier in [&aliases.old, &aliases.new] {
221            let identity = ColumnIdentity::qualified(qualifier, &target.columns()[position]);
222            schema = schema
223                .with_collation_override(crate::schema::CollationBinding::Alias(&identity), oid)
224                .expect("RETURNING image alias retains its target's type");
225        }
226    }
227    schema
228}
229
230pub fn returning_expression_schema(
231    target: &RowSchema,
232    target_qualifier: &str,
233    aliases: &ReturningAliases,
234    supplemental: Option<&RowSchema>,
235) -> RowSchema {
236    let composite_width = target.len();
237    let (columns, types) = target_with_system_columns(target);
238    let width = columns.len();
239    let schema = RowSchema::with_qualified_types(target_qualifier, columns, types)
240        .with_column_collations((0..width).map(|position| target.column_collation(position)));
241    let target = returning_schema_for_target(schema, composite_width, aliases);
242    supplemental.map_or(target.clone(), |source| {
243        RowSchema::join(&target, source, std::iter::empty())
244    })
245}
246
247/// The row scope of the clauses of a data-modifying statement other than `RETURNING`: the target, named by its name or alias, with its system columns, and the statement's other sources. The `old` and `new` aliases of the target belong to `RETURNING` alone.
248#[must_use]
249pub fn mutation_clause_schema(
250    target: &RowSchema,
251    target_qualifier: &str,
252    supplemental: Option<&RowSchema>,
253) -> RowSchema {
254    let composite_width = target.len();
255    let (columns, types) = target_with_system_columns(target);
256    let width = columns.len();
257    let target = RowSchema::with_wildcard_hidden_positions(
258        &RowSchema::with_qualified_types(target_qualifier, columns, types)
259            .with_column_collations((0..width).map(|position| target.column_collation(position))),
260        composite_width..width,
261    );
262    supplemental.map_or(target.clone(), |source| {
263        RowSchema::join(&target, source, std::iter::empty())
264    })
265}
266
267/// The target's columns followed by the system columns a statement can name on it.
268fn target_with_system_columns(
269    target: &RowSchema,
270) -> (Vec<String>, Vec<Option<crate::ast::ColumnType>>) {
271    let mut columns = target.columns().to_vec();
272    let mut types = target.column_types().to_vec();
273    if !columns.iter().any(|column| column == DOC_ID_COLUMN) {
274        columns.push(DOC_ID_COLUMN.into());
275        types.push(Some(crate::ast::ColumnType::BigInteger));
276    }
277    columns.push(TABLE_OID_COLUMN.into());
278    types.push(Some(crate::ast::ColumnType::Oid));
279    columns.push(crate::semantics::XMIN_COLUMN.into());
280    types.push(Some(crate::ast::ColumnType::Xid));
281    (columns, types)
282}
283
284/// Observe declared output width without constructing or copying public labels.
285pub fn query_plan_output_width_with_control(
286    mut plan: &crate::plan::QueryPlan,
287    control: &uqa_core::memory::ProductionControl<'_>,
288) -> Result<Option<usize>, SQLError> {
289    loop {
290        control.check()?;
291        match &plan.root {
292            crate::plan::RelationalPlan::QueryBlock(block) => {
293                return Ok(Some(block.projections.len()))
294            }
295            crate::plan::RelationalPlan::SetOp { left, .. } => plan = left,
296            crate::plan::RelationalPlan::Values { rows, .. } => {
297                return Ok(rows.first().map(Vec::len))
298            }
299        }
300    }
301}
302
303pub fn query_plan_output_columns(plan: &crate::plan::QueryPlan) -> Option<Vec<String>> {
304    match &plan.root {
305        crate::plan::RelationalPlan::QueryBlock(block) => {
306            Some(projection_columns(&block.projections))
307        }
308        crate::plan::RelationalPlan::SetOp { left, .. } => query_plan_output_columns(left),
309        crate::plan::RelationalPlan::Values { rows, .. } => rows.first().map(|row| {
310            (1..=row.len())
311                .map(|index| format!("column{index}"))
312                .collect()
313        }),
314    }
315}
316
317pub fn should_defer_distinct_limit(stmt: &crate::plan::QueryBlockPlan) -> bool {
318    stmt.distinct && (stmt.limit.is_some() || stmt.offset.is_some())
319}
320
321pub fn select_execution_stmt(
322    stmt: &crate::plan::QueryBlockPlan,
323    defer_distinct_limit: bool,
324) -> crate::plan::QueryBlockPlan {
325    if !defer_distinct_limit {
326        return stmt.clone();
327    }
328    let mut exec_stmt = stmt.clone();
329    exec_stmt.limit = None;
330    exec_stmt.offset = None;
331    exec_stmt
332}
333
334pub fn query_plan_output_columns_with_control(
335    plan: &crate::plan::QueryPlan,
336    control: &uqa_core::memory::ProductionControl<'_>,
337) -> Result<Option<uqa_core::memory::Produced<Vec<String>>>, SQLError> {
338    let mut names = uqa_core::memory::ProductionVec::new(*control);
339    if !visit_query_output_columns(plan, &[], control, &mut |name| {
340        names.push_produced(control.copy_text(name)?)?;
341        Ok(())
342    })? {
343        return Ok(None);
344    }
345    Ok(Some(names.finish()?))
346}