clia_rustorm_dao/
table_name.rs

1use crate::common;
2use serde_derive::{
3    Deserialize,
4    Serialize,
5};
6use std::hash::{
7    Hash,
8    Hasher,
9};
10
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
12pub struct TableName {
13    pub name: String,
14    pub schema: Option<String>,
15    pub alias: Option<String>,
16}
17
18impl Eq for TableName {}
19
20impl TableName {
21    /// create table with name
22    pub fn from(arg: &str) -> Self {
23        if arg.contains('.') {
24            let splinters = arg.split('.').collect::<Vec<&str>>();
25            assert!(splinters.len() == 2, "There should only be 2 parts");
26            let schema = splinters[0].to_owned();
27            let table = splinters[1].to_owned();
28            TableName {
29                schema: Some(schema),
30                name: table,
31                alias: None,
32            }
33        } else {
34            TableName {
35                schema: None,
36                name: arg.to_owned(),
37                alias: None,
38            }
39        }
40    }
41
42    pub fn name(&self) -> String { self.name.to_owned() }
43
44    pub fn safe_name(&self) -> String { common::keywords_safe(&self.name) }
45
46    /// return the long name of the table using schema.table_name
47    pub fn complete_name(&self) -> String {
48        match self.schema {
49            Some(ref schema) => format!("{}.{}", schema, self.name),
50            None => self.name.to_owned(),
51        }
52    }
53
54    pub fn safe_complete_name(&self) -> String {
55        match self.schema {
56            Some(ref schema) => format!("{}.{}", schema, self.safe_name()),
57            None => self.name.to_owned(),
58        }
59    }
60}
61
62impl Hash for TableName {
63    fn hash<H: Hasher>(&self, state: &mut H) {
64        self.schema.hash(state);
65        self.name.hash(state);
66    }
67}
68
69pub trait ToTableName {
70    /// extract the table name from a struct
71    fn to_table_name() -> TableName;
72}