use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::FunctionBuildError;
use crate::schema::{
FunctionSecurity, FunctionVolatility, ProcedureLanguage, ProcedureParameter, StoredFunction,
};
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct FunctionBuilder {
name: Option<String>,
schema: Option<String>,
parameters: Vec<ProcedureParameter>,
return_type: Option<String>,
language: Option<ProcedureLanguage>,
volatility: Option<FunctionVolatility>,
security: Option<FunctionSecurity>,
body: Option<String>,
comment: Option<String>,
}
impl FunctionBuilder {
pub fn new() -> Self {
Self {
name: None,
schema: None,
parameters: Vec::new(),
return_type: None,
language: None,
volatility: None,
security: Option::None,
body: None,
comment: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
let full_name = name.into();
if let Some(dot_pos) = full_name.find('.') {
let schema_name = &full_name[..dot_pos];
let function_name = &full_name[dot_pos + 1..];
self.schema = Some(schema_name.to_string());
self.name = Some(function_name.to_string());
} else {
self.name = Some(full_name);
}
self
}
pub fn set_name(&mut self, name: impl Into<String>) {
let full_name = name.into();
if let Some(dot_pos) = full_name.find('.') {
let schema_name = &full_name[..dot_pos];
let function_name = &full_name[dot_pos + 1..];
self.schema = Some(schema_name.to_string());
self.name = Some(function_name.to_string());
} else {
self.name = Some(full_name);
}
}
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 parameter(mut self, name: impl Into<String>, param_type: impl Into<String>) -> Self {
let param = ProcedureParameter::new(name, param_type);
self.parameters.push(param);
self
}
pub fn add_parameter(&mut self, name: impl Into<String>, param_type: impl Into<String>) {
let param = ProcedureParameter::new(name, param_type);
self.parameters.push(param);
}
pub fn parameters(
mut self,
params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
for (name, param_type) in params {
let param = ProcedureParameter::new(name, param_type);
self.parameters.push(param);
}
self
}
pub fn add_parameters(
&mut self,
params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) {
for (name, param_type) in params {
let param = ProcedureParameter::new(name, param_type);
self.parameters.push(param);
}
}
pub fn returns(mut self, return_type: impl Into<String>) -> Self {
self.return_type = Some(return_type.into());
self
}
pub fn set_return_type(&mut self, return_type: impl Into<String>) {
self.return_type = Some(return_type.into());
}
pub fn language(mut self, language: ProcedureLanguage) -> Self {
self.language = Some(language);
self
}
pub fn set_language(&mut self, language: ProcedureLanguage) {
self.language = Some(language);
}
pub fn volatility(mut self, volatility: FunctionVolatility) -> Self {
self.volatility = Some(volatility);
self
}
pub fn set_volatility(&mut self, volatility: FunctionVolatility) {
self.volatility = Some(volatility);
}
pub fn security(mut self, security: FunctionSecurity) -> Self {
self.security = Some(security);
self
}
pub fn set_security(&mut self, security: FunctionSecurity) {
self.security = Some(security);
}
pub fn body(mut self, body: impl Into<String>) -> Self {
self.body = Some(body.into());
self
}
pub fn set_body(&mut self, body: impl Into<String>) {
self.body = Some(body.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 plpgsql() -> Self {
Self::new().language(ProcedureLanguage::PlPgSql)
}
pub fn sql() -> Self {
Self::new().language(ProcedureLanguage::Sql)
}
pub fn c() -> Self {
Self::new().language(ProcedureLanguage::C)
}
pub fn immutable() -> Self {
Self::new().volatility(FunctionVolatility::Immutable)
}
pub fn stable() -> Self {
Self::new().volatility(FunctionVolatility::Stable)
}
pub fn volatile() -> Self {
Self::new().volatility(FunctionVolatility::Volatile)
}
pub fn invoker() -> Self {
Self::new().security(FunctionSecurity::Invoker)
}
pub fn definer() -> Self {
Self::new().security(FunctionSecurity::Definer)
}
pub fn math() -> Self {
Self::new()
.language(ProcedureLanguage::Sql)
.volatility(FunctionVolatility::Immutable)
}
pub fn utility() -> Self {
Self::new()
.language(ProcedureLanguage::PlPgSql)
.volatility(FunctionVolatility::Stable)
}
pub fn trigger() -> Self {
Self::new()
.language(ProcedureLanguage::PlPgSql)
.volatility(FunctionVolatility::Volatile)
.returns("TRIGGER")
}
#[inline]
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
#[inline]
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
#[inline]
pub fn get_parameters(&self) -> &[ProcedureParameter] {
&self.parameters
}
#[inline]
pub fn get_return_type(&self) -> Option<&str> {
self.return_type.as_deref()
}
pub fn get_language(&self) -> Option<&ProcedureLanguage> {
self.language.as_ref()
}
pub fn get_volatility(&self) -> Option<&FunctionVolatility> {
self.volatility.as_ref()
}
pub fn get_security(&self) -> Option<&FunctionSecurity> {
self.security.as_ref()
}
pub fn get_body(&self) -> Option<&str> {
self.body.as_deref()
}
pub fn get_comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn parameter_count(&self) -> usize {
self.parameters.len()
}
pub fn has_parameter(&self, param_name: &str) -> bool {
self.parameters.iter().any(|p| p.name == param_name)
}
pub fn get_parameter(&self, param_name: &str) -> Option<&ProcedureParameter> {
self.parameters.iter().find(|p| p.name == param_name)
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
pub fn has_schema(&self) -> bool {
self.schema.is_some()
}
pub fn has_return_type(&self) -> bool {
self.return_type.is_some()
}
pub fn has_language(&self) -> bool {
self.language.is_some()
}
pub fn has_volatility(&self) -> bool {
self.volatility.is_some()
}
pub fn has_security(&self) -> bool {
self.security.is_some()
}
pub fn has_body(&self) -> bool {
self.body.is_some()
}
pub fn has_comment(&self) -> bool {
self.comment.is_some()
}
pub fn has_parameters(&self) -> bool {
!self.parameters.is_empty()
}
}
impl SchemaBuilder for FunctionBuilder {
type Output = StoredFunction;
type Error = FunctionBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(FunctionBuildError::ValidationError(errors.join("; ")));
}
let function = StoredFunction {
name: self.name.unwrap_or_else(|| "function".to_string()),
schema: self.schema,
parameters: self.parameters,
return_type: self.return_type,
language: self.language.unwrap_or(ProcedureLanguage::PlPgSql),
body: self.body.unwrap_or_else(|| "SELECT 1".to_string()),
volatility: self.volatility.unwrap_or(FunctionVolatility::Volatile),
security: self.security.unwrap_or(FunctionSecurity::Invoker),
strict: false, };
Ok(function)
}
}
impl ValidatableBuilder for FunctionBuilder {
fn is_valid(&self) -> bool {
self.validation_errors().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.body.is_none() {
errors.push("Function must have a body".to_string());
}
if let Some(ref body) = self.body {
if body.trim().is_empty() {
errors.push("Function body cannot be empty".to_string());
}
}
if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Function 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, param) in self.parameters.iter().enumerate() {
if param.name.trim().is_empty() {
errors.push(format!("Parameter {} at index {} cannot be empty", i, i));
}
}
let mut seen_params = HashSet::new();
for param in &self.parameters {
if !seen_params.insert(¶m.name) {
errors.push(format!("Duplicate parameter name: {}", param.name));
}
}
if let Some(ref return_type) = self.return_type {
if return_type.trim().is_empty() {
errors.push("Return type cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for FunctionBuilder {
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 FunctionBuilder {
fn debug_info(&self) -> String {
format!(
"FunctionBuilder {{ name: {:?}, schema: {:?}, parameters: {:?}, return_type: {:?}, language: {:?}, volatility: {:?}, security: {:?} }}",
self.name, self.schema, self.parameters, self.return_type, self.language, self.volatility, self.security
)
}
fn summary(&self) -> String {
let mut parts = Vec::new();
parts.push("Function".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.parameters.is_empty() {
let param_descriptions: Vec<String> = self
.parameters
.iter()
.map(|p| format!("{}: {}", p.name, p.data_type))
.collect();
parts.push(format!(
"with parameters: {}",
param_descriptions.join(", ")
));
}
if let Some(ref return_type) = self.return_type {
parts.push(format!("returns: {}", return_type));
}
if let Some(ref language) = self.language {
parts.push(format!("language: {:?}", language));
}
if let Some(ref volatility) = self.volatility {
parts.push(format!("volatility: {:?}", volatility));
}
if let Some(ref security) = self.security {
parts.push(format!("security: {:?}", security));
}
if let Some(ref comment) = self.comment {
parts.push(format!("with comment: {}", comment));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{FunctionSecurity, FunctionVolatility, ProcedureLanguage};
#[test]
fn test_basic_function() {
let function = FunctionBuilder::new()
.name("add_numbers")
.parameter("a", "INTEGER")
.parameter("b", "INTEGER")
.returns("INTEGER")
.language(ProcedureLanguage::Sql)
.body("SELECT a + b")
.build()
.unwrap();
assert_eq!(function.name, "add_numbers");
assert_eq!(function.parameters.len(), 2);
assert_eq!(function.parameters[0].name, "a");
assert_eq!(function.parameters[0].data_type, "INTEGER");
assert_eq!(function.parameters[1].name, "b");
assert_eq!(function.parameters[1].data_type, "INTEGER");
assert_eq!(function.return_type, Some("INTEGER".to_string()));
assert_eq!(function.language, ProcedureLanguage::Sql);
assert_eq!(function.body, "SELECT a + b");
}
#[test]
fn test_function_with_schema() {
let function = FunctionBuilder::new()
.name("calculate_area")
.in_schema("math")
.parameter("radius", "DOUBLE PRECISION")
.returns("DOUBLE PRECISION")
.body("SELECT PI() * radius * radius")
.build()
.unwrap();
assert_eq!(function.name, "calculate_area");
assert_eq!(function.schema, Some("math".to_string()));
assert_eq!(function.parameters.len(), 1);
}
#[test]
fn test_convenience_methods() {
let plpgsql_func = FunctionBuilder::plpgsql()
.name("get_user_count")
.returns("INTEGER")
.body("SELECT COUNT(*) FROM users")
.build()
.unwrap();
let immutable_func = FunctionBuilder::immutable()
.name("get_constant")
.returns("TEXT")
.body("SELECT 'constant'")
.build()
.unwrap();
let invoker_func = FunctionBuilder::invoker()
.name("get_user_info")
.parameter("user_id", "INTEGER")
.returns("TEXT")
.body("SELECT name FROM users WHERE id = user_id")
.build()
.unwrap();
assert_eq!(plpgsql_func.language, ProcedureLanguage::PlPgSql);
assert_eq!(immutable_func.volatility, FunctionVolatility::Immutable);
assert_eq!(invoker_func.security, FunctionSecurity::Invoker);
}
#[test]
fn test_function_with_multiple_parameters() {
let function = FunctionBuilder::new()
.name("create_user")
.parameters(vec![
("name", "VARCHAR(255)"),
("email", "VARCHAR(255)"),
("age", "INTEGER"),
("is_active", "BOOLEAN"),
])
.returns("INTEGER")
.body("INSERT INTO users (name, email, age, is_active) VALUES (name, email, age, is_active) RETURNING id")
.build()
.unwrap();
assert_eq!(function.name, "create_user");
assert_eq!(function.parameters.len(), 4);
assert_eq!(function.parameters[0].name, "name");
assert_eq!(function.parameters[0].data_type, "VARCHAR(255)");
assert_eq!(function.parameters[3].name, "is_active");
assert_eq!(function.parameters[3].data_type, "BOOLEAN");
}
#[test]
fn test_function_with_comment() {
let function = FunctionBuilder::new()
.name("validate_email")
.parameter("email", "TEXT")
.returns("BOOLEAN")
.body("SELECT email ~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
.comment("Validates email format using regex")
.build()
.unwrap();
assert_eq!(function.name, "validate_email");
}
#[test]
fn test_validation_errors() {
let result = FunctionBuilder::new().name("test").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
FunctionBuildError::ValidationError(_)
));
let result = FunctionBuilder::new().name("test").body("").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
FunctionBuildError::ValidationError(_)
));
}
#[test]
fn test_conditional_builder() {
let condition = true;
let function = FunctionBuilder::new()
.when(condition, |f| {
f.set_name("function_when_true");
f.add_parameter("param1", "INTEGER");
f.set_body("SELECT param1 * 2");
})
.build()
.unwrap();
assert_eq!(function.name, "function_when_true");
assert_eq!(function.parameters.len(), 1);
}
#[test]
fn test_inspection_methods() {
let builder = FunctionBuilder::new()
.name("test_function")
.in_schema("public")
.parameters(vec![("param1", "TEXT"), ("param2", "INTEGER")]);
assert_eq!(builder.get_name(), Some("test_function"));
assert_eq!(builder.get_schema(), Some("public"));
assert_eq!(builder.get_parameters().len(), 2);
assert_eq!(builder.parameter_count(), 2);
assert!(builder.has_parameter("param1"));
assert!(!builder.has_parameter("nonexistent"));
assert!(builder.has_name());
assert!(builder.has_schema());
assert!(builder.has_parameters());
assert!(!builder.has_return_type());
assert!(!builder.has_language());
assert!(!builder.has_volatility());
assert!(!builder.has_security());
assert!(!builder.has_body());
assert!(!builder.has_comment());
let param = builder.get_parameter("param1");
assert!(param.is_some());
assert_eq!(param.unwrap().name, "param1");
assert_eq!(param.unwrap().data_type, "TEXT");
}
#[test]
fn test_debug_info_and_summary() {
let builder = FunctionBuilder::new()
.name("calculate_distance")
.in_schema("geometry")
.parameters(vec![
("x1", "DOUBLE PRECISION"),
("y1", "DOUBLE PRECISION"),
("x2", "DOUBLE PRECISION"),
("y2", "DOUBLE PRECISION"),
])
.returns("DOUBLE PRECISION")
.language(ProcedureLanguage::Sql)
.volatility(FunctionVolatility::Immutable)
.comment("Calculates Euclidean distance between two points");
let debug_info = builder.debug_info();
let summary = builder.summary();
assert!(debug_info.contains("FunctionBuilder"));
assert!(debug_info.contains("calculate_distance"));
assert!(debug_info.contains("geometry"));
assert!(summary.contains("Function"));
assert!(summary.contains("geometry.calculate_distance"));
assert!(summary.contains("with parameters: x1: DOUBLE PRECISION, y1: DOUBLE PRECISION, x2: DOUBLE PRECISION, y2: DOUBLE PRECISION"));
assert!(summary.contains("returns: DOUBLE PRECISION"));
assert!(summary.contains("language: Sql"));
assert!(summary.contains("volatility: Immutable"));
}
#[test]
fn test_specialized_function_types() {
let math_func = FunctionBuilder::math()
.name("square_root")
.parameter("value", "DOUBLE PRECISION")
.returns("DOUBLE PRECISION")
.body("SELECT SQRT(value)")
.build()
.unwrap();
let utility_func = FunctionBuilder::utility()
.name("get_current_user")
.returns("TEXT")
.body("SELECT current_user")
.build()
.unwrap();
let trigger_func = FunctionBuilder::trigger()
.name("audit_changes")
.body("RETURN NEW")
.build()
.unwrap();
assert_eq!(math_func.language, ProcedureLanguage::Sql);
assert_eq!(math_func.volatility, FunctionVolatility::Immutable);
assert_eq!(utility_func.language, ProcedureLanguage::PlPgSql);
assert_eq!(utility_func.volatility, FunctionVolatility::Stable);
assert_eq!(trigger_func.language, ProcedureLanguage::PlPgSql);
assert_eq!(trigger_func.volatility, FunctionVolatility::Volatile);
assert_eq!(trigger_func.return_type, Some("TRIGGER".to_string()));
}
#[test]
fn test_function_with_all_properties() {
let function = FunctionBuilder::new()
.name("complex_calculation")
.in_schema("finance")
.parameters(vec![
("principal", "NUMERIC(19,4)"),
("rate", "NUMERIC(5,4)"),
("time", "NUMERIC(5,2)"),
])
.returns("NUMERIC(19,4)")
.language(ProcedureLanguage::PlPgSql)
.volatility(FunctionVolatility::Immutable)
.security(FunctionSecurity::Invoker)
.body("RETURN principal * POWER(1 + rate, time)")
.comment("Calculates compound interest")
.build()
.unwrap();
assert_eq!(function.name, "complex_calculation");
assert_eq!(function.schema, Some("finance".to_string()));
assert_eq!(function.parameters.len(), 3);
assert_eq!(function.return_type, Some("NUMERIC(19,4)".to_string()));
assert_eq!(function.language, ProcedureLanguage::PlPgSql);
assert_eq!(function.volatility, FunctionVolatility::Immutable);
assert_eq!(function.security, FunctionSecurity::Invoker);
assert_eq!(function.body, "RETURN principal * POWER(1 + rate, time)");
}
}