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