elefant_tools/models/
unique_constraint.rs

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