use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ViewBuildError;
use crate::schema::{Column, ColumnType, View};
use std::collections::HashSet;
#[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 {
pub fn new() -> Self {
Self {
name: None,
schema: None,
query: None,
columns: Vec::new(),
materialized: false,
with_data: false,
check_option: None,
comment: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn set_name(&mut self, name: impl Into<String>) {
self.name = Some(name.into());
}
pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn set_schema(&mut self, schema: impl Into<String>) {
self.schema = Some(schema.into());
}
pub fn query(mut self, query: impl Into<String>) -> Self {
self.query = Some(query.into());
self
}
pub fn set_query(&mut self, query: impl Into<String>) {
self.query = Some(query.into());
}
pub fn column(mut self, column: impl Into<String>) -> Self {
self.columns.push(column.into());
self
}
pub fn add_column(&mut self, column: impl Into<String>) {
self.columns.push(column.into());
}
pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.columns.extend(columns.into_iter().map(|c| c.into()));
self
}
pub fn add_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
self.columns.extend(columns.into_iter().map(|c| c.into()));
}
pub fn materialized(mut self) -> Self {
self.materialized = true;
self
}
pub fn set_materialized(&mut self) {
self.materialized = true;
}
pub fn with_data(mut self) -> Self {
self.with_data = true;
self
}
pub fn set_with_data(&mut self) {
self.with_data = true;
}
pub fn check_option(mut self, option: impl Into<String>) -> Self {
self.check_option = Some(option.into());
self
}
pub fn set_check_option(&mut self, option: impl Into<String>) {
self.check_option = Some(option.into());
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn set_comment(&mut self, comment: impl Into<String>) {
self.comment = Some(comment.into());
}
pub fn simple() -> Self {
Self::new()
}
pub fn materialized_view() -> Self {
Self::new().materialized()
}
pub fn with_check_option(option: impl Into<String>) -> Self {
Self::new().check_option(option)
}
pub fn with_local_check() -> Self {
Self::new().check_option("LOCAL")
}
pub fn with_cascaded_check() -> Self {
Self::new().check_option("CASCADED")
}
pub fn from_table(table_name: impl Into<String>) -> Self {
let table = table_name.into();
Self::new().query(format!("SELECT * FROM {}", table))
}
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)
}
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))
}
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
))
}
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn get_query(&self) -> Option<&str> {
self.query.as_deref()
}
pub fn get_columns(&self) -> &[String] {
&self.columns
}
pub fn is_materialized(&self) -> bool {
self.materialized
}
pub fn is_with_data(&self) -> bool {
self.with_data
}
pub fn get_check_option(&self) -> Option<&str> {
self.check_option.as_deref()
}
pub fn get_comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn column_count(&self) -> usize {
self.columns.len()
}
pub fn has_column(&self, column_name: &str) -> bool {
self.columns.iter().any(|c| c == column_name)
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
pub fn has_schema(&self) -> bool {
self.schema.is_some()
}
pub fn has_query(&self) -> bool {
self.query.is_some()
}
pub fn has_check_option(&self) -> bool {
self.check_option.is_some()
}
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> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(ViewBuildError::ValidationError(errors.join("; ")));
}
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, dependencies: Vec::new(), indexes: Vec::new(), };
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();
if self.query.is_none() {
errors.push("View must have a query".to_string());
}
if let Some(ref query) = self.query {
if query.trim().is_empty() {
errors.push("View query cannot be empty".to_string());
}
}
if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("View name cannot be empty".to_string());
}
}
if let Some(ref schema) = self.schema {
if schema.trim().is_empty() {
errors.push("Schema name cannot be empty".to_string());
}
}
for (i, column) in self.columns.iter().enumerate() {
if column.trim().is_empty() {
errors.push(format!("Column {} at index {} cannot be empty", i, i));
}
}
let mut seen_columns = HashSet::new();
for column in &self.columns {
if !seen_columns.insert(column) {
errors.push(format!("Duplicate column name: {}", column));
}
}
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(", ")
));
}
}
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();
if self.materialized {
parts.push("Materialized view".to_string());
} else {
parts.push("View".to_string());
}
if let Some(ref name) = self.name {
if let Some(ref schema) = self.schema {
parts.push(format!("{}.{}", schema, name));
} else {
parts.push(format!("'{}'", name));
}
}
if !self.columns.is_empty() {
parts.push(format!("with columns: {}", self.columns.join(", ")));
}
if let Some(ref query) = self.query {
let preview = if query.len() > 50 {
format!("{}...", &query[..50])
} else {
query.clone()
};
parts.push(format!("query: {}", preview));
}
if self.materialized {
if self.with_data {
parts.push("with data".to_string());
} else {
parts.push("without data".to_string());
}
}
if let Some(ref check_option) = self.check_option {
parts.push(format!("check option: {}", check_option));
}
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");
}
#[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() {
let result = ViewBuilder::new().name("v_test").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ViewBuildError::ValidationError(_)
));
let result = ViewBuilder::new().name("v_test").query("").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ViewBuildError::ValidationError(_)
));
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(_)
));
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"));
}
}