Skip to main content

ignis_db/builders/
view.rs

1use crate::builders::traits::{
2    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
3};
4use crate::builders::validation::ViewBuildError;
5use crate::schema::{Column, ColumnType, View};
6use std::collections::HashSet;
7
8/// Builder for constructing database views
9#[derive(Debug, Clone)]
10pub struct ViewBuilder {
11    name: Option<String>,
12    schema: Option<String>,
13    query: Option<String>,
14    columns: Vec<String>,
15    materialized: bool,
16    with_data: bool,
17    check_option: Option<String>,
18    comment: Option<String>,
19}
20
21impl ViewBuilder {
22    /// Create a new view builder
23    pub fn new() -> Self {
24        Self {
25            name: None,
26            schema: None,
27            query: None,
28            columns: Vec::new(),
29            materialized: false,
30            with_data: false,
31            check_option: None,
32            comment: None,
33        }
34    }
35
36    /// Set the view name
37    pub fn name(mut self, name: impl Into<String>) -> Self {
38        self.name = Some(name.into());
39        self
40    }
41
42    /// Set the view name (mutable reference version for conditional building)
43    pub fn set_name(&mut self, name: impl Into<String>) {
44        self.name = Some(name.into());
45    }
46
47    /// Set the schema name
48    pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
49        self.schema = Some(schema.into());
50        self
51    }
52
53    /// Set the schema name (mutable reference version for conditional building)
54    pub fn set_schema(&mut self, schema: impl Into<String>) {
55        self.schema = Some(schema.into());
56    }
57
58    /// Set the view query
59    pub fn query(mut self, query: impl Into<String>) -> Self {
60        self.query = Some(query.into());
61        self
62    }
63
64    /// Set the view query (mutable reference version for conditional building)
65    pub fn set_query(&mut self, query: impl Into<String>) {
66        self.query = Some(query.into());
67    }
68
69    /// Add a column definition to the view
70    pub fn column(mut self, column: impl Into<String>) -> Self {
71        self.columns.push(column.into());
72        self
73    }
74
75    /// Add a column definition to the view (mutable reference version for conditional building)
76    pub fn add_column(&mut self, column: impl Into<String>) {
77        self.columns.push(column.into());
78    }
79
80    /// Add multiple column definitions to the view
81    pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
82        self.columns.extend(columns.into_iter().map(|c| c.into()));
83        self
84    }
85
86    /// Add multiple column definitions to the view (mutable reference version for conditional building)
87    pub fn add_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
88        self.columns.extend(columns.into_iter().map(|c| c.into()));
89    }
90
91    /// Make the view materialized
92    pub fn materialized(mut self) -> Self {
93        self.materialized = true;
94        self
95    }
96
97    /// Make the view materialized (mutable reference version for conditional building)
98    pub fn set_materialized(&mut self) {
99        self.materialized = true;
100    }
101
102    /// Set the view to be created with data (for materialized views)
103    pub fn with_data(mut self) -> Self {
104        self.with_data = true;
105        self
106    }
107
108    /// Set the view to be created with data (mutable reference version for conditional building)
109    pub fn set_with_data(&mut self) {
110        self.with_data = true;
111    }
112
113    /// Set the check option for updatable views
114    pub fn check_option(mut self, option: impl Into<String>) -> Self {
115        self.check_option = Some(option.into());
116        self
117    }
118
119    /// Set the check option for updatable views (mutable reference version for conditional building)
120    pub fn set_check_option(&mut self, option: impl Into<String>) {
121        self.check_option = Some(option.into());
122    }
123
124    /// Set a comment on the view
125    pub fn comment(mut self, comment: impl Into<String>) -> Self {
126        self.comment = Some(comment.into());
127        self
128    }
129
130    /// Set a comment on the view (mutable reference version for conditional building)
131    pub fn set_comment(&mut self, comment: impl Into<String>) {
132        self.comment = Some(comment.into());
133    }
134
135    // Convenience methods for specific view types
136    /// Create a simple view
137    pub fn simple() -> Self {
138        Self::new()
139    }
140
141    /// Create a materialized view
142    pub fn materialized_view() -> Self {
143        Self::new().materialized()
144    }
145
146    /// Create a view with check option
147    pub fn with_check_option(option: impl Into<String>) -> Self {
148        Self::new().check_option(option)
149    }
150
151    /// Create a view with local check option
152    pub fn with_local_check() -> Self {
153        Self::new().check_option("LOCAL")
154    }
155
156    /// Create a view with cascaded check option
157    pub fn with_cascaded_check() -> Self {
158        Self::new().check_option("CASCADED")
159    }
160
161    /// Create a view from a table
162    pub fn from_table(table_name: impl Into<String>) -> Self {
163        let table = table_name.into();
164        Self::new().query(format!("SELECT * FROM {}", table))
165    }
166
167    /// Create a view from a table with specific columns
168    pub fn from_table_columns(
169        table_name: impl Into<String>,
170        columns: impl IntoIterator<Item = impl Into<String>>,
171    ) -> Self {
172        let table = table_name.into();
173        let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
174        let cols_str = cols.join(", ");
175        Self::new()
176            .query(format!("SELECT {} FROM {}", cols_str, table))
177            .columns(cols)
178    }
179
180    /// Create a view with a JOIN
181    pub fn with_join(
182        table1: impl Into<String>,
183        table2: impl Into<String>,
184        join_condition: impl Into<String>,
185    ) -> Self {
186        let t1 = table1.into();
187        let t2 = table2.into();
188        let condition = join_condition.into();
189        Self::new().query(format!("SELECT * FROM {} JOIN {} ON {}", t1, t2, condition))
190    }
191
192    /// Create a view with aggregation
193    pub fn with_aggregation(
194        table_name: impl Into<String>,
195        group_by: impl Into<String>,
196        aggregates: impl IntoIterator<Item = impl Into<String>>,
197    ) -> Self {
198        let table = table_name.into();
199        let group = group_by.into();
200        let aggs: Vec<String> = aggregates.into_iter().map(|a| a.into()).collect();
201        let aggs_str = aggs.join(", ");
202        Self::new().query(format!(
203            "SELECT {}, {} FROM {} GROUP BY {}",
204            group, aggs_str, table, group
205        ))
206    }
207
208    // Inspection methods
209    /// Get the view name
210    pub fn get_name(&self) -> Option<&str> {
211        self.name.as_deref()
212    }
213
214    /// Get the schema name
215    pub fn get_schema(&self) -> Option<&str> {
216        self.schema.as_deref()
217    }
218
219    /// Get the view query
220    pub fn get_query(&self) -> Option<&str> {
221        self.query.as_deref()
222    }
223
224    /// Get the column definitions
225    pub fn get_columns(&self) -> &[String] {
226        &self.columns
227    }
228
229    /// Check if the view is materialized
230    pub fn is_materialized(&self) -> bool {
231        self.materialized
232    }
233
234    /// Check if the view is created with data
235    pub fn is_with_data(&self) -> bool {
236        self.with_data
237    }
238
239    /// Get the check option
240    pub fn get_check_option(&self) -> Option<&str> {
241        self.check_option.as_deref()
242    }
243
244    /// Get the comment
245    pub fn get_comment(&self) -> Option<&str> {
246        self.comment.as_deref()
247    }
248
249    /// Get the number of columns in the view
250    pub fn column_count(&self) -> usize {
251        self.columns.len()
252    }
253
254    /// Check if the view has a specific column
255    pub fn has_column(&self, column_name: &str) -> bool {
256        self.columns.iter().any(|c| c == column_name)
257    }
258
259    /// Check if the view has a name
260    pub fn has_name(&self) -> bool {
261        self.name.is_some()
262    }
263
264    /// Check if the view has a schema
265    pub fn has_schema(&self) -> bool {
266        self.schema.is_some()
267    }
268
269    /// Check if the view has a query
270    pub fn has_query(&self) -> bool {
271        self.query.is_some()
272    }
273
274    /// Check if the view has a check option
275    pub fn has_check_option(&self) -> bool {
276        self.check_option.is_some()
277    }
278
279    /// Check if the view has a comment
280    pub fn has_comment(&self) -> bool {
281        self.comment.is_some()
282    }
283}
284
285impl SchemaBuilder for ViewBuilder {
286    type Output = View;
287    type Error = ViewBuildError;
288
289    fn build(self) -> Result<Self::Output, Self::Error> {
290        // Validate the view before building
291        if !self.is_valid() {
292            let errors = self.validation_errors();
293            return Err(ViewBuildError::ValidationError(errors.join("; ")));
294        }
295
296        // Build the view
297        let view = View {
298            name: self.name.unwrap_or_else(|| "view".to_string()),
299            schema: self.schema,
300            columns: self
301                .columns
302                .iter()
303                .map(|col_name| Column::new(col_name.clone(), ColumnType::Text))
304                .collect(),
305            ddl: self.query.clone(),
306            materialized: self.materialized,
307            refresh_strategy: None,   // Default refresh strategy
308            dependencies: Vec::new(), // No dependencies by default
309            indexes: Vec::new(),      // No indexes by default
310        };
311
312        Ok(view)
313    }
314}
315
316impl ValidatableBuilder for ViewBuilder {
317    fn is_valid(&self) -> bool {
318        self.validation_errors().is_empty()
319    }
320
321    fn validation_errors(&self) -> Vec<String> {
322        let mut errors = Vec::new();
323
324        // Validate that a query is specified
325        if self.query.is_none() {
326            errors.push("View must have a query".to_string());
327        }
328
329        // Validate query is not empty if provided
330        if let Some(ref query) = self.query {
331            if query.trim().is_empty() {
332                errors.push("View query cannot be empty".to_string());
333            }
334        }
335
336        // Validate view name if provided
337        if let Some(ref name) = self.name {
338            if name.trim().is_empty() {
339                errors.push("View name cannot be empty".to_string());
340            }
341        }
342
343        // Validate schema name if provided
344        if let Some(ref schema) = self.schema {
345            if schema.trim().is_empty() {
346                errors.push("Schema name cannot be empty".to_string());
347            }
348        }
349
350        // Validate column names are not empty
351        for (i, column) in self.columns.iter().enumerate() {
352            if column.trim().is_empty() {
353                errors.push(format!("Column {} at index {} cannot be empty", i, i));
354            }
355        }
356
357        // Check for duplicate column names
358        let mut seen_columns = HashSet::new();
359        for column in &self.columns {
360            if !seen_columns.insert(column) {
361                errors.push(format!("Duplicate column name: {}", column));
362            }
363        }
364
365        // Validate check option if provided
366        if let Some(ref check_option) = self.check_option {
367            let valid_options = ["LOCAL", "CASCADED"];
368            if !valid_options.contains(&check_option.to_uppercase().as_str()) {
369                errors.push(format!(
370                    "Invalid check option: {}. Must be one of: {}",
371                    check_option,
372                    valid_options.join(", ")
373                ));
374            }
375        }
376
377        // Validate materialized view constraints
378        if self.materialized {
379            if self.check_option.is_some() {
380                errors.push("Materialized views cannot have check options".to_string());
381            }
382        }
383
384        errors
385    }
386}
387
388impl ConditionalBuilder for ViewBuilder {
389    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
390    where
391        F: FnOnce(&mut Self),
392        Self: Sized,
393    {
394        if condition {
395            config_fn(&mut self);
396        }
397        self
398    }
399}
400
401impl InspectableBuilder for ViewBuilder {
402    fn debug_info(&self) -> String {
403        format!(
404            "ViewBuilder {{ name: {:?}, schema: {:?}, query: {:?}, columns: {:?}, materialized: {}, with_data: {}, check_option: {:?} }}",
405            self.name, self.schema, self.query, self.columns, self.materialized, self.with_data, self.check_option
406        )
407    }
408
409    fn summary(&self) -> String {
410        let mut parts = Vec::new();
411
412        // View type
413        if self.materialized {
414            parts.push("Materialized view".to_string());
415        } else {
416            parts.push("View".to_string());
417        }
418
419        // Name and schema
420        if let Some(ref name) = self.name {
421            if let Some(ref schema) = self.schema {
422                parts.push(format!("{}.{}", schema, name));
423            } else {
424                parts.push(format!("'{}'", name));
425            }
426        }
427
428        // Columns
429        if !self.columns.is_empty() {
430            parts.push(format!("with columns: {}", self.columns.join(", ")));
431        }
432
433        // Query preview
434        if let Some(ref query) = self.query {
435            let preview = if query.len() > 50 {
436                format!("{}...", &query[..50])
437            } else {
438                query.clone()
439            };
440            parts.push(format!("query: {}", preview));
441        }
442
443        // Materialized view options
444        if self.materialized {
445            if self.with_data {
446                parts.push("with data".to_string());
447            } else {
448                parts.push("without data".to_string());
449            }
450        }
451
452        // Check option
453        if let Some(ref check_option) = self.check_option {
454            parts.push(format!("check option: {}", check_option));
455        }
456
457        // Comment
458        if let Some(ref comment) = self.comment {
459            parts.push(format!("with comment: {}", comment));
460        }
461
462        parts.join(", ")
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn test_simple_view() {
472        let view = ViewBuilder::new()
473            .name("v_users")
474            .query("SELECT id, email FROM users")
475            .build()
476            .unwrap();
477
478        assert_eq!(view.name, "v_users");
479        assert_eq!(view.ddl, Some("SELECT id, email FROM users".to_string()));
480        assert!(!view.materialized);
481    }
482
483    #[test]
484    fn test_materialized_view() {
485        let view = ViewBuilder::materialized_view()
486            .name("mv_users_summary")
487            .query("SELECT status, COUNT(*) FROM users GROUP BY status")
488            .with_data()
489            .build()
490            .unwrap();
491
492        assert_eq!(view.name, "mv_users_summary");
493        assert!(view.materialized);
494    }
495
496    #[test]
497    fn test_view_with_columns() {
498        let view = ViewBuilder::new()
499            .name("v_user_details")
500            .query("SELECT id, email, name FROM users")
501            .columns(vec!["id", "email", "name"])
502            .build()
503            .unwrap();
504
505        assert_eq!(view.name, "v_user_details");
506        assert_eq!(view.columns.len(), 3);
507        assert_eq!(view.columns[0].name, "id");
508        assert_eq!(view.columns[1].name, "email");
509        assert_eq!(view.columns[2].name, "name");
510    }
511
512    #[test]
513    fn test_view_with_check_option() {
514        let view = ViewBuilder::with_local_check()
515            .name("v_updatable_users")
516            .query("SELECT id, email FROM users WHERE active = true")
517            .build()
518            .unwrap();
519
520        assert_eq!(view.name, "v_updatable_users");
521        // Note: check_option is not stored in the actual View struct
522    }
523
524    #[test]
525    fn test_view_with_schema() {
526        let view = ViewBuilder::new()
527            .name("v_users")
528            .in_schema("public")
529            .query("SELECT * FROM users")
530            .build()
531            .unwrap();
532
533        assert_eq!(view.name, "v_users");
534        assert_eq!(view.schema, Some("public".to_string()));
535    }
536
537    #[test]
538    fn test_convenience_methods() {
539        let from_table_view = ViewBuilder::from_table("users")
540            .name("v_users")
541            .build()
542            .unwrap();
543
544        let from_table_columns_view = ViewBuilder::from_table_columns("users", vec!["id", "email"])
545            .name("v_users_limited")
546            .build()
547            .unwrap();
548
549        let join_view = ViewBuilder::with_join("users", "posts", "users.id = posts.user_id")
550            .name("v_user_posts")
551            .build()
552            .unwrap();
553
554        let agg_view = ViewBuilder::with_aggregation("users", "status", vec!["COUNT(*)"])
555            .name("v_user_status_count")
556            .build()
557            .unwrap();
558
559        assert_eq!(from_table_view.name, "v_users");
560        assert_eq!(from_table_columns_view.name, "v_users_limited");
561        assert_eq!(join_view.name, "v_user_posts");
562        assert_eq!(agg_view.name, "v_user_status_count");
563    }
564
565    #[test]
566    fn test_validation_errors() {
567        // No query
568        let result = ViewBuilder::new().name("v_test").build();
569        assert!(result.is_err());
570        assert!(matches!(
571            result.unwrap_err(),
572            ViewBuildError::ValidationError(_)
573        ));
574
575        // Empty query
576        let result = ViewBuilder::new().name("v_test").query("").build();
577        assert!(result.is_err());
578        assert!(matches!(
579            result.unwrap_err(),
580            ViewBuildError::ValidationError(_)
581        ));
582
583        // Invalid check option
584        let result = ViewBuilder::new()
585            .name("v_test")
586            .query("SELECT 1")
587            .check_option("INVALID")
588            .build();
589        assert!(result.is_err());
590        assert!(matches!(
591            result.unwrap_err(),
592            ViewBuildError::ValidationError(_)
593        ));
594
595        // Materialized view with check option
596        let result = ViewBuilder::materialized_view()
597            .name("v_test")
598            .query("SELECT 1")
599            .check_option("LOCAL")
600            .build();
601        assert!(result.is_err());
602        assert!(matches!(
603            result.unwrap_err(),
604            ViewBuildError::ValidationError(_)
605        ));
606    }
607
608    #[test]
609    fn test_conditional_builder() {
610        let condition = true;
611        let view = ViewBuilder::new()
612            .when(condition, |v| {
613                v.set_name("v_when_true");
614                v.set_query("SELECT * FROM table1");
615            })
616            .build()
617            .unwrap();
618
619        assert_eq!(view.name, "v_when_true");
620        assert_eq!(view.ddl, Some("SELECT * FROM table1".to_string()));
621    }
622
623    #[test]
624    fn test_inspection_methods() {
625        let builder = ViewBuilder::new()
626            .name("v_test")
627            .in_schema("public")
628            .columns(vec!["col1", "col2"]);
629
630        assert_eq!(builder.get_name(), Some("v_test"));
631        assert_eq!(builder.get_schema(), Some("public"));
632        assert_eq!(builder.get_columns(), &["col1", "col2"]);
633        assert_eq!(builder.column_count(), 2);
634        assert!(builder.has_column("col1"));
635        assert!(!builder.has_column("nonexistent"));
636        assert!(builder.has_name());
637        assert!(builder.has_schema());
638        assert!(!builder.has_query());
639        assert!(!builder.has_check_option());
640        assert!(!builder.has_comment());
641        assert!(!builder.is_materialized());
642        assert!(!builder.is_with_data());
643    }
644
645    #[test]
646    fn test_debug_info_and_summary() {
647        let builder = ViewBuilder::new()
648            .name("v_users")
649            .in_schema("public")
650            .query("SELECT id, email FROM users WHERE active = true")
651            .columns(vec!["id", "email"])
652            .comment("Active users view");
653
654        let debug_info = builder.debug_info();
655        let summary = builder.summary();
656
657        assert!(debug_info.contains("ViewBuilder"));
658        assert!(debug_info.contains("v_users"));
659        assert!(debug_info.contains("public"));
660
661        assert!(summary.contains("View"));
662        assert!(summary.contains("public.v_users"));
663        assert!(summary.contains("with columns: id, email"));
664        assert!(summary.contains("query: SELECT id, email FROM users WHERE active = true"));
665        assert!(summary.contains("with comment: Active users view"));
666    }
667}