1use super::{CatalogReadView, RelationNameResolution};
8use uqa_core::RelationIdentity;
9use uqa_graph::{GraphLabelInfo, LabelKind};
10use uqa_sql::catalog::{age_agtype, age_graphid};
11use uqa_sql::{ColumnType, SQLError};
12
13pub struct GraphCatalogEntry {
15 pub name: String,
16 pub labels: Vec<GraphLabelInfo>,
17}
18
19#[derive(Clone)]
20pub struct AgeLabelRelation {
21 pub graph: String,
22 pub label: GraphLabelInfo,
23}
24
25impl AgeLabelRelation {
26 pub fn canonical_name(&self) -> String {
27 format!(
28 "{}.{}",
29 uqa_sql::expr::quote_ident(&self.graph),
30 uqa_sql::expr::quote_ident(&self.label.name)
31 )
32 }
33}
34
35pub fn graph_catalog_entries(
36 catalog: &CatalogReadView,
37) -> Result<Vec<GraphCatalogEntry>, SQLError> {
38 catalog
39 .read_graph_names()?
40 .into_iter()
41 .map(|name| {
42 let labels = catalog.graph_labels(&name)?.ok_or_else(|| {
43 SQLError::Internal(format!("graph `{name}` disappeared from catalog snapshot"))
44 })?;
45 Ok(GraphCatalogEntry { name, labels })
46 })
47 .collect()
48}
49
50pub fn resolve_age_label_relation(
54 catalog: &CatalogReadView,
55 resolution: &RelationNameResolution,
56 name: &str,
57) -> Result<Option<AgeLabelRelation>, SQLError> {
58 let (schema, label_name) = RelationIdentity::parse_reference(name).map_err(|error| {
59 SQLError::Internal(format!("invalid AGE label relation `{name}`: {error}"))
60 })?;
61 let graph_names =
62 schema.map_or_else(|| resolution.search_path().to_vec(), |schema| vec![schema]);
63 for graph_name in graph_names {
64 let Some(labels) = catalog.graph_labels(&graph_name)? else {
65 continue;
66 };
67 if let Some(label) = labels.into_iter().find(|label| label.name == label_name) {
68 return Ok(Some(AgeLabelRelation {
69 graph: graph_name,
70 label,
71 }));
72 }
73 }
74 Ok(None)
75}
76
77pub fn resolve_age_label_relation_name(
78 catalog: &CatalogReadView,
79 resolution: &RelationNameResolution,
80 name: &str,
81) -> Result<Option<String>, SQLError> {
82 Ok(resolve_age_label_relation(catalog, resolution, name)?
83 .map(|relation| relation.canonical_name()))
84}
85
86pub fn age_label_relation_schema(
87 catalog: &CatalogReadView,
88 resolution: &RelationNameResolution,
89 name: &str,
90) -> Result<Option<Vec<(String, ColumnType)>>, SQLError> {
91 let Some(relation) = resolve_age_label_relation(catalog, resolution, name)? else {
92 return Ok(None);
93 };
94 let columns = match relation.label.kind {
95 LabelKind::Vertex => vec![
96 ("id".into(), age_graphid()),
97 ("properties".into(), age_agtype()),
98 ],
99 LabelKind::Edge => vec![
100 ("id".into(), age_graphid()),
101 ("start_id".into(), age_graphid()),
102 ("end_id".into(), age_graphid()),
103 ("properties".into(), age_agtype()),
104 ],
105 };
106 Ok(Some(columns))
107}
108
109pub fn age_label_relation_columns_with_control(
110 catalog: &CatalogReadView,
111 resolution: &RelationNameResolution,
112 name: &str,
113 control: &uqa_core::memory::ProductionControl<'_>,
114) -> Result<Option<uqa_core::memory::Produced<Vec<String>>>, SQLError> {
115 let Some(kind) = age_label_kind_with_control(catalog, resolution, name, control)? else {
116 return Ok(None);
117 };
118 let mut output = uqa_core::memory::ProductionVec::new(*control);
119 for column in age_columns(kind) {
120 output.push_produced(control.copy_text(column)?)?;
121 }
122 Ok(Some(output.finish()?))
123}
124
125pub fn age_label_relation_schema_with_control(
126 catalog: &CatalogReadView,
127 resolution: &RelationNameResolution,
128 name: &str,
129 control: &uqa_core::memory::ProductionControl<'_>,
130) -> Result<
131 Option<uqa_core::memory::Produced<uqa_sql::catalog::analysis::VirtualRelationSchema>>,
132 SQLError,
133> {
134 let Some(kind) = age_label_kind_with_control(catalog, resolution, name, control)? else {
135 return Ok(None);
136 };
137 let mut output = uqa_core::memory::ProductionVec::new(*control);
138 for column in age_columns(kind) {
139 let qualified = if *column == "properties" {
140 "ag_catalog.agtype"
141 } else {
142 "ag_catalog.graphid"
143 };
144 let oid = u32::try_from(uqa_sql::catalog::oids::stable_oid("type", qualified))
145 .expect("AGE type OID");
146 let (ty, type_memory) = uqa_sql::catalog::system_catalog_domain_with_control(oid, control)?
147 .expect("AGE declaration")
148 .into_parts();
149 let (name, name_memory) = control.copy_text(column)?.into_parts();
150 output.push_produced(
151 control.finish((name, ty), control.combine(name_memory, type_memory))?,
152 )?;
153 }
154 Ok(Some(output.finish()?))
155}
156
157fn age_columns(kind: LabelKind) -> &'static [&'static str] {
158 match kind {
159 LabelKind::Vertex => &["id", "properties"],
160 LabelKind::Edge => &["id", "start_id", "end_id", "properties"],
161 }
162}
163
164fn age_label_kind_with_control(
165 catalog: &CatalogReadView,
166 resolution: &RelationNameResolution,
167 name: &str,
168 control: &uqa_core::memory::ProductionControl<'_>,
169) -> Result<Option<LabelKind>, SQLError> {
170 control.check()?;
171 let reference = RelationIdentity::try_borrowed_reference(name).map_err(|error| {
172 control
173 .format(format_args!("invalid AGE label relation `{name}`: {error}"))
174 .map(|text| SQLError::Internal(text.into_parts().0))
175 .unwrap_or_else(Into::into)
176 })?;
177 let schema = reference
178 .schema
179 .map(|schema| control.format(format_args!("{schema}")))
180 .transpose()?;
181 let label = control.format(format_args!("{}", reference.name))?;
182 let names = schema
183 .as_ref()
184 .map(|schema| schema.as_str())
185 .into_iter()
186 .chain(
187 schema
188 .is_none()
189 .then_some(resolution.search_path())
190 .into_iter()
191 .flatten()
192 .map(String::as_str),
193 );
194 for graph in names {
195 control.check()?;
196 let Some(kind) = catalog.graph_label_kind(graph, &label)? else {
197 continue;
198 };
199 return Ok(Some(kind));
200 }
201 Ok(None)
202}
203
204impl AgeLabelRelation {
205 pub fn includes_graphid(&self, graphid: u64) -> bool {
206 self.label.id == self.label.kind.default_label_id()
207 || uqa_graph::graphid_label_id(graphid) == self.label.id
208 }
209}