Derive Macro sql_tool_kit::GenWhere

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

GenWhere 派生宏

用于生成 SQL WHERE 语句部分。此宏依赖于 WhereAttributeMacro trait。 使用方法 where_data.generate_where_clause() 会返回一个字段和条件组成的字符串数组。

宏参数:

  • #[config(...)]: 设置全局配置。

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

    • ignore: 忽略该字段。
    • rename: 字段重命名,接受字符串类型。
    • condition: 指定字段的比较条件,默认值为 ”=“,如果该值设置为空及 “”, 会报错。
    • condition_all: 应用于所有字段的通用条件,缺省值为 "{name} {condition} {index}"
      • {name}: 字段名称或 rename 指定的名称。
      • {condition}: condition 参数指定的比较条件。如果 condition_all
      • {index}: index 参数指定的占位符索引。如果字段未设置 index,则使用全局 index
    • ignore_none: 当字段为 Option::None 时是否忽略,接受布尔类型。
    • value: 自定义字段的值,接受字符串类型。
    • index: 自定义占位符序号(如果数据库支持),接受整型。

字段宏属性优先级: ignore > ignore_none > condition_all > rename = condition = value > index

示例:

#[derive(GenWhere, Debug)]
#[config(database = "postgres")]
pub struct WhereStruct {
    // 字段定义
    // ...
}

fn main() {
    let data = WhereStruct {
        // 初始化字段
        // ...
    };
    println!("{:?}", data.generate_where_clause());
}