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#[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 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 pub fn name(mut self, name: impl Into<String>) -> Self {
38 self.name = Some(name.into());
39 self
40 }
41
42 pub fn set_name(&mut self, name: impl Into<String>) {
44 self.name = Some(name.into());
45 }
46
47 pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
49 self.schema = Some(schema.into());
50 self
51 }
52
53 pub fn set_schema(&mut self, schema: impl Into<String>) {
55 self.schema = Some(schema.into());
56 }
57
58 pub fn query(mut self, query: impl Into<String>) -> Self {
60 self.query = Some(query.into());
61 self
62 }
63
64 pub fn set_query(&mut self, query: impl Into<String>) {
66 self.query = Some(query.into());
67 }
68
69 pub fn column(mut self, column: impl Into<String>) -> Self {
71 self.columns.push(column.into());
72 self
73 }
74
75 pub fn add_column(&mut self, column: impl Into<String>) {
77 self.columns.push(column.into());
78 }
79
80 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 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 pub fn materialized(mut self) -> Self {
93 self.materialized = true;
94 self
95 }
96
97 pub fn set_materialized(&mut self) {
99 self.materialized = true;
100 }
101
102 pub fn with_data(mut self) -> Self {
104 self.with_data = true;
105 self
106 }
107
108 pub fn set_with_data(&mut self) {
110 self.with_data = true;
111 }
112
113 pub fn check_option(mut self, option: impl Into<String>) -> Self {
115 self.check_option = Some(option.into());
116 self
117 }
118
119 pub fn set_check_option(&mut self, option: impl Into<String>) {
121 self.check_option = Some(option.into());
122 }
123
124 pub fn comment(mut self, comment: impl Into<String>) -> Self {
126 self.comment = Some(comment.into());
127 self
128 }
129
130 pub fn set_comment(&mut self, comment: impl Into<String>) {
132 self.comment = Some(comment.into());
133 }
134
135 pub fn simple() -> Self {
138 Self::new()
139 }
140
141 pub fn materialized_view() -> Self {
143 Self::new().materialized()
144 }
145
146 pub fn with_check_option(option: impl Into<String>) -> Self {
148 Self::new().check_option(option)
149 }
150
151 pub fn with_local_check() -> Self {
153 Self::new().check_option("LOCAL")
154 }
155
156 pub fn with_cascaded_check() -> Self {
158 Self::new().check_option("CASCADED")
159 }
160
161 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 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 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 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 pub fn get_name(&self) -> Option<&str> {
211 self.name.as_deref()
212 }
213
214 pub fn get_schema(&self) -> Option<&str> {
216 self.schema.as_deref()
217 }
218
219 pub fn get_query(&self) -> Option<&str> {
221 self.query.as_deref()
222 }
223
224 pub fn get_columns(&self) -> &[String] {
226 &self.columns
227 }
228
229 pub fn is_materialized(&self) -> bool {
231 self.materialized
232 }
233
234 pub fn is_with_data(&self) -> bool {
236 self.with_data
237 }
238
239 pub fn get_check_option(&self) -> Option<&str> {
241 self.check_option.as_deref()
242 }
243
244 pub fn get_comment(&self) -> Option<&str> {
246 self.comment.as_deref()
247 }
248
249 pub fn column_count(&self) -> usize {
251 self.columns.len()
252 }
253
254 pub fn has_column(&self, column_name: &str) -> bool {
256 self.columns.iter().any(|c| c == column_name)
257 }
258
259 pub fn has_name(&self) -> bool {
261 self.name.is_some()
262 }
263
264 pub fn has_schema(&self) -> bool {
266 self.schema.is_some()
267 }
268
269 pub fn has_query(&self) -> bool {
271 self.query.is_some()
272 }
273
274 pub fn has_check_option(&self) -> bool {
276 self.check_option.is_some()
277 }
278
279 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 if !self.is_valid() {
292 let errors = self.validation_errors();
293 return Err(ViewBuildError::ValidationError(errors.join("; ")));
294 }
295
296 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, dependencies: Vec::new(), indexes: Vec::new(), };
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 if self.query.is_none() {
326 errors.push("View must have a query".to_string());
327 }
328
329 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 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 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 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 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 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 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 if self.materialized {
414 parts.push("Materialized view".to_string());
415 } else {
416 parts.push("View".to_string());
417 }
418
419 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 if !self.columns.is_empty() {
430 parts.push(format!("with columns: {}", self.columns.join(", ")));
431 }
432
433 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 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 if let Some(ref check_option) = self.check_option {
454 parts.push(format!("check option: {}", check_option));
455 }
456
457 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 }
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 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 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 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 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}