Skip to main content

endpoint_libs/model/
pg_func.rs

1use alloc::format;
2use alloc::string::String;
3use alloc::vec::Vec;
4
5use crate::model::{Field, Type};
6#[cfg(not(feature = "std"))]
7use crate::convert_case::{Case, Casing};
8#[cfg(feature = "std")]
9use convert_case::Case;
10#[cfg(feature = "std")]
11use convert_case::Casing;
12use itertools::Itertools;
13
14/// `ProceduralFunction` is a struct that represents a single procedural function in the API.
15#[derive(Clone, Debug)]
16pub struct ProceduralFunction {
17    /// The name of the function (e.g. `fun_user_get_user`)
18    pub name: String,
19
20    /// A list of parameters that the function accepts (e.g. "user_id" of type `Type::BigInt`)
21    pub parameters: Vec<Field>,
22
23    /// The return type of the function (e.g. `Type::struct_`)
24    pub return_row_type: Type,
25
26    /// The actual SQL body of the function (e.g. `SELECT * FROM user WHERE user_id = $1`)
27    pub body: String,
28}
29
30/// Sorts the parameters by the type, so that optional parameters are last.
31fn sort_parameters(parameters: Vec<Field>) -> Vec<Field> {
32    parameters
33        .into_iter()
34        .sorted_by_cached_key(|x| matches!(x.ty, Type::Optional(_)))
35        .collect()
36}
37
38impl ProceduralFunction {
39    /// Creates a new `ProceduralFunction` with the given name, parameters, returns and body.
40    pub fn new(
41        name: impl Into<String>,
42        parameters: Vec<Field>,
43        returns: Vec<Field>,
44        body: impl Into<String>,
45    ) -> Self {
46        let name = name.into();
47        Self {
48            name: name.clone(),
49            parameters: sort_parameters(parameters),
50            return_row_type: Type::struct_(
51                format!("{}RespRow", name.to_case(Case::Pascal)),
52                returns,
53            ),
54            body: body.into(),
55        }
56    }
57
58    /// Creates a new `ProceduralFunction` with the given name, parameters, row type and body.
59    pub fn new_with_row_type(
60        name: impl Into<String>,
61        parameters: Vec<Field>,
62        return_row_type: Type,
63        body: impl Into<String>,
64    ) -> Self {
65        Self {
66            name: name.into(),
67            parameters: sort_parameters(parameters),
68            return_row_type,
69            body: body.into(),
70        }
71    }
72}