Skip to main content

uqa_core/
relation_identity.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical SQL relation identities and legacy name decoding.
8
9use serde::{Deserialize, Serialize};
10
11mod borrowed;
12pub use borrowed::{RelationName, RelationReference};
13#[cfg(test)]
14mod tests;
15
16/// Durable identity of a SQL relation.
17///
18/// The schema and local name are stored separately so `foo` and
19/// `public.foo` can never become two physical catalog identities for the
20/// same SQL object.
21#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
22pub struct RelationIdentity {
23    pub schema: String,
24    pub name: String,
25}
26
27impl RelationIdentity {
28    pub fn new(schema: impl Into<String>, name: impl Into<String>) -> Self {
29        Self {
30            schema: schema.into(),
31            name: name.into(),
32        }
33    }
34
35    pub fn qualified_name(&self) -> String {
36        format!(
37            "{}.{}",
38            render_relation_component(&self.schema),
39            render_relation_component(&self.name)
40        )
41    }
42
43    /// Physical owner keys that can refer to this relation. New writes use
44    /// only the canonical qualified name. Catalog cleanup also accepts the
45    /// former unqualified key for `public` relations so data written before
46    /// relation identities became schema-aware cannot survive its owner.
47    pub fn canonical_and_legacy_public_names(&self) -> Vec<String> {
48        let canonical = self.qualified_name();
49        if self.schema != "public" {
50            return vec![canonical];
51        }
52        let mut names = vec![canonical];
53        let rendered_alias = render_relation_component(&self.name);
54        if !names.contains(&rendered_alias) {
55            names.push(rendered_alias);
56        }
57        // The direct Rust API historically accepted a decoded local name as
58        // well as SQL-rendered text. Include that spelling only when parsing
59        // it maps back to this exact relation; for example, raw `a.b` must not
60        // be removed while dropping the distinct public relation `"a.b"`.
61        if RelationIdentity::from_legacy_name(&self.name).is_ok_and(|raw| raw == *self)
62            && !names.contains(&self.name)
63        {
64            names.push(self.name.clone());
65        }
66        names
67    }
68
69    /// Decode a SQL relation reference or a former flat catalog key.
70    /// Unqualified objects belong to `public`. Quoted components preserve
71    /// embedded dots and escaped quotes, so `public.\"a.b\"` is distinct from
72    /// `\"public.a\".b` all the way down to physical storage keys.
73    pub fn from_legacy_name(value: &str) -> Result<Self, String> {
74        let (schema, name) = Self::parse_reference(value)?;
75        Ok(Self::new(
76            schema.unwrap_or_else(|| "public".to_string()),
77            name,
78        ))
79    }
80
81    /// Recover an index identity from the former flat index catalog. The stored value is a decoded local identifier rather than a relation reference, so dots and quotes remain part of the local name and the owning table supplies the schema.
82    pub fn from_legacy_index_name(value: &str, table: &Self) -> Self {
83        Self::new(&table.schema, value)
84    }
85
86    /// Parse a possibly-unqualified SQL relation reference without choosing a
87    /// search-path schema. Components use `PostgreSQL` double-quote escaping.
88    pub fn parse_reference(value: &str) -> Result<(Option<String>, String), String> {
89        let reference = borrowed::parse(value).map_err(|error| error.message(value))?;
90        Ok((
91            reference.schema.map(|schema| schema.to_string()),
92            reference.name.to_string(),
93        ))
94    }
95
96    /// Parse a relation reference without allocating decoded names or error text. Qualified references retain their separate schema component.
97    pub fn borrowed_reference(value: &str) -> Option<RelationReference<'_>> {
98        borrowed::parse(value).ok()
99    }
100}
101
102fn render_relation_component(component: &str) -> String {
103    let can_render_bare = component
104        .bytes()
105        .enumerate()
106        .all(|(index, byte)| match byte {
107            b'a'..=b'z' | b'_' => true,
108            b'0'..=b'9' | b'$' => index != 0,
109            _ => false,
110        });
111    if can_render_bare && !component.is_empty() {
112        component.to_string()
113    } else {
114        format!("\"{}\"", component.replace('"', "\"\""))
115    }
116}