Skip to main content

uqa_execution/query/
cypher.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Graph invocation and physical row construction for SQL Cypher table functions.
8
9use std::collections::BTreeMap;
10
11use uqa_core::Value;
12use uqa_graph::cypher::{CypherError, ResultRow};
13use uqa_sql::{semantics::age_cypher, SQLError, ScalarExpr};
14use uqa_storage::StorageBackendResult;
15
16use super::graph_effects::query_is_mutating;
17
18/// Live graph access within the caller's existing statement and transaction boundary.
19pub trait CypherTableRuntime {
20    fn current_transaction_is_read_only(&self) -> bool;
21    fn has_graph(&self, name: &str) -> StorageBackendResult<bool>;
22    fn run_cypher(
23        &self,
24        graph: &str,
25        query: &str,
26        params: BTreeMap<String, Value>,
27    ) -> Result<(Vec<String>, Vec<ResultRow>), CypherError>;
28}
29
30pub fn build_rows(
31    runtime: &dyn CypherTableRuntime,
32    args: &[ScalarExpr],
33    evaluated: &[Value],
34    column_aliases: &[String],
35    column_types: &[String],
36) -> Result<Vec<Vec<Value>>, SQLError> {
37    let (graph, query) = age_cypher::analyze_call(args, evaluated, column_aliases)?;
38    if runtime.current_transaction_is_read_only() && query_is_mutating(&query)? {
39        return Err(SQLError::Routine {
40            sqlstate: "25006".into(),
41            message: "cannot execute SELECT in a read-only transaction".into(),
42        });
43    }
44    if !runtime
45        .has_graph(&graph)
46        .map_err(|error| crate::storage_errors::storage_error("read graph catalog", &error))?
47    {
48        return Err(SQLError::Unsupported(format!(
49            "graph \"{graph}\" does not exist"
50        )));
51    }
52
53    let params = match evaluated.get(2) {
54        Some(value) => age_cypher::parameter_map(value)?,
55        None => BTreeMap::new(),
56    };
57    let (cypher_columns, cypher_rows) =
58        runtime
59            .run_cypher(&graph, &query, params)
60            .map_err(|error| match error {
61                CypherError::MissingLabelRelation(relation) => SQLError::UnknownTable(relation),
62                error @ CypherError::Backend(_) => crate::storage_errors::storage_error(
63                    "cypher",
64                    &uqa_storage::StorageBackendError::backend("graph", error),
65                ),
66                CypherError::SerializationFailure(message) => SQLError::Routine {
67                    sqlstate: "40001".into(),
68                    message,
69                },
70                other => SQLError::Unsupported(format!("cypher: {other}")),
71            })?;
72    if !cypher_columns.is_empty() && cypher_columns.len() != column_aliases.len() {
73        return Err(SQLError::TypeMismatch(
74            "return row and column definition list do not match".into(),
75        ));
76    }
77
78    let mut out = Vec::with_capacity(cypher_rows.len());
79    for src in cypher_rows {
80        let mut row = Vec::with_capacity(column_aliases.len());
81        for (idx, target_col) in column_aliases.iter().enumerate() {
82            let value = cypher_columns
83                .get(idx)
84                .and_then(|source_col| src.get(source_col))
85                .cloned()
86                .unwrap_or(Value::Null);
87            let declared = column_types.get(idx).map_or("agtype", String::as_str);
88            let value = age_cypher::coerce_to_column_type(value, declared, target_col)?;
89            row.push(value);
90        }
91        out.push(row);
92    }
93    Ok(out)
94}
95
96#[cfg(test)]
97mod tests;