elefant_tools/models/
database.rs1use crate::models::extension::PostgresExtension;
2use crate::models::schema::PostgresSchema;
3use crate::object_id::ObjectId;
4use crate::{default, TimescaleDbUserDefinedJob};
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Eq, PartialEq, Default, Clone, Serialize, Deserialize)]
8pub struct PostgresDatabase {
9 pub schemas: Vec<PostgresSchema>,
10 pub enabled_extensions: Vec<PostgresExtension>,
11 pub timescale_support: TimescaleSupport,
12 pub object_id: ObjectId,
13}
14
15#[derive(Debug, Eq, PartialEq, Default, Clone, Serialize, Deserialize)]
16pub struct TimescaleSupport {
17 pub is_enabled: bool,
18 pub timescale_toolkit_is_enabled: bool,
19 pub user_defined_jobs: Vec<TimescaleDbUserDefinedJob>,
20}
21
22impl PostgresDatabase {
23 pub fn get_or_create_schema_mut(&mut self, schema_name: &str) -> &mut PostgresSchema {
24 if let Some(position) = self.schemas.iter().position(|s| s.name == schema_name) {
25 self.schemas.get_mut(position).unwrap()
26 } else {
27 let new_schema = PostgresSchema {
28 name: schema_name.to_string(),
29 ..default()
30 };
31
32 self.schemas.push(new_schema);
33 self.schemas.last_mut().unwrap()
34 }
35 }
36
37 pub fn filtered_to_schema(&self, schema: &str) -> Self {
38 PostgresDatabase {
39 timescale_support: TimescaleSupport {
40 user_defined_jobs: self
41 .timescale_support
42 .user_defined_jobs
43 .iter()
44 .filter(|j| j.function_schema == schema)
45 .cloned()
46 .collect(),
47 ..self.timescale_support.clone()
48 },
49 schemas: self
50 .schemas
51 .iter()
52 .filter(|s| s.name == schema)
53 .cloned()
54 .collect(),
55 ..self.clone()
56 }
57 }
58
59 pub fn with_renamed_schema(&self, old_schema_name: &str, new_schema_name: &str) -> Self {
60 PostgresDatabase {
61 timescale_support: TimescaleSupport {
62 user_defined_jobs: self
63 .timescale_support
64 .user_defined_jobs
65 .iter()
66 .map(|j| {
67 if j.function_schema == old_schema_name {
68 TimescaleDbUserDefinedJob {
69 function_schema: new_schema_name.to_string(),
70 ..j.clone()
71 }
72 } else {
73 j.clone()
74 }
75 })
76 .collect(),
77 ..self.timescale_support.clone()
78 },
79 schemas: self
80 .schemas
81 .iter()
82 .map(|s| {
83 if s.name == old_schema_name {
84 PostgresSchema {
85 name: new_schema_name.to_string(),
86 ..s.clone()
87 }
88 } else {
89 s.clone()
90 }
91 })
92 .collect(),
93 ..self.clone()
94 }
95 }
96
97 pub(crate) fn try_get_schema(&self, schema_name: &str) -> Option<&PostgresSchema> {
98 self.schemas.iter().find(|s| s.name == schema_name)
99 }
100}