sqlx_query_dsl/whitelist.rs
1
2/// 字段白名单
3/// 用于在构建动态 SQL 时验证字段名,防止 SQL 注入
4pub struct FieldWhitelist {
5 allowed: &'static [&'static str],
6}
7
8impl FieldWhitelist {
9 /// 创建一个新的白名单实例
10 ///
11 /// * `allowed` - 允许的字段名静态切片
12 pub fn new(allowed: &'static [&'static str]) -> Self {
13 Self { allowed }
14 }
15
16 /// 检查字段是否在白名单中
17 ///
18 /// 返回 Result 而不是 panic
19 pub fn check(&self, field: &str) -> Result<(), String> {
20 if !self.allowed.contains(&field) {
21 return Err(format!("Illegal field: {}", field));
22 }
23 Ok(())
24 }
25}