Skip to main content

uqa_execution/query/
table_functions.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Table-function call metadata and positional result transport.
8
9use crate::functions::{SQLTableFunctionResult, SQLTableFunctionStream};
10use crate::ScalarExpr;
11use uqa_core::Value;
12use uqa_sql::SQLError;
13
14#[derive(Clone, Copy)]
15pub struct TableFunctionCall<'a> {
16    pub name: &'a str,
17    pub binding: Option<&'a uqa_sql::ast::FunctionBinding>,
18    pub output_name: &'a str,
19    pub relations: Option<&'a uqa_sql::ast::OperatorJoinRelations>,
20    pub args: &'a [ScalarExpr],
21    /// State owned by the caller's already-bound argument expressions. A one-shot
22    /// caller may leave this absent and let the table-function entry bind them.
23    pub function_states: Option<&'a crate::scalar::FunctionCallStates>,
24    pub alias: Option<&'a str>,
25    pub column_aliases: &'a [String],
26    pub ordinality: bool,
27    pub column_types: &'a [String],
28}
29
30/// SQL-visible column metadata paired with positional table-function rows. Column names never participate in row transport, so duplicate and unnamed outputs remain distinct physical attributes.
31pub struct TableFunctionRows {
32    pub columns: Vec<String>,
33    pub rows: crate::PhysicalProjectRows,
34}
35
36impl TableFunctionRows {
37    pub fn new(columns: Vec<String>, rows: crate::PhysicalProjectRows) -> Self {
38        Self { columns, rows }
39    }
40
41    pub fn materialized(columns: Vec<String>, rows: Vec<Vec<Value>>) -> Self {
42        Self::new(
43            columns,
44            Box::new(
45                rows.into_iter()
46                    .map(|values| Ok(crate::PhysicalRow::from_values(values))),
47            ),
48        )
49    }
50}
51
52pub fn registered_table_function_rows(
53    name: &str,
54    result: SQLTableFunctionResult,
55    _alias: Option<&str>,
56    column_aliases: &[String],
57) -> Result<TableFunctionRows, SQLError> {
58    if result.columns.is_empty() {
59        return Err(SQLError::TypeMismatch(format!(
60            "table function `{name}` returned no columns"
61        )));
62    }
63    let columns: Vec<String> = result
64        .columns
65        .iter()
66        .enumerate()
67        .map(|(idx, column)| {
68            column_aliases
69                .get(idx)
70                .cloned()
71                .unwrap_or_else(|| column.clone())
72        })
73        .collect();
74    let mut out = Vec::with_capacity(result.rows.len());
75    for values in result.rows {
76        if values.len() != result.columns.len() {
77            return Err(SQLError::TypeMismatch(format!(
78                "table function `{name}` row has {} values for {} columns",
79                values.len(),
80                result.columns.len()
81            )));
82        }
83        out.push(values);
84    }
85    Ok(TableFunctionRows::materialized(columns, out))
86}
87
88pub fn registered_table_function_row_stream(
89    name: &str,
90    result: SQLTableFunctionStream,
91    _alias: Option<&str>,
92    column_aliases: &[String],
93) -> Result<TableFunctionRows, SQLError> {
94    if result.columns.is_empty() {
95        return Err(SQLError::TypeMismatch(format!(
96            "table function `{name}` returned no columns"
97        )));
98    }
99    let expected_width = result.columns.len();
100    let columns = result
101        .columns
102        .iter()
103        .enumerate()
104        .map(|(index, column)| {
105            column_aliases
106                .get(index)
107                .cloned()
108                .unwrap_or_else(|| column.clone())
109        })
110        .collect::<Vec<_>>();
111    let function_name = name.to_string();
112    Ok(TableFunctionRows::new(
113        columns,
114        Box::new(
115            result
116                .rows
117                .map(move |values| -> crate::ExecResult<crate::PhysicalRow> {
118                    let values = values.map_err(crate::ExecError::from)?;
119                    if values.len() != expected_width {
120                        return Err(SQLError::TypeMismatch(format!(
121                "table function `{function_name}` row has {} values for {expected_width} columns",
122                values.len()
123            ))
124                        .into());
125                    }
126                    Ok(crate::PhysicalRow::from_values(values))
127                }),
128        ),
129    ))
130}
131
132pub mod values;
133
134pub mod rows_from;
135
136mod acl;
137mod analyzers;
138pub use analyzers::analyze_text;
139pub mod context;
140mod deferred;
141pub use deferred::DeferredTableFunctionRows;
142mod dispatch;
143mod graphs;
144mod records;
145mod regular_expressions;
146mod stream;
147pub use stream::{build_table_function_row_stream_with_row, deferred_table_function_columns};