1use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
8pub enum ParameterMode {
9 In,
11 Out,
13 InOut,
15 Variadic,
17}
18
19impl Default for ParameterMode {
20 fn default() -> Self {
21 ParameterMode::In
22 }
23}
24
25impl ParameterMode {
26 pub fn to_sql(&self) -> &'static str {
27 match self {
28 ParameterMode::In => "IN",
29 ParameterMode::Out => "OUT",
30 ParameterMode::InOut => "INOUT",
31 ParameterMode::Variadic => "VARIADIC",
32 }
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct ProcedureParameter {
39 pub name: String,
40 pub data_type: String,
41 pub mode: ParameterMode,
42 pub default_value: Option<String>,
43}
44
45impl ProcedureParameter {
46 pub fn new(name: impl Into<String>, data_type: impl Into<String>) -> Self {
48 Self {
49 name: name.into(),
50 data_type: data_type.into(),
51 mode: ParameterMode::In,
52 default_value: None,
53 }
54 }
55
56 pub fn with_mode(mut self, mode: ParameterMode) -> Self {
58 self.mode = mode;
59 self
60 }
61
62 pub fn with_default(mut self, default: impl Into<String>) -> Self {
64 self.default_value = Some(default.into());
65 self
66 }
67
68 pub fn to_sql(&self) -> String {
70 let mut sql = String::new();
71
72 if self.mode != ParameterMode::In {
74 sql.push_str(self.mode.to_sql());
75 sql.push(' ');
76 }
77
78 sql.push_str(&self.name);
79 sql.push(' ');
80 sql.push_str(&self.data_type);
81
82 if let Some(ref default) = self.default_value {
84 sql.push_str(" DEFAULT ");
85 sql.push_str(default);
86 }
87
88 sql
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
94pub enum ProcedureLanguage {
95 PlPgSql,
97 Sql,
99 PlPython3,
101 C,
103 Custom(String),
105}
106
107impl Default for ProcedureLanguage {
108 fn default() -> Self {
109 ProcedureLanguage::PlPgSql
110 }
111}
112
113impl ProcedureLanguage {
114 pub fn to_sql(&self) -> &str {
115 match self {
116 ProcedureLanguage::PlPgSql => "plpgsql",
117 ProcedureLanguage::Sql => "sql",
118 ProcedureLanguage::PlPython3 => "plpython3u",
119 ProcedureLanguage::C => "c",
120 ProcedureLanguage::Custom(lang) => lang,
121 }
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127pub struct StoredFunction {
128 pub name: String,
129 pub schema: Option<String>,
130 pub parameters: Vec<ProcedureParameter>,
131 pub return_type: Option<String>,
132 pub language: ProcedureLanguage,
133 pub body: String,
134 pub volatility: FunctionVolatility,
135 pub security: FunctionSecurity,
136 pub strict: bool,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct StoredProcedure {
142 pub name: String,
143 pub schema: Option<String>,
144 pub parameters: Vec<ProcedureParameter>,
145 pub language: ProcedureLanguage,
146 pub body: String,
147 pub security: FunctionSecurity,
148}
149
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152pub enum FunctionVolatility {
153 Immutable,
155 Stable,
157 Volatile,
159}
160
161impl Default for FunctionVolatility {
162 fn default() -> Self {
163 FunctionVolatility::Volatile
164 }
165}
166
167impl FunctionVolatility {
168 pub fn to_sql(&self) -> &'static str {
169 match self {
170 FunctionVolatility::Immutable => "IMMUTABLE",
171 FunctionVolatility::Stable => "STABLE",
172 FunctionVolatility::Volatile => "VOLATILE",
173 }
174 }
175}
176
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
179pub enum FunctionSecurity {
180 Invoker,
182 Definer,
184}
185
186impl Default for FunctionSecurity {
187 fn default() -> Self {
188 FunctionSecurity::Invoker
189 }
190}
191
192impl FunctionSecurity {
193 pub fn to_sql(&self) -> &'static str {
194 match self {
195 FunctionSecurity::Invoker => "SECURITY INVOKER",
196 FunctionSecurity::Definer => "SECURITY DEFINER",
197 }
198 }
199}
200
201impl StoredFunction {
202 pub fn new(name: impl Into<String>) -> Self {
204 Self {
205 name: name.into(),
206 schema: None,
207 parameters: Vec::new(),
208 return_type: None,
209 language: ProcedureLanguage::PlPgSql,
210 body: String::new(),
211 volatility: FunctionVolatility::Volatile,
212 security: FunctionSecurity::Invoker,
213 strict: false,
214 }
215 }
216
217 pub fn qualified_name(&self) -> String {
219 if let Some(ref schema) = self.schema {
220 format!("\"{}\".\"{}\"", schema, self.name)
221 } else {
222 format!("\"{}\"", self.name)
223 }
224 }
225
226 pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
228 self.schema = Some(schema.into());
229 self
230 }
231
232 pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
234 self.parameters.push(param);
235 self
236 }
237
238 pub fn with_return_type(mut self, return_type: impl Into<String>) -> Self {
240 self.return_type = Some(return_type.into());
241 self
242 }
243
244 pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
246 self.language = language;
247 self
248 }
249
250 pub fn with_body(mut self, body: impl Into<String>) -> Self {
252 self.body = body.into();
253 self
254 }
255
256 pub fn with_volatility(mut self, volatility: FunctionVolatility) -> Self {
258 self.volatility = volatility;
259 self
260 }
261
262 pub fn with_security(mut self, security: FunctionSecurity) -> Self {
264 self.security = security;
265 self
266 }
267
268 pub fn with_strict(mut self, strict: bool) -> Self {
270 self.strict = strict;
271 self
272 }
273
274 pub fn full_name(&self) -> String {
276 match &self.schema {
277 Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
278 None => format!("\"{}\"", self.name),
279 }
280 }
281
282 pub fn generate_create_ddl(&self) -> String {
284 let mut ddl = String::from("CREATE OR REPLACE FUNCTION ");
285
286 ddl.push_str(&self.full_name());
288 ddl.push('(');
289
290 let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
292 ddl.push_str(¶m_strings.join(", "));
293 ddl.push(')');
294
295 if let Some(ref return_type) = self.return_type {
297 ddl.push_str(" RETURNS ");
298 ddl.push_str(return_type);
299 } else {
300 let out_params: Vec<&ProcedureParameter> = self
302 .parameters
303 .iter()
304 .filter(|p| matches!(p.mode, ParameterMode::Out | ParameterMode::InOut))
305 .collect();
306
307 if !out_params.is_empty() {
308 ddl.push_str(" RETURNS ");
309 if out_params.len() == 1 {
310 ddl.push_str(&out_params[0].data_type);
311 } else {
312 ddl.push_str("RECORD");
313 }
314 }
315 }
316
317 ddl.push_str(" LANGUAGE ");
319 ddl.push_str(self.language.to_sql());
320
321 ddl.push(' ');
323 ddl.push_str(self.volatility.to_sql());
324
325 ddl.push(' ');
327 ddl.push_str(self.security.to_sql());
328
329 if self.strict {
331 ddl.push_str(" STRICT");
332 }
333
334 ddl.push_str(" AS $$\n");
336 ddl.push_str(&self.body);
337 ddl.push_str("\n$$;");
338
339 ddl
340 }
341
342 pub fn generate_drop_ddl(&self) -> String {
344 let param_types: Vec<String> = self
345 .parameters
346 .iter()
347 .filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
348 .map(|p| p.data_type.clone())
349 .collect();
350
351 format!(
352 "DROP FUNCTION IF EXISTS {}({}) CASCADE;",
353 self.full_name(),
354 param_types.join(", ")
355 )
356 }
357}
358
359impl StoredProcedure {
360 pub fn new(name: impl Into<String>) -> Self {
362 Self {
363 name: name.into(),
364 schema: None,
365 parameters: Vec::new(),
366 language: ProcedureLanguage::PlPgSql,
367 body: String::new(),
368 security: FunctionSecurity::Invoker,
369 }
370 }
371
372 pub fn qualified_name(&self) -> String {
374 if let Some(ref schema) = self.schema {
375 format!("\"{}\".\"{}\"", schema, self.name)
376 } else {
377 format!("\"{}\"", self.name)
378 }
379 }
380
381 pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
383 self.schema = Some(schema.into());
384 self
385 }
386
387 pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
389 self.parameters.push(param);
390 self
391 }
392
393 pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
395 self.language = language;
396 self
397 }
398
399 pub fn with_body(mut self, body: impl Into<String>) -> Self {
401 self.body = body.into();
402 self
403 }
404
405 pub fn with_security(mut self, security: FunctionSecurity) -> Self {
407 self.security = security;
408 self
409 }
410
411 pub fn full_name(&self) -> String {
413 match &self.schema {
414 Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
415 None => format!("\"{}\"", self.name),
416 }
417 }
418
419 pub fn generate_create_ddl(&self) -> String {
421 let mut ddl = String::from("CREATE OR REPLACE PROCEDURE ");
422
423 ddl.push_str(&self.full_name());
425 ddl.push('(');
426
427 let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
429 ddl.push_str(¶m_strings.join(", "));
430 ddl.push(')');
431
432 ddl.push_str(" LANGUAGE ");
434 ddl.push_str(self.language.to_sql());
435
436 ddl.push(' ');
438 ddl.push_str(self.security.to_sql());
439
440 ddl.push_str(" AS $$\n");
442 ddl.push_str(&self.body);
443 ddl.push_str("\n$$;");
444
445 ddl
446 }
447
448 pub fn generate_drop_ddl(&self) -> String {
450 let param_types: Vec<String> = self
451 .parameters
452 .iter()
453 .filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
454 .map(|p| p.data_type.clone())
455 .collect();
456
457 format!(
458 "DROP PROCEDURE IF EXISTS {}({}) CASCADE;",
459 self.full_name(),
460 param_types.join(", ")
461 )
462 }
463}
464
465pub struct ProcedureRegistry {
467 functions: HashMap<String, StoredFunction>,
468 procedures: HashMap<String, StoredProcedure>,
469}
470
471impl ProcedureRegistry {
472 pub fn new() -> Self {
474 Self {
475 functions: HashMap::new(),
476 procedures: HashMap::new(),
477 }
478 }
479
480 pub fn register_function(&mut self, function: StoredFunction) {
482 self.functions.insert(function.full_name(), function);
483 }
484
485 pub fn register_procedure(&mut self, procedure: StoredProcedure) {
487 self.procedures.insert(procedure.full_name(), procedure);
488 }
489
490 pub fn all_functions(&self) -> impl Iterator<Item = &StoredFunction> {
492 self.functions.values()
493 }
494
495 pub fn all_procedures(&self) -> impl Iterator<Item = &StoredProcedure> {
497 self.procedures.values()
498 }
499
500 pub fn get_function(&self, name: &str) -> Option<&StoredFunction> {
502 self.functions.get(name)
503 }
504
505 pub fn get_procedure(&self, name: &str) -> Option<&StoredProcedure> {
507 self.procedures.get(name)
508 }
509}
510
511impl Default for ProcedureRegistry {
512 fn default() -> Self {
513 Self::new()
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520
521 #[test]
522 fn test_parameter_creation() {
523 let param = ProcedureParameter::new("user_id", "INTEGER")
524 .with_mode(ParameterMode::In)
525 .with_default("0");
526
527 assert_eq!(param.name, "user_id");
528 assert_eq!(param.data_type, "INTEGER");
529 assert_eq!(param.mode, ParameterMode::In);
530 assert_eq!(param.default_value, Some("0".to_string()));
531 }
532
533 #[test]
534 fn test_parameter_sql_generation() {
535 let in_param = ProcedureParameter::new("id", "INTEGER");
536 assert_eq!(in_param.to_sql(), "id INTEGER");
537
538 let out_param = ProcedureParameter::new("result", "TEXT").with_mode(ParameterMode::Out);
539 assert_eq!(out_param.to_sql(), "OUT result TEXT");
540
541 let inout_param = ProcedureParameter::new("counter", "INTEGER")
542 .with_mode(ParameterMode::InOut)
543 .with_default("1");
544 assert_eq!(inout_param.to_sql(), "INOUT counter INTEGER DEFAULT 1");
545 }
546
547 #[test]
548 fn test_stored_function_creation() {
549 let function = StoredFunction::new("calculate_age")
550 .with_parameter(ProcedureParameter::new("birth_date", "DATE"))
551 .with_return_type("INTEGER")
552 .with_body("BEGIN\n RETURN EXTRACT(YEAR FROM AGE(birth_date));\nEND;")
553 .with_volatility(FunctionVolatility::Immutable);
554
555 assert_eq!(function.name, "calculate_age");
556 assert_eq!(function.parameters.len(), 1);
557 assert_eq!(function.return_type, Some("INTEGER".to_string()));
558 assert_eq!(function.volatility, FunctionVolatility::Immutable);
559 }
560
561 #[test]
562 fn test_stored_procedure_creation() {
563 let procedure = StoredProcedure::new("update_user_status")
564 .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
565 .with_parameter(ProcedureParameter::new("new_status", "TEXT"))
566 .with_body("BEGIN\n UPDATE users SET status = new_status WHERE id = user_id;\n COMMIT;\nEND;");
567
568 assert_eq!(procedure.name, "update_user_status");
569 assert_eq!(procedure.parameters.len(), 2);
570 }
571
572 #[test]
573 fn test_function_ddl_generation() {
574 let function = StoredFunction::new("get_user_name")
575 .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
576 .with_return_type("TEXT")
577 .with_body("BEGIN\n RETURN (SELECT name FROM users WHERE id = user_id);\nEND;");
578
579 let ddl = function.generate_create_ddl();
580 assert!(ddl.contains("CREATE OR REPLACE FUNCTION \"get_user_name\""));
581 assert!(ddl.contains("user_id INTEGER"));
582 assert!(ddl.contains("RETURNS TEXT"));
583 assert!(ddl.contains("LANGUAGE plpgsql"));
584 assert!(ddl.contains("VOLATILE"));
585 }
586
587 #[test]
588 fn test_procedure_ddl_generation() {
589 let procedure = StoredProcedure::new("batch_update")
590 .with_parameter(ProcedureParameter::new("batch_size", "INTEGER"))
591 .with_body("BEGIN\n -- Update logic here\n COMMIT;\nEND;");
592
593 let ddl = procedure.generate_create_ddl();
594 assert!(ddl.contains("CREATE OR REPLACE PROCEDURE \"batch_update\""));
595 assert!(ddl.contains("batch_size INTEGER"));
596 assert!(!ddl.contains("RETURNS")); assert!(ddl.contains("LANGUAGE plpgsql"));
598 }
599
600 #[test]
601 fn test_function_with_out_parameters() {
602 let function = StoredFunction::new("get_user_stats")
603 .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
604 .with_parameter(ProcedureParameter::new("total_posts", "INTEGER").with_mode(ParameterMode::Out))
605 .with_parameter(ProcedureParameter::new("last_login", "TIMESTAMP").with_mode(ParameterMode::Out))
606 .with_body("BEGIN\n SELECT COUNT(*), MAX(login_time) INTO total_posts, last_login FROM user_activity WHERE user_id = user_id;\nEND;");
607
608 let ddl = function.generate_create_ddl();
609 assert!(ddl.contains("RETURNS RECORD")); assert!(ddl.contains("OUT total_posts INTEGER"));
611 assert!(ddl.contains("OUT last_login TIMESTAMP"));
612 }
613
614 #[test]
615 fn test_registry() {
616 let mut registry = ProcedureRegistry::new();
617
618 let function = StoredFunction::new("test_func").with_return_type("INTEGER");
619 let procedure = StoredProcedure::new("test_proc");
620
621 registry.register_function(function);
622 registry.register_procedure(procedure);
623
624 assert_eq!(registry.all_functions().count(), 1);
625 assert_eq!(registry.all_procedures().count(), 1);
626 assert!(registry.get_function("\"test_func\"").is_some());
627 assert!(registry.get_procedure("\"test_proc\"").is_some());
628 }
629}