Skip to main content

ignis_db/builders/
schema.rs

1//! Schema Builder for Ignis-DB
2//!
3//! This module provides a builder for creating database schemas.
4
5use crate::builders::traits::{
6    ConditionalBuilder, InspectableBuilder, SchemaBuilder as SchemaBuilderTrait, ValidatableBuilder,
7};
8use crate::builders::validation::BuilderValidationError;
9
10/// Builder for constructing database schemas
11#[derive(Debug, Clone)]
12pub struct DatabaseSchemaBuilder {
13    name: String,
14    comment: Option<String>,
15    owner: Option<String>,
16    if_not_exists: bool,
17}
18
19impl DatabaseSchemaBuilder {
20    /// Create a new schema builder
21    ///
22    /// # Parameters
23    ///
24    /// - `name`: The name of the schema
25    ///
26    /// # Examples
27    ///
28    /// ```rust
29    /// use ignis_db::builders::SchemaBuilder;
30    ///
31    /// let schema = SchemaBuilder::new("my_schema");
32    /// ```
33    pub fn new(name: impl Into<String>) -> Self {
34        Self {
35            name: name.into(),
36            comment: None,
37            owner: None,
38            if_not_exists: true,
39        }
40    }
41
42    /// Set a comment for the schema
43    ///
44    /// # Parameters
45    ///
46    /// - `comment`: The comment text
47    ///
48    /// # Examples
49    ///
50    /// ```rust
51    /// let schema = SchemaBuilder::new("my_schema")
52    ///     .comment("Schema for user data");
53    /// ```
54    pub fn comment(mut self, comment: impl Into<String>) -> Self {
55        self.comment = Some(comment.into());
56        self
57    }
58
59    /// Set the owner of the schema
60    ///
61    /// # Parameters
62    ///
63    /// - `owner`: The owner role name
64    ///
65    /// # Examples
66    ///
67    /// ```rust
68    /// let schema = SchemaBuilder::new("my_schema")
69    ///     .owner("my_user");
70    /// ```
71    pub fn owner(mut self, owner: impl Into<String>) -> Self {
72        self.owner = Some(owner.into());
73        self
74    }
75
76    /// Set whether to use IF NOT EXISTS
77    ///
78    /// # Parameters
79    ///
80    /// - `if_not_exists`: Whether to use IF NOT EXISTS
81    ///
82    /// # Examples
83    ///
84    /// ```rust
85    /// let schema = SchemaBuilder::new("my_schema")
86    ///     .if_not_exists(false);
87    /// ```
88    pub fn if_not_exists(mut self, if_not_exists: bool) -> Self {
89        self.if_not_exists = if_not_exists;
90        self
91    }
92
93    /// Get the schema name
94    pub fn name(&self) -> &str {
95        &self.name
96    }
97
98    /// Get the comment
99    pub fn get_comment(&self) -> Option<&str> {
100        self.comment.as_deref()
101    }
102
103    /// Get the owner
104    pub fn get_owner(&self) -> Option<&str> {
105        self.owner.as_deref()
106    }
107
108    /// Check if IF NOT EXISTS is enabled
109    pub fn is_if_not_exists(&self) -> bool {
110        self.if_not_exists
111    }
112
113    /// Generate the CREATE SCHEMA SQL
114    pub fn to_sql(&self) -> String {
115        let mut sql = String::new();
116
117        sql.push_str("CREATE SCHEMA");
118
119        if self.if_not_exists {
120            sql.push_str(" IF NOT EXISTS");
121        }
122
123        sql.push_str(&format!(" \"{}\"", self.name));
124
125        if let Some(ref owner) = self.owner {
126            sql.push_str(&format!(" AUTHORIZATION \"{}\"", owner));
127        }
128
129        if let Some(ref comment) = self.comment {
130            sql.push_str(&format!(
131                "; COMMENT ON SCHEMA \"{}\" IS {}",
132                self.name, comment
133            ));
134        }
135
136        sql.push(';');
137        sql
138    }
139}
140
141impl SchemaBuilderTrait for DatabaseSchemaBuilder {
142    type Output = String; // Returns the SQL string
143    type Error = BuilderValidationError;
144
145    fn build(self) -> Result<Self::Output, Self::Error> {
146        // Validate the configuration
147        if !self.is_valid() {
148            let errors = self.validation_errors();
149            return Err(BuilderValidationError::Generic(format!(
150                "SchemaBuilder validation failed: {}",
151                errors.join(", ")
152            )));
153        }
154
155        // Return the SQL string
156        Ok(self.to_sql())
157    }
158}
159
160impl ValidatableBuilder for DatabaseSchemaBuilder {
161    fn is_valid(&self) -> bool {
162        // Validate schema name
163        if self.name.is_empty() {
164            return false;
165        }
166
167        // Validate schema name format (basic validation)
168        if !self.name.chars().all(|c| c.is_alphanumeric() || c == '_') {
169            return false;
170        }
171
172        true
173    }
174
175    fn validation_errors(&self) -> Vec<String> {
176        let mut errors = Vec::new();
177
178        // Validate schema name
179        if self.name.is_empty() {
180            errors.push("Schema name cannot be empty".to_string());
181        }
182
183        // Validate schema name format (basic validation)
184        if !self.name.chars().all(|c| c.is_alphanumeric() || c == '_') {
185            errors.push("Schema name contains invalid characters".to_string());
186        }
187
188        errors
189    }
190}
191
192impl ConditionalBuilder for DatabaseSchemaBuilder {
193    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
194    where
195        F: FnOnce(&mut Self),
196        Self: Sized,
197    {
198        if condition {
199            config_fn(&mut self);
200        }
201        self
202    }
203}
204
205impl InspectableBuilder for DatabaseSchemaBuilder {
206    fn debug_info(&self) -> String {
207        format!(
208            "SchemaBuilder {{\n  name: {:?},\n  comment: {:?},\n  owner: {:?},\n  if_not_exists: {}\n}}",
209            self.name, self.comment, self.owner, self.if_not_exists
210        )
211    }
212
213    fn summary(&self) -> String {
214        format!("Schema '{}'", self.name)
215    }
216}
217
218/// Helper function to create a schema builder
219pub fn schema(name: impl Into<String>) -> DatabaseSchemaBuilder {
220    DatabaseSchemaBuilder::new(name)
221}
222
223/// Helper function to extract schema name from a schema-qualified identifier
224///
225/// # Parameters
226///
227/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
228///
229/// # Returns
230///
231/// - `Some(schema_name)` if the name is schema-qualified
232/// - `None` if the name is not schema-qualified
233///
234/// # Examples
235///
236/// ```rust
237/// use ignis_db::builders::schema::extract_schema_name;
238///
239/// assert_eq!(extract_schema_name("auth.users"), Some("auth"));
240/// assert_eq!(extract_schema_name("users"), None);
241/// assert_eq!(extract_schema_name("public.my_table"), Some("public"));
242/// ```
243pub fn extract_schema_name(qualified_name: &str) -> Option<&str> {
244    if let Some(dot_pos) = qualified_name.find('.') {
245        Some(&qualified_name[..dot_pos])
246    } else {
247        None
248    }
249}
250
251/// Helper function to extract table name from a schema-qualified identifier
252///
253/// # Parameters
254///
255/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
256///
257/// # Returns
258///
259/// - The table name part (everything after the dot, or the whole string if no dot)
260///
261/// # Examples
262///
263/// ```rust
264/// use ignis_db::builders::schema::extract_table_name;
265///
266/// assert_eq!(extract_table_name("auth.users"), "users");
267/// assert_eq!(extract_table_name("users"), "users");
268/// assert_eq!(extract_table_name("public.my_table"), "my_table");
269/// ```
270pub fn extract_table_name(qualified_name: &str) -> &str {
271    if let Some(dot_pos) = qualified_name.find('.') {
272        &qualified_name[dot_pos + 1..]
273    } else {
274        qualified_name
275    }
276}