ignis_db/builders/traits.rs
1//! Core Builder Traits for Ignis-DB
2//!
3//! This module defines the fundamental traits that all builders implement,
4//! providing a consistent interface for schema object construction.
5
6/// Core trait for all schema builders
7///
8/// This trait defines the common interface that all builders must implement.
9/// It ensures that every builder has a `build()` method that produces
10/// the final schema object.
11///
12/// # Generic Parameters
13///
14/// - `Output`: The type of schema object that this builder produces
15///
16/// # Examples
17///
18/// ```rust
19/// use ignis_db::builders::SchemaBuilder;
20///
21/// // All builders implement this trait
22/// let table_builder: TableBuilder = TableBuilder::new("users");
23/// let column_builder: ColumnBuilder = ColumnBuilder::new("id", ColumnType::Int4);
24///
25/// // All can be built into their final form
26/// let table = table_builder.build()?;
27/// let column = column_builder.build()?;
28/// ```
29pub trait SchemaBuilder {
30 /// The type of schema object that this builder produces
31 type Output;
32
33 /// The type of error that can occur during building
34 type Error;
35
36 /// Build the final schema object from the builder configuration
37 ///
38 /// This method consumes the builder and returns either the final
39 /// schema object or an error if the configuration is invalid.
40 ///
41 /// # Returns
42 ///
43 /// - `Ok(Output)`: The successfully built schema object
44 /// - `Err(Error)`: An error describing what went wrong during building
45 ///
46 /// # Examples
47 ///
48 /// ```rust
49 /// use ignis_db::builders::{TableBuilder, ColumnBuilder};
50 ///
51 /// let table = TableBuilder::new("users")
52 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
53 /// .build()?; // Returns Result<Table, TableBuildError>
54 /// ```
55 fn build(self) -> Result<Self::Output, Self::Error>;
56}
57
58/// Trait for builders that can be validated before building
59///
60/// This trait provides a way to validate builder configuration
61/// without consuming the builder. This is useful for checking
62/// configuration validity before attempting to build.
63///
64/// # Examples
65///
66/// ```rust
67/// use ignis_db::builders::ValidatableBuilder;
68///
69/// let table_builder = TableBuilder::new("users");
70///
71/// // Check if the configuration is valid
72/// if table_builder.is_valid() {
73/// let table = table_builder.build()?;
74/// } else {
75/// // Handle validation errors
76/// for error in table_builder.validation_errors() {
77/// eprintln!("Validation error: {}", error);
78/// }
79/// }
80/// ```
81pub trait ValidatableBuilder: SchemaBuilder {
82 /// Check if the current builder configuration is valid
83 ///
84 /// This method performs validation without consuming the builder.
85 /// It returns `true` if the configuration is valid, `false` otherwise.
86 ///
87 /// # Returns
88 ///
89 /// `true` if the configuration is valid, `false` otherwise
90 ///
91 /// # Examples
92 ///
93 /// ```rust
94 /// use ignis_db::builders::ValidatableBuilder;
95 ///
96 /// let table_builder = TableBuilder::new("users");
97 ///
98 /// if table_builder.is_valid() {
99 /// println!("Configuration is valid!");
100 /// } else {
101 /// println!("Configuration has validation errors");
102 /// }
103 /// ```
104 fn is_valid(&self) -> bool;
105
106 /// Get a list of validation errors for the current configuration
107 ///
108 /// This method returns a collection of validation errors without
109 /// consuming the builder. If there are no errors, an empty collection
110 /// is returned.
111 ///
112 /// # Returns
113 ///
114 /// A collection of validation errors, or an empty collection if valid
115 ///
116 /// # Examples
117 ///
118 /// ```rust
119 /// use ignis_db::builders::ValidatableBuilder;
120 ///
121 /// let table_builder = TableBuilder::new("users");
122 ///
123 /// for error in table_builder.validation_errors() {
124 /// eprintln!("Validation error: {}", error);
125 /// }
126 /// ```
127 fn validation_errors(&self) -> Vec<String>;
128}
129
130/// Trait for builders that support conditional configuration
131///
132/// This trait provides methods for conditionally applying configuration
133/// based on runtime conditions. This is useful for building schemas
134/// that depend on external factors or configuration.
135///
136/// # Examples
137///
138/// ```rust
139/// use ignis_db::builders::ConditionalBuilder;
140///
141/// let is_production = std::env::var("ENV").unwrap_or_default() == "production";
142///
143/// let table = TableBuilder::new("users")
144/// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
145/// .when(is_production, |t| t.comment("Production users table"))
146/// .when(!is_production, |t| t.comment("Development users table"))
147/// .build()?;
148/// ```
149pub trait ConditionalBuilder: SchemaBuilder {
150 /// Apply configuration conditionally
151 ///
152 /// This method applies the given configuration function only if
153 /// the condition is true. The function receives a mutable reference
154 /// to the builder and can modify it as needed.
155 ///
156 /// # Parameters
157 ///
158 /// - `condition`: The condition that determines whether to apply the configuration
159 /// - `config_fn`: A function that takes a mutable reference to the builder and modifies it
160 ///
161 /// # Returns
162 ///
163 /// `self` for method chaining
164 ///
165 /// # Examples
166 ///
167 /// ```rust
168 /// use ignis_db::builders::ConditionalBuilder;
169 ///
170 /// let table = TableBuilder::new("users")
171 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
172 /// .when(true, |t| t.comment("This comment will be applied"))
173 /// .when(false, |t| t.comment("This comment will NOT be applied"))
174 /// .build()?;
175 /// ```
176 fn when<F>(mut self, condition: bool, config_fn: F) -> Self
177 where
178 F: FnOnce(&mut Self),
179 Self: Sized,
180 {
181 if condition {
182 config_fn(&mut self);
183 }
184 self
185 }
186
187 /// Apply configuration conditionally with a default fallback
188 ///
189 /// This method applies one configuration function if the condition is true,
190 /// and a different configuration function if the condition is false.
191 ///
192 /// # Parameters
193 ///
194 /// - `condition`: The condition that determines which configuration to apply
195 /// - `if_true`: Function to apply when condition is true
196 /// - `if_false`: Function to apply when condition is false
197 ///
198 /// # Returns
199 ///
200 /// `self` for method chaining
201 ///
202 /// # Examples
203 ///
204 /// ```rust
205 /// use ignis_db::builders::ConditionalBuilder;
206 ///
207 /// let is_production = std::env::var("ENV").unwrap_or_default() == "production";
208 ///
209 /// let table = TableBuilder::new("users")
210 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
211 /// .when_else(
212 /// is_production,
213 /// |t| t.comment("Production table"),
214 /// |t| t.comment("Development table")
215 /// )
216 /// .build()?;
217 /// ```
218 fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
219 where
220 F: FnOnce(&mut Self),
221 G: FnOnce(&mut Self),
222 Self: Sized,
223 {
224 if condition {
225 if_true(&mut self);
226 } else {
227 if_false(&mut self);
228 }
229 self
230 }
231}
232
233/// Trait for builders that can be cloned for modification
234///
235/// This trait provides methods for creating modified copies of builders
236/// without consuming the original. This is useful for creating multiple
237/// variations of a schema or for testing different configurations.
238///
239/// # Examples
240///
241/// ```rust
242/// use ignis_db::builders::CloneableBuilder;
243///
244/// let base_table = TableBuilder::new("users")
245/// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
246///
247/// // Create a development version
248/// let dev_table = base_table.clone()
249/// .comment("Development users table")
250/// .build()?;
251///
252/// // Create a production version
253/// let prod_table = base_table.clone()
254/// .comment("Production users table")
255/// .build()?;
256/// ```
257pub trait CloneableBuilder: SchemaBuilder + Clone {
258 /// Create a modified copy of this builder
259 ///
260 /// This method creates a new builder with the same configuration
261 /// as the current one, allowing you to modify it without affecting
262 /// the original.
263 ///
264 /// # Parameters
265 ///
266 /// - `modify_fn`: A function that takes a mutable reference to the new builder and modifies it
267 ///
268 /// # Returns
269 ///
270 /// A new builder with the modified configuration
271 ///
272 /// # Examples
273 ///
274 /// ```rust
275 /// use ignis_db::builders::CloneableBuilder;
276 ///
277 /// let base_table = TableBuilder::new("users")
278 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
279 ///
280 /// let modified_table = base_table.modify(|t| {
281 /// t.comment("Modified table");
282 /// });
283 ///
284 /// // Both builders can now be used independently
285 /// let table1 = base_table.build()?;
286 /// let table2 = modified_table.build()?;
287 /// ```
288 fn modify<F>(self, modify_fn: F) -> Self
289 where
290 F: FnOnce(&mut Self),
291 Self: Sized,
292 {
293 let mut new_builder = self.clone();
294 modify_fn(&mut new_builder);
295 new_builder
296 }
297}
298
299/// Trait for builders that support debugging and inspection
300///
301/// This trait provides methods for inspecting the current state of a builder
302/// without consuming it. This is useful for debugging, logging, and
303/// understanding what configuration has been applied.
304///
305/// # Examples
306///
307/// ```rust
308/// use ignis_db::builders::InspectableBuilder;
309///
310/// let table_builder = TableBuilder::new("users")
311/// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
312///
313/// // Inspect the current configuration
314/// println!("Table name: {}", table_builder.name());
315/// println!("Column count: {}", table_builder.column_count());
316/// println!("Has primary key: {}", table_builder.has_primary_key());
317/// ```
318pub trait InspectableBuilder: SchemaBuilder {
319 /// Get a debug representation of the current builder state
320 ///
321 /// This method returns a debug representation that shows the current
322 /// configuration of the builder. This is useful for debugging and
323 /// understanding what has been configured.
324 ///
325 /// # Returns
326 ///
327 /// A debug representation of the builder state
328 ///
329 /// # Examples
330 ///
331 /// ```rust
332 /// use ignis_db::builders::InspectableBuilder;
333 ///
334 /// let table_builder = TableBuilder::new("users")
335 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
336 ///
337 /// println!("Builder state: {:?}", table_builder.debug_info());
338 /// ```
339 fn debug_info(&self) -> String;
340
341 /// Get a summary of the current configuration
342 ///
343 /// This method returns a human-readable summary of the current
344 /// builder configuration. This is useful for logging and user
345 /// feedback.
346 ///
347 /// # Returns
348 ///
349 /// A human-readable summary of the configuration
350 ///
351 /// # Examples
352 ///
353 /// ```rust
354 /// use ignis_db::builders::InspectableBuilder;
355 ///
356 /// let table_builder = TableBuilder::new("users")
357 /// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
358 ///
359 /// println!("Configuration summary: {}", table_builder.summary());
360 /// ```
361 fn summary(&self) -> String;
362}
363
364// Re-export commonly used traits
365pub use CloneableBuilder as Cloneable;
366pub use ConditionalBuilder as Conditional;
367pub use InspectableBuilder as Inspectable;
368pub use SchemaBuilder as Builder;
369pub use ValidatableBuilder as Validatable;
370
371/// Trait for column builders specifically
372pub trait ColumnBuilderTrait: SchemaBuilder<Output = crate::schema::Column> {
373 fn nullable(self) -> Self;
374 fn not_null(self) -> Self;
375 fn default(self, default: impl Into<String>) -> Self;
376 fn primary_key(self) -> Self;
377 fn unique(self) -> Self;
378}