uqa-sql 0.5.4

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Projection labels, star expansion, and DML row-image schemas.

use super::{DOC_ID_COLUMN, TABLE_OID_COLUMN};
use crate::ast::ReturningAliases;
use crate::plan::ProjectionPlan;
use crate::{ColumnIdentity, RowSchema, SQLError, ScalarExpr};

pub fn projection_columns(projections: &[ProjectionPlan]) -> Vec<String> {
    projections.iter().map(projection_label_at).collect()
}

/// Resolve an SQL92 output ordinal against the expanded SELECT list before using its type or physical expression.
pub fn query_output_position(position: i64, width: usize, clause: &str) -> Result<usize, SQLError> {
    usize::try_from(position)
        .ok()
        .and_then(|position| position.checked_sub(1))
        .filter(|position| *position < width)
        .ok_or_else(|| output_position_error(clause, position))
}

pub fn output_position_error(clause: &str, position: i64) -> SQLError {
    SQLError::Routine {
        sqlstate: "42P10".into(),
        message: format!("{clause} position {position} is not in the select list"),
    }
}

/// Compute a projection's `PostgreSQL` output column name. Standalone expressions use `?column?`; repeated labels remain repeated until the final named-map compatibility boundary.
pub fn projection_label_at(proj: &ProjectionPlan) -> String {
    if let Some(a) = &proj.alias {
        return a.clone();
    }
    let mut expression = &proj.expr;
    while let ScalarExpr::Collated { expr, .. } = expression {
        expression = expr;
    }
    match expression {
        ScalarExpr::Column(c) => c.clone(),
        ScalarExpr::QualifiedColumn { column, .. } => column.clone(),
        ScalarExpr::Star | ScalarExpr::QualifiedStar(_) => "*".into(),
        ScalarExpr::Func {
            name,
            binding,
            args,
            ..
        } => field_selection_label(binding.as_ref(), args.get(1))
            .unwrap_or_else(|| function_projection_label(name, binding.as_ref())),
        ScalarExpr::WindowCall { name, .. } => function_projection_label(name, None),
        _ => "?column?".into(),
    }
}

/// `FigureColname` names a field selection by its field.
pub(crate) fn field_selection_label<E: FieldNameLiteral>(
    binding: Option<&crate::ast::FunctionBinding>,
    field: Option<&E>,
) -> Option<String> {
    (binding.and_then(|binding| binding.dispatch)
        == Some(crate::ast::FunctionDispatch::FieldSelect))
    .then(|| field.and_then(FieldNameLiteral::field_name))
    .flatten()
    .map(str::to_owned)
}

/// The field name literal of a field selection in parsed or planned expressions.
pub(crate) trait FieldNameLiteral {
    fn field_name(&self) -> Option<&str>;
}

impl FieldNameLiteral for ScalarExpr {
    fn field_name(&self) -> Option<&str> {
        match self {
            ScalarExpr::Literal(uqa_core::Value::Str(field)) => Some(field),
            _ => None,
        }
    }
}

impl FieldNameLiteral for crate::ast::Expr {
    fn field_name(&self) -> Option<&str> {
        match self {
            crate::ast::Expr::Literal(uqa_core::Value::Str(field)) => Some(field),
            _ => None,
        }
    }
}

pub fn function_projection_label(
    name: &str,
    binding: Option<&crate::ast::FunctionBinding>,
) -> String {
    // Operators and other syntax that the parser lowers to calls have no name of their own.
    if matches!(
        binding.and_then(|binding| binding.dispatch),
        Some(
            crate::ast::FunctionDispatch::NumericOperator(_)
                | crate::ast::FunctionDispatch::Pattern { .. }
                | crate::ast::FunctionDispatch::Concat { .. }
                | crate::ast::FunctionDispatch::ArrayConcat
                | crate::ast::FunctionDispatch::ArrayAppend
                | crate::ast::FunctionDispatch::ArrayPrepend
                | crate::ast::FunctionDispatch::IsDistinct
                | crate::ast::FunctionDispatch::ValueIsDistinct
                | crate::ast::FunctionDispatch::ValueNullTest { .. }
                | crate::ast::FunctionDispatch::BooleanTest(_)
                | crate::ast::FunctionDispatch::AnyOperator
                | crate::ast::FunctionDispatch::AllOperator
                | crate::ast::FunctionDispatch::BetweenSymmetric
                | crate::ast::FunctionDispatch::JsonExtract { .. }
        )
    ) {
        return "?column?".into();
    }
    let name = crate::parse_regobject_name(name)
        .and_then(|mut names| names.pop())
        .unwrap_or_else(|| name.to_string());
    if operator_call(&name) {
        return "?column?".into();
    }
    name
}

/// The calls the parser lowers operator syntax to under names no `PostgreSQL` function has: `||`, `@@`, `@?`, `@>`, `<@`, `&&`, `?`, `?|`, `?&`, `#-`, `~`, `~*`, `LIKE`, `ILIKE` and `SIMILAR TO`.
fn operator_call(name: &str) -> bool {
    matches!(
        name,
        "fts_match"
            | "jsonpath_exists"
            | "contains_op"
            | "contained_by_op"
            | "array_overlap"
            | "json_has_key"
            | "json_has_any_key"
            | "json_has_all_keys"
            | "json_delete_path"
    )
}

pub fn expand_from_star_columns(
    columns: Vec<String>,
    projections: &[ProjectionPlan],
    source_schema: &RowSchema,
) -> Result<Vec<String>, SQLError> {
    let mut output = Vec::new();
    for (position, projection) in projections.iter().enumerate() {
        match &projection.expr {
            ScalarExpr::Star => {
                output.extend(
                    source_schema
                        .columns()
                        .iter()
                        .enumerate()
                        .filter(|(position, _)| {
                            visible_projection_source_position(source_schema, *position)
                        })
                        .map(|(source_position, column)| {
                            source_schema
                                .public_name(source_position)
                                .unwrap_or(column)
                                .to_string()
                        }),
                );
            }
            ScalarExpr::QualifiedStar(qualifier) => {
                let qualified_columns = source_schema
                    .qualified_star_position_layout(qualifier)
                    .into_iter()
                    .filter(|(_, logical, _, _)| {
                        logical.is_none_or(|position| {
                            visible_projection_source_position(source_schema, position)
                        })
                    })
                    .map(|(column, _, _, _)| column)
                    .collect::<Vec<_>>();
                if qualified_columns.is_empty() {
                    return Err(SQLError::UnknownTable(qualifier.clone()));
                }
                output.extend(qualified_columns);
            }
            _ => output.push(columns[position].clone()),
        }
    }
    Ok(output)
}

pub fn bound_projection_expression(schema: &RowSchema, position: usize) -> ScalarExpr {
    let Some(identity) = schema.identity(position) else {
        return ScalarExpr::Position(position);
    };
    if let Some(qualifier) = identity.qualifier() {
        if schema.qualified_position(qualifier, identity.column()) == Some(position) {
            return ScalarExpr::qualified_column(qualifier, identity.column());
        }
    } else if schema.unqualified_position(identity.column()) == Some(position) {
        return ScalarExpr::Column(identity.column().to_string());
    }
    ScalarExpr::Position(position)
}

pub fn expand_bound_projection_stars(
    projections: &[ProjectionPlan],
    schema: &RowSchema,
) -> Result<Vec<ProjectionPlan>, SQLError> {
    let mut expanded = Vec::new();
    for projection in projections {
        match &projection.expr {
            ScalarExpr::Star => {
                for (position, column) in schema.columns().iter().enumerate() {
                    if !visible_projection_source_position(schema, position) {
                        continue;
                    }
                    expanded.push(ProjectionPlan {
                        expr: bound_projection_expression(schema, position),
                        alias: Some(schema.public_name(position).unwrap_or(column).to_string()),
                    });
                }
            }
            ScalarExpr::QualifiedStar(qualifier) => {
                let layout = schema.qualified_star_position_layout(qualifier);
                if layout.is_empty() {
                    return Err(SQLError::UnknownTable(qualifier.clone()));
                }
                for (column, logical, _, _) in layout {
                    if logical.is_some_and(|position| {
                        !visible_projection_source_position(schema, position)
                    }) {
                        continue;
                    }
                    expanded.push(ProjectionPlan {
                        expr: logical.map_or_else(
                            || ScalarExpr::qualified_column(qualifier, &column),
                            |position| bound_projection_expression(schema, position),
                        ),
                        alias: Some(column),
                    });
                }
            }
            _ => expanded.push(projection.clone()),
        }
    }
    Ok(expanded)
}

pub fn visible_projection_source_position(schema: &RowSchema, position: usize) -> bool {
    schema.wildcard_position_visible(position)
}

pub fn returning_context_schema(
    columns: &[String],
    types: &[Option<crate::ast::ColumnType>],
    composite_width: usize,
    target_qualifier: &str,
    aliases: &ReturningAliases,
) -> RowSchema {
    let target =
        RowSchema::with_qualified_types(target_qualifier, columns.to_vec(), types.to_vec());
    returning_schema_for_target(target, composite_width, aliases)
}

/// 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.
pub fn returning_schema_for_target(
    target: RowSchema,
    composite_width: usize,
    aliases: &ReturningAliases,
) -> RowSchema {
    let width = target.len();
    assert_eq!(
        target.physical_width(),
        width,
        "RETURNING target must be positional"
    );
    assert!(
        composite_width <= width,
        "RETURNING user columns must belong to the target"
    );
    debug_assert!((0..width).all(|position| target.slot(position) == Some(position)));
    let target = RowSchema::with_wildcard_hidden_positions(&target, composite_width..width);
    let types = target.column_types();
    let hidden_types = types
        .iter()
        .cloned()
        .chain(types.iter().cloned())
        .collect::<Vec<_>>();
    let schema = RowSchema::append_hidden_typed(&target, &hidden_types);
    let identity_aliases = target
        .columns()
        .iter()
        .enumerate()
        .flat_map(|(position, column)| {
            [
                (
                    ColumnIdentity::qualified(&aliases.old, column),
                    width + position,
                    types[position].clone(),
                ),
                (
                    ColumnIdentity::qualified(&aliases.new, column),
                    width * 2 + position,
                    types[position].clone(),
                ),
            ]
        })
        .collect::<Vec<_>>();
    let mut schema = RowSchema::with_physical_identity_aliases(&schema, &identity_aliases);
    for (binding, oid) in target.collation_overrides() {
        let crate::schema::CollationBinding::Column(position) = binding else {
            continue;
        };
        for qualifier in [&aliases.old, &aliases.new] {
            let identity = ColumnIdentity::qualified(qualifier, &target.columns()[position]);
            schema = schema
                .with_collation_override(crate::schema::CollationBinding::Alias(&identity), oid)
                .expect("RETURNING image alias retains its target's type");
        }
    }
    schema
}

pub fn returning_expression_schema(
    target: &RowSchema,
    target_qualifier: &str,
    aliases: &ReturningAliases,
    supplemental: Option<&RowSchema>,
) -> RowSchema {
    let composite_width = target.len();
    let (columns, types) = target_with_system_columns(target);
    let width = columns.len();
    let schema = RowSchema::with_qualified_types(target_qualifier, columns, types)
        .with_column_collations((0..width).map(|position| target.column_collation(position)));
    let target = returning_schema_for_target(schema, composite_width, aliases);
    supplemental.map_or(target.clone(), |source| {
        RowSchema::join(&target, source, std::iter::empty())
    })
}

/// 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.
#[must_use]
pub fn mutation_clause_schema(
    target: &RowSchema,
    target_qualifier: &str,
    supplemental: Option<&RowSchema>,
) -> RowSchema {
    let composite_width = target.len();
    let (columns, types) = target_with_system_columns(target);
    let width = columns.len();
    let target = RowSchema::with_wildcard_hidden_positions(
        &RowSchema::with_qualified_types(target_qualifier, columns, types)
            .with_column_collations((0..width).map(|position| target.column_collation(position))),
        composite_width..width,
    );
    supplemental.map_or(target.clone(), |source| {
        RowSchema::join(&target, source, std::iter::empty())
    })
}

/// The target's columns followed by the system columns a statement can name on it.
fn target_with_system_columns(
    target: &RowSchema,
) -> (Vec<String>, Vec<Option<crate::ast::ColumnType>>) {
    let mut columns = target.columns().to_vec();
    let mut types = target.column_types().to_vec();
    if !columns.iter().any(|column| column == DOC_ID_COLUMN) {
        columns.push(DOC_ID_COLUMN.into());
        types.push(Some(crate::ast::ColumnType::BigInteger));
    }
    columns.push(TABLE_OID_COLUMN.into());
    types.push(Some(crate::ast::ColumnType::Oid));
    columns.push(crate::semantics::XMIN_COLUMN.into());
    types.push(Some(crate::ast::ColumnType::Xid));
    (columns, types)
}

pub fn query_plan_output_columns(plan: &crate::plan::QueryPlan) -> Option<Vec<String>> {
    match &plan.root {
        crate::plan::RelationalPlan::QueryBlock(block) => {
            Some(projection_columns(&block.projections))
        }
        crate::plan::RelationalPlan::SetOp { left, .. } => query_plan_output_columns(left),
        crate::plan::RelationalPlan::Values { rows, .. } => rows.first().map(|row| {
            (1..=row.len())
                .map(|index| format!("column{index}"))
                .collect()
        }),
    }
}

pub fn should_defer_distinct_limit(stmt: &crate::plan::QueryBlockPlan) -> bool {
    stmt.distinct && (stmt.limit.is_some() || stmt.offset.is_some())
}

pub fn select_execution_stmt(
    stmt: &crate::plan::QueryBlockPlan,
    defer_distinct_limit: bool,
) -> crate::plan::QueryBlockPlan {
    if !defer_distinct_limit {
        return stmt.clone();
    }
    let mut exec_stmt = stmt.clone();
    exec_stmt.limit = None;
    exec_stmt.offset = None;
    exec_stmt
}