Skip to main content

elefant_tools/models/
not_null_constraint.rs

1use crate::object_id::ObjectId;
2use crate::quoting::AttemptedKeywordUsage::ColumnName;
3use crate::quoting::{IdentifierQuoter, Quotable};
4use crate::{PostgresSchema, PostgresTable};
5use serde::{Deserialize, Serialize};
6use std::cmp::Ordering;
7
8#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
9pub struct PostgresNotNullConstraint {
10    pub name: String,
11    pub column_name: String,
12    pub is_validated: bool,
13    pub comment: Option<String>,
14    pub object_id: ObjectId,
15}
16
17impl Default for PostgresNotNullConstraint {
18    fn default() -> Self {
19        Self {
20            name: String::new(),
21            column_name: String::new(),
22            is_validated: true,
23            comment: None,
24            object_id: ObjectId::default(),
25        }
26    }
27}
28
29impl PostgresNotNullConstraint {
30    pub fn get_create_statement(
31        &self,
32        table: &PostgresTable,
33        schema: &PostgresSchema,
34        identifier_quoter: &IdentifierQuoter,
35    ) -> String {
36        let mut sql = format!(
37            "alter table {}.{} add constraint {} not null {}",
38            schema.name.quote(identifier_quoter, ColumnName),
39            table.name.quote(identifier_quoter, ColumnName),
40            self.name.quote(identifier_quoter, ColumnName),
41            self.column_name.quote(identifier_quoter, ColumnName),
42        );
43
44        if !self.is_validated {
45            sql.push_str(" not valid");
46        }
47
48        sql.push(';');
49
50        sql
51    }
52}
53
54impl PartialOrd for PostgresNotNullConstraint {
55    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
56        Some(self.cmp(other))
57    }
58}
59
60impl Ord for PostgresNotNullConstraint {
61    fn cmp(&self, other: &Self) -> Ordering {
62        self.name.cmp(&other.name)
63    }
64}