Skip to main content

uqa_execution/catalog/
comments.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Transactional descriptions keyed by catalog object address, independently of its current name or type form.
8
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    ops::Deref,
12    sync::Arc,
13};
14use uqa_sql::{catalog::dependencies::ObjectAddress, SQLError};
15use uqa_storage::{CatalogFacade, StorageBackendError, StorageBackendResult};
16
17/// Object-first ordering gives both forms of `obj_description` a bounded key lookup.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
19pub struct CommentAddress {
20    object_id: u32,
21    sub_id: i32,
22    class_id: u32,
23}
24impl From<ObjectAddress> for CommentAddress {
25    fn from(object: ObjectAddress) -> Self {
26        Self {
27            object_id: object.object_id,
28            sub_id: object.sub_id,
29            class_id: object.class_id,
30        }
31    }
32}
33pub type CommentRegistry = BTreeMap<CommentAddress, String>;
34pub trait CommentPublication {
35    fn comments(&self) -> Box<dyn Deref<Target = CommentRegistry> + '_>;
36    fn comment_catalog(&self) -> Option<&dyn CatalogFacade>;
37    fn publish_comments(&self, registry: CommentRegistry);
38}
39
40const PREFIX: &str = "uqa.sql.comment.v1:";
41
42fn key(address: CommentAddress) -> String {
43    format!(
44        "{PREFIX}{}:{}:{}",
45        address.class_id, address.object_id, address.sub_id
46    )
47}
48
49fn address(key_text: &str) -> Option<CommentAddress> {
50    let mut parts = key_text.strip_prefix(PREFIX)?.split(':');
51    let value = CommentAddress {
52        class_id: parts.next()?.parse().ok()?,
53        object_id: parts.next()?.parse().ok()?,
54        sub_id: parts.next()?.parse().ok()?,
55    };
56    (parts.next().is_none()
57        && value.class_id != 0
58        && value.object_id != 0
59        && value.sub_id >= 0
60        && key(value) == key_text)
61        .then_some(value)
62}
63
64pub fn restore(catalog: &dyn CatalogFacade) -> StorageBackendResult<CommentRegistry> {
65    let mut registry = CommentRegistry::new();
66    for (name, description) in catalog.metadata_with_prefix(PREFIX)? {
67        let object = address(&name)
68            .ok_or_else(|| StorageBackendError::Other("invalid catalog comment address".into()))?;
69        if description.is_empty() || description.contains('\0') {
70            return Err(StorageBackendError::Other(
71                "invalid catalog comment text".into(),
72            ));
73        }
74        registry.insert(object, description);
75    }
76    Ok(registry)
77}
78
79pub fn merge_private(
80    catalog: Option<&dyn CatalogFacade>,
81    current: &CommentRegistry,
82    mut committed: Arc<CommentRegistry>,
83) -> StorageBackendResult<Arc<CommentRegistry>> {
84    let addresses = current
85        .keys()
86        .chain(committed.keys())
87        .copied()
88        .collect::<BTreeSet<_>>();
89    for object in addresses {
90        if catalog.map_or(Ok(false), |catalog| {
91            catalog.metadata_has_private_changes(&key(object))
92        })? {
93            if let Some(description) = current.get(&object) {
94                Arc::make_mut(&mut committed).insert(object, description.clone());
95            } else {
96                Arc::make_mut(&mut committed).remove(&object);
97            }
98        }
99    }
100    Ok(committed)
101}
102
103/// The caller retains the addressed object's lock and existing definition transaction.
104pub fn set(
105    publication: &dyn CommentPublication,
106    object: ObjectAddress,
107    description: Option<&str>,
108) -> Result<(), SQLError> {
109    let object = CommentAddress::from(object);
110    let description = description.filter(|text| !text.is_empty());
111    let mut registry = publication.comments().clone();
112    if let Some(catalog) = publication.comment_catalog() {
113        match description {
114            Some(text) => catalog.set_metadata(&key(object), text),
115            None => catalog.delete_metadata(&key(object)),
116        }
117        .map_err(|error| uqa_sql::catalog::errors::storage_error("catalog comment", &error))?;
118    }
119    if let Some(text) = description {
120        registry.insert(object, text.to_owned());
121    } else {
122        registry.remove(&object);
123    }
124    publication.publish_comments(registry);
125    Ok(())
126}
127
128/// Drop descriptions in the same transaction that removes their owning objects.
129pub fn remove(
130    publication: &dyn CommentPublication,
131    class: u32,
132    targets: &BTreeSet<u32>,
133) -> Result<bool, SQLError> {
134    let comments = publication.comments();
135    let addresses = targets
136        .iter()
137        .flat_map(|&object_id| {
138            let first = CommentAddress {
139                object_id,
140                sub_id: 0,
141                class_id: 0,
142            };
143            let last = CommentAddress {
144                object_id,
145                sub_id: i32::MAX,
146                class_id: u32::MAX,
147            };
148            comments
149                .range(first..=last)
150                .filter_map(move |(object, _)| (object.class_id == class).then_some(*object))
151        })
152        .collect::<Vec<_>>();
153    drop(comments);
154    if addresses.is_empty() {
155        return Ok(false);
156    }
157    let mut registry = publication.comments().clone();
158    for object in addresses {
159        if let Some(catalog) = publication.comment_catalog() {
160            catalog.delete_metadata(&key(object)).map_err(|error| {
161                uqa_sql::catalog::errors::storage_error("remove catalog comment", &error)
162            })?;
163        }
164        registry.remove(&object);
165    }
166    publication.publish_comments(registry);
167    Ok(true)
168}
169
170pub fn rows(catalog: &super::CatalogReadView) -> Vec<uqa_sql::ResultRow> {
171    use uqa_core::Value;
172    catalog
173        .snapshot()
174        .definitions
175        .comments
176        .iter()
177        .map(|(object, description)| {
178            BTreeMap::from([
179                ("objoid".into(), Value::Int(i64::from(object.object_id))),
180                ("classoid".into(), Value::Int(i64::from(object.class_id))),
181                ("objsubid".into(), Value::Int(i64::from(object.sub_id))),
182                ("description".into(), Value::Str(description.clone())),
183            ])
184        })
185        .collect()
186}
187
188pub fn object_description(
189    catalog: &super::CatalogReadView,
190    arguments: &[uqa_core::Value],
191) -> Result<uqa_core::Value, SQLError> {
192    use uqa_core::Value;
193    if arguments.contains(&Value::Null) {
194        return Ok(Value::Null);
195    }
196    let (oid, class) = match arguments {
197        [Value::Int(oid)] => (*oid, None),
198        [Value::Int(oid), Value::Str(class)] => {
199            let Some(class) = uqa_sql::catalog::SystemRelation::at("pg_catalog", class) else {
200                return Ok(Value::Null);
201            };
202            (*oid, Some(class.oid()))
203        }
204        _ => {
205            return Err(SQLError::TypeMismatch(
206                "obj_description requires an oid and an optional catalog name".into(),
207            ))
208        }
209    };
210    let Ok(object_id) = u32::try_from(oid) else {
211        return Ok(Value::Null);
212    };
213    let snapshot = catalog.snapshot();
214    let comments = &snapshot.definitions.comments;
215    let first = CommentAddress {
216        object_id,
217        sub_id: 0,
218        class_id: 0,
219    };
220    let description = if let Some(class_id) = class {
221        u32::try_from(class_id)
222            .ok()
223            .and_then(|class_id| comments.get(&CommentAddress { class_id, ..first }))
224    } else {
225        let last = CommentAddress {
226            class_id: u32::MAX,
227            ..first
228        };
229        comments.range(first..=last).next().map(|(_, text)| text)
230    };
231    Ok(description.map_or(Value::Null, |text| Value::Str(text.clone())))
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use std::cell::RefCell;
238    use uqa_storage::{KeyValueCatalog, MemoryKeyValueStore};
239
240    struct Publication {
241        catalog: KeyValueCatalog,
242        comments: RefCell<CommentRegistry>,
243    }
244    impl CommentPublication for Publication {
245        fn comments(&self) -> Box<dyn Deref<Target = CommentRegistry> + '_> {
246            Box::new(self.comments.borrow())
247        }
248        fn comment_catalog(&self) -> Option<&dyn CatalogFacade> {
249            Some(&self.catalog)
250        }
251        fn publish_comments(&self, registry: CommentRegistry) {
252            *self.comments.borrow_mut() = registry;
253        }
254    }
255
256    #[test]
257    fn object_descriptions_restore_replace_and_drop_by_identity() {
258        let publication = Publication {
259            catalog: KeyValueCatalog::new(Arc::new(MemoryKeyValueStore::new())),
260            comments: RefCell::default(),
261        };
262        let first = ObjectAddress::whole(uqa_sql::catalog::dependencies::TYPE_CLASS, 20_000);
263        let second = ObjectAddress::whole(uqa_sql::catalog::dependencies::TYPE_CLASS, 20_001);
264        set(&publication, first, Some("original\n설명")).unwrap();
265        set(&publication, second, Some("independent")).unwrap();
266        assert_eq!(
267            restore(&publication.catalog).unwrap(),
268            *publication.comments.borrow()
269        );
270        set(&publication, first, Some("replacement")).unwrap();
271        assert_eq!(
272            restore(&publication.catalog).unwrap()[&first.into()],
273            "replacement"
274        );
275        remove(
276            &publication,
277            first.class_id,
278            &BTreeSet::from([first.object_id]),
279        )
280        .unwrap();
281        assert_eq!(
282            restore(&publication.catalog).unwrap(),
283            BTreeMap::from([(second.into(), "independent".into())])
284        );
285        set(&publication, second, Some("")).unwrap();
286        assert!(restore(&publication.catalog).unwrap().is_empty());
287    }
288
289    #[test]
290    fn malformed_description_addresses_cannot_alias_a_catalog_object() {
291        for (name, text) in [
292            ("0:20000:0", "description"),
293            ("1247:0:0", "description"),
294            ("1247:20000:-1", "description"),
295            ("1247:020000:0", "description"),
296            ("1247:20000:0:extra", "description"),
297            ("1247:20000:0", ""),
298            ("1247:20000:0", "invalid\0text"),
299        ] {
300            let catalog = KeyValueCatalog::new(Arc::new(MemoryKeyValueStore::new()));
301            catalog
302                .set_metadata(&format!("{PREFIX}{name}"), text)
303                .unwrap();
304            assert!(restore(&catalog).is_err(), "{name}");
305        }
306    }
307}