elefant_tools/models/
domain.rs1use 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 not_null_constraint_name: Option<String>,
14 pub description: Option<String>,
15 pub depends_on: Vec<ObjectId>,
16 pub data_type_length: Option<i32>,
17}
18
19#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
20pub struct PostgresDomainConstraint {
21 pub name: String,
22 pub definition: String,
23}
24
25impl PostgresDomain {
26 pub fn get_create_sql(
27 &self,
28 schema: &PostgresSchema,
29 identifier_quoter: &IdentifierQuoter,
30 ) -> String {
31 let mut sql = format!(
32 "create domain {}.{} as {}",
33 schema
34 .name
35 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
36 self.name
37 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
38 self.base_type_name
39 );
40
41 if let Some(length) = self.data_type_length {
42 sql.push_str(&format!("({length})"));
43 }
44 if let Some(default_value) = &self.default_value {
45 sql.push_str(&format!(" default {default_value}"));
46 }
47 if self.not_null {
48 if let Some(constraint_name) = &self.not_null_constraint_name {
49 sql.push_str(&format!(
50 " constraint {} not null",
51 constraint_name
52 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName)
53 ));
54 } else {
55 sql.push_str(" not null");
56 }
57 }
58 if let Some(constraint) = &self.constraint {
59 sql.push_str(&format!(
60 " constraint {} check {}",
61 constraint
62 .name
63 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
64 constraint.definition
65 ));
66 }
67 sql.push(';');
68
69 if let Some(description) = &self.description {
70 sql.push_str(&format!(
71 "\ncomment on domain {}.{} is {};",
72 schema
73 .name
74 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
75 self.name
76 .quote(identifier_quoter, AttemptedKeywordUsage::TypeOrFunctionName),
77 quote_value_string(description)
78 ));
79 }
80
81 sql
82 }
83}