Skip to main content

py_sql/node/
bind_node.rs

1use crate::ast::RbatisAST;
2use crate::error::Error;
3use crate::node::node_type::NodeType;
4use rexpr;
5use rexpr::ast::Node;
6use rexpr::runtime::RExprRuntime;
7use serde_json::Value;
8
9#[derive(Clone, Debug)]
10pub struct BindNode {
11    pub name: String,
12    pub value: String,
13    pub func: Node,
14}
15
16impl BindNode {
17    pub fn def_name() -> &'static str {
18        "let"
19    }
20    pub fn from(
21        runtime: &RExprRuntime,
22        source: &str,
23        express: &str,
24        childs: Vec<NodeType>,
25    ) -> Result<Self, crate::error::Error> {
26        let source = source.trim();
27        if express.starts_with(Self::def_name()) {
28            let express = express[Self::def_name().len()..].trim();
29            let name_value: Vec<&str> = express.split("=").collect();
30            if name_value.len() != 2 {
31                return Err(crate::error::Error::from(
32                    "[rbatis] parser bind express fail:".to_string() + source,
33                ));
34            }
35            return Ok(BindNode {
36                name: name_value[0].to_owned(),
37                value: name_value[1].to_owned(),
38                func: runtime.parse(name_value[1])?,
39            });
40        } else if express.starts_with(Self::name()) {
41            let express = express[Self::name().len()..].trim();
42            let name_value: Vec<&str> = express.split("=").collect();
43            if name_value.len() != 2 {
44                return Err(crate::error::Error::from(
45                    "[rbatis] parser bind express fail:".to_string() + source,
46                ));
47            }
48            return Ok(BindNode {
49                name: name_value[0].to_owned(),
50                value: name_value[1].to_owned(),
51                func: runtime.parse(name_value[1])?,
52            });
53        } else {
54            return Err(Error::from(
55                "[rbaits] OtherwiseNode must start with '_:' or 'otherwise:'",
56            ));
57        }
58    }
59}
60
61impl RbatisAST for BindNode {
62    fn name() -> &'static str {
63        "bind"
64    }
65    fn eval(
66        &self,
67        convert: &dyn crate::StringConvert,
68        env: &mut Value,
69        engine: &RExprRuntime,
70        arg_array: &mut Vec<Value>,
71        arg_sql: &mut String,
72    ) -> Result<serde_json::Value, crate::error::Error> {
73        let r = self.func.eval(env)?;
74        env[self.name.as_str()] = r;
75        return Result::Ok(serde_json::Value::Null);
76    }
77}