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
14pub fn projection_columns(projections: &[ProjectionPlan]) -> Vec<String> {
15    projections.iter().map(projection_label_at).collect()
16}
17
18/// Resolve an SQL92 output ordinal against the expanded SELECT list before using its type or physical expression.
19pub fn query_output_position(position: i64, width: usize, clause: &str) -> Result<usize, SQLError> {
20    usize::try_from(position)
21        .ok()
22        .and_then(|position| position.checked_sub(1))
23        .filter(|position| *position < width)
24        .ok_or_else(|| output_position_error(clause, position))
25}
26
27pub fn output_position_error(clause: &str, position: i64) -> SQLError {
28    SQLError::Routine {
29        sqlstate: "42P10".into(),
30        message: format!("{clause} position {position} is not in the select list"),
31    }
32}
33
34/// Compute a projection's `PostgreSQL` output column name. Standalone expressions use `?column?`; repeated labels remain repeated until the final named-map compatibility boundary.
35pub fn projection_label_at(proj: &ProjectionPlan) -> String {
36    if let Some(a) = &proj.alias {
37        return a.clone();
38    }
39    let mut expression = &proj.expr;
40    while let ScalarExpr::Collated { expr, .. } = expression {
41        expression = expr;
42    }
43    match expression {
44        ScalarExpr::Column(c) => c.clone(),
45        ScalarExpr::QualifiedColumn { column, .. } => column.clone(),
46        ScalarExpr::Star | ScalarExpr::QualifiedStar(_) => "*".into(),
47        ScalarExpr::Func {
48            name,
49            binding,
50            args,
51            ..
52        } => field_selection_label(binding.as_ref(), args.get(1))
53            .unwrap_or_else(|| function_projection_label(name, binding.as_ref())),
54        ScalarExpr::WindowCall { name, .. } => function_projection_label(name, None),
55        _ => "?column?".into(),
56    }
57}
58
59/// `FigureColname` names a field selection by its field.
60pub(crate) fn field_selection_label<E: FieldNameLiteral>(
61    binding: Option<&crate::ast::FunctionBinding>,
62    field: Option<&E>,
63) -> Option<String> {
64    (binding.and_then(|binding| binding.dispatch)
65        == Some(crate::ast::FunctionDispatch::FieldSelect))
66    .then(|| field.and_then(FieldNameLiteral::field_name))
67    .flatten()
68    .map(str::to_owned)
69}
70
71/// The field name literal of a field selection in parsed or planned expressions.
72pub(crate) trait FieldNameLiteral {
73    fn field_name(&self) -> Option<&str>;
74}
75
76impl FieldNameLiteral for ScalarExpr {
77    fn field_name(&self) -> Option<&str> {
78        match self {
79            ScalarExpr::Literal(uqa_core::Value::Str(field)) => Some(field),
80            _ => None,
81        }
82    }
83}
84
85impl FieldNameLiteral for crate::ast::Expr {
86    fn field_name(&self) -> Option<&str> {
87        match self {
88            crate::ast::Expr::Literal(uqa_core::Value::Str(field)) => Some(field),
89            _ => None,
90        }
91    }
92}
93
94pub fn function_projection_label(
95    name: &str,
96    binding: Option<&crate::ast::FunctionBinding>,
97) -> String {
98    // Operators and other syntax that the parser lowers to calls have no name of their own.
99    if matches!(
100        binding.and_then(|binding| binding.dispatch),
101        Some(
102            crate::ast::FunctionDispatch::NumericOperator(_)
103                | crate::ast::FunctionDispatch::Pattern { .. }
104                | crate::ast::FunctionDispatch::Concat { .. }
105                | crate::ast::FunctionDispatch::ArrayConcat
106                | crate::ast::FunctionDispatch::ArrayAppend
107                | crate::ast::FunctionDispatch::ArrayPrepend
108                | crate::ast::FunctionDispatch::IsDistinct
109                | crate::ast::FunctionDispatch::DistinctNot
110                | crate::ast::FunctionDispatch::RowDistinct
111                | crate::ast::FunctionDispatch::ValueIsDistinct
112                | crate::ast::FunctionDispatch::ValueNullTest { .. }
113                | crate::ast::FunctionDispatch::BooleanTest(_)
114                | crate::ast::FunctionDispatch::AnyOperator
115                | crate::ast::FunctionDispatch::AllOperator
116                | crate::ast::FunctionDispatch::BetweenSymmetric
117                | crate::ast::FunctionDispatch::JsonExtract { .. }
118        )
119    ) {
120        return "?column?".into();
121    }
122    let name = crate::parse_regobject_name(name)
123        .and_then(|mut names| names.pop())
124        .unwrap_or_else(|| name.to_string());
125    if operator_call(&name) {
126        return "?column?".into();
127    }
128    name
129}
130
131/// The calls the parser lowers operator syntax to under names no `PostgreSQL` function has: `||`, `@@`, `@?`, `@>`, `<@`, `&&`, `?`, `?|`, `?&`, `#-`, `~`, `~*`, `LIKE`, `ILIKE` and `SIMILAR TO`.
132fn operator_call(name: &str) -> bool {
133    matches!(
134        name,
135        "fts_match"
136            | "jsonpath_exists"
137            | "contains_op"
138            | "contained_by_op"
139            | "array_overlap"
140            | "json_has_key"
141            | "json_has_any_key"
142            | "json_has_all_keys"
143            | "json_delete_path"
144    )
145}
146
147pub fn expand_from_star_columns(
148    columns: Vec<String>,
149    projections: &[ProjectionPlan],
150    source_schema: &RowSchema,
151) -> Result<Vec<String>, SQLError> {
152    let mut output = Vec::new();
153    for (position, projection) in projections.iter().enumerate() {
154        match &projection.expr {
155            ScalarExpr::Star => {
156                output.extend(
157                    source_schema
158                        .columns()
159                        .iter()
160                        .enumerate()
161                        .filter(|(position, _)| {
162                            visible_projection_source_position(source_schema, *position)
163                        })
164                        .map(|(source_position, column)| {
165                            source_schema
166                                .public_name(source_position)
167                                .unwrap_or(column)
168                                .to_string()
169                        }),
170                );
171            }
172            ScalarExpr::QualifiedStar(qualifier) => {
173                let qualified_columns = source_schema
174                    .qualified_star_position_layout(qualifier)
175                    .into_iter()
176                    .filter(|(_, logical, _, _)| {
177                        logical.is_none_or(|position| {
178                            visible_projection_source_position(source_schema, position)
179                        })
180                    })
181                    .map(|(column, _, _, _)| column)
182                    .collect::<Vec<_>>();
183                if qualified_columns.is_empty() {
184                    return Err(SQLError::UnknownTable(qualifier.clone()));
185                }
186                output.extend(qualified_columns);
187            }
188            _ => output.push(columns[position].clone()),
189        }
190    }
191    Ok(output)
192}
193
194pub fn bound_projection_expression(schema: &RowSchema, position: usize) -> ScalarExpr {
195    let Some(identity) = schema.identity(position) else {
196        return ScalarExpr::Position(position);
197    };
198    if let Some(qualifier) = identity.qualifier() {
199        if schema.qualified_position(qualifier, identity.column()) == Some(position) {
200            return ScalarExpr::qualified_column(qualifier, identity.column());
201        }
202    } else if schema.unqualified_position(identity.column()) == Some(position) {
203        return ScalarExpr::Column(identity.column().to_string());
204    }
205    ScalarExpr::Position(position)
206}
207
208pub fn expand_bound_projection_stars(
209    projections: &[ProjectionPlan],
210    schema: &RowSchema,
211) -> Result<Vec<ProjectionPlan>, SQLError> {
212    let mut expanded = Vec::new();
213    for projection in projections {
214        match &projection.expr {
215            ScalarExpr::Star => {
216                for (position, column) in schema.columns().iter().enumerate() {
217                    if !visible_projection_source_position(schema, position) {
218                        continue;
219                    }
220                    expanded.push(ProjectionPlan {
221                        expr: bound_projection_expression(schema, position),
222                        alias: Some(schema.public_name(position).unwrap_or(column).to_string()),
223                    });
224                }
225            }
226            ScalarExpr::QualifiedStar(qualifier) => {
227                let layout = schema.qualified_star_position_layout(qualifier);
228                if layout.is_empty() {
229                    return Err(SQLError::UnknownTable(qualifier.clone()));
230                }
231                for (column, logical, _, _) in layout {
232                    if logical.is_some_and(|position| {
233                        !visible_projection_source_position(schema, position)
234                    }) {
235                        continue;
236                    }
237                    expanded.push(ProjectionPlan {
238                        expr: logical.map_or_else(
239                            || ScalarExpr::qualified_column(qualifier, &column),
240                            |position| bound_projection_expression(schema, position),
241                        ),
242                        alias: Some(column),
243                    });
244                }
245            }
246            _ => expanded.push(projection.clone()),
247        }
248    }
249    Ok(expanded)
250}
251
252pub fn visible_projection_source_position(schema: &RowSchema, position: usize) -> bool {
253    schema.wildcard_position_visible(position)
254}
255
256pub fn returning_context_schema(
257    columns: &[String],
258    types: &[Option<crate::ast::ColumnType>],
259    composite_width: usize,
260    target_qualifier: &str,
261    aliases: &ReturningAliases,
262) -> RowSchema {
263    let target =
264        RowSchema::with_qualified_types(target_qualifier, columns.to_vec(), types.to_vec());
265    returning_schema_for_target(target, composite_width, aliases)
266}
267
268/// 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.
269pub fn returning_schema_for_target(
270    target: RowSchema,
271    composite_width: usize,
272    aliases: &ReturningAliases,
273) -> RowSchema {
274    let width = target.len();
275    assert_eq!(
276        target.physical_width(),
277        width,
278        "RETURNING target must be positional"
279    );
280    assert!(
281        composite_width <= width,
282        "RETURNING user columns must belong to the target"
283    );
284    debug_assert!((0..width).all(|position| target.slot(position) == Some(position)));
285    let target = RowSchema::with_wildcard_hidden_positions(&target, composite_width..width);
286    let types = target.column_types();
287    let hidden_types = types
288        .iter()
289        .cloned()
290        .chain(types.iter().cloned())
291        .collect::<Vec<_>>();
292    let schema = RowSchema::append_hidden_typed(&target, &hidden_types);
293    let identity_aliases = target
294        .columns()
295        .iter()
296        .enumerate()
297        .flat_map(|(position, column)| {
298            [
299                (
300                    ColumnIdentity::qualified(&aliases.old, column),
301                    width + position,
302                    types[position].clone(),
303                ),
304                (
305                    ColumnIdentity::qualified(&aliases.new, column),
306                    width * 2 + position,
307                    types[position].clone(),
308                ),
309            ]
310        })
311        .collect::<Vec<_>>();
312    let mut schema = RowSchema::with_physical_identity_aliases(&schema, &identity_aliases);
313    for (binding, oid) in target.collation_overrides() {
314        let crate::schema::CollationBinding::Column(position) = binding else {
315            continue;
316        };
317        for qualifier in [&aliases.old, &aliases.new] {
318            let identity = ColumnIdentity::qualified(qualifier, &target.columns()[position]);
319            schema = schema
320                .with_collation_override(crate::schema::CollationBinding::Alias(&identity), oid)
321                .expect("RETURNING image alias retains its target's type");
322        }
323    }
324    schema
325}
326
327pub fn returning_expression_schema(
328    target: &RowSchema,
329    target_qualifier: &str,
330    aliases: &ReturningAliases,
331    supplemental: Option<&RowSchema>,
332) -> RowSchema {
333    let composite_width = target.len();
334    let (columns, types) = target_with_system_columns(target);
335    let width = columns.len();
336    let schema = RowSchema::with_qualified_types(target_qualifier, columns, types)
337        .with_column_collations((0..width).map(|position| target.column_collation(position)));
338    let target = returning_schema_for_target(schema, composite_width, aliases);
339    supplemental.map_or(target.clone(), |source| {
340        RowSchema::join(&target, source, std::iter::empty())
341    })
342}
343
344/// 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.
345#[must_use]
346pub fn mutation_clause_schema(
347    target: &RowSchema,
348    target_qualifier: &str,
349    supplemental: Option<&RowSchema>,
350) -> RowSchema {
351    let composite_width = target.len();
352    let (columns, types) = target_with_system_columns(target);
353    let width = columns.len();
354    let target = RowSchema::with_wildcard_hidden_positions(
355        &RowSchema::with_qualified_types(target_qualifier, columns, types)
356            .with_column_collations((0..width).map(|position| target.column_collation(position))),
357        composite_width..width,
358    );
359    supplemental.map_or(target.clone(), |source| {
360        RowSchema::join(&target, source, std::iter::empty())
361    })
362}
363
364/// The target's columns followed by the system columns a statement can name on it.
365fn target_with_system_columns(
366    target: &RowSchema,
367) -> (Vec<String>, Vec<Option<crate::ast::ColumnType>>) {
368    let mut columns = target.columns().to_vec();
369    let mut types = target.column_types().to_vec();
370    if !columns.iter().any(|column| column == DOC_ID_COLUMN) {
371        columns.push(DOC_ID_COLUMN.into());
372        types.push(Some(crate::ast::ColumnType::BigInteger));
373    }
374    columns.push(TABLE_OID_COLUMN.into());
375    types.push(Some(crate::ast::ColumnType::Oid));
376    columns.push(crate::semantics::XMIN_COLUMN.into());
377    types.push(Some(crate::ast::ColumnType::Xid));
378    (columns, types)
379}
380
381pub fn query_plan_output_columns(plan: &crate::plan::QueryPlan) -> Option<Vec<String>> {
382    match &plan.root {
383        crate::plan::RelationalPlan::QueryBlock(block) => {
384            Some(projection_columns(&block.projections))
385        }
386        crate::plan::RelationalPlan::SetOp { left, .. } => query_plan_output_columns(left),
387        crate::plan::RelationalPlan::Values { rows, .. } => rows.first().map(|row| {
388            (1..=row.len())
389                .map(|index| format!("column{index}"))
390                .collect()
391        }),
392    }
393}
394
395pub fn should_defer_distinct_limit(stmt: &crate::plan::QueryBlockPlan) -> bool {
396    stmt.distinct && (stmt.limit.is_some() || stmt.offset.is_some())
397}
398
399pub fn select_execution_stmt(
400    stmt: &crate::plan::QueryBlockPlan,
401    defer_distinct_limit: bool,
402) -> crate::plan::QueryBlockPlan {
403    if !defer_distinct_limit {
404        return stmt.clone();
405    }
406    let mut exec_stmt = stmt.clone();
407    exec_stmt.limit = None;
408    exec_stmt.offset = None;
409    exec_stmt
410}