Skip to main content

rbatis_codegen/codegen/syntax_tree_pysql/
foreach_node.rs

1use crate::codegen::syntax_tree_pysql::{Name, NodeType, ToHtml};
2
3/// Represents a `for` loop node in py_sql.
4/// It iterates over a collection and executes the nested SQL block for each item.
5///
6/// # Attributes
7///
8/// - `collection`: The expression providing the collection to iterate over.
9/// - `item`: The name of the variable to hold the current item in each iteration.
10/// - `index`: The name of the variable to hold the current key/index in each iteration.
11///
12/// # Example
13///
14/// PySQL syntax:
15/// ```py
16/// for item in ids:
17///   AND id = #{item}
18///
19/// for key, item in user_map:
20///   (#{key}, #{item.name})
21/// ```
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct ForEachNode {
24    pub childs: Vec<NodeType>,
25    pub collection: String,
26    pub index: String,
27    pub item: String,
28}
29
30impl Name for ForEachNode {
31    fn name() -> &'static str {
32        "for"
33    }
34}
35
36impl ToHtml for ForEachNode {
37    fn as_html(&self) -> String {
38        let mut childs = String::new();
39        for x in &self.childs {
40            childs.push_str(&x.as_html());
41        }
42        format!(
43            "<foreach collection=\"{}\" index=\"{}\" item=\"{}\" >{}</foreach>",
44            self.collection, self.index, self.item, childs
45        )
46    }
47}