Derive Macro sql_tool_kit::GenSet

source ·
#[derive(GenSet)]
{
    // Attributes available to this derive:
    #[set]
    #[config]
}
Expand description

GenSet 派生宏

用于生成 SQL UPDATE 语句中的 SET 部分。它依赖于 SetAttributeMacro trait。 例如,update table_name set field1 = $1, field2 = $2 ... where ... 使用方法 update_data.generate_set_clause() 返回值类似于 ["field1 = $1", "field2 = $2", ...]

宏参数:

  • #[config(...)]: 设置一些配置。

    • database: 指定数据库类型,影响占位符的格式(支持 mysql, postgres, sqlite, mariadb, mssql)。
    • index: 设置占位符的起始索引。
    • ignore_none: 是否忽略 Option::None 值,默认为 true
    • ignore_no_macro_set: 默认忽略没有 #[set(...)] 宏的字段,为 true 时配合 GenWhere 宏使用。
    • ignore_set_and_where: 当 #[set(...)]存在 where 参数是,会忽略 set 值,默认为 false
  • #[set(...)]: 字段级别的宏,用于自定义字段在生成的 SET 语句中的表现。

    • ignore: 忽略该字段。
    • r#where: 将该字段设置为 where,有多种使用方式。1. #[set(r#where)] #[set(r#where = "{field = {index}")]
    • ignore_none: 当字段为 Option::None 时是否忽略,接受布尔类型。
    • ignore_set: 在 set 上忽略该字段。
    • rename: 字段重命名,接受字符串类型。
    • condition: 当设置 r#where 时生效
    • value: 自定义字段的值,接受字符串类型。
    • index: 自定义占位符序号(如果数据库支持),接受整型。 宏的优先级:ignore > ignore_none > r#where = ignore_set > rename = value = condition > index

示例: #[doc = “hidden”] #[cfg(test)]

#[derive(GenSet, Debug)]
#[config(database = "postgres", index = 4)]
pub struct SetStruct {
    #[set(rename = "id")]
    pub field1: i32,
    #[set()]
    pub field2: i32,
    #[set(rename = "email")]
    pub field3: Option<String>,
    #[set(value = "'用户名称'")] // 设置 field = '用户名称' 而不是 ${index}
    pub field4: String,
    #[set(index = 10)] // 设置当前字段的 索引
    pub field5: String,
    #[set()]
    pub field6: String,
}

#[cfg(test)]
fn set_macro_test() {
    let data = SetStruct {
        field1: 12,
        // 初始化其他字段...
        field2: 0,
        field3: None, // 为 None 值会默认被忽略
        field4: "".to_string(),
        field5: "".to_string(),
        field6: "".to_string(),
    };
    let set_values = vec![
        "id = $4".to_string(),
        "email = $5".to_string(),
        "field4 = '用户名称'".to_string(),
        "field5 = $10".to_string(),  // 自带的 index 不会影响接下来的序列
        "field6 = $8".to_string(), // 这里会是8是因为 field4 和 field5 会
    ];
    assert_eq!(set_values, data.generate_set_clause());
}