elefant_tools/models/
domain.rs

1use crate::quoting::{quote_value_string, AttemptedKeywordUsage, Quotable};
2use crate::{IdentifierQuoter, ObjectId, PostgresSchema};
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Eq, PartialEq, Clone, Default, Serialize, Deserialize)]
6pub struct PostgresDomain {
7    pub name: String,
8    pub object_id: ObjectId,
9    pub base_type_name: String,
10    pub default_value: Option<String>,
11    pub constraint: Option<PostgresDomainConstraint>,
12    pub not_null: bool,
13    pub description: Option<String>,
14    pub depends_on: Vec<ObjectId>,
15    pub data_type_length: Option<i32>,
16}
17
18#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
19pub struct PostgresDomainConstraint {
20    pub name: String,
21    pub definition: String,
22}
23
24impl PostgresDomain {
25    pub fn get_create_sql(
26        &self,
27        schema: &PostgresSchema,
28        identifier_quoter: &IdentifierQuoter,
29    ) -> String {
30        let mut sql = format!(
31            "create domain {}.{} as {}",
32            schema
33                .name
34                .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
35            self.name
36                .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
37            self.base_type_name
38        );
39
40        if let Some(length) = self.data_type_length {
41            sql.push_str(&format!("({})", length));
42        }
43        if let Some(default_value) = &self.default_value {
44            sql.push_str(&format!(" default {}", default_value));
45        }
46        if self.not_null {
47            sql.push_str(" not null");
48        }
49        if let Some(constraint) = &self.constraint {
50            sql.push_str(&format!(
51                " constraint {} check {}",
52                constraint
53                    .name
54                    .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
55                constraint.definition
56            ));
57        }
58        sql.push(';');
59
60        if let Some(description) = &self.description {
61            sql.push_str(&format!(
62                "\ncomment on domain {}.{} is {};",
63                schema
64                    .name
65                    .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
66                self.name
67                    .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
68                quote_value_string(description)
69            ));
70        }
71
72        sql
73    }
74}