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;
12mod production;
13pub use borrowed::{RelationName, RelationReference, RelationReferenceError};
14#[cfg(test)]
15mod tests;
16
17/// Durable identity of a SQL relation.
18///
19/// The schema and local name are stored separately so `foo` and
20/// `public.foo` can never become two physical catalog identities for the
21/// same SQL object.
22#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
23pub struct RelationIdentity {
24    pub schema: String,
25    pub name: String,
26}
27
28impl RelationIdentity {
29    pub fn new(schema: impl Into<String>, name: impl Into<String>) -> Self {
30        Self {
31            schema: schema.into(),
32            name: name.into(),
33        }
34    }
35
36    pub fn qualified_name(&self) -> String {
37        self.qualified_name_with_control(&crate::memory::ProductionControl::uncontrolled())
38            .expect("ordinary relation names cannot be cancelled or limited")
39            .into_uncontrolled()
40            .expect("ordinary relation names have no reservation")
41    }
42
43    pub fn qualified_name_with_control(
44        &self,
45        control: &crate::memory::ProductionControl<'_>,
46    ) -> Result<crate::memory::Produced<String>, crate::ValueRetentionError> {
47        RelationReference {
48            schema: Some(RelationName::decoded(&self.schema)),
49            name: RelationName::decoded(&self.name),
50        }
51        .render_with_control(control)
52    }
53
54    /// Physical owner keys that can refer to this relation. New writes use
55    /// only the canonical qualified name. Catalog cleanup also accepts the
56    /// former unqualified key for `public` relations so data written before
57    /// relation identities became schema-aware cannot survive its owner.
58    pub fn canonical_and_legacy_public_names(&self) -> Vec<String> {
59        let canonical = self.qualified_name();
60        if self.schema != "public" {
61            return vec![canonical];
62        }
63        let mut names = vec![canonical];
64        let rendered_alias = render_relation_component(&self.name);
65        if !names.contains(&rendered_alias) {
66            names.push(rendered_alias);
67        }
68        // The direct Rust API historically accepted a decoded local name as
69        // well as SQL-rendered text. Include that spelling only when parsing
70        // it maps back to this exact relation; for example, raw `a.b` must not
71        // be removed while dropping the distinct public relation `"a.b"`.
72        if RelationIdentity::from_legacy_name(&self.name).is_ok_and(|raw| raw == *self)
73            && !names.contains(&self.name)
74        {
75            names.push(self.name.clone());
76        }
77        names
78    }
79
80    /// Decode a SQL relation reference or a former flat catalog key.
81    /// Unqualified objects belong to `public`. Quoted components preserve
82    /// embedded dots and escaped quotes, so `public.\"a.b\"` is distinct from
83    /// `\"public.a\".b` all the way down to physical storage keys.
84    pub fn from_legacy_name(value: &str) -> Result<Self, String> {
85        let (schema, name) = Self::parse_reference(value)?;
86        Ok(Self::new(
87            schema.unwrap_or_else(|| "public".to_string()),
88            name,
89        ))
90    }
91
92    /// 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.
93    pub fn from_legacy_index_name(value: &str, table: &Self) -> Self {
94        Self::new(&table.schema, value)
95    }
96
97    /// Parse a possibly-unqualified SQL relation reference without choosing a
98    /// search-path schema. Components use `PostgreSQL` double-quote escaping.
99    pub fn parse_reference(value: &str) -> Result<(Option<String>, String), String> {
100        let reference = Self::try_borrowed_reference(value).map_err(|error| error.to_string())?;
101        Ok((
102            reference.schema.map(|schema| schema.to_string()),
103            reference.name.to_string(),
104        ))
105    }
106
107    /// Parse a relation reference without allocating decoded names or error text. Qualified references retain their separate schema component.
108    pub fn borrowed_reference(value: &str) -> Option<RelationReference<'_>> {
109        Self::try_borrowed_reference(value).ok()
110    }
111
112    /// Retain an invalid reference as a borrowing diagnostic so controlled consumers can admit its formatting.
113    pub fn try_borrowed_reference(
114        value: &str,
115    ) -> Result<RelationReference<'_>, RelationReferenceError<'_>> {
116        borrowed::parse_result(value)
117    }
118}
119
120fn render_relation_component(component: &str) -> String {
121    let can_render_bare = component
122        .bytes()
123        .enumerate()
124        .all(|(index, byte)| match byte {
125            b'a'..=b'z' | b'_' => true,
126            b'0'..=b'9' | b'$' => index != 0,
127            _ => false,
128        });
129    if can_render_bare && !component.is_empty() {
130        component.to_string()
131    } else {
132        format!("\"{}\"", component.replace('"', "\"\""))
133    }
134}