use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ExtensionBuildError;
use crate::schema::Extension;
#[derive(Debug, Clone)]
pub struct ExtensionBuilder {
name: Option<String>,
schema: Option<String>,
version: Option<String>,
cascade: bool,
if_not_exists: bool,
}
impl ExtensionBuilder {
pub fn new() -> Self {
Self {
name: None,
schema: None,
version: None,
cascade: false,
if_not_exists: false,
}
}
pub fn name(name: impl Into<String>) -> Self {
Self::new().extension_name(name)
}
pub fn extension_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub fn cascade(mut self) -> Self {
self.cascade = true;
self
}
pub fn if_not_exists(mut self) -> Self {
self.if_not_exists = true;
self
}
pub fn uuid_ossp() -> Self {
Self::name("uuid-ossp").if_not_exists()
}
pub fn pgcrypto() -> Self {
Self::name("pgcrypto").if_not_exists()
}
pub fn citext() -> Self {
Self::name("citext").if_not_exists()
}
pub fn pgjwt() -> Self {
Self::name("pgjwt").if_not_exists()
}
pub fn pg_stat_statements() -> Self {
Self::name("pg_stat_statements").if_not_exists()
}
pub fn btree_gin() -> Self {
Self::name("btree_gin").if_not_exists()
}
pub fn btree_gist() -> Self {
Self::name("btree_gist").if_not_exists()
}
pub fn hstore() -> Self {
Self::name("hstore").if_not_exists()
}
pub fn ltree() -> Self {
Self::name("ltree").if_not_exists()
}
pub fn unaccent() -> Self {
Self::name("unaccent").if_not_exists()
}
pub fn pg_trgm() -> Self {
Self::name("pg_trgm").if_not_exists()
}
pub fn intarray() -> Self {
Self::name("intarray").if_not_exists()
}
pub fn earthdistance() -> Self {
Self::name("earthdistance").if_not_exists()
}
pub fn cube() -> Self {
Self::name("cube").if_not_exists()
}
pub fn postgis() -> Self {
Self::name("postgis").if_not_exists()
}
pub fn timescaledb() -> Self {
Self::name("timescaledb").if_not_exists()
}
}
impl SchemaBuilder for ExtensionBuilder {
type Output = Extension;
type Error = ExtensionBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
let name = self.name.ok_or(ExtensionBuildError::MissingName)?;
Ok(Extension {
name,
schema: self.schema,
version: self.version,
cascade: self.cascade,
if_not_exists: self.if_not_exists,
})
}
}
impl ValidatableBuilder for ExtensionBuilder {
fn is_valid(&self) -> bool {
self.name.is_some() && !self.name.as_ref().unwrap().trim().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.name.is_none() {
errors.push("Extension name is required".to_string());
} else if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Extension name cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for ExtensionBuilder {
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
}
fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
where
F: FnOnce(&mut Self),
G: FnOnce(&mut Self),
Self: Sized,
{
if condition {
if_true(&mut self);
} else {
if_false(&mut self);
}
self
}
}
impl InspectableBuilder for ExtensionBuilder {
fn debug_info(&self) -> String {
format!(
"ExtensionBuilder {{ name: {:?}, schema: {:?}, version: {:?}, cascade: {}, if_not_exists: {} }}",
self.name, self.schema, self.version, self.cascade, self.if_not_exists
)
}
fn summary(&self) -> String {
let mut parts = vec![format!(
"extension '{}'",
self.name.as_deref().unwrap_or("unnamed")
)];
if let Some(ref schema) = self.schema {
parts.push(format!("in schema '{}'", schema));
}
if let Some(ref version) = self.version {
parts.push(format!("version '{}'", version));
}
if self.cascade {
parts.push("with CASCADE".to_string());
}
if self.if_not_exists {
parts.push("IF NOT EXISTS".to_string());
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extension_builder_basic() {
let extension = ExtensionBuilder::name("uuid-ossp")
.if_not_exists()
.build()
.unwrap();
assert_eq!(extension.name, "uuid-ossp");
assert!(extension.if_not_exists);
assert!(!extension.cascade);
}
#[test]
fn test_extension_builder_with_schema() {
let extension = ExtensionBuilder::name("pgcrypto")
.schema("public")
.version("1.3")
.cascade()
.build()
.unwrap();
assert_eq!(extension.name, "pgcrypto");
assert_eq!(extension.schema, Some("public".to_string()));
assert_eq!(extension.version, Some("1.3".to_string()));
assert!(extension.cascade);
}
#[test]
fn test_extension_builder_convenience_methods() {
let uuid_ext = ExtensionBuilder::uuid_ossp().build().unwrap();
assert_eq!(uuid_ext.name, "uuid-ossp");
assert!(uuid_ext.if_not_exists);
let crypto_ext = ExtensionBuilder::pgcrypto().build().unwrap();
assert_eq!(crypto_ext.name, "pgcrypto");
assert!(crypto_ext.if_not_exists);
let citext_ext = ExtensionBuilder::citext().build().unwrap();
assert_eq!(citext_ext.name, "citext");
assert!(citext_ext.if_not_exists);
}
#[test]
fn test_extension_builder_validation() {
let result = ExtensionBuilder::new().build();
assert!(matches!(result, Err(ExtensionBuildError::MissingName)));
let result = ExtensionBuilder::name("").build();
assert!(matches!(result, Err(ExtensionBuildError::MissingName)));
}
#[test]
fn test_extension_sql_generation() {
let extension = ExtensionBuilder::uuid_ossp().build().unwrap();
let sql = extension.to_sql();
assert!(sql.contains("CREATE EXTENSION IF NOT EXISTS"));
assert!(sql.contains("\"uuid-ossp\""));
assert!(sql.ends_with(';'));
let drop_sql = extension.to_drop_sql();
assert!(drop_sql.contains("DROP EXTENSION IF EXISTS"));
assert!(drop_sql.contains("\"uuid-ossp\""));
}
}