Skip to main content

sz_rust_core/
lib.rs

1//! SZ-Rust Core — 主框架包
2//!
3//! 对标 ThinkPHP 8 的 Rust Web 框架核心,基于 axum 0.8 + SZ-ORM。
4//!
5//! ## 模块结构
6//!
7//! 所有模块均已实现并通过测试。`addons` 重导出 `sz-rust-addons-loader`,
8//! `macros` 重导出 `sz-rust-macros` 的过程宏。
9//!
10//! | 模块 | 对齐 PHP | 状态 |
11//! |------|---------|------|
12//! | `controller` | `app\SzController` / `app\BaseController` | ✅ |
13//! | `model` | `think\Model` | ✅ |
14//! | `schema_cache` | `think\db\Fetch` 字段缓存(SchemaCache + TableSchema + ColumnDefinition) | ✅ |
15//! | `relation` | `think\Model` 关联关系(HasMany/BelongsTo/HasOne/BelongsToMany/Morph) | ✅ |
16//! | `request` | `$this->request->post/get` | ✅ |
17//! | `response` | `renderJson/renderSuccess/renderError` | ✅ |
18//! | `middleware` | CORS/Auth/Log/RateLimit/Trace | ✅ |
19//! | `guard` | NestJS Guard + Spring Security(sz-rust 自研) | ✅ |
20//! | `hooks` | think-orm Model 钩子(HookDispatcher 16 事件) | ✅ |
21//! | `multi_app` | `auto_multi_app` | ✅ |
22//! | `health` | 健康检查端点(K8s liveness/readiness) | ✅ |
23//! | `static_files` | 静态文件路由(`tower-http::ServeDir`) | ✅ |
24//! | `error_handler` | 404/500 标准化 JSON 响应 | ✅ |
25//! | `h2` | HTTP/2 + TLS(`think-swoole` SSL) | ✅ |
26//! | `routing` | 三层路由机制(属性宏/配置式/约定式) | ✅ |
27//! | `addons` | `addons/` 插件 | ✅ 重导出 `sz-rust-addons-loader` |
28//! | `router` | `with_route` | ✅ |
29//! | `container` | `app()` 容器 | ✅ |
30//! | `error` | `BaseException` | ✅ |
31//! | `macros` | `compact()` | ✅ 重导出 `sz-rust-macros` |
32//! | `config` | `config/app.php` / `database.php` | ✅ |
33//! | `log` | `think-logger` | ✅ |
34//! | `server` | `think-swoole` / `think-worker` 启动入口 | ✅ |
35//! | `validate` | `think\Validate` 数据验证器 | ✅ |
36//! | `upload` | `think\File` + `think\file\UploadedFile` 文件上传 | ✅ |
37//! | `cache` | `think\facade\Cache` 缓存 facade | ✅ |
38//! | `session` | `think\facade\Session` 会话管理(SessionStore trait + MemorySessionStore) | ✅ |
39//! | `cookie` | `think\Cookie` Cookie 管理(CookieJar + CookieOptions) | ✅ |
40//! | `event` | `think\Event` 事件系统(Listener/Subscriber/Observer) | ✅ |
41//! | `env` | `think\facade\Env` 环境变量管理 | ✅ |
42//! | `i18n` | `think\facade\Lang` 多语言国际化 | ✅ |
43//! | `mail` | `think\facade\Mail` 邮件抽象(Mailer trait + MemoryMailer) | ✅ |
44//! | `notify` | `think\facade\Notify` 通知抽象(Notifier trait + MemoryNotifier + SlackNotifier) | ✅ |
45//! | `oauth` | Laravel Socialite OAuth2 客户端(OAuth2Provider trait + GenericOAuth2Provider) | ✅ |
46//! | `pay` | `yansongda/pay` 支付聚合(PayProvider trait + MemoryPayProvider + PayHttpTransport) | ✅ |
47//! | `migration_history` | `think migrate` 迁移历史表(多方言 DDL + CRUD SQL 生成) | ✅ |
48//! | `api_version` | API 版本管理(URL/Header/Query 多策略协商) | ✅ |
49//! | `cache_warmer` | 缓存预热管道(部署/启动时预热,串行/并行+超时控制) | ✅ |
50//! | `debug_page` | Whoops-style 调试页(开发环境 HTML + 生产环境简洁页) | ✅ |
51//! | `openapi` | OpenAPI 3.0.3 规范构建器 + Swagger UI / Redoc 渲染 | ✅ |
52//! | `qr_code` | `endroid/qr-code` 二维码生成(PNG/SVG/矩阵) | ✅ |
53//! | `wechat` | `overtrue/wechat` / `EasyWeChat` 微信 SDK(公众号/小程序/开放平台/企业微信) | ✅ |
54//! | `gateway` | `GatewayWorker\Gateway` WebSocket 客户端管理(Gateway API 抽象 + GatewayTransport trait + MemoryGatewayTransport) | ✅ |
55
56#![forbid(unsafe_code)]
57// v0.2.0:启用 missing_docs 警告,要求所有公开项必须有文档注释
58#![warn(missing_docs)]
59// 文档构建时将 missing_docs 作为错误(CI 中 RUSTDOCFLAGS="-D warnings" 会强制)
60#![cfg_attr(doctest, warn(missing_docs))]
61
62pub mod addons;
63pub mod api_version;
64pub mod cache;
65pub mod cache_warmer;
66pub mod config;
67pub mod container;
68pub mod controller;
69pub mod cookie;
70pub mod debug_page;
71pub mod env;
72pub mod error;
73pub mod error_handler;
74pub mod event;
75pub mod gateway;
76pub mod guard;
77pub mod h2;
78pub mod health;
79pub mod hooks;
80pub mod i18n;
81pub mod log;
82pub mod macros;
83pub mod mail;
84pub mod middleware;
85pub mod migration_history;
86pub mod model;
87pub mod multi_app;
88pub mod notify;
89pub mod oauth;
90pub mod openapi;
91pub mod orm;
92pub mod pay;
93pub mod qr_code;
94pub mod relation;
95pub mod request;
96pub mod response;
97pub mod router;
98pub mod routing;
99pub mod runtime;
100pub mod schema_cache;
101pub mod seed;
102pub mod server;
103pub mod session;
104pub mod static_files;
105pub mod upload;
106pub mod validate;
107pub mod view;
108pub mod websocket_route;
109pub mod wechat;
110
111// ============================================================================
112// 过程宏重导出
113// ============================================================================
114
115/// 编译时 SQL 校验宏 — 复用自 `sz-orm-macros`
116///
117/// 在编译期对 SQL 字符串字面量进行语法和注入模式校验,校验通过后
118/// 将 SQL 作为 `&'static str` 发出到调用处。任何校验失败都会触发
119/// `compile_error!`,二进制无法构建。
120///
121/// ## 校验规则
122///
123/// - SELECT 必须包含 FROM
124/// - INSERT 必须包含 INTO 和 VALUES
125/// - UPDATE 必须包含 SET
126/// - DELETE 必须包含 FROM
127/// - 括号必须平衡
128/// - 字符串字面量必须闭合
129/// - 禁止 SQL 注入模式(`; DROP TABLE` / `OR 1=1` / `UNION SELECT` / `--` / `/*` 等)
130///
131/// ## 用法
132///
133/// ```ignore
134/// use sz_rust_core::sql_string;
135///
136/// // 基础用法:校验通过后返回 &str
137/// let sql = sql_string!("SELECT * FROM users WHERE id = 1");
138///
139/// // 带参数数量校验
140/// let sql = sql_string!("SELECT * FROM users WHERE id = ?"; params: 1);
141///
142/// // ❌ 编译错误:SELECT 缺少 FROM
143/// // let sql = sql_string!("SELECT * users");
144///
145/// // ❌ 编译错误:检测到 SQL 注入模式
146/// // let sql = sql_string!("SELECT * FROM users WHERE name = 'x' OR '1'='1'");
147/// ```
148pub use crate::orm::sql_string;
149
150/// 编译时 SQL 校验 + 可选真实 DB 验证宏 — 复用自 `sz-orm-macros`
151///
152/// 与 [`sql_string!`] 行为一致,额外支持在 `db-verify` feature 启用且
153/// `SZ_ORM_QUERY_VERIFY=1` 环境变量设置时,连接 `DATABASE_URL` 指向的
154/// 数据库执行 `EXPLAIN` 进行真实 schema 校验。
155pub use crate::orm::query;
156
157// ============================================================================
158// 运行时 SQL 校验 — 复用自 sz-orm-sql-validator
159// ============================================================================
160
161pub use crate::orm::{
162    detect_statement_type, validate, validate_column_name, validate_delete, validate_insert,
163    validate_parameter_count, validate_select, validate_sql, validate_table_name, validate_update,
164    SqlStatementType, SqlValidationError, ValidationResult,
165};
166
167/// 运行时 SQL 校验便捷函数
168///
169/// 对 [`validate_sql`] 的薄包装,返回 `Result<(), String>` 以便上层不依赖
170/// `SqlValidationError` 类型也能处理错误。
171///
172/// ## 用法
173///
174/// ```rust,ignore
175/// use sz_rust_core::validate_sql_runtime;
176///
177/// // 合法 SQL
178/// assert!(validate_sql_runtime("SELECT * FROM users WHERE id = 1").is_ok());
179///
180/// // 非法 SQL(缺少 FROM)
181/// assert!(validate_sql_runtime("SELECT * users").is_err());
182///
183/// // SQL 注入
184/// assert!(validate_sql_runtime("SELECT * FROM users WHERE name = 'x' OR '1'='1'").is_err());
185/// ```
186pub fn validate_sql_runtime(sql: &str) -> Result<(), String> {
187    validate_sql(sql).map_err(|e| e.to_string())
188}