database_reflection/reflection/
column.rs

1use crate::metadata::consts::METADATA_FLAG_UNSIGNED;
2use crate::metadata::WithMetadata;
3use crate::reflection::datatypes::{DefaultValue, JsonDatatype, RustDatatype, SqlDatatype};
4use crate::reflection::SqlSigned;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::sync::Arc;
8
9#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
10pub struct Column {
11    table: Arc<String>,
12    name: Arc<String>,
13    datatype: SqlDatatype,
14    datatype_json: JsonDatatype,
15    datatype_rust: RustDatatype,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    default: Option<DefaultValue>,
18    metadata: HashMap<String, String>,
19}
20
21impl WithMetadata for Column {
22    /// Borrow metadata container for reading
23    fn get_metadata(&self) -> &HashMap<String, String> {
24        &self.metadata
25    }
26
27    /// Borrow metadata container for writing
28    fn get_metadata_mut(&mut self) -> &mut HashMap<String, String> {
29        &mut self.metadata
30    }
31}
32
33impl Column {
34    /// Create a new column by supplying at minimum its name, type and table
35    pub fn new(table: impl ToString, name: impl ToString, datatype: SqlDatatype) -> Column {
36        let mut c = Column {
37            table: Arc::new(table.to_string()),
38            name: Arc::new(name.to_string()),
39            datatype: datatype.clone(),
40            datatype_json: (&datatype).into(),
41            datatype_rust: (&datatype).into(),
42            ..Default::default()
43        };
44
45        if datatype.sign() == Some(SqlSigned::Unsigned) {
46            c.set_meta_flag(METADATA_FLAG_UNSIGNED);
47        }
48
49        c
50    }
51
52    /// Set an optional default value
53    pub fn set_default(&mut self, value: Option<DefaultValue>) -> &mut Column {
54        self.default = value;
55        self
56    }
57
58    /// Get table name
59    pub fn table(&self) -> Arc<String> {
60        self.table.clone()
61    }
62
63    /// Get column name
64    pub fn name(&self) -> Arc<String> {
65        self.name.clone()
66    }
67
68    /// Get datatype
69    pub fn datatype(&self) -> &SqlDatatype {
70        &self.datatype
71    }
72
73    /// Get JS/JSON datatype
74    pub fn datatype_json(&self) -> &JsonDatatype {
75        &self.datatype_json
76    }
77
78    /// Get rust datatype
79    pub fn datatype_rust(&self) -> &RustDatatype {
80        &self.datatype_rust
81    }
82
83    /// Get default value if available
84    pub fn default(&self) -> Option<DefaultValue> {
85        self.default.clone()
86    }
87}