Skip to main content

sql_string

Macro sql_string 

Source
sql_string!() { /* proc-macro */ }
Expand description

编译时 SQL 校验宏 — 复用自 sz-orm-macros

在编译期对 SQL 字符串字面量进行语法和注入模式校验,校验通过后 将 SQL 作为 &'static str 发出到调用处。任何校验失败都会触发 compile_error!,二进制无法构建。

§校验规则

  • SELECT 必须包含 FROM
  • INSERT 必须包含 INTO 和 VALUES
  • UPDATE 必须包含 SET
  • DELETE 必须包含 FROM
  • 括号必须平衡
  • 字符串字面量必须闭合
  • 禁止 SQL 注入模式(; DROP TABLE / OR 1=1 / UNION SELECT / -- / /* 等)

§用法

use sz_rust_core::sql_string;

// 基础用法:校验通过后返回 &str
let sql = sql_string!("SELECT * FROM users WHERE id = 1");

// 带参数数量校验
let sql = sql_string!("SELECT * FROM users WHERE id = ?"; params: 1);

// ❌ 编译错误:SELECT 缺少 FROM
// let sql = sql_string!("SELECT * users");

// ❌ 编译错误:检测到 SQL 注入模式
// let sql = sql_string!("SELECT * FROM users WHERE name = 'x' OR '1'='1'");

Compile-time SQL validation macro.

Validates SQL syntax at compile time and emits the validated SQL string.

§Syntax

  • sql_string!("SQL") — validates the SQL and emits it as a &str
  • sql_string!("SQL"; params: N) — additionally checks that the SQL has exactly N parameters

§Validation rules

  • SELECT must contain FROM
  • INSERT must contain INTO and VALUES
  • UPDATE must contain SET
  • DELETE must contain FROM
  • Parentheses must be balanced
  • String literals must be properly closed
  • No SQL injection patterns (OR ‘1’=‘1’, UNION SELECT, '; DROP TABLE, --, /*)
  • Table/column identifiers must be valid