Skip to main content

uqa_sql/binding/
catalog_sources.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Engine-independent catalog source binding.
8
9use crate::ast::OperatorJoinRelations;
10use crate::RowSchema;
11use crate::SQLError;
12
13use crate::catalog::analysis::CatalogReadView;
14use crate::catalog::resolution::RelationNameResolution;
15
16use super::analysis;
17
18/// Bind both operator-join relations independently so each retrieval operand has its own namespace.
19pub(super) fn operator_join_relation_schemas(
20    catalog: &CatalogReadView,
21    resolution: &RelationNameResolution,
22    relations: Option<&OperatorJoinRelations>,
23) -> Result<(RowSchema, RowSchema), SQLError> {
24    let relations = relations.ok_or_else(|| {
25        SQLError::TypeMismatch("operator join requires left and right table identifiers".into())
26    })?;
27    Ok((
28        relation_schema(catalog, resolution, &relations.left, "left")?,
29        relation_schema(catalog, resolution, &relations.right, "right")?,
30    ))
31}
32
33fn relation_schema(
34    catalog: &CatalogReadView,
35    resolution: &RelationNameResolution,
36    relation: &str,
37    side: &str,
38) -> Result<RowSchema, SQLError> {
39    let resolved = catalog
40        .table_name_resolved(resolution, relation)?
41        .ok_or_else(|| SQLError::UnknownTable(relation.to_string()))?;
42    let identity = crate::RelationIdentity::from_legacy_name(&resolved).map_err(|error| {
43        SQLError::Internal(format!(
44            "decode operator join {side} relation `{resolved}` schema: {error}"
45        ))
46    })?;
47    let table = catalog
48        .table_resolved(resolution, &resolved)?
49        .ok_or_else(|| SQLError::UnknownTable(relation.to_string()))?;
50    let schema = RowSchema::with_column_definitions(Some(&identity.name), &table.columns);
51    Ok(analysis::with_table_pseudo_columns(&schema, &identity.name))
52}
53
54/// Output column names of a user-defined routine used as a FROM source: OUT / INOUT / `RETURNS TABLE` parameter names. `None` when the name is not a user routine or its result is a single unnamed column, which keeps the function-name default.
55pub fn user_function_output_columns(
56    catalog: &dyn crate::catalog::analysis::AnalysisCatalog,
57    resolution: &RelationNameResolution,
58    name: &str,
59) -> Result<Option<Vec<String>>, SQLError> {
60    let Some(overloads) = catalog.sql_functions(resolution, name)? else {
61        return Ok(None);
62    };
63    for function in &overloads {
64        if let Some(columns) = crate::semantics::user_function_output_columns_for(function) {
65            return Ok(Some(columns));
66        }
67    }
68    Ok(None)
69}
70
71#[cfg(test)]
72mod tests {
73    use std::collections::BTreeMap;
74
75    use crate::ast::{ColumnDef, ColumnType};
76
77    use super::operator_join_relation_schemas;
78    use crate::RelationIdentity;
79
80    #[test]
81    fn relation_schema_binds_against_catalog_fixture_without_engine() {
82        let column = ColumnDef {
83            collation_oid: None,
84            name: "id".into(),
85            ty: ColumnType::BigInteger,
86            object_id: None,
87            attribute_number: None,
88            missing_value: None,
89            primary_key: true,
90            not_null: true,
91            not_null_explicit: false,
92            not_null_name: None,
93            not_null_identity: None,
94            not_null_validated: true,
95            not_null_no_inherit: false,
96            not_null_is_local: true,
97            auto_increment: None,
98            unique: false,
99            default: None,
100            generated: None,
101            check: None,
102            check_name: None,
103            check_enforced: true,
104            check_validated: true,
105            check_no_inherit: false,
106            check_is_local: true,
107            check_object_id: None,
108            check_catalog_oid: None,
109            default_catalog_oid: None,
110            references: None,
111        };
112        let catalog = crate::binding::fixture::catalog(BTreeMap::from([
113            (
114                RelationIdentity::new("app", "documents"),
115                crate::binding::fixture::table_definition(vec![column.clone()]),
116            ),
117            (
118                RelationIdentity::new("app", "archive"),
119                crate::binding::fixture::table_definition(vec![column]),
120            ),
121        ]));
122        let resolution =
123            crate::binding::fixture::resolution(vec!["app".into()], "pg_temp_fixture".into());
124        let relations = crate::ast::OperatorJoinRelations {
125            left: "documents".into(),
126            right: "archive".into(),
127        };
128        let (left, right) =
129            operator_join_relation_schemas(&catalog, &resolution, Some(&relations)).unwrap();
130        assert!(left.has_qualified_column("documents", "id"));
131        assert!(right.has_qualified_column("archive", "id"));
132        assert_eq!(left.column_type(0), Some(&ColumnType::BigInteger));
133        assert_eq!(right.column_type(0), Some(&ColumnType::BigInteger));
134    }
135}