uqa_core/
relation_identity.rs1use serde::{Deserialize, Serialize};
10
11mod borrowed;
12pub use borrowed::{RelationName, RelationReference};
13#[cfg(test)]
14mod tests;
15
16#[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 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 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 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 pub fn from_legacy_index_name(value: &str, table: &Self) -> Self {
83 Self::new(&table.schema, value)
84 }
85
86 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 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}