Skip to main content

ignis_db/dsl/
procedure_call.rs

1//! Type-safe procedure and function calling DSL
2
3use crate::schema::{ParameterMode, ProcedureParameter, StoredFunction, StoredProcedure};
4use std::marker::PhantomData;
5
6/// Type-safe procedure call builder
7#[derive(Debug, Clone)]
8pub struct ProcedureCall {
9    procedure: StoredProcedure,
10    parameters: Vec<String>,
11    parameter_bindings: Vec<ParameterBinding>,
12}
13
14/// Type-safe function call builder  
15#[derive(Debug, Clone)]
16pub struct FunctionCall<R> {
17    function: StoredFunction,
18    parameters: Vec<String>,
19    parameter_bindings: Vec<ParameterBinding>,
20    _phantom: PhantomData<R>,
21}
22
23/// Parameter binding for type safety
24#[derive(Debug, Clone)]
25pub struct ParameterBinding {
26    pub name: String,
27    pub value: String,
28    pub data_type: String,
29    pub mode: ParameterMode,
30}
31
32impl ProcedureCall {
33    /// Create a new procedure call
34    pub fn new(procedure: StoredProcedure) -> Self {
35        Self {
36            procedure,
37            parameters: Vec::new(),
38            parameter_bindings: Vec::new(),
39        }
40    }
41
42    /// Add an IN parameter
43    pub fn with_in_param<T>(mut self, name: &str, value: T) -> Self
44    where
45        T: std::fmt::Display,
46    {
47        // Find the parameter definition
48        if let Some(param_def) = self
49            .procedure
50            .parameters
51            .iter()
52            .find(|p| p.name == name && matches!(p.mode, ParameterMode::In))
53        {
54            self.parameter_bindings.push(ParameterBinding {
55                name: name.to_string(),
56                value: format!("${}", self.parameters.len() + 1),
57                data_type: param_def.data_type.clone(),
58                mode: ParameterMode::In,
59            });
60            self.parameters.push(value.to_string());
61        }
62        self
63    }
64
65    /// Add an INOUT parameter (procedures only)
66    pub fn with_inout_param<T>(mut self, name: &str, value: T) -> Self
67    where
68        T: std::fmt::Display,
69    {
70        // Find the parameter definition
71        if let Some(param_def) = self
72            .procedure
73            .parameters
74            .iter()
75            .find(|p| p.name == name && matches!(p.mode, ParameterMode::InOut))
76        {
77            self.parameter_bindings.push(ParameterBinding {
78                name: name.to_string(),
79                value: format!("${}", self.parameters.len() + 1),
80                data_type: param_def.data_type.clone(),
81                mode: ParameterMode::InOut,
82            });
83            self.parameters.push(value.to_string());
84        }
85        self
86    }
87
88    /// Generate CALL SQL statement
89    pub fn to_sql(&self) -> String {
90        let qualified_name = self.procedure.qualified_name();
91
92        if self.parameter_bindings.is_empty() {
93            format!("CALL {}()", qualified_name)
94        } else {
95            let params: Vec<String> = self
96                .parameter_bindings
97                .iter()
98                .map(|binding| binding.value.clone())
99                .collect();
100            format!("CALL {}({})", qualified_name, params.join(", "))
101        }
102    }
103
104    /// Get parameter bindings for execution
105    pub fn get_parameters(&self) -> &[String] {
106        &self.parameters
107    }
108
109    /// Get parameter metadata
110    pub fn get_parameter_bindings(&self) -> &[ParameterBinding] {
111        &self.parameter_bindings
112    }
113
114    /// Validate that all required parameters are provided
115    pub fn validate(&self) -> Result<(), String> {
116        // Check that all IN and INOUT parameters are provided
117        let required_params: Vec<&ProcedureParameter> = self
118            .procedure
119            .parameters
120            .iter()
121            .filter(|p| matches!(p.mode, ParameterMode::In | ParameterMode::InOut))
122            .collect();
123
124        for required_param in required_params {
125            if !self
126                .parameter_bindings
127                .iter()
128                .any(|binding| binding.name == required_param.name)
129            {
130                return Err(format!(
131                    "Missing required parameter: {}",
132                    required_param.name
133                ));
134            }
135        }
136
137        Ok(())
138    }
139}
140
141impl<R> FunctionCall<R> {
142    /// Create a new function call
143    pub fn new(function: StoredFunction) -> Self {
144        Self {
145            function,
146            parameters: Vec::new(),
147            parameter_bindings: Vec::new(),
148            _phantom: PhantomData,
149        }
150    }
151
152    /// Add an IN parameter
153    pub fn with_in_param<T>(mut self, name: &str, value: T) -> Self
154    where
155        T: std::fmt::Display,
156    {
157        // Find the parameter definition
158        if let Some(param_def) = self
159            .function
160            .parameters
161            .iter()
162            .find(|p| p.name == name && matches!(p.mode, ParameterMode::In))
163        {
164            self.parameter_bindings.push(ParameterBinding {
165                name: name.to_string(),
166                value: format!("${}", self.parameters.len() + 1),
167                data_type: param_def.data_type.clone(),
168                mode: ParameterMode::In,
169            });
170            self.parameters.push(value.to_string());
171        }
172        self
173    }
174
175    /// Generate SELECT SQL statement for function call
176    pub fn to_sql(&self) -> String {
177        let qualified_name = self.function.qualified_name();
178
179        if self.parameter_bindings.is_empty() {
180            format!("SELECT {}() as result", qualified_name)
181        } else {
182            let params: Vec<String> = self
183                .parameter_bindings
184                .iter()
185                .map(|binding| binding.value.clone())
186                .collect();
187            format!("SELECT {}({}) as result", qualified_name, params.join(", "))
188        }
189    }
190
191    /// Generate SELECT with multiple return columns for functions with OUT parameters
192    pub fn to_sql_with_out_params(&self) -> String {
193        let qualified_name = self.function.qualified_name();
194
195        // Get OUT parameters for column selection
196        let out_params: Vec<&ProcedureParameter> = self
197            .function
198            .parameters
199            .iter()
200            .filter(|p| matches!(p.mode, ParameterMode::Out))
201            .collect();
202
203        if out_params.is_empty() {
204            // Simple function with return type
205            self.to_sql()
206        } else {
207            // Function with OUT parameters returns RECORD
208            let select_cols: Vec<String> = out_params
209                .iter()
210                .map(|p| format!("({}).{}", qualified_name, p.name))
211                .collect();
212
213            if self.parameter_bindings.is_empty() {
214                format!(
215                    "SELECT {} FROM {}() as f",
216                    select_cols.join(", "),
217                    qualified_name
218                )
219            } else {
220                let params: Vec<String> = self
221                    .parameter_bindings
222                    .iter()
223                    .filter(|b| matches!(b.mode, ParameterMode::In))
224                    .map(|binding| binding.value.clone())
225                    .collect();
226                format!(
227                    "SELECT {} FROM {}({}) as f",
228                    select_cols.join(", "),
229                    qualified_name,
230                    params.join(", ")
231                )
232            }
233        }
234    }
235
236    /// Get parameter bindings for execution
237    pub fn get_parameters(&self) -> &[String] {
238        &self.parameters
239    }
240
241    /// Get parameter metadata
242    pub fn get_parameter_bindings(&self) -> &[ParameterBinding] {
243        &self.parameter_bindings
244    }
245
246    /// Validate that all required parameters are provided
247    pub fn validate(&self) -> Result<(), String> {
248        // Check that all IN parameters are provided
249        let required_params: Vec<&ProcedureParameter> = self
250            .function
251            .parameters
252            .iter()
253            .filter(|p| matches!(p.mode, ParameterMode::In))
254            .collect();
255
256        for required_param in required_params {
257            if !self
258                .parameter_bindings
259                .iter()
260                .any(|binding| binding.name == required_param.name)
261            {
262                return Err(format!(
263                    "Missing required parameter: {}",
264                    required_param.name
265                ));
266            }
267        }
268
269        Ok(())
270    }
271}
272
273/// Convenience function to create a procedure call
274pub fn call_procedure(procedure: StoredProcedure) -> ProcedureCall {
275    ProcedureCall::new(procedure)
276}
277
278/// Convenience function to create a function call
279pub fn call_function<R>(function: StoredFunction) -> FunctionCall<R> {
280    FunctionCall::new(function)
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use crate::schema::{FunctionSecurity, FunctionVolatility, ProcedureLanguage};
287
288    fn create_test_procedure() -> StoredProcedure {
289        let mut proc = StoredProcedure::new("test_proc");
290        proc = proc.with_parameter(
291            ProcedureParameter::new("user_id", "INTEGER").with_mode(ParameterMode::In),
292        );
293        proc = proc
294            .with_parameter(ProcedureParameter::new("status", "TEXT").with_mode(ParameterMode::In));
295        proc = proc.with_parameter(
296            ProcedureParameter::new("result_count", "INTEGER").with_mode(ParameterMode::InOut),
297        );
298        proc
299    }
300
301    fn create_test_function() -> StoredFunction {
302        let mut func = StoredFunction::new("test_func");
303        func = func.with_parameter(
304            ProcedureParameter::new("birth_date", "DATE").with_mode(ParameterMode::In),
305        );
306        func = func.with_return_type("INTEGER");
307        func
308    }
309
310    #[test]
311    fn test_procedure_call_sql_generation() {
312        let procedure = create_test_procedure();
313        let call = ProcedureCall::new(procedure)
314            .with_in_param("user_id", 123)
315            .with_in_param("status", "active")
316            .with_inout_param("result_count", 0);
317
318        let sql = call.to_sql();
319        assert_eq!(sql, "CALL \"test_proc\"($1, $2, $3)");
320
321        let params = call.get_parameters();
322        assert_eq!(params, &["123", "active", "0"]);
323    }
324
325    #[test]
326    fn test_function_call_sql_generation() {
327        let function = create_test_function();
328        let call: FunctionCall<i32> =
329            FunctionCall::new(function).with_in_param("birth_date", "2000-01-01");
330
331        let sql = call.to_sql();
332        assert_eq!(sql, "SELECT \"test_func\"($1) as result");
333
334        let params = call.get_parameters();
335        assert_eq!(params, &["2000-01-01"]);
336    }
337
338    #[test]
339    fn test_procedure_call_validation() {
340        let procedure = create_test_procedure();
341
342        // Missing required parameters should fail validation
343        let incomplete_call = ProcedureCall::new(procedure.clone());
344        assert!(incomplete_call.validate().is_err());
345
346        // Complete call should pass validation
347        let complete_call = ProcedureCall::new(procedure)
348            .with_in_param("user_id", 123)
349            .with_in_param("status", "active")
350            .with_inout_param("result_count", 0);
351        assert!(complete_call.validate().is_ok());
352    }
353
354    #[test]
355    fn test_function_call_validation() {
356        let function = create_test_function();
357
358        // Missing required parameters should fail validation
359        let incomplete_call: FunctionCall<i32> = FunctionCall::new(function.clone());
360        assert!(incomplete_call.validate().is_err());
361
362        // Complete call should pass validation
363        let complete_call: FunctionCall<i32> =
364            FunctionCall::new(function).with_in_param("birth_date", "2000-01-01");
365        assert!(complete_call.validate().is_ok());
366    }
367}