use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::IndexBuildError;
use crate::schema::{Index, IndexType};
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct IndexBuilder {
name: Option<String>,
columns: Vec<String>,
unique: bool,
table_name: Option<String>,
schema: Option<String>,
index_type: IndexType,
partial: Option<String>,
include: Vec<String>,
storage_parameters: Vec<(String, String)>,
comment: Option<String>,
}
impl IndexBuilder {
pub fn new() -> Self {
Self {
name: None,
columns: Vec::new(),
unique: false,
table_name: None,
schema: None,
index_type: IndexType::BTree,
partial: None,
include: Vec::new(),
storage_parameters: Vec::new(),
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 on_table(mut self, table_name: impl Into<String>) -> Self {
self.table_name = Some(table_name.into());
self
}
pub fn set_table(&mut self, table_name: impl Into<String>) {
self.table_name = Some(table_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 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 index_type(mut self, index_type: IndexType) -> Self {
self.index_type = index_type;
self
}
pub fn set_index_type(&mut self, index_type: IndexType) {
self.index_type = index_type;
}
pub fn unique(mut self) -> Self {
self.unique = true;
self
}
pub fn set_unique(&mut self) {
self.unique = true;
}
pub fn partial(mut self, condition: impl Into<String>) -> Self {
self.partial = Some(condition.into());
self
}
pub fn set_partial(&mut self, condition: impl Into<String>) {
self.partial = Some(condition.into());
}
pub fn include(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.include.extend(columns.into_iter().map(|c| c.into()));
self
}
pub fn add_include(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
self.include.extend(columns.into_iter().map(|c| c.into()));
}
pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.storage_parameters.push((key.into(), value.into()));
self
}
pub fn add_storage_parameter(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.storage_parameters.push((key.into(), value.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 btree() -> Self {
Self::new().index_type(IndexType::BTree)
}
pub fn hash() -> Self {
Self::new().index_type(IndexType::Hash)
}
pub fn gist() -> Self {
Self::new().index_type(IndexType::GIST)
}
pub fn gin() -> Self {
Self::new().index_type(IndexType::GIN)
}
pub fn spgist() -> Self {
Self::new().index_type(IndexType::SPGIST)
}
pub fn brin() -> Self {
Self::new().index_type(IndexType::BRIN)
}
pub fn unique_index() -> Self {
Self::new().unique()
}
pub fn partial_index(condition: impl Into<String>) -> Self {
Self::new().partial(condition)
}
pub fn covering(
columns: impl IntoIterator<Item = impl Into<String>>,
include: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self::new().columns(columns).include(include)
}
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn get_table_name(&self) -> Option<&str> {
self.table_name.as_deref()
}
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn get_columns(&self) -> &[String] {
&self.columns
}
pub fn get_index_type(&self) -> &IndexType {
&self.index_type
}
pub fn is_unique(&self) -> bool {
self.unique
}
pub fn get_partial(&self) -> Option<&str> {
self.partial.as_deref()
}
pub fn get_include(&self) -> &[String] {
&self.include
}
pub fn get_storage_parameters(&self) -> &[(String, String)] {
&self.storage_parameters
}
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_table(&self) -> bool {
self.table_name.is_some()
}
pub fn has_schema(&self) -> bool {
self.schema.is_some()
}
pub fn has_partial(&self) -> bool {
self.partial.is_some()
}
pub fn has_include(&self) -> bool {
!self.include.is_empty()
}
pub fn has_storage_parameters(&self) -> bool {
!self.storage_parameters.is_empty()
}
pub fn has_comment(&self) -> bool {
self.comment.is_some()
}
}
impl SchemaBuilder for IndexBuilder {
type Output = Index;
type Error = IndexBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(IndexBuildError::ValidationError(errors.join("; ")));
}
let index = Index {
name: self.name.unwrap_or_else(|| "index".to_string()),
columns: self.columns,
unique: self.unique,
};
Ok(index)
}
}
impl ValidatableBuilder for IndexBuilder {
fn is_valid(&self) -> bool {
self.validation_errors().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.columns.is_empty() {
errors.push("Index must specify at least one column".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 name) = self.name {
if name.trim().is_empty() {
errors.push("Index name cannot be empty".to_string());
}
}
if let Some(ref table_name) = self.table_name {
if table_name.trim().is_empty() {
errors.push("Table 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());
}
}
if let Some(ref partial) = self.partial {
if partial.trim().is_empty() {
errors.push("Partial condition cannot be empty".to_string());
}
}
for (i, column) in self.include.iter().enumerate() {
if column.trim().is_empty() {
errors.push(format!(
"Included column {} at index {} cannot be empty",
i, i
));
}
}
let mut seen_include = HashSet::new();
for column in &self.include {
if !seen_include.insert(column) {
errors.push(format!("Duplicate included column name: {}", column));
}
}
for (key, value) in &self.storage_parameters {
if key.trim().is_empty() {
errors.push("Storage parameter key cannot be empty".to_string());
}
if value.trim().is_empty() {
errors.push("Storage parameter value cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for IndexBuilder {
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 IndexBuilder {
fn debug_info(&self) -> String {
format!(
"IndexBuilder {{ name: {:?}, table: {:?}, schema: {:?}, columns: {:?}, type: {:?}, unique: {}, partial: {:?}, include: {:?} }}",
self.name, self.table_name, self.schema, self.columns, self.index_type, self.unique, self.partial, self.include
)
}
fn summary(&self) -> String {
let mut parts = Vec::new();
let type_desc = match self.index_type {
IndexType::BTree => "B-tree",
IndexType::Hash => "Hash",
IndexType::GIST => "GiST",
IndexType::GIN => "GIN",
IndexType::SPGIST => "SP-GiST",
IndexType::BRIN => "BRIN",
};
if self.unique {
parts.push(format!("Unique {} index", type_desc));
} else {
parts.push(format!("{} index", type_desc));
}
if !self.columns.is_empty() {
parts.push(format!("on columns: {}", self.columns.join(", ")));
}
if let Some(ref table) = self.table_name {
if let Some(ref schema) = self.schema {
parts.push(format!("on {}.{}", schema, table));
} else {
parts.push(format!("on {}", table));
}
}
if let Some(ref name) = self.name {
parts.push(format!("named '{}'", name));
}
if let Some(ref partial) = self.partial {
parts.push(format!("with partial condition: {}", partial));
}
if !self.include.is_empty() {
parts.push(format!("including columns: {}", self.include.join(", ")));
}
if !self.storage_parameters.is_empty() {
let params: Vec<String> = self
.storage_parameters
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect();
parts.push(format!("with storage parameters: {}", params.join(", ")));
}
if let Some(ref comment) = self.comment {
parts.push(format!("with comment: {}", comment));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::IndexType;
#[test]
fn test_btree_index() {
let index = IndexBuilder::btree()
.name("idx_users_email")
.on_table("users")
.column("email")
.build()
.unwrap();
assert_eq!(index.name, "idx_users_email");
assert_eq!(index.columns, vec!["email"]);
assert!(!index.unique);
}
#[test]
fn test_unique_hash_index() {
let index = IndexBuilder::hash()
.name("idx_users_id")
.on_table("users")
.column("id")
.unique()
.build()
.unwrap();
assert_eq!(index.name, "idx_users_id");
assert_eq!(index.columns, vec!["id"]);
assert!(index.unique);
}
#[test]
fn test_composite_gist_index() {
let index = IndexBuilder::gist()
.name("idx_users_location")
.on_table("users")
.columns(vec!["latitude", "longitude"])
.build()
.unwrap();
assert_eq!(index.name, "idx_users_location");
assert_eq!(index.columns, vec!["latitude", "longitude"]);
}
#[test]
fn test_partial_index() {
let index = IndexBuilder::partial_index("status = 'active'")
.name("idx_active_users")
.on_table("users")
.column("email")
.build()
.unwrap();
assert_eq!(index.name, "idx_active_users");
assert_eq!(index.columns, vec!["email"]);
}
#[test]
fn test_covering_index() {
let index = IndexBuilder::covering(vec!["user_id"], vec!["email", "name"])
.name("idx_posts_user_covering")
.on_table("posts")
.build()
.unwrap();
assert_eq!(index.name, "idx_posts_user_covering");
assert_eq!(index.columns, vec!["user_id"]);
}
#[test]
fn test_index_with_storage_parameters() {
let index = IndexBuilder::btree()
.name("idx_users_created")
.on_table("users")
.column("created_at")
.storage_parameter("fillfactor", "90")
.storage_parameter("gin_pending_list_limit", "64")
.build()
.unwrap();
assert_eq!(index.name, "idx_users_created");
}
#[test]
fn test_index_with_schema() {
let index = IndexBuilder::btree()
.name("idx_users_email")
.in_schema("public")
.on_table("users")
.column("email")
.build()
.unwrap();
assert_eq!(index.name, "idx_users_email");
}
#[test]
fn test_convenience_methods() {
let btree_index = IndexBuilder::btree()
.name("idx_btree")
.column("col1")
.build()
.unwrap();
let gin_index = IndexBuilder::gin()
.name("idx_gin")
.column("col2")
.build()
.unwrap();
let unique_index = IndexBuilder::unique_index()
.name("idx_unique")
.column("col3")
.build()
.unwrap();
assert!(unique_index.unique);
}
#[test]
fn test_validation_errors() {
let result = IndexBuilder::new().build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
IndexBuildError::ValidationError(_)
));
let result = IndexBuilder::new().column("").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
IndexBuildError::ValidationError(_)
));
}
#[test]
fn test_conditional_builder() {
let condition = true;
let index = IndexBuilder::btree()
.when(condition, |i| {
i.set_name("idx_when_true");
i.add_column("id");
})
.on_table("users")
.build()
.unwrap();
assert_eq!(index.name, "idx_when_true");
assert_eq!(index.columns, vec!["id"]);
}
#[test]
fn test_inspection_methods() {
let builder = IndexBuilder::btree()
.name("idx_test")
.on_table("users")
.columns(vec!["id", "email"]);
assert_eq!(builder.get_name(), Some("idx_test"));
assert_eq!(builder.get_table_name(), Some("users"));
assert_eq!(builder.get_columns(), &["id", "email"]);
assert_eq!(builder.column_count(), 2);
assert!(builder.has_column("id"));
assert!(!builder.has_column("nonexistent"));
assert!(builder.has_name());
assert!(builder.has_table());
assert!(!builder.has_schema());
assert!(!builder.has_partial());
assert!(!builder.has_include());
assert!(!builder.has_storage_parameters());
assert!(!builder.has_comment());
}
#[test]
fn test_debug_info_and_summary() {
let builder = IndexBuilder::btree()
.name("idx_email")
.on_table("users")
.column("email")
.unique()
.comment("Ensure fast email lookups");
let debug_info = builder.debug_info();
let summary = builder.summary();
assert!(debug_info.contains("IndexBuilder"));
assert!(debug_info.contains("idx_email"));
assert!(debug_info.contains("users"));
assert!(debug_info.contains("email"));
assert!(summary.contains("Unique B-tree index"));
assert!(summary.contains("on columns: email"));
assert!(summary.contains("on users"));
assert!(summary.contains("named 'idx_email'"));
assert!(summary.contains("with comment: Ensure fast email lookups"));
}
}