Skip to main content

uqa_execution/query/
graph_lifecycle.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Native and AGE graph command scheduling and result values.
8
9use crate::storage_errors::storage_error;
10use crate::{eval_scalar, ScalarEvalContext};
11use uqa_core::{ScoredEntry, Value};
12use uqa_graph::{GraphLabelInfo, LabelKind};
13use uqa_sql::{
14    expr::EngineHook,
15    semantics::graph_commands::{
16        age_error, eval_age_bool_with, eval_age_graph_name_with, eval_age_name_with,
17        graph_create_name, graph_drop_name, require_age_arity, validate_graph_drop_cascade,
18        AGE_DEPENDENT_OBJECTS_STILL_EXIST, AGE_DUPLICATE_SCHEMA, AGE_FEATURE_NOT_SUPPORTED,
19        AGE_INVALID_PARAMETER_VALUE, AGE_UNDEFINED_SCHEMA, AGE_UNDEFINED_TABLE,
20    },
21    SQLError, SQLParam, ScalarExpr,
22};
23use uqa_storage::{StorageBackendError, StorageBackendResult};
24
25/// Graph catalog operations inside the public graph API's existing transaction boundary.
26pub trait GraphLifecycle {
27    fn has_graph(&self, name: &str) -> StorageBackendResult<bool>;
28    fn has_namespace(&self, name: &str) -> StorageBackendResult<bool>;
29    fn create_graph(&self, name: String) -> StorageBackendResult<bool>;
30    fn drop_graph(&self, name: &str) -> StorageBackendResult<bool>;
31    fn list_graph_labels(&self, graph: &str) -> StorageBackendResult<Option<Vec<GraphLabelInfo>>>;
32    fn create_graph_label(
33        &self,
34        graph: &str,
35        label: &str,
36        kind: LabelKind,
37    ) -> StorageBackendResult<bool>;
38    fn drop_graph_label(&self, graph: &str, label: &str) -> StorageBackendResult<bool>;
39    fn graph_label_relation_dependents(
40        &self,
41        graph: &str,
42        label: &str,
43    ) -> StorageBackendResult<Vec<String>>;
44    fn rename_graph(&self, from: &str, to: &str) -> StorageBackendResult<bool>;
45}
46
47pub fn run_graph_create(
48    runtime: &dyn GraphLifecycle,
49    args: &[ScalarExpr],
50    params: &[SQLParam],
51    hook: &dyn EngineHook,
52) -> Result<Vec<ScoredEntry>, SQLError> {
53    let ctx = ScalarEvalContext::new(None, params).with_function_hook(hook);
54    run_graph_create_with_evaluator(runtime, args, &mut |expr| eval_scalar(expr, &ctx))?;
55    Ok(Vec::new())
56}
57
58pub fn run_graph_create_with_evaluator(
59    runtime: &dyn GraphLifecycle,
60    args: &[ScalarExpr],
61    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
62) -> Result<bool, SQLError> {
63    let name = graph_create_name(args, evaluate)?;
64    runtime
65        .create_graph(name)
66        .map_err(|err| storage_error("create graph", &err))
67}
68
69pub fn run_graph_drop(
70    runtime: &dyn GraphLifecycle,
71    args: &[ScalarExpr],
72    params: &[SQLParam],
73    hook: &dyn EngineHook,
74) -> Result<Vec<ScoredEntry>, SQLError> {
75    let ctx = ScalarEvalContext::new(None, params).with_function_hook(hook);
76    run_graph_drop_with_evaluator(runtime, args, &mut |expr| eval_scalar(expr, &ctx))?;
77    Ok(Vec::new())
78}
79
80pub fn run_graph_drop_with_evaluator(
81    runtime: &dyn GraphLifecycle,
82    args: &[ScalarExpr],
83    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
84) -> Result<bool, SQLError> {
85    let name = graph_drop_name(args, evaluate)?;
86    let graph_exists = runtime
87        .has_graph(&name)
88        .map_err(|err| storage_error("read graph catalog", &err))?;
89    validate_graph_drop_cascade(&name, graph_exists, args.get(1), evaluate)?;
90    runtime
91        .drop_graph(&name)
92        .map_err(|err| storage_error("drop graph", &err))
93}
94
95fn age_graph_catalog_error(error: StorageBackendError) -> SQLError {
96    storage_error("read graph catalog", &error)
97}
98
99/// `SELECT create_graph('name')` with AGE semantics: validates the name,
100/// rejects duplicate graphs and namespace collisions, and returns void
101/// (SQL NULL). The graph namespace is reserved like AGE's `CREATE SCHEMA`.
102pub fn run_age_create_graph_with_evaluator(
103    runtime: &dyn GraphLifecycle,
104    args: &[ScalarExpr],
105    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
106) -> Result<Value, SQLError> {
107    require_age_arity("create_graph", args, 1..=1)?;
108    let name = eval_age_graph_name_with(&args[0], evaluate)?;
109    if !uqa_graph::age_names::is_valid_graph_name(&name) {
110        return Err(age_error(
111            AGE_INVALID_PARAMETER_VALUE,
112            "graph name is invalid",
113        ));
114    }
115    if runtime.has_graph(&name).map_err(age_graph_catalog_error)? {
116        return Err(age_error(
117            AGE_UNDEFINED_SCHEMA,
118            format!("graph \"{name}\" already exists"),
119        ));
120    }
121    if runtime
122        .has_namespace(&name)
123        .map_err(age_graph_catalog_error)?
124    {
125        return Err(age_error(
126            AGE_DUPLICATE_SCHEMA,
127            format!("schema \"{name}\" already exists"),
128        ));
129    }
130    runtime
131        .create_graph(name)
132        .map_err(|err| storage_error("create graph", &err))?;
133    Ok(Value::Null)
134}
135
136/// `SELECT drop_graph('name'[, cascade])` with AGE semantics: false uses
137/// `DROP SCHEMA ... RESTRICT` and succeeds only after every label relation is
138/// gone, while true removes surviving labels; success returns void.
139pub fn run_age_drop_graph_with_evaluator(
140    runtime: &dyn GraphLifecycle,
141    args: &[ScalarExpr],
142    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
143) -> Result<Value, SQLError> {
144    require_age_arity("drop_graph", args, 1..=2)?;
145    let name = eval_age_graph_name_with(&args[0], evaluate)?;
146    if !runtime.has_graph(&name).map_err(age_graph_catalog_error)? {
147        return Err(age_error(
148            AGE_UNDEFINED_SCHEMA,
149            format!("graph \"{name}\" does not exist"),
150        ));
151    }
152    let cascade = match args.get(1) {
153        Some(expr) => eval_age_bool_with(expr, "drop_graph.cascade", evaluate)?,
154        None => false,
155    };
156    if !cascade {
157        let labels = runtime
158            .list_graph_labels(&name)
159            .map_err(age_graph_catalog_error)?
160            .unwrap_or_default();
161        if !labels.is_empty() {
162            return Err(age_error(
163                AGE_DEPENDENT_OBJECTS_STILL_EXIST,
164                format!("cannot drop schema {name} because other objects depend on it"),
165            ));
166        }
167    }
168    runtime
169        .drop_graph(&name)
170        .map_err(|err| storage_error("drop graph", &err))?;
171    Ok(Value::Null)
172}
173
174/// `SELECT graph_exists('name')`: AGE returns an agtype boolean, which
175/// surfaces through SQL as the agtype text `true` / `false`.
176pub fn run_age_graph_exists_with_evaluator(
177    runtime: &dyn GraphLifecycle,
178    args: &[ScalarExpr],
179    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
180) -> Result<Value, SQLError> {
181    require_age_arity("graph_exists", args, 1..=1)?;
182    let name = eval_age_graph_name_with(&args[0], evaluate)?;
183    let exists = runtime.has_graph(&name).map_err(age_graph_catalog_error)?;
184    Ok(Value::Str(uqa_core::agtype::render(&Value::Bool(exists))))
185}
186
187/// Shared body of `create_vlabel` / `create_elabel`.
188fn run_age_create_label_with_evaluator(
189    runtime: &dyn GraphLifecycle,
190    function_name: &str,
191    kind: uqa_graph::LabelKind,
192    args: &[ScalarExpr],
193    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
194) -> Result<Value, SQLError> {
195    require_age_arity(function_name, args, 2..=2)?;
196    let graph = eval_age_name_with(&args[0], "graph name must not be NULL", evaluate)?;
197    let label = eval_age_name_with(&args[1], "label name must not be NULL", evaluate)?;
198    if !uqa_graph::age_names::is_valid_graph_name(&graph) {
199        return Err(age_error(
200            AGE_INVALID_PARAMETER_VALUE,
201            "graph name is invalid",
202        ));
203    }
204    if !uqa_graph::age_names::is_valid_label_name(&label) {
205        return Err(age_error(
206            AGE_INVALID_PARAMETER_VALUE,
207            "label name is invalid",
208        ));
209    }
210    if !runtime.has_graph(&graph).map_err(age_graph_catalog_error)? {
211        return Err(age_error(
212            AGE_UNDEFINED_SCHEMA,
213            format!("graph \"{graph}\" does not exist."),
214        ));
215    }
216    let labels = runtime
217        .list_graph_labels(&graph)
218        .map_err(age_graph_catalog_error)?
219        .unwrap_or_default();
220    if !labels
221        .iter()
222        .any(|entry| entry.name == kind.default_label_name())
223    {
224        return Err(age_error(
225            AGE_UNDEFINED_TABLE,
226            format!(
227                "relation \"{graph}.{}\" does not exist",
228                kind.default_label_name()
229            ),
230        ));
231    }
232    let created = runtime
233        .create_graph_label(&graph, &label, kind)
234        .map_err(|err| storage_error("create label", &err))?;
235    if !created {
236        return Err(age_error(
237            AGE_UNDEFINED_SCHEMA,
238            format!("label \"{label}\" already exists"),
239        ));
240    }
241    Ok(Value::Null)
242}
243
244/// `SELECT create_vlabel('graph', 'label')` with AGE semantics.
245pub fn run_age_create_vlabel_with_evaluator(
246    runtime: &dyn GraphLifecycle,
247    args: &[ScalarExpr],
248    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
249) -> Result<Value, SQLError> {
250    run_age_create_label_with_evaluator(
251        runtime,
252        "create_vlabel",
253        uqa_graph::LabelKind::Vertex,
254        args,
255        evaluate,
256    )
257}
258
259/// `SELECT create_elabel('graph', 'label')` with AGE semantics.
260pub fn run_age_create_elabel_with_evaluator(
261    runtime: &dyn GraphLifecycle,
262    args: &[ScalarExpr],
263    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
264) -> Result<Value, SQLError> {
265    run_age_create_label_with_evaluator(
266        runtime,
267        "create_elabel",
268        uqa_graph::LabelKind::Edge,
269        args,
270        evaluate,
271    )
272}
273
274/// `SELECT drop_label('graph', 'label'[, force])` with AGE semantics: the
275/// label relation is dropped together with every entity that carries the
276/// label, `force => true` is rejected exactly like AGE, and a default label
277/// is restricted only while user labels of the same kind inherit from it.
278pub fn run_age_drop_label_with_evaluator(
279    runtime: &dyn GraphLifecycle,
280    args: &[ScalarExpr],
281    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
282) -> Result<Value, SQLError> {
283    require_age_arity("drop_label", args, 2..=3)?;
284    let graph = eval_age_name_with(&args[0], "graph name must not be NULL", evaluate)?;
285    let label = eval_age_name_with(&args[1], "label name must not be NULL", evaluate)?;
286    let force = match args.get(2) {
287        Some(expr) => eval_age_bool_with(expr, "drop_label.force", evaluate)?,
288        None => false,
289    };
290    if !runtime.has_graph(&graph).map_err(age_graph_catalog_error)? {
291        return Err(age_error(
292            AGE_UNDEFINED_SCHEMA,
293            format!("graph \"{graph}\" does not exist"),
294        ));
295    }
296    let labels = runtime
297        .list_graph_labels(&graph)
298        .map_err(age_graph_catalog_error)?
299        .unwrap_or_default();
300    let Some(entry) = labels.iter().find(|entry| entry.name == label) else {
301        return Err(age_error(
302            AGE_UNDEFINED_TABLE,
303            format!("label \"{label}\" does not exist"),
304        ));
305    };
306    if force {
307        return Err(age_error(
308            AGE_FEATURE_NOT_SUPPORTED,
309            "force option is not supported yet",
310        ));
311    }
312    let dependent_views = runtime
313        .graph_label_relation_dependents(&graph, &label)
314        .map_err(|error| storage_error("inspect label dependencies", &error))?;
315    if !dependent_views.is_empty() {
316        return Err(age_error(
317            AGE_DEPENDENT_OBJECTS_STILL_EXIST,
318            format!("cannot drop table {graph}.{label} because other objects depend on it"),
319        ));
320    }
321    // AGE issues `DROP TABLE ... RESTRICT`: user label relations inherit from
322    // the default relation of their kind, while the graph catalog itself does
323    // not depend on either default relation.
324    if (entry.id == uqa_graph::VERTEX_DEFAULT_LABEL_ID
325        || entry.id == uqa_graph::EDGE_DEFAULT_LABEL_ID)
326        && labels.iter().any(|candidate| {
327            candidate.id >= uqa_graph::FIRST_USER_LABEL_ID && candidate.kind == entry.kind
328        })
329    {
330        return Err(age_error(
331            AGE_DEPENDENT_OBJECTS_STILL_EXIST,
332            format!("cannot drop table {graph}.{label} because other objects depend on it"),
333        ));
334    }
335    runtime
336        .drop_graph_label(&graph, &label)
337        .map_err(|err| storage_error("drop label", &err))?;
338    Ok(Value::Null)
339}
340
341/// `SELECT alter_graph('graph', 'RENAME', 'new_name')` with AGE
342/// semantics; `RENAME` is the only operation AGE implements.
343pub fn run_age_alter_graph_with_evaluator(
344    runtime: &dyn GraphLifecycle,
345    args: &[ScalarExpr],
346    evaluate: &mut dyn FnMut(&ScalarExpr) -> Result<Value, SQLError>,
347) -> Result<Value, SQLError> {
348    require_age_arity("alter_graph", args, 3..=3)?;
349    let graph = eval_age_name_with(&args[0], "graph_name must not be NULL", evaluate)?;
350    let operation = eval_age_name_with(&args[1], "operation must not be NULL", evaluate)?;
351    let new_value = eval_age_name_with(&args[2], "new_value must not be NULL", evaluate)?;
352    if !operation.eq_ignore_ascii_case("RENAME") {
353        return Err(age_error(
354            AGE_INVALID_PARAMETER_VALUE,
355            format!("invalid operation \"{operation}\""),
356        ));
357    }
358    if !uqa_graph::age_names::is_valid_graph_name(&new_value) {
359        return Err(age_error(
360            AGE_INVALID_PARAMETER_VALUE,
361            "new graph name is invalid",
362        ));
363    }
364    if !runtime.has_graph(&graph).map_err(age_graph_catalog_error)? {
365        return Err(age_error(
366            AGE_UNDEFINED_SCHEMA,
367            format!("graph \"{graph}\" does not exist"),
368        ));
369    }
370    // `RenameSchema` rejects any taken name, including the graph's own
371    // current name, so renaming a graph onto itself is a duplicate schema.
372    if runtime
373        .has_namespace(&new_value)
374        .map_err(age_graph_catalog_error)?
375    {
376        return Err(age_error(
377            AGE_DUPLICATE_SCHEMA,
378            format!("schema \"{new_value}\" already exists"),
379        ));
380    }
381    runtime
382        .rename_graph(&graph, &new_value)
383        .map_err(|err| storage_error("rename graph", &err))?;
384    Ok(Value::Null)
385}