1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*!
Defining the [Identifier] struct for identifying tables in an iceberg catalog.
*/

use core::fmt::{self, Display};

use serde_derive::{Deserialize, Serialize};

use crate::error::Error;

use super::namespace::Namespace;

/// Seperator of different namespace levels.
pub static SEPARATOR: &str = ".";

///Identifies a table in an iceberg catalog.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Identifier {
    #[serde(flatten)]
    namespace: Namespace,
    name: String,
}

impl Identifier {
    ///Create Identifier
    pub fn try_new(names: &[String]) -> Result<Self, Error> {
        let length = names.len();
        if names.is_empty() {
            Err(Error::InvalidFormat("identifier sequence".to_string()))
        } else if names[length - 1].is_empty() {
            Err(Error::InvalidFormat("table name".to_string()))
        } else {
            Ok(Identifier {
                namespace: Namespace::try_new(&names[0..length - 1])?,
                name: names[length - 1].clone(),
            })
        }
    }
    ///Parse
    pub fn parse(identifier: &str) -> Result<Self, Error> {
        let names = identifier
            .split(SEPARATOR)
            .map(|x| x.to_string())
            .collect::<Vec<String>>();
        Identifier::try_new(&names)
    }
    /// Return namespace of table
    pub fn namespace(&self) -> &Namespace {
        &self.namespace
    }
    /// Return name of table
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl Display for Identifier {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}{}", self.namespace, SEPARATOR, self.name)
    }
}

impl TryFrom<&str> for Identifier {
    type Error = Error;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

#[cfg(test)]

mod tests {
    use super::Identifier;

    #[test]
    fn test_new() {
        let identifier = Identifier::try_new(&[
            "level1".to_string(),
            "level2".to_string(),
            "table".to_string(),
        ])
        .unwrap();
        assert_eq!(&format!("{}", identifier), "level1.level2.table");
    }
    #[test]
    #[should_panic]
    fn test_empty() {
        let _ = Identifier::try_new(&["level1".to_string(), "level2".to_string(), "".to_string()])
            .unwrap();
    }
    #[test]
    #[should_panic]
    fn test_empty_identifier() {
        let _ = Identifier::try_new(&[]).unwrap();
    }
    #[test]
    fn test_parse() {
        let identifier = Identifier::parse("level1.level2.table").unwrap();
        assert_eq!(&format!("{}", identifier), "level1.level2.table");
    }
}