Skip to main content

sz_orm_core/
lib.rs

1//! # SZ-ORM — 鲜视达 ORM
2//!
3//! Rust 异步 ORM 工作空间(原型阶段),兼容 ThinkORM 风格。
4//!
5//! ## 架构概览
6//!
7//! SZ-ORM 工作空间由 **43 个成员** 组成(41 个 sz-orm-* lib + cli + examples):
8//!
9//! ### 核心引擎 (sz-orm-core)
10//! | 模块 | 功能 |
11//! |------|------|
12//! | `model` | `Model` trait — 定义表名、主键、时间戳、软删除、关联关系 |
13//! | `query` | `QueryBuilder<M>` — 链式 API,支持 SELECT/INSERT/UPDATE/DELETE/聚合/分页/JOIN |
14//! | `dialect` | 多数据库方言 — MySQL (反引号)、PostgreSQL (双引号)、SQLite、Oracle 23ai |
15//! | `pool` | 异步连接池 — 可配置大小、超时、空闲回收、健康检查、最大生命周期 |
16//! | `transaction` | ACID 事务 — 隔离级别、保存点、`TransactionManager` 多事务管理 |
17//! | `migration` | 文件迁移系统 — up/down/rollback/reset/refresh,含 `SchemaBuilder` |
18//! | `cache` | 多级缓存 — `MemoryCache`、`MultiLevelCache`,支持 TTL |
19//! | `value` | 统一值类型 — 20 种变体 (整数/浮点/字符串/字节/UUID/日期/JSON/数组) |
20//! | `db_type` | 数据库类型枚举 — MySQL、PostgreSQL、SQLite、Oracle、Redis、MongoDB 等 11 种 |
21//! | `error` | 错误类型体系 — `DbError`(20 变体)、`PoolError`、`CacheError`、`TxError` |
22//!
23//! ### 数据库适配器
24//! - **sz-orm-sqlx** — sqlx 适配器,连接真实 MySQL/PostgreSQL/SQLite/Oracle
25//! - **sz-orm-sql-validator** — SQL 校验与注入检测
26//!
27//! ### 扩展生态包 (18 个)
28//! | 包名 | 功能 |
29//! |------|------|
30//! | sz-orm-crypto | 加密原语 (AES-256-GCM, PBKDF2, HMAC-SHA256) |
31//! | sz-orm-auth | JWT 鉴权 (HS256) |
32//! | sz-orm-scheduler | Cron 定时任务调度 |
33//! | sz-orm-mqtt | MQTT 客户端 (rumqttc) |
34//! | sz-orm-websocket | WebSocket 服务端 (tokio-tungstenite) |
35//! | sz-orm-queue | 消息队列 (RabbitMQ/lapin, Kafka, NATS, ActiveMQ, RocketMQ, Pulsar) |
36//! | sz-orm-storage | 对象存储 (S3/阿里云/腾讯云/华为云/七牛/又拍云/本地) |
37//! | sz-orm-ai | AI 集成 (Embedding, RAG, Vector) |
38//! | sz-orm-grpc | gRPC 服务/客户端 |
39//! | sz-orm-graphql | GraphQL 查询支持 |
40//! | sz-orm-es | Elasticsearch 集成 |
41//! | sz-orm-tracing | 分布式追踪 |
42//! | sz-orm-logger | 日志系统 |
43//! | sz-orm-swagger | API 文档生成 |
44//! | sz-orm-masking | 数据脱敏 |
45//! | sz-orm-health | 健康检查 |
46//! | sz-orm-audit | 审计日志 |
47//! | sz-orm-batch | 批量操作 |
48//!
49//! ### 高级特性包 (6 个)
50//! | 包名 | 功能 |
51//! |------|------|
52//! | sz-orm-dtx | 分布式事务 |
53//! | sz-orm-rw | 读写分离 |
54//! | sz-orm-sharding | 分库分表 |
55//! | sz-orm-limit | 限流控制 |
56//! | sz-orm-config | 配置管理 |
57//! | sz-orm-mig | 迁移管理增强 |
58//!
59//! ### 平台支持
60//! - **sz-orm-wasm** — WebAssembly 编译目标
61//! - **sz-orm-lc** — 本地/边缘计算
62//! - **sz-orm-back** — 备份与恢复
63//!
64//! ## 快速入门
65//!
66//! ```rust,ignore
67//! use sz_orm_core::*;
68//!
69//! // 1. 定义模型
70//! #[derive(Clone)]
71//! struct User {
72//!     id: i64,
73//!     name: String,
74//!     email: String,
75//! }
76//!
77//! impl Model for User {
78//!     type PrimaryKey = i64;
79//!     fn table_name() -> &'static str { "users" }
80//!     fn pk(&self) -> Self::PrimaryKey { self.id }
81//!     fn set_pk(&mut self, pk: Self::PrimaryKey) { self.id = pk; }
82//! }
83//!
84//! // 2. 构建查询
85//! let dialect = get_dialect(DbType::MySQL).unwrap();
86//! let sql = QueryBuilder::<User>::new(dialect)
87//!     .table("users")
88//!     .select(vec!["id", "name", "email"])
89//!     .where_eq("status", Value::String("active".to_string()))
90//!     .order_by("created_at")
91//!     .order_desc("id")
92//!     .limit(10)
93//!     .build_select();
94//!
95//! // 3. 执行前校验
96//! QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
97//!     .table("users")
98//!     .select(vec!["id", "name"])
99//!     .validate()?; // 校验 SQL 语法、注入、括号平衡
100//!
101//! // 4. 其他操作
102//! let mut data = std::collections::HashMap::new();
103//! data.insert("name".to_string(), Value::String("Alice".to_string()));
104//! data.insert("age".to_string(), Value::I64(25));
105//!
106//! let insert_sql = QueryBuilder::<User>::new(dialect)
107//!     .table("users")
108//!     .build_insert(&data);
109//!
110//! let update_sql = QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
111//!     .table("users")
112//!     .where_eq("id", Value::I64(1))
113//!     .build_update(&data);
114//!
115//! let delete_sql = QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
116//!     .table("users")
117//!     .where_eq("id", Value::I64(1))
118//!     .build_delete();
119//! ```
120//!
121//! ## 支持的数据库
122//!
123//! | 数据库 | 方言实现 | 真实连接 | 引用方式 |
124//! |--------|---------|---------|---------|
125//! | MySQL | `MySqlDialect` (`` ` `` 反引号) | sz-orm-sqlx | ✅ |
126//! | PostgreSQL | `PostgreSqlDialect` (`"` 双引号) | sz-orm-sqlx | ✅ |
127//! | SQLite 3.35+ | `SqliteDialect` (`"` 双引号) | sz-orm-sqlx | ✅ |
128//! | Oracle 23ai | `OracleDialect` (类型自动映射) | sz-orm-sqlx | ✅ |
129//!
130//! 通过 `get_dialect(DbType::MySQL)` 获取方言实例。每个方言处理:
131//! - 标识符引用风格
132//! - 字符串转义规则
133//! - 分页语法 (LIMIT/OFFSET vs OFFSET/FETCH)
134//! - JSON 提取函数 (JSON_EXTRACT vs #>> vs json_extract vs JSON_VALUE)
135//! - 全文搜索 (MATCH AGAINST vs to_tsvector vs CONTAINS)
136//! - 布尔转整数 (IF/CASE)
137//! - 自增关键字 (AUTO_INCREMENT/GENERATED BY DEFAULT AS IDENTITY)
138//!
139//! ## 核心功能详解
140//!
141//! ### QueryBuilder API
142//!
143//! 大部分查询方法返回 `Self`,支持链式调用;`select`/`having` 等校验类方法
144//! 返回 `Result<Self>`(审计 M-5/M-6 后列名/聚合表达式经标识符校验):
145//!
146//! ```rust,ignore
147//! // 基础查询
148//! QueryBuilder::<M>::new(dialect)
149//!     .table("users")
150//!     .select(vec!["id", "name"])?                 // 列名校验 + quote
151//!     .where_eq("status", Value::String("active".to_string()))    // AND
152//!     .or_where_eq("role", Value::String("admin".to_string()))     // OR
153//!     .where_in("id", vec![Value::I64(1), Value::I64(2)])
154//!     .where_between("age", Value::I64(18), Value::I64(30))
155//!     .where_null("deleted_at")
156//!     .order_by("created_at")
157//!     .order_desc("id")
158//!     .group_by("status")
159//!     .having(AggExpr::CountStar, HavingOp::Gt, Value::I64(5))?   // 参数化 HAVING
160//!     .limit(20)
161//!     .offset(40)
162//!     .page(3, 20)                       // page=3, page_size=20
163//!     .join_inner("posts", "users.id", "posts.user_id")
164//!     .join_left("profiles", "users.id", "profiles.user_id")
165//!     .build_select();
166//!
167//! // 聚合函数
168//! builder.build_count();    // SELECT COUNT(*)
169//! builder.build_exists();   // SELECT EXISTS(...)
170//! builder.build_max("score");
171//! builder.build_min("price");
172//! builder.build_sum("amount");
173//! builder.build_avg("value");
174//! ```
175//!
176//! ### SQL 校验
177//!
178//! ```rust,ignore
179//! // 编译时 + 运行时双重校验
180//! builder.validate()?;              // 校验 SELECT
181//! builder.validate_insert(&data)?;  // 校验 INSERT(含空数据检测)
182//! builder.validate_update(&data)?;  // 校验 UPDATE(含空数据检测)
183//! builder.validate_delete()?;       // 校验 DELETE
184//!
185//! // 校验内容包括:SQL 语法、注入检测、括号平衡、
186//! // 表名/列名合法性、JOIN 列名校验
187//! ```
188//!
189//! ### Model Trait
190//!
191//! ```rust,ignore
192//! pub trait Model: Send + Sync + Sized + 'static {
193//!     type PrimaryKey: Send + Sync + Debug + Display + Clone + Default;
194//!
195//!     fn table_name() -> &'static str;          // 表名(必需)
196//!     fn pk_name() -> &'static str { "id" }     // 主键列名
197//!     fn pk(&self) -> Self::PrimaryKey;         // 获取主键值
198//!     fn set_pk(&mut self, pk: Self::PrimaryKey); // 设置主键值
199//!     fn foreign_key(relation: &str) -> String; // 外键命名 "user_id"
200//!     fn timestamp_fields() -> Option<TimestampFields>; // 自动时间戳
201//!     fn soft_delete_field() -> Option<&'static str>;   // 软删除字段
202//! }
203//!
204//! // ModelExt 扩展
205//! pub trait ModelExt: Model {
206//!     fn columns() -> Vec<&'static str>;     // 所有列
207//!     fn fillable() -> Vec<&'static str>;    // 可填充列
208//!     fn guarded() -> Vec<&'static str>;     // 保护列(默认含主键)
209//!     fn hidden() -> Vec<&'static str>;      // 隐藏列(不序列化)
210//!     fn relations() -> HashMap<&str, Relation>; // 关联关系
211//!     fn fill(&mut self, data: HashMap<String, Value>); // 批量赋值
212//!     fn to_json(&self) -> serde_json::Value; // 序列化
213//! }
214//!
215//! // 四种关联关系
216//! // BelongsTo   — 多对一(Order → User)
217//! // HasMany     — 一对多(User → Orders)
218//! // HasOne      — 一对一(User → Profile)
219//! // BelongsToMany — 多对多(User ↔ Role,通过中间表)
220//! ```
221//!
222//! ### 连接池
223//!
224//! ```rust,ignore
225//! // 通过 Builder 配置
226//! let config = PoolConfigBuilder::new()
227//!     .max_size(100)       // 最大连接数
228//!     .min_idle(10)        // 最小空闲连接
229//!     .acquire_timeout(30) // 获取超时(秒)
230//!     .idle_timeout(600)   // 空闲超时(秒)
231//!     .max_lifetime(1800)  // 最大生命周期(秒)
232//!     .build()?;
233//!
234//! let pool = Pool::new(config, factory)?;
235//! let conn = pool.acquire().await?;  // 获取连接(带超时)
236//! pool.release(conn).await;         // 归还连接
237//! pool.status().await;               // PoolStatus { idle, active, max, min }
238//! pool.reap_idle().await;           // 回收空闲连接
239//! pool.close_all().await;           // 关闭所有连接
240//! ```
241//!
242//! ### 事务
243//!
244//! ```rust,ignore
245//! // 事务选项
246//! let opts = TransactOptions::default()
247//!     .with_isolation(IsolationLevel::Serializable)
248//!     .read_only()
249//!     .with_timeout(Duration::from_secs(30));
250//!
251//! let mut tx = Transaction::new(conn, opts);
252//! tx.execute("INSERT INTO users VALUES (1)").await?;
253//! tx.query("SELECT * FROM users").await?;
254//!
255//! // 保存点(嵌套事务)
256//! let sp = tx.savepoint().await?;         // SAVEPOINT sp_N
257//! tx.rollback_to_savepoint(&sp).await?;   // ROLLBACK TO SAVEPOINT sp_N
258//! tx.release_savepoint(&sp).await?;       // RELEASE SAVEPOINT sp_N
259//!
260//! tx.commit().await?;
261//! // tx.rollback().await?;
262//!
263//! // TransactionManager:管理多个命名事务
264//! let mgr = TransactionManager::new();
265//! mgr.begin("tx1", conn, opts).await?;
266//! mgr.commit("tx1").await?;
267//! mgr.list().await;        // ["tx1"]
268//! mgr.state("tx1").await;  // Some(TransactionState::Committed)
269//! ```
270//!
271//! ### 迁移系统
272//!
273//! ```rust,ignore
274//! // 文件命名:<version>_<name>_up.sql / <version>_<name>_down.sql
275//! // 示例:001_create_users_up.sql, 001_create_users_down.sql
276//!
277//! let resolver = FileMigrationResolver::new(PathBuf::from("./migrations"));
278//! let migrations = resolver.resolve(DbType::MySQL)?;
279//!
280//! let mut migrator = Migrator::new(MigrationContext::default())
281//!     .add_migrations(migrations);
282//!
283//! migrator.migrate().await?;                     // 执行所有待迁移
284//! migrator.up(Some("003")).await?;               // 执行到指定版本
285//! migrator.down(Some("001")).await?;             // 回滚到指定版本
286//! migrator.rollback("002").await?;               // 回滚单个迁移
287//! migrator.reset().await?;                       // 全部回滚 + 重新执行
288//! migrator.refresh().await?;                     // 同 reset
289//! migrator.progress();                            // MigrationProgress { total, applied, pending }
290//!
291//! // SchemaBuilder:程序化建表
292//! let sql = SchemaBuilder::new("users")
293//!     .add_column(ColumnDef::new("id", "INT").not_null().auto_increment())
294//!     .add_column(ColumnDef::new("name", "VARCHAR").length(255).not_null())
295//!     .add_index(IndexDef::new("idx_name", vec!["name"]).unique())
296//!     .add_foreign_key(
297//!         ForeignKeyDef::new("fk_role", "role_id", "roles", "id")
298//!             .on_delete("CASCADE")
299//!     )
300//!     .build(DbType::MySQL);
301//! ```
302//!
303//! ### 值类型 (Value)
304//!
305//! ```rust,ignore
306//! // 20 种变体,覆盖所有数据库类型
307//! Value::Null | Bool(bool) | I8..I64 | U8..U64 | F32 | F64
308//! | String(String) | Bytes(Vec<u8>) | Uuid(String) | Date(String)
309//! | DateTime(String) | Time(String) | Json(String) | Array(Vec<Value>)
310//!
311//! // 类型转换
312//! value.as_str()    // Option<&str>
313//! value.as_i64()    // Option<i64>(支持 F32/F64/Bool/String→i64 转换)
314//! value.as_f64()    // Option<f64>
315//! value.as_bool()   // Option<bool>(支持 "true"/"1"/"yes"/"on" 等)
316//! value.as_bytes()  // Option<&[u8]>
317//! value.to_param()  // Cow<str> — SQL 参数格式
318//!
319//! // From 实现
320//! let v: Value = 42i64.into();
321//! let v: Value = "hello".into();
322//! let v: Value = vec![1u8, 2u8].into();
323//! ```
324//!
325//! ## 错误处理
326//!
327//! 统一错误类型体系,每种错误携带唯一错误码:
328//!
329//! ```rust,ignore
330//! // DbError — 20 种变体,错误码 DB001-DB020
331//! DbError::QueryError("...")
332//! DbError::ConnectionRefused("...")
333//! DbError::ConnectionTimeout("...")
334//! DbError::NotFound("...")
335//! DbError::ConstraintViolation("...")
336//! // ... 等
337//!
338//! // PoolError — 6 种变体,错误码 PL001-PL006
339//! PoolError::Exhausted | Timeout | AlreadyAcquired | InvalidConfig | ...
340//!
341//! // CacheError — 6 种变体,错误码 CH001-CH006
342//! // TxError — 6 种变体(NotStarted, CommitFailed, SavepointError 等)
343//!
344//! // 便捷方法
345//! DbError::query("test failed")        // 创建查询错误
346//! DbError::connection("timeout")       // 创建连接错误
347//! DbError::not_found("user #42")       // 创建未找到错误
348//! err.is_retryable()                   // 是否可重试
349//! err.error_code()                     // "DB001"
350//! ```
351//!
352//! ## 验证方法
353//!
354//! SZ-ORM 通过 **7 线验证体系** 保证质量:
355//!
356//! | 验证方法 | 描述 | 测试文件 |
357//! |---------|------|---------|
358//! | **TDD** | 核心模块 115+ 单元测试 | `core.rs` |
359//! | **集成** | 真实 MySQL/PG/SQLite/Oracle 端到端 | `integration_mysql.rs`, `integration_pg.rs`, `integration_sqlite.rs` |
360//! | **Jepsen** | 29 并发正确性测试 + 10 真实 DB Jepsen | `jepsen.rs`, `real_db_jepsen.rs` |
361//! | **Fuzz** | 11 边界/边缘案例发现 | `fuzz.rs` |
362//! | **Stress** | 77 性能基准测试 | `stress.rs`, `core_bench.rs` |
363//! | **Chaos** | 16 故障鲁棒性测试 | `chaos.rs` |
364//! | **Formal** | 14 形式化验证不变量 | `formal.rs` |
365//!
366//! **总计:1,723 测试**(1,317 `#[test]` + 406 `#[tokio::test]`;部分需真实服务)
367//!
368//! ## 类型别名与常量
369//!
370//! ```rust,ignore
371//! // 类型别名
372//! pub type Shared<T> = Arc<T>;
373//! pub type Boxed<T> = Box<T>;
374//! pub type DbResult<T> = Result<T, DbError>;
375//! pub type PoolResult<T> = Result<T, PoolError>;
376//! pub type CacheResult<T> = Result<T, CacheError>;
377//! pub type TxResult<T> = Result<T, TxError>;
378//!
379//! // 默认常量
380//! pub const DEFAULT_BATCH_SIZE: usize = 1000;
381//! pub const DEFAULT_ACQUIRE_TIMEOUT: u64 = 30;   // 秒
382//! pub const DEFAULT_IDLE_TIMEOUT: u64 = 600;      // 秒
383//! pub const DEFAULT_MAX_LIFETIME: u64 = 1800;     // 秒
384//! pub const DEFAULT_MIN_IDLE: u32 = 5;
385//! pub const DEFAULT_MAX_SIZE: u32 = 100;
386//! ```
387//!
388//! ## 导出清单
389//!
390//! `use sz_orm_core::*;` 将导入以下模块的全部公共符号:
391//!
392//! - `async_trait` (重导出)、`bytes::Bytes`、`chrono::{DateTime, Utc}`、`serde::{Deserialize, Serialize}`
393//! - `cache::*` — `Cache`, `MemoryCache`, `MultiLevelCache`, `CacheStats`
394//! - `db_type::*` — `DbType` 枚举 (11 种数据库)
395//! - `dialect::*` — `Dialect`, `MySqlDialect`, `PostgreSqlDialect`, `SqliteDialect`, `OracleDialect`, `get_dialect()`
396//! - `error::*` — `DbError`, `PoolError`, `CacheError`, `TxError`
397//! - `migration::*` — `Migration`, `Migrator`, `SchemaBuilder`, `ColumnDef`, `IndexDef`, `ForeignKeyDef`
398//! - `model::*` — `Model`, `ModelExt`, `Relation`, `BelongsTo`, `HasMany`, `HasOne`, `BelongsToMany`
399//! - `pool::*` — `Pool`, `PoolConfig`, `PoolConfigBuilder`, `Connection`, `ConnectionFactory`, `PoolStatus`
400//! - `query::*` — `QueryBuilder<M>` (链式 SQL 构造器)
401//! - `transaction::*` — `Transaction`, `TransactionManager`, `TransactOptions`, `IsolationLevel`
402//! - `value::*` — `Value` 枚举 (20 种变体)
403
404// 文档完整性:全局启用 missing_docs lint(v3.6.0 已补齐全部 pub API 文档)
405#![warn(missing_docs)]
406
407// v3.9.0 M1-T3:derive(Validate) 宏生成 sz_orm_core 绝对路径,
408// crate 内部测试需 self 别名使该路径解析到当前 crate
409#[cfg(all(test, feature = "data-validation"))]
410extern crate self as sz_orm_core;
411
412use std::sync::Arc;
413
414/// Re-export async traits
415pub use async_trait::async_trait;
416
417/// Re-export common types
418pub use bytes::Bytes;
419pub use chrono::{DateTime, Utc};
420pub use serde::{Deserialize, Serialize};
421
422pub mod access_control;
423pub mod accessors;
424pub mod active_model;
425pub mod behaviors;
426#[cfg(feature = "benchmark-suite")]
427pub mod benchmark;
428pub mod bloom;
429mod cache;
430pub mod circuit_breaker;
431#[cfg(feature = "type-safe-columns")]
432pub mod column;
433#[cfg(feature = "zero-copy")]
434pub mod columnar;
435pub mod cursor_stream;
436pub mod cycle_detection;
437pub mod data_permission;
438mod db_type;
439pub mod dialect;
440#[cfg(feature = "prod-dialect-security")]
441pub mod dialect_security;
442pub mod dirty_attributes;
443#[cfg(feature = "dist-cache")]
444pub mod dist_cache;
445pub mod dynamic_filter;
446pub mod dynamic_sql;
447pub mod eager_loader;
448pub mod entity_graph;
449mod error;
450pub mod find_with_related;
451#[cfg(feature = "compile-governance")]
452pub mod governance;
453pub mod guard;
454pub mod hooks;
455pub mod hydration_plugin;
456pub mod i18n;
457pub mod join_dsl;
458pub mod json_query;
459#[cfg(feature = "l1-cache")]
460pub mod l1_cache;
461pub mod l2_cache;
462pub mod lambda;
463pub mod migration;
464#[cfg(feature = "migration-dry-run")]
465pub mod migration_dry_run;
466pub mod mock;
467mod model;
468pub mod n1_eliminator;
469pub mod nested_active_model;
470pub mod observer;
471pub mod optimistic_lock;
472pub mod paginator;
473pub mod partial_model;
474pub mod phinx_migration;
475#[cfg(feature = "plan-cache")]
476pub mod plan_cache;
477mod pool;
478#[cfg(feature = "auto-prewarm")]
479pub mod prewarm;
480#[cfg(feature = "prod-ready")]
481pub mod prod_ready_check;
482mod query;
483#[cfg(feature = "data-validation")]
484pub mod validation;
485/// 重导出 QueryBuilder 供外部使用
486pub use query::QueryBuilder;
487#[cfg(feature = "cache-coherence")]
488pub mod cache_coherence;
489#[cfg(feature = "cache-warmup-protection")]
490#[allow(missing_docs)]
491pub mod cache_warmup_protection;
492#[cfg(feature = "connection-level-tenant")]
493pub mod connection_tenant;
494#[cfg(feature = "forward-compat-sandbox")]
495#[allow(missing_docs)]
496pub mod forward_compat_sandbox;
497#[cfg(feature = "migration-branch")]
498pub mod migration_branch;
499#[cfg(feature = "process-l1-cache")]
500pub mod process_l1_cache;
501#[cfg(feature = "qb-migration-tool")]
502pub mod qb_migration_fix;
503#[cfg(feature = "qb-migration-tool")]
504pub mod qb_migration_lint;
505pub mod queryable;
506pub mod quick_query;
507pub mod rate_limiter;
508pub mod relation_trait;
509pub mod repository;
510pub mod result_map;
511pub mod retry;
512#[cfg(feature = "zero-downtime-rollback")]
513pub mod rollback_zero_downtime;
514#[cfg(feature = "schema-diff-viz")]
515pub mod schema_diff_viz;
516pub mod schema_gen;
517pub mod schema_sync;
518#[cfg(feature = "data-seeding")]
519pub mod seeding;
520pub mod select_types;
521pub mod shadow;
522#[cfg(feature = "simd")]
523pub mod simd;
524pub mod smart_eager_loader;
525pub mod sql_buffer;
526pub mod sql_safety;
527#[cfg(feature = "sql-verify-proc")]
528pub mod sql_verify;
529pub mod stream_api;
530#[cfg(feature = "streaming-export")]
531pub mod streaming_export;
532pub mod telemetry;
533#[cfg(feature = "multi-tenant-enhanced")]
534pub mod tenant_context;
535#[cfg(feature = "tenant-quota-rls-enhanced")]
536#[allow(missing_docs)]
537pub mod tenant_quota_rls;
538#[cfg(feature = "multi-tenant-enhanced")]
539pub mod tenant_security;
540mod transaction;
541pub mod type_handler;
542pub mod typed;
543pub mod typed_ast;
544#[cfg(feature = "typed-relation")]
545pub mod typed_relation;
546mod value;
547#[cfg(feature = "zero-copy")]
548pub mod value_borrowed;
549
550// Re-export proc macros
551pub use queryable::Query;
552pub use queryable::QueryAs;
553pub use sz_orm_macros::query;
554pub use sz_orm_macros::query_as;
555pub use sz_orm_macros::schema;
556pub use sz_orm_macros::sql_string;
557pub use sz_orm_macros::typed_query;
558// FromQueryResult derive 宏(与 value.rs 中同名 trait 通过显式 use 遮蔽 glob 导出)
559#[cfg(feature = "n1-lint")]
560pub use sz_orm_macros::detect_n_plus_one;
561pub use sz_orm_macros::FromQueryResult;
562pub use sz_orm_macros::RelationTrait;
563#[cfg(feature = "data-validation")]
564pub use sz_orm_macros::Validate;
565
566pub use cache::*;
567pub use cycle_detection::{CycleDetector, CyclePolicy};
568pub use db_type::*;
569#[allow(ambiguous_glob_reexports)]
570pub use dialect::*;
571pub use eager_loader::NestedEagerResult;
572pub use error::*;
573#[allow(ambiguous_glob_reexports)]
574pub use migration::*;
575pub use model::*;
576pub use nested_active_model::CascadeStrategy;
577pub use pool::*;
578#[allow(unused_imports)]
579pub use query::*;
580pub use schema_sync::{Confirm, DataMigrationHook, DestructiveSyncResult};
581pub use transaction::*;
582pub use value::*;
583
584/// Alias for `Arc<T>`
585pub type Shared<T> = Arc<T>;
586
587/// Alias for `Box<T>`
588pub type Boxed<T> = Box<T>;
589
590/// Alias for Result<T, DbError>
591pub type DbResult<T> = Result<T, DbError>;
592
593/// Result type for pool operations
594pub type PoolResult<T> = Result<T, PoolError>;
595
596/// Result type for cache operations
597pub type CacheResult<T> = Result<T, CacheError>;
598
599/// Result type for transaction operations
600pub type TxResult<T> = Result<T, TxError>;
601
602/// Default batch size for bulk operations
603pub const DEFAULT_BATCH_SIZE: usize = 1000;
604
605/// Default connection timeout in seconds
606pub const DEFAULT_ACQUIRE_TIMEOUT: u64 = 30;
607
608/// Default idle timeout in seconds
609pub const DEFAULT_IDLE_TIMEOUT: u64 = 600;
610
611/// Default max lifetime in seconds
612pub const DEFAULT_MAX_LIFETIME: u64 = 1800;
613
614/// Default minimum idle connections
615pub const DEFAULT_MIN_IDLE: u32 = 5;
616
617/// Default maximum pool size
618pub const DEFAULT_MAX_SIZE: u32 = 100;
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use std::error::Error;
624
625    #[test]
626    fn test_db_type() {
627        assert_eq!(DbType::MySQL.as_str(), "mysql");
628        assert_eq!(DbType::PostgreSQL.as_str(), "postgres");
629        assert_eq!(DbType::Sqlite.as_str(), "sqlite");
630    }
631
632    #[test]
633    fn test_value() {
634        let v = Value::Null;
635        assert!(v.is_null());
636
637        let v = Value::I64(42);
638        assert!(v.is_i64());
639
640        let v = Value::String("hello".to_string());
641        assert!(v.is_string());
642    }
643
644    #[test]
645    fn test_db_error_display() {
646        let err = DbError::QueryError("test query failed".to_string());
647        assert_eq!(format!("{}", err), "Query error: test query failed");
648
649        let err = DbError::ConnectionRefused("localhost".to_string());
650        assert_eq!(format!("{}", err), "Connection refused: localhost");
651    }
652
653    #[test]
654    fn test_db_error_source() {
655        let err = DbError::PoolError(PoolError::Timeout);
656        assert!(err.source().is_some());
657    }
658
659    #[tokio::test]
660    async fn test_async_trait_export() {
661        fn _check_send_sync<T: Send + Sync>() {}
662
663        struct TestImpl;
664        #[async_trait]
665        trait AsyncFoo: Send + Sync {
666            async fn foo(&self);
667        }
668
669        #[async_trait]
670        impl AsyncFoo for TestImpl {
671            async fn foo(&self) {}
672        }
673
674        let impl_ = TestImpl;
675        impl_.foo().await;
676        _check_send_sync::<TestImpl>();
677    }
678
679    // ---- compile-time SQL validation macro tests ----
680
681    /// Valid SQL should compile and be usable as a string
682    #[test]
683    fn test_sql_string_valid_select() {
684        let sql = sql_string!("SELECT * FROM users WHERE id = 1");
685        assert!(sql.contains("SELECT"));
686        assert!(sql.contains("FROM"));
687    }
688
689    #[test]
690    fn test_sql_string_valid_insert() {
691        let sql = sql_string!("INSERT INTO users (name) VALUES ('alice')");
692        assert!(sql.contains("INSERT"));
693    }
694
695    #[test]
696    fn test_sql_string_valid_update() {
697        let sql = sql_string!("UPDATE users SET name = 'bob' WHERE id = 1");
698        assert!(sql.contains("UPDATE"));
699    }
700
701    #[test]
702    fn test_sql_string_valid_delete() {
703        let sql = sql_string!("DELETE FROM users WHERE id = 1");
704        assert!(sql.contains("DELETE"));
705    }
706
707    #[test]
708    fn test_sql_string_valid_create() {
709        let sql = sql_string!("CREATE TABLE test (id INT PRIMARY KEY)");
710        assert!(sql.contains("CREATE"));
711    }
712
713    #[test]
714    fn test_sql_string_with_params() {
715        let sql = sql_string!("SELECT * FROM users WHERE id = ?"; params: 1);
716        assert!(sql.contains("?"));
717    }
718
719    #[test]
720    fn test_sql_string_complex_query() {
721        let sql = sql_string!(
722            "SELECT u.*, o.total FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.status = 'active'"
723        );
724        assert!(sql.contains("LEFT JOIN"));
725    }
726
727    #[test]
728    fn test_sql_string_nested_parens() {
729        let sql = sql_string!("SELECT * FROM (SELECT * FROM users) t");
730        assert!(sql.contains("SELECT"));
731    }
732}