use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParameterMode {
In,
Out,
InOut,
Variadic,
}
impl Default for ParameterMode {
fn default() -> Self {
ParameterMode::In
}
}
impl ParameterMode {
pub fn to_sql(&self) -> &'static str {
match self {
ParameterMode::In => "IN",
ParameterMode::Out => "OUT",
ParameterMode::InOut => "INOUT",
ParameterMode::Variadic => "VARIADIC",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcedureParameter {
pub name: String,
pub data_type: String,
pub mode: ParameterMode,
pub default_value: Option<String>,
}
impl ProcedureParameter {
pub fn new(name: impl Into<String>, data_type: impl Into<String>) -> Self {
Self {
name: name.into(),
data_type: data_type.into(),
mode: ParameterMode::In,
default_value: None,
}
}
pub fn with_mode(mut self, mode: ParameterMode) -> Self {
self.mode = mode;
self
}
pub fn with_default(mut self, default: impl Into<String>) -> Self {
self.default_value = Some(default.into());
self
}
pub fn to_sql(&self) -> String {
let mut sql = String::new();
if self.mode != ParameterMode::In {
sql.push_str(self.mode.to_sql());
sql.push(' ');
}
sql.push_str(&self.name);
sql.push(' ');
sql.push_str(&self.data_type);
if let Some(ref default) = self.default_value {
sql.push_str(" DEFAULT ");
sql.push_str(default);
}
sql
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProcedureLanguage {
PlPgSql,
Sql,
PlPython3,
C,
Custom(String),
}
impl Default for ProcedureLanguage {
fn default() -> Self {
ProcedureLanguage::PlPgSql
}
}
impl ProcedureLanguage {
pub fn to_sql(&self) -> &str {
match self {
ProcedureLanguage::PlPgSql => "plpgsql",
ProcedureLanguage::Sql => "sql",
ProcedureLanguage::PlPython3 => "plpython3u",
ProcedureLanguage::C => "c",
ProcedureLanguage::Custom(lang) => lang,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredFunction {
pub name: String,
pub schema: Option<String>,
pub parameters: Vec<ProcedureParameter>,
pub return_type: Option<String>,
pub language: ProcedureLanguage,
pub body: String,
pub volatility: FunctionVolatility,
pub security: FunctionSecurity,
pub strict: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredProcedure {
pub name: String,
pub schema: Option<String>,
pub parameters: Vec<ProcedureParameter>,
pub language: ProcedureLanguage,
pub body: String,
pub security: FunctionSecurity,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FunctionVolatility {
Immutable,
Stable,
Volatile,
}
impl Default for FunctionVolatility {
fn default() -> Self {
FunctionVolatility::Volatile
}
}
impl FunctionVolatility {
pub fn to_sql(&self) -> &'static str {
match self {
FunctionVolatility::Immutable => "IMMUTABLE",
FunctionVolatility::Stable => "STABLE",
FunctionVolatility::Volatile => "VOLATILE",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FunctionSecurity {
Invoker,
Definer,
}
impl Default for FunctionSecurity {
fn default() -> Self {
FunctionSecurity::Invoker
}
}
impl FunctionSecurity {
pub fn to_sql(&self) -> &'static str {
match self {
FunctionSecurity::Invoker => "SECURITY INVOKER",
FunctionSecurity::Definer => "SECURITY DEFINER",
}
}
}
impl StoredFunction {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
parameters: Vec::new(),
return_type: None,
language: ProcedureLanguage::PlPgSql,
body: String::new(),
volatility: FunctionVolatility::Volatile,
security: FunctionSecurity::Invoker,
strict: false,
}
}
pub fn qualified_name(&self) -> String {
if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
}
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
self.parameters.push(param);
self
}
pub fn with_return_type(mut self, return_type: impl Into<String>) -> Self {
self.return_type = Some(return_type.into());
self
}
pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
self.language = language;
self
}
pub fn with_body(mut self, body: impl Into<String>) -> Self {
self.body = body.into();
self
}
pub fn with_volatility(mut self, volatility: FunctionVolatility) -> Self {
self.volatility = volatility;
self
}
pub fn with_security(mut self, security: FunctionSecurity) -> Self {
self.security = security;
self
}
pub fn with_strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn full_name(&self) -> String {
match &self.schema {
Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
None => format!("\"{}\"", self.name),
}
}
pub fn generate_create_ddl(&self) -> String {
let mut ddl = String::from("CREATE OR REPLACE FUNCTION ");
ddl.push_str(&self.full_name());
ddl.push('(');
let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
ddl.push_str(¶m_strings.join(", "));
ddl.push(')');
if let Some(ref return_type) = self.return_type {
ddl.push_str(" RETURNS ");
ddl.push_str(return_type);
} else {
let out_params: Vec<&ProcedureParameter> = self
.parameters
.iter()
.filter(|p| matches!(p.mode, ParameterMode::Out | ParameterMode::InOut))
.collect();
if !out_params.is_empty() {
ddl.push_str(" RETURNS ");
if out_params.len() == 1 {
ddl.push_str(&out_params[0].data_type);
} else {
ddl.push_str("RECORD");
}
}
}
ddl.push_str(" LANGUAGE ");
ddl.push_str(self.language.to_sql());
ddl.push(' ');
ddl.push_str(self.volatility.to_sql());
ddl.push(' ');
ddl.push_str(self.security.to_sql());
if self.strict {
ddl.push_str(" STRICT");
}
ddl.push_str(" AS $$\n");
ddl.push_str(&self.body);
ddl.push_str("\n$$;");
ddl
}
pub fn generate_drop_ddl(&self) -> String {
let param_types: Vec<String> = self
.parameters
.iter()
.filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
.map(|p| p.data_type.clone())
.collect();
format!(
"DROP FUNCTION IF EXISTS {}({}) CASCADE;",
self.full_name(),
param_types.join(", ")
)
}
}
impl StoredProcedure {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
parameters: Vec::new(),
language: ProcedureLanguage::PlPgSql,
body: String::new(),
security: FunctionSecurity::Invoker,
}
}
pub fn qualified_name(&self) -> String {
if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
}
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
self.parameters.push(param);
self
}
pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
self.language = language;
self
}
pub fn with_body(mut self, body: impl Into<String>) -> Self {
self.body = body.into();
self
}
pub fn with_security(mut self, security: FunctionSecurity) -> Self {
self.security = security;
self
}
pub fn full_name(&self) -> String {
match &self.schema {
Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
None => format!("\"{}\"", self.name),
}
}
pub fn generate_create_ddl(&self) -> String {
let mut ddl = String::from("CREATE OR REPLACE PROCEDURE ");
ddl.push_str(&self.full_name());
ddl.push('(');
let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
ddl.push_str(¶m_strings.join(", "));
ddl.push(')');
ddl.push_str(" LANGUAGE ");
ddl.push_str(self.language.to_sql());
ddl.push(' ');
ddl.push_str(self.security.to_sql());
ddl.push_str(" AS $$\n");
ddl.push_str(&self.body);
ddl.push_str("\n$$;");
ddl
}
pub fn generate_drop_ddl(&self) -> String {
let param_types: Vec<String> = self
.parameters
.iter()
.filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
.map(|p| p.data_type.clone())
.collect();
format!(
"DROP PROCEDURE IF EXISTS {}({}) CASCADE;",
self.full_name(),
param_types.join(", ")
)
}
}
pub struct ProcedureRegistry {
functions: HashMap<String, StoredFunction>,
procedures: HashMap<String, StoredProcedure>,
}
impl ProcedureRegistry {
pub fn new() -> Self {
Self {
functions: HashMap::new(),
procedures: HashMap::new(),
}
}
pub fn register_function(&mut self, function: StoredFunction) {
self.functions.insert(function.full_name(), function);
}
pub fn register_procedure(&mut self, procedure: StoredProcedure) {
self.procedures.insert(procedure.full_name(), procedure);
}
pub fn all_functions(&self) -> impl Iterator<Item = &StoredFunction> {
self.functions.values()
}
pub fn all_procedures(&self) -> impl Iterator<Item = &StoredProcedure> {
self.procedures.values()
}
pub fn get_function(&self, name: &str) -> Option<&StoredFunction> {
self.functions.get(name)
}
pub fn get_procedure(&self, name: &str) -> Option<&StoredProcedure> {
self.procedures.get(name)
}
}
impl Default for ProcedureRegistry {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parameter_creation() {
let param = ProcedureParameter::new("user_id", "INTEGER")
.with_mode(ParameterMode::In)
.with_default("0");
assert_eq!(param.name, "user_id");
assert_eq!(param.data_type, "INTEGER");
assert_eq!(param.mode, ParameterMode::In);
assert_eq!(param.default_value, Some("0".to_string()));
}
#[test]
fn test_parameter_sql_generation() {
let in_param = ProcedureParameter::new("id", "INTEGER");
assert_eq!(in_param.to_sql(), "id INTEGER");
let out_param = ProcedureParameter::new("result", "TEXT").with_mode(ParameterMode::Out);
assert_eq!(out_param.to_sql(), "OUT result TEXT");
let inout_param = ProcedureParameter::new("counter", "INTEGER")
.with_mode(ParameterMode::InOut)
.with_default("1");
assert_eq!(inout_param.to_sql(), "INOUT counter INTEGER DEFAULT 1");
}
#[test]
fn test_stored_function_creation() {
let function = StoredFunction::new("calculate_age")
.with_parameter(ProcedureParameter::new("birth_date", "DATE"))
.with_return_type("INTEGER")
.with_body("BEGIN\n RETURN EXTRACT(YEAR FROM AGE(birth_date));\nEND;")
.with_volatility(FunctionVolatility::Immutable);
assert_eq!(function.name, "calculate_age");
assert_eq!(function.parameters.len(), 1);
assert_eq!(function.return_type, Some("INTEGER".to_string()));
assert_eq!(function.volatility, FunctionVolatility::Immutable);
}
#[test]
fn test_stored_procedure_creation() {
let procedure = StoredProcedure::new("update_user_status")
.with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
.with_parameter(ProcedureParameter::new("new_status", "TEXT"))
.with_body("BEGIN\n UPDATE users SET status = new_status WHERE id = user_id;\n COMMIT;\nEND;");
assert_eq!(procedure.name, "update_user_status");
assert_eq!(procedure.parameters.len(), 2);
}
#[test]
fn test_function_ddl_generation() {
let function = StoredFunction::new("get_user_name")
.with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
.with_return_type("TEXT")
.with_body("BEGIN\n RETURN (SELECT name FROM users WHERE id = user_id);\nEND;");
let ddl = function.generate_create_ddl();
assert!(ddl.contains("CREATE OR REPLACE FUNCTION \"get_user_name\""));
assert!(ddl.contains("user_id INTEGER"));
assert!(ddl.contains("RETURNS TEXT"));
assert!(ddl.contains("LANGUAGE plpgsql"));
assert!(ddl.contains("VOLATILE"));
}
#[test]
fn test_procedure_ddl_generation() {
let procedure = StoredProcedure::new("batch_update")
.with_parameter(ProcedureParameter::new("batch_size", "INTEGER"))
.with_body("BEGIN\n -- Update logic here\n COMMIT;\nEND;");
let ddl = procedure.generate_create_ddl();
assert!(ddl.contains("CREATE OR REPLACE PROCEDURE \"batch_update\""));
assert!(ddl.contains("batch_size INTEGER"));
assert!(!ddl.contains("RETURNS")); assert!(ddl.contains("LANGUAGE plpgsql"));
}
#[test]
fn test_function_with_out_parameters() {
let function = StoredFunction::new("get_user_stats")
.with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
.with_parameter(ProcedureParameter::new("total_posts", "INTEGER").with_mode(ParameterMode::Out))
.with_parameter(ProcedureParameter::new("last_login", "TIMESTAMP").with_mode(ParameterMode::Out))
.with_body("BEGIN\n SELECT COUNT(*), MAX(login_time) INTO total_posts, last_login FROM user_activity WHERE user_id = user_id;\nEND;");
let ddl = function.generate_create_ddl();
assert!(ddl.contains("RETURNS RECORD")); assert!(ddl.contains("OUT total_posts INTEGER"));
assert!(ddl.contains("OUT last_login TIMESTAMP"));
}
#[test]
fn test_registry() {
let mut registry = ProcedureRegistry::new();
let function = StoredFunction::new("test_func").with_return_type("INTEGER");
let procedure = StoredProcedure::new("test_proc");
registry.register_function(function);
registry.register_procedure(procedure);
assert_eq!(registry.all_functions().count(), 1);
assert_eq!(registry.all_procedures().count(), 1);
assert!(registry.get_function("\"test_func\"").is_some());
assert!(registry.get_procedure("\"test_proc\"").is_some());
}
}