sqlx_ledger/tx_template/
tx_params.rs

1use cel_interpreter::{CelContext, CelMap, CelValue};
2use std::collections::HashMap;
3
4use super::param_definition::{ParamDataType, ParamDefinition};
5use crate::error::SqlxLedgerError;
6
7#[derive(Debug)]
8pub struct TxParams {
9    values: HashMap<String, CelValue>,
10}
11
12impl TxParams {
13    pub fn new() -> Self {
14        Self {
15            values: HashMap::new(),
16        }
17    }
18
19    pub fn insert(&mut self, k: impl Into<String>, v: impl Into<CelValue>) {
20        self.values.insert(k.into(), v.into());
21    }
22
23    pub fn to_context(
24        mut self,
25        defs: Option<&Vec<ParamDefinition>>,
26    ) -> Result<CelContext, SqlxLedgerError> {
27        let mut ctx = super::cel_context::initialize();
28        if let Some(defs) = defs {
29            let mut cel_map = CelMap::new();
30            for d in defs {
31                if let Some(v) = self.values.remove(&d.name) {
32                    match ParamDataType::try_from(&v) {
33                        Ok(t) if t == d.r#type => {
34                            cel_map.insert(d.name.clone(), v);
35                            continue;
36                        }
37                        _ => return Err(SqlxLedgerError::TxParamTypeMismatch(d.r#type.clone())),
38                    }
39                }
40                if let Some(expr) = d.default_expr() {
41                    cel_map.insert(d.name.clone(), expr.evaluate(&ctx)?);
42                }
43            }
44            ctx.add_variable("params", cel_map);
45        }
46
47        if !self.values.is_empty() {
48            return Err(SqlxLedgerError::TooManyParameters);
49        }
50
51        Ok(ctx)
52    }
53}
54
55impl Default for TxParams {
56    fn default() -> Self {
57        Self::new()
58    }
59}