ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ViewBuildError;
use crate::schema::{Column, ColumnType, View};
use std::collections::HashSet;

/// Builder for constructing database views
#[derive(Debug, Clone)]
pub struct ViewBuilder {
    name: Option<String>,
    schema: Option<String>,
    query: Option<String>,
    columns: Vec<String>,
    materialized: bool,
    with_data: bool,
    check_option: Option<String>,
    comment: Option<String>,
}

impl ViewBuilder {
    /// Create a new view builder
    pub fn new() -> Self {
        Self {
            name: None,
            schema: None,
            query: None,
            columns: Vec::new(),
            materialized: false,
            with_data: false,
            check_option: None,
            comment: None,
        }
    }

    /// Set the view name
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the view name (mutable reference version for conditional building)
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = Some(name.into());
    }

    /// Set the schema name
    pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Set the schema name (mutable reference version for conditional building)
    pub fn set_schema(&mut self, schema: impl Into<String>) {
        self.schema = Some(schema.into());
    }

    /// Set the view query
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query = Some(query.into());
        self
    }

    /// Set the view query (mutable reference version for conditional building)
    pub fn set_query(&mut self, query: impl Into<String>) {
        self.query = Some(query.into());
    }

    /// Add a column definition to the view
    pub fn column(mut self, column: impl Into<String>) -> Self {
        self.columns.push(column.into());
        self
    }

    /// Add a column definition to the view (mutable reference version for conditional building)
    pub fn add_column(&mut self, column: impl Into<String>) {
        self.columns.push(column.into());
    }

    /// Add multiple column definitions to the view
    pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.columns.extend(columns.into_iter().map(|c| c.into()));
        self
    }

    /// Add multiple column definitions to the view (mutable reference version for conditional building)
    pub fn add_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
        self.columns.extend(columns.into_iter().map(|c| c.into()));
    }

    /// Make the view materialized
    pub fn materialized(mut self) -> Self {
        self.materialized = true;
        self
    }

    /// Make the view materialized (mutable reference version for conditional building)
    pub fn set_materialized(&mut self) {
        self.materialized = true;
    }

    /// Set the view to be created with data (for materialized views)
    pub fn with_data(mut self) -> Self {
        self.with_data = true;
        self
    }

    /// Set the view to be created with data (mutable reference version for conditional building)
    pub fn set_with_data(&mut self) {
        self.with_data = true;
    }

    /// Set the check option for updatable views
    pub fn check_option(mut self, option: impl Into<String>) -> Self {
        self.check_option = Some(option.into());
        self
    }

    /// Set the check option for updatable views (mutable reference version for conditional building)
    pub fn set_check_option(&mut self, option: impl Into<String>) {
        self.check_option = Some(option.into());
    }

    /// Set a comment on the view
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set a comment on the view (mutable reference version for conditional building)
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.comment = Some(comment.into());
    }

    // Convenience methods for specific view types
    /// Create a simple view
    pub fn simple() -> Self {
        Self::new()
    }

    /// Create a materialized view
    pub fn materialized_view() -> Self {
        Self::new().materialized()
    }

    /// Create a view with check option
    pub fn with_check_option(option: impl Into<String>) -> Self {
        Self::new().check_option(option)
    }

    /// Create a view with local check option
    pub fn with_local_check() -> Self {
        Self::new().check_option("LOCAL")
    }

    /// Create a view with cascaded check option
    pub fn with_cascaded_check() -> Self {
        Self::new().check_option("CASCADED")
    }

    /// Create a view from a table
    pub fn from_table(table_name: impl Into<String>) -> Self {
        let table = table_name.into();
        Self::new().query(format!("SELECT * FROM {}", table))
    }

    /// Create a view from a table with specific columns
    pub fn from_table_columns(
        table_name: impl Into<String>,
        columns: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let table = table_name.into();
        let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
        let cols_str = cols.join(", ");
        Self::new()
            .query(format!("SELECT {} FROM {}", cols_str, table))
            .columns(cols)
    }

    /// Create a view with a JOIN
    pub fn with_join(
        table1: impl Into<String>,
        table2: impl Into<String>,
        join_condition: impl Into<String>,
    ) -> Self {
        let t1 = table1.into();
        let t2 = table2.into();
        let condition = join_condition.into();
        Self::new().query(format!("SELECT * FROM {} JOIN {} ON {}", t1, t2, condition))
    }

    /// Create a view with aggregation
    pub fn with_aggregation(
        table_name: impl Into<String>,
        group_by: impl Into<String>,
        aggregates: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let table = table_name.into();
        let group = group_by.into();
        let aggs: Vec<String> = aggregates.into_iter().map(|a| a.into()).collect();
        let aggs_str = aggs.join(", ");
        Self::new().query(format!(
            "SELECT {}, {} FROM {} GROUP BY {}",
            group, aggs_str, table, group
        ))
    }

    // Inspection methods
    /// Get the view name
    pub fn get_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Get the schema name
    pub fn get_schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// Get the view query
    pub fn get_query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    /// Get the column definitions
    pub fn get_columns(&self) -> &[String] {
        &self.columns
    }

    /// Check if the view is materialized
    pub fn is_materialized(&self) -> bool {
        self.materialized
    }

    /// Check if the view is created with data
    pub fn is_with_data(&self) -> bool {
        self.with_data
    }

    /// Get the check option
    pub fn get_check_option(&self) -> Option<&str> {
        self.check_option.as_deref()
    }

    /// Get the comment
    pub fn get_comment(&self) -> Option<&str> {
        self.comment.as_deref()
    }

    /// Get the number of columns in the view
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// Check if the view has a specific column
    pub fn has_column(&self, column_name: &str) -> bool {
        self.columns.iter().any(|c| c == column_name)
    }

    /// Check if the view has a name
    pub fn has_name(&self) -> bool {
        self.name.is_some()
    }

    /// Check if the view has a schema
    pub fn has_schema(&self) -> bool {
        self.schema.is_some()
    }

    /// Check if the view has a query
    pub fn has_query(&self) -> bool {
        self.query.is_some()
    }

    /// Check if the view has a check option
    pub fn has_check_option(&self) -> bool {
        self.check_option.is_some()
    }

    /// Check if the view has a comment
    pub fn has_comment(&self) -> bool {
        self.comment.is_some()
    }
}

impl SchemaBuilder for ViewBuilder {
    type Output = View;
    type Error = ViewBuildError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        // Validate the view before building
        if !self.is_valid() {
            let errors = self.validation_errors();
            return Err(ViewBuildError::ValidationError(errors.join("; ")));
        }

        // Build the view
        let view = View {
            name: self.name.unwrap_or_else(|| "view".to_string()),
            schema: self.schema,
            columns: self
                .columns
                .iter()
                .map(|col_name| Column::new(col_name.clone(), ColumnType::Text))
                .collect(),
            ddl: self.query.clone(),
            materialized: self.materialized,
            refresh_strategy: None,   // Default refresh strategy
            dependencies: Vec::new(), // No dependencies by default
            indexes: Vec::new(),      // No indexes by default
        };

        Ok(view)
    }
}

impl ValidatableBuilder for ViewBuilder {
    fn is_valid(&self) -> bool {
        self.validation_errors().is_empty()
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Validate that a query is specified
        if self.query.is_none() {
            errors.push("View must have a query".to_string());
        }

        // Validate query is not empty if provided
        if let Some(ref query) = self.query {
            if query.trim().is_empty() {
                errors.push("View query cannot be empty".to_string());
            }
        }

        // Validate view name if provided
        if let Some(ref name) = self.name {
            if name.trim().is_empty() {
                errors.push("View name cannot be empty".to_string());
            }
        }

        // Validate schema name if provided
        if let Some(ref schema) = self.schema {
            if schema.trim().is_empty() {
                errors.push("Schema name cannot be empty".to_string());
            }
        }

        // Validate column names are not empty
        for (i, column) in self.columns.iter().enumerate() {
            if column.trim().is_empty() {
                errors.push(format!("Column {} at index {} cannot be empty", i, i));
            }
        }

        // Check for duplicate column names
        let mut seen_columns = HashSet::new();
        for column in &self.columns {
            if !seen_columns.insert(column) {
                errors.push(format!("Duplicate column name: {}", column));
            }
        }

        // Validate check option if provided
        if let Some(ref check_option) = self.check_option {
            let valid_options = ["LOCAL", "CASCADED"];
            if !valid_options.contains(&check_option.to_uppercase().as_str()) {
                errors.push(format!(
                    "Invalid check option: {}. Must be one of: {}",
                    check_option,
                    valid_options.join(", ")
                ));
            }
        }

        // Validate materialized view constraints
        if self.materialized {
            if self.check_option.is_some() {
                errors.push("Materialized views cannot have check options".to_string());
            }
        }

        errors
    }
}

impl ConditionalBuilder for ViewBuilder {
    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
    where
        F: FnOnce(&mut Self),
        Self: Sized,
    {
        if condition {
            config_fn(&mut self);
        }
        self
    }
}

impl InspectableBuilder for ViewBuilder {
    fn debug_info(&self) -> String {
        format!(
            "ViewBuilder {{ name: {:?}, schema: {:?}, query: {:?}, columns: {:?}, materialized: {}, with_data: {}, check_option: {:?} }}",
            self.name, self.schema, self.query, self.columns, self.materialized, self.with_data, self.check_option
        )
    }

    fn summary(&self) -> String {
        let mut parts = Vec::new();

        // View type
        if self.materialized {
            parts.push("Materialized view".to_string());
        } else {
            parts.push("View".to_string());
        }

        // Name and schema
        if let Some(ref name) = self.name {
            if let Some(ref schema) = self.schema {
                parts.push(format!("{}.{}", schema, name));
            } else {
                parts.push(format!("'{}'", name));
            }
        }

        // Columns
        if !self.columns.is_empty() {
            parts.push(format!("with columns: {}", self.columns.join(", ")));
        }

        // Query preview
        if let Some(ref query) = self.query {
            let preview = if query.len() > 50 {
                format!("{}...", &query[..50])
            } else {
                query.clone()
            };
            parts.push(format!("query: {}", preview));
        }

        // Materialized view options
        if self.materialized {
            if self.with_data {
                parts.push("with data".to_string());
            } else {
                parts.push("without data".to_string());
            }
        }

        // Check option
        if let Some(ref check_option) = self.check_option {
            parts.push(format!("check option: {}", check_option));
        }

        // Comment
        if let Some(ref comment) = self.comment {
            parts.push(format!("with comment: {}", comment));
        }

        parts.join(", ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_view() {
        let view = ViewBuilder::new()
            .name("v_users")
            .query("SELECT id, email FROM users")
            .build()
            .unwrap();

        assert_eq!(view.name, "v_users");
        assert_eq!(view.ddl, Some("SELECT id, email FROM users".to_string()));
        assert!(!view.materialized);
    }

    #[test]
    fn test_materialized_view() {
        let view = ViewBuilder::materialized_view()
            .name("mv_users_summary")
            .query("SELECT status, COUNT(*) FROM users GROUP BY status")
            .with_data()
            .build()
            .unwrap();

        assert_eq!(view.name, "mv_users_summary");
        assert!(view.materialized);
    }

    #[test]
    fn test_view_with_columns() {
        let view = ViewBuilder::new()
            .name("v_user_details")
            .query("SELECT id, email, name FROM users")
            .columns(vec!["id", "email", "name"])
            .build()
            .unwrap();

        assert_eq!(view.name, "v_user_details");
        assert_eq!(view.columns.len(), 3);
        assert_eq!(view.columns[0].name, "id");
        assert_eq!(view.columns[1].name, "email");
        assert_eq!(view.columns[2].name, "name");
    }

    #[test]
    fn test_view_with_check_option() {
        let view = ViewBuilder::with_local_check()
            .name("v_updatable_users")
            .query("SELECT id, email FROM users WHERE active = true")
            .build()
            .unwrap();

        assert_eq!(view.name, "v_updatable_users");
        // Note: check_option is not stored in the actual View struct
    }

    #[test]
    fn test_view_with_schema() {
        let view = ViewBuilder::new()
            .name("v_users")
            .in_schema("public")
            .query("SELECT * FROM users")
            .build()
            .unwrap();

        assert_eq!(view.name, "v_users");
        assert_eq!(view.schema, Some("public".to_string()));
    }

    #[test]
    fn test_convenience_methods() {
        let from_table_view = ViewBuilder::from_table("users")
            .name("v_users")
            .build()
            .unwrap();

        let from_table_columns_view = ViewBuilder::from_table_columns("users", vec!["id", "email"])
            .name("v_users_limited")
            .build()
            .unwrap();

        let join_view = ViewBuilder::with_join("users", "posts", "users.id = posts.user_id")
            .name("v_user_posts")
            .build()
            .unwrap();

        let agg_view = ViewBuilder::with_aggregation("users", "status", vec!["COUNT(*)"])
            .name("v_user_status_count")
            .build()
            .unwrap();

        assert_eq!(from_table_view.name, "v_users");
        assert_eq!(from_table_columns_view.name, "v_users_limited");
        assert_eq!(join_view.name, "v_user_posts");
        assert_eq!(agg_view.name, "v_user_status_count");
    }

    #[test]
    fn test_validation_errors() {
        // No query
        let result = ViewBuilder::new().name("v_test").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ViewBuildError::ValidationError(_)
        ));

        // Empty query
        let result = ViewBuilder::new().name("v_test").query("").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ViewBuildError::ValidationError(_)
        ));

        // Invalid check option
        let result = ViewBuilder::new()
            .name("v_test")
            .query("SELECT 1")
            .check_option("INVALID")
            .build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ViewBuildError::ValidationError(_)
        ));

        // Materialized view with check option
        let result = ViewBuilder::materialized_view()
            .name("v_test")
            .query("SELECT 1")
            .check_option("LOCAL")
            .build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ViewBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_conditional_builder() {
        let condition = true;
        let view = ViewBuilder::new()
            .when(condition, |v| {
                v.set_name("v_when_true");
                v.set_query("SELECT * FROM table1");
            })
            .build()
            .unwrap();

        assert_eq!(view.name, "v_when_true");
        assert_eq!(view.ddl, Some("SELECT * FROM table1".to_string()));
    }

    #[test]
    fn test_inspection_methods() {
        let builder = ViewBuilder::new()
            .name("v_test")
            .in_schema("public")
            .columns(vec!["col1", "col2"]);

        assert_eq!(builder.get_name(), Some("v_test"));
        assert_eq!(builder.get_schema(), Some("public"));
        assert_eq!(builder.get_columns(), &["col1", "col2"]);
        assert_eq!(builder.column_count(), 2);
        assert!(builder.has_column("col1"));
        assert!(!builder.has_column("nonexistent"));
        assert!(builder.has_name());
        assert!(builder.has_schema());
        assert!(!builder.has_query());
        assert!(!builder.has_check_option());
        assert!(!builder.has_comment());
        assert!(!builder.is_materialized());
        assert!(!builder.is_with_data());
    }

    #[test]
    fn test_debug_info_and_summary() {
        let builder = ViewBuilder::new()
            .name("v_users")
            .in_schema("public")
            .query("SELECT id, email FROM users WHERE active = true")
            .columns(vec!["id", "email"])
            .comment("Active users view");

        let debug_info = builder.debug_info();
        let summary = builder.summary();

        assert!(debug_info.contains("ViewBuilder"));
        assert!(debug_info.contains("v_users"));
        assert!(debug_info.contains("public"));

        assert!(summary.contains("View"));
        assert!(summary.contains("public.v_users"));
        assert!(summary.contains("with columns: id, email"));
        assert!(summary.contains("query: SELECT id, email FROM users WHERE active = true"));
        assert!(summary.contains("with comment: Active users view"));
    }
}