Expand description
§SZ-ORM — Xianshida ORM
Rust asynchronous ORM workspace (prototype stage), ThinkORM-style compatible.
§Architecture Overview
The SZ-ORM workspace consists of 43 members (41 sz-orm-* libs + cli + examples):
§Core Engine (sz-orm-core)
| Module | Function |
|---|---|
model | Model trait — defines table name, primary key, timestamps, soft delete, relations |
query | QueryBuilder<M> — chainable API, supports SELECT/INSERT/UPDATE/DELETE/aggregation/pagination/JOIN |
dialect | Multi-database dialects — MySQL (backtick), PostgreSQL (double quote), SQLite, Oracle 23ai |
pool | Asynchronous connection pool — configurable size, timeout, idle reaping, health checks, max lifetime |
transaction | ACID transactions — isolation levels, savepoints, TransactionManager for multi-transaction management |
migration | File-based migration system — up/down/rollback/reset/refresh, with SchemaBuilder |
cache | Multi-level cache — MemoryCache, MultiLevelCache, with TTL support |
value | Unified value type — 20 variants (integer/float/string/bytes/UUID/date/JSON/array) |
db_type | Database type enum — MySQL, PostgreSQL, SQLite, Oracle, Redis, MongoDB and 11 total |
error | Error type system — DbError (20 variants), PoolError, CacheError, TxError |
§Database Adapters
- sz-orm-sqlx — sqlx adapter, connects to real MySQL/PostgreSQL/SQLite/Oracle
- sz-orm-sql-validator — SQL validation and injection detection
§Extension Ecosystem Packages (18)
| Package | Function |
|---|---|
| sz-orm-crypto | Crypto primitives (AES-256-GCM, PBKDF2, HMAC-SHA256) |
| sz-orm-auth | JWT authentication (HS256) |
| sz-orm-scheduler | Cron scheduled task dispatch |
| sz-orm-mqtt | MQTT client (rumqttc) |
| sz-orm-websocket | WebSocket server (tokio-tungstenite) |
| sz-orm-queue | Message queue (RabbitMQ/lapin, Kafka, NATS, ActiveMQ, RocketMQ, Pulsar) |
| sz-orm-storage | Object storage (S3/Alibaba Cloud/Tencent Cloud/Huawei Cloud/Qiniu/Upyun/Local) |
| sz-orm-ai | AI integration (Embedding, RAG, Vector) |
| sz-orm-grpc | gRPC server/client |
| sz-orm-graphql | GraphQL query support |
| sz-orm-es | Elasticsearch integration |
| sz-orm-tracing | Distributed tracing |
| sz-orm-logger | Logging system |
| sz-orm-swagger | API documentation generation |
| sz-orm-masking | Data masking |
| sz-orm-health | Health checks |
| sz-orm-audit | Audit log |
| sz-orm-batch | Batch operations |
§Advanced Feature Packages (6)
| Package | Function |
|---|---|
| sz-orm-dtx | Distributed transactions |
| sz-orm-rw | Read-write splitting |
| sz-orm-sharding | Sharding |
| sz-orm-limit | Rate limiting |
| sz-orm-config | Configuration management |
| sz-orm-mig | Enhanced migration management |
§Platform Support
- sz-orm-wasm — WebAssembly compile target
- sz-orm-lc — Local/edge computing
- sz-orm-back — Backup and restore
§Quick Start
ⓘ
use sz_orm_core::*;
// 1. Define the model
#[derive(Clone)]
struct User {
id: i64,
name: String,
email: String,
}
impl Model for User {
type PrimaryKey = i64;
fn table_name() -> &'static str { "users" }
fn pk(&self) -> Self::PrimaryKey { self.id }
fn set_pk(&mut self, pk: Self::PrimaryKey) { self.id = pk; }
}
// 2. Build a query
let dialect = get_dialect(DbType::MySQL).unwrap();
let sql = QueryBuilder::<User>::new(dialect)
.table("users")
.select(vec!["id", "name", "email"])
.where_eq("status", Value::String("active".to_string()))
.order_by("created_at")
.order_desc("id")
.limit(10)
.build_select();
// 3. Validate before execution
QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
.table("users")
.select(vec!["id", "name"])
.validate()?; // Validate SQL syntax, injection, parenthesis balance
// 4. Other operations
let mut data = std::collections::HashMap::new();
data.insert("name".to_string(), Value::String("Alice".to_string()));
data.insert("age".to_string(), Value::I64(25));
let insert_sql = QueryBuilder::<User>::new(dialect)
.table("users")
.build_insert(&data);
let update_sql = QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
.table("users")
.where_eq("id", Value::I64(1))
.build_update(&data);
let delete_sql = QueryBuilder::<User>::new(get_dialect(DbType::MySQL).unwrap())
.table("users")
.where_eq("id", Value::I64(1))
.build_delete();§Supported Databases
| Database | Dialect Implementation | Real Connection | Quoting |
|---|---|---|---|
| MySQL | MySqlDialect (` backtick) | sz-orm-sqlx | ✅ |
| PostgreSQL | PostgreSqlDialect (" double quote) | sz-orm-sqlx | ✅ |
| SQLite 3.35+ | SqliteDialect (" double quote) | sz-orm-sqlx | ✅ |
| Oracle 23ai | OracleDialect (automatic type mapping) | sz-orm-sqlx | ✅ |
Obtain a dialect instance via get_dialect(DbType::MySQL). Each dialect handles:
- Identifier quoting style
- String escaping rules
- Pagination syntax (LIMIT/OFFSET vs OFFSET/FETCH)
- JSON extraction functions (JSON_EXTRACT vs #>> vs json_extract vs JSON_VALUE)
- Full-text search (MATCH AGAINST vs to_tsvector vs CONTAINS)
- Boolean-to-integer conversion (IF/CASE)
- Auto-increment keyword (AUTO_INCREMENT/GENERATED BY DEFAULT AS IDENTITY)
§Core Features in Detail
§QueryBuilder API
Most query methods return Self, enabling chainable calls; validation methods like select/having
return Result<Self> (after audit M-5/M-6, column names/aggregate expressions go through identifier validation):
ⓘ
// Basic query
QueryBuilder::<M>::new(dialect)
.table("users")
.select(vec!["id", "name"])? // Column validation + quote
.where_eq("status", Value::String("active".to_string())) // AND
.or_where_eq("role", Value::String("admin".to_string())) // OR
.where_in("id", vec![Value::I64(1), Value::I64(2)])
.where_between("age", Value::I64(18), Value::I64(30))
.where_null("deleted_at")
.order_by("created_at")
.order_desc("id")
.group_by("status")
.having(AggExpr::CountStar, HavingOp::Gt, Value::I64(5))? // Parameterized HAVING
.limit(20)
.offset(40)
.page(3, 20) // page=3, page_size=20
.join_inner("posts", "users.id", "posts.user_id")
.join_left("profiles", "users.id", "profiles.user_id")
.build_select();
// Aggregate functions
builder.build_count(); // SELECT COUNT(*)
builder.build_exists(); // SELECT EXISTS(...)
builder.build_max("score");
builder.build_min("price");
builder.build_sum("amount");
builder.build_avg("value");§SQL Validation
ⓘ
// Compile-time + runtime dual validation
builder.validate()?; // Validate SELECT
builder.validate_insert(&data)?; // Validate INSERT (including empty data check)
builder.validate_update(&data)?; // Validate UPDATE (including empty data check)
builder.validate_delete()?; // Validate DELETE
// Validation covers: SQL syntax, injection detection, parenthesis balance,
// table/column name legitimacy, JOIN column validation§Model Trait
ⓘ
pub trait Model: Send + Sync + Sized + 'static {
type PrimaryKey: Send + Sync + Debug + Display + Clone + Default;
fn table_name() -> &'static str; // Table name (required)
fn pk_name() -> &'static str { "id" } // Primary key column name
fn pk(&self) -> Self::PrimaryKey; // Get primary key value
fn set_pk(&mut self, pk: Self::PrimaryKey); // Set primary key value
fn foreign_key(relation: &str) -> String; // Foreign key naming "user_id"
fn timestamp_fields() -> Option<TimestampFields>; // Automatic timestamps
fn soft_delete_field() -> Option<&'static str>; // Soft delete field
}
// ModelExt extension
pub trait ModelExt: Model {
fn columns() -> Vec<&'static str>; // All columns
fn fillable() -> Vec<&'static str>; // Fillable columns
fn guarded() -> Vec<&'static str>; // Guarded columns (includes primary key by default)
fn hidden() -> Vec<&'static str>; // Hidden columns (not serialized)
fn relations() -> HashMap<&str, Relation>; // Relations
fn fill(&mut self, data: HashMap<String, Value>); // Mass assignment
fn to_json(&self) -> serde_json::Value; // Serialize
}
// Four relation types
// BelongsTo — many-to-one (Order → User)
// HasMany — one-to-many (User → Orders)
// HasOne — one-to-one (User → Profile)
// BelongsToMany — many-to-many (User ↔ Role, through junction table)§Connection Pool
ⓘ
// Configure via Builder
let config = PoolConfigBuilder::new()
.max_size(100) // Maximum connections
.min_idle(10) // Minimum idle connections
.acquire_timeout(30) // Acquire timeout (seconds)
.idle_timeout(600) // Idle timeout (seconds)
.max_lifetime(1800) // Max lifetime (seconds)
.build()?;
let pool = Pool::new(config, factory)?;
let conn = pool.acquire().await?; // Acquire connection (with timeout)
pool.release(conn).await; // Release connection
pool.status().await; // PoolStatus { idle, active, max, min }
pool.reap_idle().await; // Reap idle connections
pool.close_all().await; // Close all connections§Transactions
ⓘ
// Transaction options
let opts = TransactOptions::default()
.with_isolation(IsolationLevel::Serializable)
.read_only()
.with_timeout(Duration::from_secs(30));
let mut tx = Transaction::new(conn, opts);
tx.execute("INSERT INTO users VALUES (1)").await?;
tx.query("SELECT * FROM users").await?;
// Savepoints (nested transactions)
let sp = tx.savepoint().await?; // SAVEPOINT sp_N
tx.rollback_to_savepoint(&sp).await?; // ROLLBACK TO SAVEPOINT sp_N
tx.release_savepoint(&sp).await?; // RELEASE SAVEPOINT sp_N
tx.commit().await?;
// tx.rollback().await?;
// TransactionManager: manages multiple named transactions
let mgr = TransactionManager::new();
mgr.begin("tx1", conn, opts).await?;
mgr.commit("tx1").await?;
mgr.list().await; // ["tx1"]
mgr.state("tx1").await; // Some(TransactionState::Committed)§Migration System
ⓘ
// File naming: <version>_<name>_up.sql / <version>_<name>_down.sql
// Example: 001_create_users_up.sql, 001_create_users_down.sql
let resolver = FileMigrationResolver::new(PathBuf::from("./migrations"));
let migrations = resolver.resolve(DbType::MySQL)?;
let mut migrator = Migrator::new(MigrationContext::default())
.add_migrations(migrations);
migrator.migrate().await?; // Execute all pending migrations
migrator.up(Some("003")).await?; // Migrate up to specified version
migrator.down(Some("001")).await?; // Rollback to specified version
migrator.rollback("002").await?; // Rollback a single migration
migrator.reset().await?; // Rollback all + re-execute
migrator.refresh().await?; // Same as reset
migrator.progress(); // MigrationProgress { total, applied, pending }
// SchemaBuilder: programmatic table creation
let sql = SchemaBuilder::new("users")
.add_column(ColumnDef::new("id", "INT").not_null().auto_increment())
.add_column(ColumnDef::new("name", "VARCHAR").length(255).not_null())
.add_index(IndexDef::new("idx_name", vec!["name"]).unique())
.add_foreign_key(
ForeignKeyDef::new("fk_role", "role_id", "roles", "id")
.on_delete("CASCADE")
)
.build(DbType::MySQL);§Value Type
ⓘ
// 20 variants, covering all database types
Value::Null | Bool(bool) | I8..I64 | U8..U64 | F32 | F64
| String(String) | Bytes(Vec<u8>) | Uuid(String) | Date(String)
| DateTime(String) | Time(String) | Json(String) | Array(Vec<Value>)
// Type conversions
value.as_str() // Option<&str>
value.as_i64() // Option<i64> (supports F32/F64/Bool/String→i64 conversion)
value.as_f64() // Option<f64>
value.as_bool() // Option<bool> (supports "true"/"1"/"yes"/"on" etc.)
value.as_bytes() // Option<&[u8]>
value.to_param() // Cow<str> — SQL parameter format
// From implementations
let v: Value = 42i64.into();
let v: Value = "hello".into();
let v: Value = vec![1u8, 2u8].into();§Error Handling
Unified error type system, each error carries a unique error code:
ⓘ
// DbError — 20 variants, error codes DB001-DB020
DbError::QueryError("...")
DbError::ConnectionRefused("...")
DbError::ConnectionTimeout("...")
DbError::NotFound("...")
DbError::ConstraintViolation("...")
// ... etc.
// PoolError — 6 variants, error codes PL001-PL006
PoolError::Exhausted | Timeout | AlreadyAcquired | InvalidConfig | ...
// CacheError — 6 variants, error codes CH001-CH006
// TxError — 6 variants (NotStarted, CommitFailed, SavepointError, etc.)
// Convenience methods
DbError::query("test failed") // Create query error
DbError::connection("timeout") // Create connection error
DbError::not_found("user #42") // Create not-found error
err.is_retryable() // Whether retryable
err.error_code() // "DB001"§Validation Methods
SZ-ORM ensures quality through a 7-layer validation system:
| Method | Description | Test File |
|---|---|---|
| TDD | 115+ unit tests for core modules | core.rs |
| Integration | End-to-end with real MySQL/PG/SQLite/Oracle | integration_mysql.rs, integration_pg.rs, integration_sqlite.rs |
| Jepsen | 29 concurrency correctness tests + 10 real DB Jepsen | jepsen.rs, real_db_jepsen.rs |
| Fuzz | 11 boundary/edge case discoveries | fuzz.rs |
| Stress | 77 performance benchmarks | stress.rs, core_bench.rs |
| Chaos | 16 fault robustness tests | chaos.rs |
| Formal | 14 formal verification invariants | formal.rs |
Total: 1,723 tests (1,317 #[test] + 406 #[tokio::test]; some require real services)
§Type Aliases and Constants
ⓘ
// Type aliases
pub type Shared<T> = Arc<T>;
pub type Boxed<T> = Box<T>;
pub type DbResult<T> = Result<T, DbError>;
pub type PoolResult<T> = Result<T, PoolError>;
pub type CacheResult<T> = Result<T, CacheError>;
pub type TxResult<T> = Result<T, TxError>;
// Default constants
pub const DEFAULT_BATCH_SIZE: usize = 1000;
pub const DEFAULT_ACQUIRE_TIMEOUT: u64 = 30; // seconds
pub const DEFAULT_IDLE_TIMEOUT: u64 = 600; // seconds
pub const DEFAULT_MAX_LIFETIME: u64 = 1800; // seconds
pub const DEFAULT_MIN_IDLE: u32 = 5;
pub const DEFAULT_MAX_SIZE: u32 = 100;§Export Manifest
use sz_orm_core::*; imports all public symbols from the following modules:
async_trait(re-exported),bytes::Bytes,chrono::{DateTime, Utc},serde::{Deserialize, Serialize}cache::*—Cache,MemoryCache,MultiLevelCache,CacheStatsdb_type::*—DbTypeenum (11 database types)dialect::*—Dialect,MySqlDialect,PostgreSqlDialect,SqliteDialect,OracleDialect,get_dialect()error::*—DbError,PoolError,CacheError,TxErrormigration::*—Migration,Migrator,SchemaBuilder,ColumnDef,IndexDef,ForeignKeyDefmodel::*—Model,ModelExt,Relation,BelongsTo,HasMany,HasOne,BelongsToManypool::*—Pool,PoolConfig,PoolConfigBuilder,Connection,ConnectionFactory,PoolStatusquery::*—QueryBuilder<M>(chainable SQL builder)transaction::*—Transaction,TransactionManager,TransactOptions,IsolationLevelvalue::*—Valueenum (20 variants)
Re-exports§
pub use queryable::Query;pub use queryable::QueryAs;pub use change_tracker::ChangeTracker;pub use change_tracker::EntityEntry;pub use change_tracker::EntityState;pub use lazy_loader::LazyCollection;pub use lazy_loader::LazyLoader;pub use lazy_loader::LazyRef;pub use linq::LinqQuery;pub use query_cache::QueryCache;pub use query_cache::QueryCacheKey;pub use query_cache::TimestampCache;pub use cycle_detection::CycleDetector;pub use cycle_detection::CyclePolicy;pub use eager_loader::NestedEagerResult;pub use nested_active_model::CascadeStrategy;pub use schema_sync::Confirm;pub use schema_sync::DataMigrationHook;pub use schema_sync::DestructiveSyncResult;pub use dialect::*;pub use migration::*;
Modules§
- access_
control - 行级和字段级权限控制
- accessors
- Accessors / Mutators + Attribute Casting
- active_
model - ActiveValue / ActiveModel — 三态字段更新模式
- adaptive_
adapter - Adaptive Adapter — sz-orm-core 自适应查询适配层
- behaviors
- 行为系统(Behaviors)— 可插拔代码复用单元
- benchmark
- Benchmark 回归对比结构(
benchmark-suitefeature) - bloom
- 布隆过滤器(公共实现)
- cache_
coherence - 缓存一致性协议模块(v4.1.0,
cache-coherencefeature gate) - cache_
warmup_ protection - 缓存预热与穿透防护
- change_
tracker - 实体变更跟踪器(Change Tracker)
- circuit_
breaker - 断路器抽象(P1-4:抽象提升到核心层,供连接池执行路径集成)
- column
- M4-T3: 类型安全列引用
- columnar
- v3.2.0 零拷贝序列化 — 列式结果集
- config_
adapter - Config Center Adapter — sz-orm-core 配置中心适配层
- connection_
tenant - 连接级多租户隔离
- cursor_
stream - 游标式流式查询(P1-2:Oracle/MSSQL 游标)
- cycle_
detection - 循环检测 — Eager Loading 多级关联递归安全保护(v2.2.0 B-1)
- data_
permission - 数据权限拦截器(Data Permission Interceptor)
- dialect
- 不同数据库的方言抽象
- dialect_
security - 五方言连接安全验证(
prod-dialect-securityfeature) - dirty_
attributes - 脏字段追踪(Dirty Attributes)+ @DynamicInsert / @DynamicUpdate
- dist_
cache - 分布式缓存一致性模块
- dynamic_
filter - 动态 Filter(Hibernate @Filter / @FilterDef 风格)
- dynamic_
sql - XML/py_sql 动态 SQL 构造器(rbatis 风格)
- eager_
loader - EagerLoader — Eager Loading 端到端自动执行与组装(P-F-1, v2.1.0)
- entity_
graph - Entity Graph + @BatchSize 批量抓取
- find_
with_ related - find_with_related 关联查询流畅 API
- forward_
compat_ sandbox - 迁移前向兼容性检查与沙箱预演
- governance
- 编译期数据治理(v4.3.0 M3-T3/T4,
compile-governancefeature) - graph_
adapter - Graph Adapter — sz-orm-core 图数据库适配层
- graphql_
adapter - GraphQL Adapter — sz-orm-core GraphQL 适配层
- guard
- 防全表 UPDATE/DELETE 攻击守卫(Safe SQL Guard)
- hooks
- 钩子系统(Hooks)— 软删除 + 多租户
- hydration_
plugin - Hydration Modes + Plugin 拦截器链
- i18n
- 国际化(i18n)支持
- join_
dsl - JoinDSL — 类型安全的 JOIN 语法(Diesel 风格)
- json_
query - JSON 字段查询增强
- l1_
cache - L1 一级缓存(Level-1 Cache)— Session 级别 Identity Map
- l2_
cache - L2 二级缓存(Level-2 Cache)
- lambda
- Lambda 类型安全 Wrapper
- lazy_
loader - 懒加载器(Lazy Loader)
- linq
- LINQ 风格查询 API
- logger_
adapter - Logger Adapter — sz-orm-core 结构化日志适配层
- migration
- Migration system
- migration_
branch - 迁移版本分支模块(v4.1.0,
migration-branchfeature gate) - migration_
dry_ run - 迁移 dry-run + 影响分析(
migration-dry-runfeature) - mock
- Mock 数据库连接 — 用于单元测试,无需真实数据库
- n1_
eliminator - N1Eliminator — N+1 自动消除器(v2.3.0 任务 C)
- nested_
active_ model - ActiveModel 嵌套持久化 — 一次
nested_save()持久化整个对象图 - observer
- Observer + Event Subscriber — 模型生命周期观察者模式
- optimistic_
lock - 乐观锁(Optimistic Locking)
- paginator
- 内置分页支持 —
PaginatorTrait+Paginator+StreamQueryTrait(M4) - partial_
model - Partial Models — 部分字段选择与聚合查询(P-F-3, v2.1.0)
- phinx_
migration - Phinx 风格 migration 链式 API
- plan_
cache - v3.2.0 查询计划缓存
- plugin
- 插件系统模块
- postgis_
adapter - PostGIS Adapter — sz-orm-core 空间数据库适配层
- prewarm
- 连接池预热增强(v3.2.0)
- process_
l1_ cache - 进程级 L1 缓存(Process-Level L1 Cache)— 跨 Session 共享 Identity Map
- prod_
ready_ check - 生产就绪检查清单执行器(
prod-readyfeature) - qb_
migration_ fix - QueryBuilder 迁移 fix 模块
- qb_
migration_ lint - QueryBuilder 迁移 lint 模块
- query_
cache - 查询缓存 + 时间戳缓存(Query Cache + Timestamp Cache)
- queryable
- derive(Queryable) — 从 SELECT 结果自动派生结构体(Diesel 风格)
- quick_
query - 快捷查询(Db::name 风格)
- rate_
limiter - 限流器抽象(P1-4:抽象提升到核心层,供连接池执行路径集成)
- relation_
trait - RelationTrait — 类型安全的关联关系定义与 JOIN 链式 API
- repository
- Repository Pattern 仓储模式
- result_
map - ResultMap 高级映射 + Native Query + ResultSetMapping
- retry
- 通用错误重试器
- rollback_
zero_ downtime - 零停机回滚(Zero-Downtime Rollback)
- rw_
adapter - Read-Write Splitting Adapter — sz-orm-core 读写分离适配层
- schema_
diff_ viz - Schema Diff 可视化模块(v4.1.0,
schema-diff-vizfeature gate) - schema_
gen - Diesel 风格 schema.rs 自动生成
- schema_
sync - Schema Sync — 自动结构同步
- search_
adapter - Search Adapter — sz-orm-core 搜索引擎适配层
- seeding
- 数据 seeding/fixture 管理模块(v4.1.0,
data-seedingfeature gate) - select_
types - 类型安全的 JOIN 选择器(SeaORM 风格)
- shadow
- 双轨影子流量校验模块
- simd
- v3.2.0 SIMD 加速 — 批量整数解码 + 列比较
- smart_
eager_ loader - SmartEagerLoader — 智能策略选择 Eager Loading(v2.3.0 任务 C)
- sql_
buffer - SQL 构造缓冲区抽象
- sql_
safety - SQL 安全工具:标识符与外键动作校验
- sql_
verify - proc-macro 编译期 SQL 验证模块
- stream_
api - Stream API — 异步流式查询
- streaming_
export - 流式导出(
streaming-exportfeature) - telemetry
- 可观测性遥测(Telemetry)
- tenant_
context - 多租户上下文与隔离策略
- tenant_
quota_ rls - 租户资源配额与行级安全增强
- tenant_
security - 多租户安全策略:行级安全 + 列级脱敏 + 多租户审计
- timeseries_
adapter - Timeseries Adapter — sz-orm-core 时序数据库适配层
- tracing_
adapter - Tracing Adapter — sz-orm-core 分布式追踪适配层
- type_
handler - TypeHandler SPI — 自定义类型处理器注册
- typed
- 强类型 AST 支持模块
- typed_
ast - 强类型 AST 表达式层(Diesel 风格探索)
- typed_
relation - 类型安全关联查询模块
- validation
- 数据验证框架(
data-validationfeature) - value_
borrowed - v3.2.0 零拷贝序列化 — 借用型值类型
Macros§
- define_
columns - 为 Model 定义一组类型安全的字段标记
- migrate
migrate!宏 — 编译时创建迁移并验证 SQL 语法- query
- Compile-time SQL validation with optional real DB verification.
- query_
as - Compile-time SQL schema generator.
- schema
- select_
typed - 类型安全多列 SELECT 宏(M3 验收标准)
- sql_
string - Compile-time SQL validation macro.
- typed_
query - Diesel-style strongly-typed AST macro (coexists with
sql_string!/query!).
Structs§
- Belongs
To - 多对一关系配置
- Belongs
ToMany - 多对多关系配置
- Bytes
- Re-export common types A cheaply cloneable and sliceable chunk of contiguous memory.
- Cache
Stats - 缓存统计信息
- Date
Time - ISO 8601 combined date and time with time zone.
- Error
Context - #6 修复:错误上下文链节点
- HasMany
- 一对多关系配置
- HasOne
- 一对一关系配置
- Leak
Detection Config - 连接泄漏检测配置
- Leak
Entry - 泄漏条目
- Leak
Report - 泄漏报告
- Memory
Cache - 基于内存的缓存实现
- Morph
Many - 多态一对多配置(父模型侧)
- MorphTo
- 多态反向配置(子模型侧)
- Multi
Level Cache - 多级缓存(按顺序查询各级缓存)
- Negative
Cache - 带负缓存的缓存包装器
- Pool
- 连接池核心实现
- Pool
Config - 连接池配置
- Pool
Config Builder - 连接池配置构建器
- Pool
Metrics - 连接池累计统计指标(Prometheus 风格)
- Pool
Prod Config - 连接池生产配置:包装既有 PoolConfig,提供生产配置加载入口
- Pool
Status - 连接池状态快照
- Pool
Tuning Advice - 连接池调优建议(启发式分析
PoolMetrics后生成) - Pooled
Connection - 连接池中的连接条目,记录创建时间和最后使用时间
- Query
Builder - Re-export QueryBuilder for external use 用于构造 SQL 查询的查询构造器
- Query
Builder Wrapper - 查询构造器包装类型,用于挂载作用域
- Timestamp
Fields - 时间戳字段配置
- TlsConfig
- TLS 配置
- Transact
Options - 事务执行选项
- Transaction
- 事务对象,封装一个数据库事务
- Transaction
Manager - 事务管理器,管理多个事务 事务管理器(按名称管理多个事务)
- Utc
- The UTC time zone. This is the most efficient time zone when you don’t need the local time. It is also used as an offset (which is also a dummy type).
- With
Relation - 关系预加载构造器
Enums§
- AggExpr
- 聚合表达式(HAVING 条件专用,审计 M-5)
- Auto
Commit - 自动提交模式
- Cache
Error - 缓存特有错误
- Cache
Lookup - 缓存查找结果
- ColType
- 列类型枚举(v1.1.0 新增)
- DbError
- 数据库错误类型
- DbType
- 支持的数据库类型
- Having
Op - HAVING 比较运算符(审计 M-5)
- Isolation
Level - 事务隔离级别
- Leak
Detection Error - 泄漏检测错误
- Pool
Error - 连接池特有错误
- Pool
Event - 连接池事件
- Pool
Prod Error - 连接池生产配置错误
- Propagation
Behavior - 事务传播行为
- Relation
- 模型间的关系描述
- Relation
Error - 关系操作错误类型 关系加载错误
- TlsVersion
- TLS 版本
- Transaction
State - 事务状态
- TxError
- 事务特有错误
- Value
- 数据库值类型
Constants§
- DEFAULT_
ACQUIRE_ TIMEOUT - Default connection timeout in seconds
- DEFAULT_
BATCH_ SIZE - Default batch size for bulk operations
- DEFAULT_
IDLE_ TIMEOUT - Default idle timeout in seconds
- DEFAULT_
MAX_ LIFETIME - Default max lifetime in seconds
- DEFAULT_
MAX_ NESTING_ DEPTH - H-8 默认最大嵌套深度
- DEFAULT_
MAX_ SIZE - Default maximum pool size
- DEFAULT_
MIN_ IDLE - Default minimum idle connections
Traits§
- Active
Record - 支持关系加载的模型 trait(ActiveRecord 模式)
- Cache
- 缓存抽象 trait
- Column
Trait - 列名枚举抽象(P2-2:由
#[derive(ColumnEnum)]自动实现)。 - Connection
- 数据库连接 trait
- Connection
Factory - 连接工厂 trait,用于创建新连接
- Deserialize
- A data structure that can be deserialized from any data format supported by Serde.
- From
Query Result - 从
Value反序列化查询结果行的字段值。 - Model
- 所有 ORM 模型必须实现的核心 trait
- Model
Ext - 模型扩展 trait,提供额外功能
- Query
Builder Ext - 查询构造器扩展 trait
- Relation
Access ModelExt的关系访问扩展方法- Relation
Loader - 可存储已加载关系数据的模型 trait
- Scope
- 查询结果过滤作用域
- Serialize
- A data structure that can be serialized into any data format supported by Serde.
Functions§
- __
sz_ orm_ const_ str_ eq - 编译期字符串相等比较(const 上下文专用,供
query_as!生成的编译期验证代码使用)。 - __
sz_ orm_ const_ types_ compatible - 编译期 SQL 类型兼容性比较(const 上下文专用,供
query_as!生成的编译期验证代码使用)。 - is_
deadlock_ error - M-8 修复:检测错误字符串是否表示死锁
- read_
through - Read-through(同步版):缓存未命中时通过
loader回源加载,写入缓存后返回 - read_
through_ async - Read-through(异步版):缓存未命中时通过异步
loader回源加载,写入缓存后返回 - retry_
on_ deadlock - M-8 修复:在死锁时自动重试事务
- rows_to
- 将
QueryRows转换为Vec<T>,其中T: FromQueryResult。 - rows_
to_ values - 将查询结果行转换为
Vec<HashMap<String, Value>>以便存入关系字段 - set_
error_ hook - 设置全局错误上报 hook
- trigger_
error_ hook - 触发错误 hook(在 DbError 创建/返回时调用)
- value_
to_ json - 将 Value 转换为 serde_json::Value(递归处理 Array)
- write_
around - Write-around(写旁路):仅写后端存储,同时失效缓存中的旧值
- write_
through - Write-through(同步版):同时写入缓存和后端存储(通过
writer回调) - write_
through_ async - Write-through(异步版):同时写入缓存和异步后端存储
Type Aliases§
- Boxed
- Alias for
Box<T> - Cache
Result - Result type for cache operations
- DbResult
- Alias for Result<T, DbError>
- Pool
Event Callback - 连接池事件回调
- Pool
Result - Result type for pool operations
- Query
Rows - 查询结果行类型别名:避免
Connection::query签名触发clippy::type_complexity。 - Query
Stream Item - 流式查询结果项类型别名:避免
Connection::query_stream签名触发clippy::type_complexity。 - Query
Values - 位置式查询结果类型
- Shared
- Alias for
Arc<T> - TxResult
- Result type for transaction operations
Attribute Macros§
- api_
beta - 标记 API 为测试版(Beta)。
cargo doc渲染 🧪 徽章。 - api_
stable - 标记 API 为稳定(Stable)。
cargo doc渲染 ✅ 徽章。 - async_
trait - Re-export async traits
- detect_
n_ plus_ one - Attribute macro: analyzes a function body, detects N+1 query patterns, and emits compile-time warnings (non-blocking).
Derive Macros§
- Deserialize
- From
Query Result - Derive macro: auto-generates an
sz_orm_core::FromQueryResulttrait impl. - Relation
Trait #[derive(RelationTrait)]— auto-generates aRelationTraitimpl (P-F-2, v2.1.0)- Serialize
- Validate
- Derives a
Validatetrait impl.