Skip to main content

uqa_sql/semantics/projection/
labels.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Borrowed output labels and admitted identifier decoding share the ordinary naming rules.
8
9use crate::{
10    ast::{FunctionBinding, FunctionDispatch},
11    plan::{ProjectionPlan, QueryPlan, RelationalPlan},
12    SQLError, ScalarExpr,
13};
14use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
15
16enum Label<'a> {
17    Borrowed(&'a str),
18    Decoded(Produced<Vec<String>>),
19}
20
21impl Label<'_> {
22    fn as_str(&self) -> &str {
23        match self {
24            Self::Borrowed(name) => name,
25            Self::Decoded(names) => names.last().expect("parsed identifier"),
26        }
27    }
28
29    fn into_uncontrolled(self) -> String {
30        match self {
31            Self::Borrowed(name) => name.to_owned(),
32            Self::Decoded(names) => names
33                .into_uncontrolled()
34                .expect("ordinary label has no reservation")
35                .pop()
36                .expect("parsed identifier"),
37        }
38    }
39}
40
41/// An immutable positional descriptor borrowing existing names and retaining admitted decoding storage only where naming requires it.
42pub struct ProjectionLabels<'a> {
43    labels: Produced<Vec<Label<'a>>>,
44}
45
46impl ProjectionLabels<'_> {
47    pub fn iter(&self) -> impl ExactSizeIterator<Item = &str> {
48        self.labels.iter().map(Label::as_str)
49    }
50}
51
52/// Capture labels for repeated observation. Aliases override individual projections; duplicate labels retain their original positions. Admit descriptor capacity before decoding any name.
53pub fn projection_labels_with_control<'a>(
54    projections: &'a [ProjectionPlan],
55    aliases: &'a [String],
56    control: &ProductionControl<'_>,
57) -> Result<ProjectionLabels<'a>, SQLError> {
58    let mut labels = ProductionVec::new(*control);
59    labels.reserve(projections.len())?;
60    for (index, projection) in projections.iter().enumerate() {
61        control.check()?;
62        let label = if let Some(alias) = aliases.get(index) {
63            Label::Borrowed(alias)
64        } else {
65            projection_label(projection, control)?
66        };
67        labels.push_produced(control.finish(label, control.empty_reservation())?)?;
68    }
69    Ok(ProjectionLabels {
70        labels: labels.finish()?,
71    })
72}
73
74/// Compute a projection's `PostgreSQL` output column name. Standalone expressions use `?column?`; repeated labels remain repeated until the final named-map compatibility boundary.
75pub fn projection_label_at(projection: &ProjectionPlan) -> String {
76    projection_label(projection, &ProductionControl::uncontrolled())
77        .expect("ordinary label observation cannot be cancelled or limited")
78        .into_uncontrolled()
79}
80
81/// Lend one projection label through an observation, admitting any decoding workspace and retaining it until the callback returns.
82pub fn with_projection_label<T>(
83    projection: &ProjectionPlan,
84    control: &ProductionControl<'_>,
85    observe: impl FnOnce(&str) -> Result<T, SQLError>,
86) -> Result<T, SQLError> {
87    let label = projection_label(projection, control)?;
88    let result = observe(label.as_str())?;
89    control.check()?;
90    Ok(result)
91}
92
93fn projection_label<'a>(
94    projection: &'a ProjectionPlan,
95    control: &ProductionControl<'_>,
96) -> Result<Label<'a>, SQLError> {
97    control.check()?;
98    if let Some(alias) = &projection.alias {
99        return Ok(Label::Borrowed(alias));
100    }
101    let mut expression = &projection.expr;
102    while let ScalarExpr::Collated { expr, .. } = expression {
103        control.check()?;
104        expression = expr;
105    }
106    Ok(match expression {
107        ScalarExpr::Column(column) | ScalarExpr::QualifiedColumn { column, .. } => {
108            Label::Borrowed(column)
109        }
110        ScalarExpr::Star | ScalarExpr::QualifiedStar(_) => Label::Borrowed("*"),
111        ScalarExpr::Func {
112            name,
113            binding,
114            args,
115            ..
116        } => match field_selection_name(binding.as_ref(), args.get(1)) {
117            Some(name) => Label::Borrowed(name),
118            None => function_label(name, binding.as_ref(), control)?,
119        },
120        ScalarExpr::WindowCall { name, .. } => function_label(name, None, control)?,
121        _ => Label::Borrowed("?column?"),
122    })
123}
124
125/// `FigureColname` names a field selection by its field.
126pub(crate) fn field_selection_label<E: FieldNameLiteral>(
127    binding: Option<&FunctionBinding>,
128    field: Option<&E>,
129) -> Option<String> {
130    field_selection_name(binding, field).map(str::to_owned)
131}
132
133fn field_selection_name<'a, E: FieldNameLiteral>(
134    binding: Option<&FunctionBinding>,
135    field: Option<&'a E>,
136) -> Option<&'a str> {
137    (binding.and_then(|binding| binding.dispatch) == Some(FunctionDispatch::FieldSelect))
138        .then(|| field.and_then(FieldNameLiteral::field_name))
139        .flatten()
140}
141
142/// The field name literal of a field selection in parsed or planned expressions.
143pub(crate) trait FieldNameLiteral {
144    fn field_name(&self) -> Option<&str>;
145}
146
147impl FieldNameLiteral for ScalarExpr {
148    fn field_name(&self) -> Option<&str> {
149        match self {
150            ScalarExpr::Literal(uqa_core::Value::Str(field)) => Some(field),
151            _ => None,
152        }
153    }
154}
155
156impl FieldNameLiteral for crate::ast::Expr {
157    fn field_name(&self) -> Option<&str> {
158        match self {
159            crate::ast::Expr::Literal(uqa_core::Value::Str(field)) => Some(field),
160            _ => None,
161        }
162    }
163}
164
165pub fn function_projection_label(name: &str, binding: Option<&FunctionBinding>) -> String {
166    function_label(name, binding, &ProductionControl::uncontrolled())
167        .expect("ordinary label decoding cannot be cancelled or limited")
168        .into_uncontrolled()
169}
170
171pub(crate) fn rule_function_label<E: FieldNameLiteral>(
172    name: &str,
173    binding: Option<&FunctionBinding>,
174    field: Option<&E>,
175    control: &ProductionControl<'_>,
176) -> Result<Produced<String>, SQLError> {
177    if let Some(name) = field_selection_name(binding, field) {
178        return Ok(control.copy_text(name)?);
179    }
180    let label = function_label(name, binding, control)?;
181    Ok(control.copy_text(label.as_str())?)
182}
183
184fn function_label<'a>(
185    name: &'a str,
186    binding: Option<&FunctionBinding>,
187    control: &ProductionControl<'_>,
188) -> Result<Label<'a>, SQLError> {
189    control.check()?;
190    // Operators and other syntax that the parser lowers to calls have no name of their own.
191    if matches!(
192        binding.and_then(|binding| binding.dispatch),
193        Some(
194            FunctionDispatch::NumericOperator(_)
195                | FunctionDispatch::Pattern { .. }
196                | FunctionDispatch::Concat { .. }
197                | FunctionDispatch::ArrayConcat
198                | FunctionDispatch::ArrayAppend
199                | FunctionDispatch::ArrayPrepend
200                | FunctionDispatch::IsDistinct
201                | FunctionDispatch::DistinctNot
202                | FunctionDispatch::RowDistinct
203                | FunctionDispatch::ValueIsDistinct
204                | FunctionDispatch::ValueNullTest { .. }
205                | FunctionDispatch::BooleanTest(_)
206                | FunctionDispatch::AnyOperator
207                | FunctionDispatch::AllOperator
208                | FunctionDispatch::BetweenSymmetric
209                | FunctionDispatch::JsonExtract { .. }
210        )
211    ) {
212        return Ok(Label::Borrowed("?column?"));
213    }
214    let label = crate::compiler::parse_regobject_name_with_control(name, control)?
215        .map_or(Label::Borrowed(name), Label::Decoded);
216    if operator_call(label.as_str()) {
217        return Ok(Label::Borrowed("?column?"));
218    }
219    Ok(label)
220}
221
222/// The calls the parser lowers operator syntax to under names no `PostgreSQL` function has: `||`, `@@`, `@?`, `@>`, `<@`, `&&`, `?`, `?|`, `?&`, `#-`, `~`, `~*`, `LIKE`, `ILIKE` and `SIMILAR TO`.
223fn operator_call(name: &str) -> bool {
224    matches!(
225        name,
226        "fts_match"
227            | "jsonpath_exists"
228            | "contains_op"
229            | "contained_by_op"
230            | "array_overlap"
231            | "json_has_key"
232            | "json_has_any_key"
233            | "json_has_all_keys"
234            | "json_delete_path"
235    )
236}
237
238/// Observe ordered positional output labels without copying the input descriptor. Explicit source aliases override individual labels. A set operation inherits its left input's names; VALUES generates names for its first row. Return false only when the root has no output descriptor. Temporary decoded/generated labels retain their own leases through the callback and are released before the next label.
239pub fn visit_query_output_columns(
240    mut query: &QueryPlan,
241    aliases: &[String],
242    control: &ProductionControl<'_>,
243    visitor: &mut impl FnMut(&str) -> Result<(), SQLError>,
244) -> Result<bool, SQLError> {
245    control.check()?;
246    while let RelationalPlan::SetOp { left, .. } = &query.root {
247        control.check()?;
248        query = left;
249    }
250    match &query.root {
251        RelationalPlan::QueryBlock(block) => {
252            for (position, projection) in block.projections.iter().enumerate() {
253                control.check()?;
254                if let Some(alias) = aliases.get(position) {
255                    visitor(alias)?;
256                } else {
257                    with_projection_label(projection, control, &mut *visitor)?;
258                }
259            }
260        }
261        RelationalPlan::Values { rows, .. } => {
262            let Some(row) = rows.first() else {
263                return Ok(false);
264            };
265            for position in 0..row.len() {
266                control.check()?;
267                if let Some(alias) = aliases.get(position) {
268                    visitor(alias)?;
269                } else {
270                    let label = control.format(format_args!("column{}", position + 1))?;
271                    visitor(&label)?;
272                }
273            }
274        }
275        RelationalPlan::SetOp { .. } => unreachable!("leftmost input"),
276    }
277    control.check()?;
278    Ok(true)
279}
280
281#[cfg(test)]
282mod tests;