Skip to main content

elefant_tools/models/
schema.rs

1use crate::models::enumeration::PostgresEnum;
2use crate::models::sequence::PostgresSequence;
3use crate::models::table::PostgresTable;
4use crate::models::view::PostgresView;
5use crate::object_id::ObjectId;
6use crate::quoting::AttemptedKeywordUsage::ColumnName;
7use crate::quoting::{quote_value_string, IdentifierQuoter, Quotable};
8use crate::{PostgresAggregateFunction, PostgresDomain, PostgresFunction, PostgresTrigger};
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Eq, PartialEq, Default, Clone, Serialize, Deserialize)]
12pub struct PostgresSchema {
13    pub tables: Vec<PostgresTable>,
14    pub sequences: Vec<PostgresSequence>,
15    pub views: Vec<PostgresView>,
16    pub functions: Vec<PostgresFunction>,
17    pub aggregate_functions: Vec<PostgresAggregateFunction>,
18    pub triggers: Vec<PostgresTrigger>,
19    pub enums: Vec<PostgresEnum>,
20    pub name: String,
21    pub comment: Option<String>,
22    pub domains: Vec<PostgresDomain>,
23    pub object_id: ObjectId,
24}
25
26impl PostgresSchema {
27    pub fn get_create_statement(&self, identifier_quoter: &IdentifierQuoter) -> String {
28        format!(
29            "create schema if not exists {};",
30            self.name.quote(identifier_quoter, ColumnName)
31        )
32    }
33
34    pub fn get_set_comment_statement(
35        &self,
36        identifier_quoter: &IdentifierQuoter,
37    ) -> Option<String> {
38        if let Some(comment) = &self.comment {
39            let mut sql = String::new();
40            sql.push_str("\ncomment on schema ");
41            sql.push_str(&self.name.quote(identifier_quoter, ColumnName));
42            sql.push_str(" is ");
43            sql.push_str(&quote_value_string(comment));
44            sql.push(';');
45            Some(sql)
46        } else {
47            None
48        }
49    }
50
51    pub(crate) fn try_get_table(&self, table_name: &str) -> Option<&PostgresTable> {
52        self.tables.iter().find(|t| t.name == table_name)
53    }
54}