关系数据库
属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io
提供基于 SeaORM 的连接池生命周期管理、启动期串行迁移、Procedure Found<E> 模型绑定、ListSpec 分页白名单、冲突自动重试事务,以及 #[audit]、#[tenant]、#[lock_version] 实体属性宏。分步实战见 关系数据库教程 与 数据库迁移教程。
在 Cargo.toml 开启主包 kxed 的数据库驱动与迁移特性(支持 seaorm-sqlite、seaorm-postgres 与 seaorm-mysql;独立组装可依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["seaorm-sqlite", "seaorm-migration"] }):
[dependencies]
kxed = { version = "0.0.5-alpha", features = [
"seaorm-sqlite",
"seaorm-migration",
] }在应用配置文件中填写数据库连接串:
[database]
url = "sqlite://data/app.db?mode=rwc"
max_connections = 20声明一个带审计列的实体,并在业务 Procedure 中完成写入、单行绑定与分页查询:
use kxed::plugins::seaorm::sea_orm::{self, entity::prelude::*, ActiveValue::Set};
use kxed::plugins::seaorm::{Found, ListSpec, MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;
#[kxed::audit]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, ToSchema)]
#[sea_orm(table_name = "notes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
const NOTE_LIST: ListSpec = ListSpec::new().sort(&["id", "title"]).search(&["title"]);
#[mutation(name = "notes.create", post = "/api/notes")]
pub async fn create_note(ctx: &AppCtx, title: String) -> Result<Model, AppErr> {
let db = ctx.db()?;
let active = ActiveModel { title: Set(title), ..Default::default() };
Ok(active.insert(&*db).await?)
}
#[query(name = "notes.list", public, get = "/api/notes")]
pub async fn list_notes(ctx: &AppCtx, input: ListInput) -> Result<Collection<Model>, AppErr> {
ctx.list::<Entity>(&input, &NOTE_LIST).await
}
#[query(name = "notes.get", can = "view", get = "/api/notes/{id}")]
pub async fn get_note(_ctx: &AppCtx, Found(note): Found<Entity>, _id: Id<i64>) -> Result<Model, AppErr> {
Ok(note)
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app.migrations")))
.policy::<Model>(NotePolicy)
.run()
.await
}子 crate 独立接入最小示例(应用中始终经 kxed::plugins::seaorm::sea_orm 引入内置 SeaORM,不要混引 crates.io 的 sea-orm):
use kxed_core::{AppCtx, AppErr, Collection};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
use kxed_plugins::seaorm::{AppCtxList, ListSpec, SeaOrmPlugin};
use kxed_runtime::procedure::ListInput;
#[kxed_plugins::seaorm::audit]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize)]
#[sea_orm(table_name = "notes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
const SPEC: ListSpec = ListSpec::new().sort(&["id", "title"]).search(&["title"]);
fn db_plugin() -> SeaOrmPlugin {
SeaOrmPlugin::new()
}
async fn list_notes(ctx: &AppCtx, input: &ListInput) -> Result<Collection<Model>, AppErr> {
ctx.list::<Entity>(input, &SPEC).await
}连接句柄#
请求、Task、Cron 与事件订阅统一通过 ctx.db()? 获取主库连接池(Arc<DatabaseConnection>),具名库用 ctx.db_of("name")?,只读副本用 ctx.read_db()?:
- 框架封装方法传
&db或&txn:PaginateJson、#[tenant]、#[lock_version]、audit::*与Factory的连接参数统一接收&impl AsConnection,无论是ctx.db()?返回的池还是ctx.transaction闭包里的事务句柄,直接传&db或&txn即可。 - SeaORM 原生方法传
&*db:调用.all(&*db)、.one(&*db)、ActiveModelTrait::insert(model, &*db)等原生 SeaORM 方法时,对Arc解引用一层传入&*db。SeaORM 的DbErr在 handler 与 Procedure 中可直接用?转为AppErr。
路由模型绑定#
Found<Entity> 自动按主键查询单行记录,在 Procedure 契约与原生 HTTP 路由中均可直接使用(普通实体写 impl RouteBinding for Entity {} 启用;标注了 #[tenant] 或 #[audit] 的实体由宏自动生成实现,自动过滤当前租户并排除软删除行):
use kxed::plugins::seaorm::Found;
use kxed::prelude::*;
#[query(name = "notes.get", can = "view", get = "/api/notes/{id}")]
pub async fn get_note(_ctx: &AppCtx, Found(note): Found<note::Entity>, _id: Id<i64>) -> Result<note::Model, AppErr> {
Ok(note)
}- Procedure 强制授权与防主键枚举:参数含
Found<E>的#[query]/#[mutation]编译期强制声明can = "..",取行后自动调用Policy<Model>校验权限;拒绝且无"view"权限时统一返回与记录不存在逐字节一致的 404not_found。界面列表批量权限预判走ProcedureBind::bind_many。 - 原生路由提取与嵌套参数选择:在
App::routes原生 handler 中提取 URL 路径参数:
use kxed_core::{AppErr, Json};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
use kxed_plugins::seaorm::{Found, RouteBinding};
pub mod team {
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "teams")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl kxed_plugins::seaorm::RouteBinding for Entity {
const PARAM: Option<&'static str> = Some("team");
}
}
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize)]
#[sea_orm(table_name = "team_notes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub team_id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl RouteBinding for Entity {
const PARAM: Option<&'static str> = Some("note");
}
async fn show(Found(team): Found<team::Entity>, Found(note): Found<Entity>) -> Result<Json<Model>, AppErr> {
if note.team_id != team.id {
return Err(AppErr::not_found());
}
Ok(Json(note))
}绑定结局与多参数规则:
| 请求情形 | 返回结局 |
|---|---|
| 主键命中(租户实体属于当前租户且未被软删除) | handler 拿到 Model |
| 主键不存在、属于其他租户或已软删除 | 404 not_found |
路径参数无法解析为主键类型(支持 i64、i32、Uuid、String 单列主键) | 400 invalid_path |
多参数路由未通过 PARAM、#[tenant(param = "..")] 或 #[audit(param = "..")] 指明参数名 | 500 invalid_path |
| 租户实体但请求身份无租户 | 403 tenant_required |
需在回收站路由中加载已软删除的记录时,改用提取器 FoundWithTrashed<Entity>(仅适用于 #[audit] 实体,租户隔离照常生效)。
分页#
提供声明式列表白名单与自定义查询收尾两套分页接口,统一返回 Collection<Model>(结构见 分页响应说明):
ListSpec+ctx.list(日常列表首选):在#[query]中接收ListInput,用const SPEC: ListSpec = ListSpec::new().sort(..).search(..).filter(..)声明允许客户端传入的排序、搜索、筛选与游标列(未列入白名单的字段返 422validation_failed),自动套用实体的租户与软删除过滤;开启回收站with_trashed(slot)或父级展开parent(col, slot)时还会自动校验对应槽位的角色权限。PaginateJson(复杂联表或手写条件查询):在自定义Select<Entity>链末尾调用:
use kxed_core::{AppCtx, AppErr, Collection, CursorQuery, PageQuery};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*, QueryOrder};
use kxed_plugins::seaorm::{AppCtxDatabase, PaginateJson};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize)]
#[sea_orm(table_name = "notes")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
async fn index(page: PageQuery, ctx: AppCtx) -> Result<Collection<Model>, AppErr> {
let db = ctx.db()?;
Entity::find().order_by_asc(Column::Id).paginate_json(&db, &page).await
}
async fn feed(query: CursorQuery, ctx: AppCtx) -> Result<Collection<Model>, AppErr> {
let db = ctx.db()?;
Entity::find().cursor_json_desc(&db, &query, [Column::Id]).await
}| 方法 | 行为与注意事项 |
|---|---|
paginate_json(db, &page) | 页码分页(先 COUNT 再取页,查询需自带确定的 order_by);结果可接 .map(View::from) 转换 DTO |
cursor_json(db, &query, by) / cursor_json_desc | 升序/降序游标分页(多读 1 条判断是否有下一页,不跑 COUNT);by 为 1..=8 个非空唯一组合列(如 [Column::CreatedAt, Column::Id],时间列统一用 DateTimeUtc),非法 after 游标返 400 invalid_page |
事务与冲突重试#
ctx.transaction(attempts, work) 在主库上开启事务执行闭包(具名连接用 ctx.transaction_of(name, attempts, work),仅持连接池用 kxed_plugins::seaorm::transaction(&db, attempts, work)):
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::ConnectionTrait;
use kxed_plugins::seaorm::AppCtxDatabase;
async fn transfer(ctx: AppCtx) -> Result<&'static str, AppErr> {
ctx.transaction(3, |txn| async move {
txn.execute_unprepared("UPDATE accounts SET balance = balance - 10 WHERE id = 1").await?;
txn.execute_unprepared("UPDATE accounts SET balance = balance + 10 WHERE id = 2").await?;
Ok(())
})
.await?;
Ok("transferred")
}- 遇锁冲突与死锁自动重放:遇到 503
database_busy(死锁、序列化冲突、锁等待超时或 SQLiteBUSY/LOCKED)时自动回滚并以10ms × 2^(n-1)(上限 160ms)随机抖动退避重放,最多尝试attempts次(越过ctx.deadline()不再重放;SQLite 自动以BEGIN IMMEDIATE开启写事务)。 - 外部副作用后置:重放会从头再次运行闭包,调用第三方 HTTP 或发送通知应放在
transaction成功返回之后;需与数据库事务原子同提交的后台任务请调用.within(&txn)。闭包结束时不得在外部残留持有txn引用。
多租户作用域#
多租户共享同一张业务表时,在实体上标注 #[kxed::tenant](默认列名 tenant_id,自定义列名写 #[kxed::tenant(column = "team_id")],类型支持非空 i64、Uuid 或 String;MySQL/TiDB 字符串列须用 utf8mb4_bin 排序规则)。
标注后,Entity::find、find_by_id 与 ActiveModel::insert/update/delete 首参全部强制要求传入租户来源,漏传租户的代码在编译期直接报错:
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*, ActiveValue::Set};
use kxed_plugins::seaorm::AppCtxDatabase;
#[kxed_plugins::seaorm::tenant]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "orders")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub tenant_id: String,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
async fn list_orders(ctx: AppCtx) -> Result<Vec<Model>, AppErr> {
let db = ctx.db()?;
Ok(Entity::find(&ctx)?.all(&*db).await?)
}
async fn create_order(ctx: AppCtx, title: String) -> Result<Model, AppErr> {
let db = ctx.db()?;
let draft = ActiveModel { title: Set(title), ..Default::default() };
draft.insert(&ctx, &db).await
}漏传租户参数的无作用域查询在编译期被拒绝:
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*, DatabaseConnection};
#[kxed_plugins::seaorm::tenant]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "orders")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub tenant_id: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
async fn every_tenant(db: &DatabaseConnection) -> Result<Vec<Model>, DbErr> {
Entity::find().all(db).await
}确需在运维命令或全局统计中跨租户查询时,显式书写完整 trait 路径 <Entity as EntityTrait>::find()。
租户从哪里来#
首参接收 &impl TenantSource,只认服务端已认证的可信身份,严禁从客户端请求参数直接构造:
| 传入值 | 适用上下文 | 说明 |
|---|---|---|
&ctx(AppCtx)或 &tenant(CurrentTenant) | Procedure 与 HTTP handler | 取 primary guard 身份的 Identity::tenant()(未登录 401,无租户或格式不规范返 403 tenant_required) |
&ws(Ws)或 &request(RequestContext) | WebSocket handler 与中间件 | 取连接升级或准入时认证的身份租户 |
&self.who(TaskIdentity) | 后台 Task 与 Resident | 取 identity.for_task() 封入载荷的发起人租户 |
&TenantId::trusted(value)? | Cron 定时任务与 CLI 运维命令 | 无请求身份时由服务端显式构造(命令入参 ? 返 400,库内脏数据 .map_err(AppErr::invariant)? 返 500) |
读写规则#
生成方法(泛型版位于 kxed::tenant::*_in) | 隔离语义 |
|---|---|
Entity::find(&ctx)? / Entity::find_by_id(&ctx, id)? | 自动附加当前租户 WHERE 条件,跨租户主键返回 None |
model.insert(&ctx, db) / save(&ctx, db) | 强制将租户列覆写为当前租户后落库,并回读校验未被数据库触发器篡改 |
model.update(&ctx, db) / delete(&ctx, db) | WHERE 同时匹配主键与当前租户,目标行属于其他租户时返回 404 not_found |
Entity::update_many(&ctx, |u| ..)? / delete_many(&ctx)? | 返回封闭包装 TenantUpdateMany(禁止在闭包外二次改写租户列,如下方编译失败示例) |
Entity::insert(&ctx, model)?.on_conflict_update(keys, cols)? | 租户安全 Upsert:主键冲突行属于其他租户时绝不覆盖他人数据 |
Entity::tenant_condition(&ctx)? | 生成带表名前缀的租户 Condition,供联表查询或 audit::soft_delete 组合使用 |
封闭包装在编译期阻止二次篡改租户列:
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*, sea_query::Expr, UpdateMany};
#[kxed_plugins::seaorm::tenant]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "orders")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub tenant_id: String,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
fn rename(ctx: &AppCtx) -> Result<(), AppErr> {
let title = |update: UpdateMany<Entity>| update.col_expr(Column::Title, Expr::value("t"));
let _moved = Entity::update_many(ctx, title)?.col_expr(Column::TenantId, Expr::value("globex"));
Ok(())
}冲突结局#
TenantInsert::on_conflict_update 与 on_conflict_do_nothing 在遇到其他租户占用冲突键时的各数据库返回值对照(409 为 database_unique_violation,500 为 database_backend_unsupported):
| 执行方法 | PostgreSQL 与 SQLite | MySQL 与 TiDB |
|---|---|---|
exec / TenantInsertMany::exec | 跳过跨租户冲突行时返回 409 | 因连接开启 CLIENT_FOUND_ROWS,跳过冲突行仍返回成功(影响行数非 0) |
exec_without_returning | 返回实际写入行数(跳过为 0) | 跳过返回 1,更新同租户已有行返回 2(值未变返回 1) |
exec_with_returning | 写入成功返回行,全跳过返 409 | 固定返回 500(无原生 RETURNING 区分新写与跳过) |
需要跨数据库完全一致地识别冲突时,建议直接执行普通 insert 捕获 409,或在 ctx.transaction 内先查后写。
乐观锁#
防止多人并发编辑静默互相覆盖:在实体上标注 #[kxed::lock_version] 并声明 pub lock_version: i64 列(建表设 NOT NULL DEFAULT 0,自定义列名写 #[kxed::lock_version(column = "ver")]),更新时调用 model.update_checked(&db):
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*, ActiveValue::Set};
use kxed_plugins::seaorm::AppCtxDatabase;
#[kxed_plugins::seaorm::lock_version]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "articles")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
pub lock_version: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
async fn rename(ctx: AppCtx, id: i64, version: i64, title: String) -> Result<Model, AppErr> {
let db = ctx.db()?;
let change = ActiveModel {
id: Set(id),
title: Set(title),
lock_version: Set(version),
};
change.update_checked(&db).await
}- 版本核验与 409 冲突:
update_checked在WHERE中核对传入的当前版本号并在SET中自动+ 1;若记录已被他人抢先修改或已删除,返回 409database_version_conflict(未设置lock_version字段值调它会返 500)。 - 与
#[tenant]叠加:同时标注两个宏时签名自动变为change.update_checked(&ctx, &db),同时核对租户与版本号(泛型入口为lock_version::update_checked与tenant::update_checked_in)。
审计实体#
在 #[derive(DeriveEntityModel)] 前标注 #[kxed::audit](主键操作者类型默认 i64,可选 id = Uuid 或 id = String,启动期自动核对与全局 audit.actor_id_type 一致),自动注入 created_at、updated_at、created_by_id、created_by_type、updated_by_id、updated_by_type 及软删除三列 deleted_at、deleted_by_id、deleted_by_type:
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
#[kxed_plugins::seaorm::audit(id = Uuid)]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "tickets")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub title: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}迁移建表时使用 audit::columns(dialect, <Entity as Audited>::ID.actor_id_kind()) 生成这九列定义(存量表补列调用 audit::add_columns(db, table, kind).await?)。需要自定义 ActiveModelBehavior 时加参数 behavior = false 并在钩子内转发 audit::before_save 与 audit::before_delete。
写入规则#
- 自动盖章与禁直接物理删:
ActiveModel::insert与update自动从audit::current_actor()和微秒级audit::now()填充创建/更新信息;直接调ActiveModel::delete会报错拒绝,请改用下方软删除函数(批量写入用audit::insert_many_stamped与audit::update_many_stamped,切勿调裸Entity::insert/update/delete绕开钩子)。 - 软删除、恢复与定期清理:
audit::soft_delete::<E>(&db, cond):标记软删除时间与操作者(幂等保留首次删除者)。audit::restore::<E>(&db, cond):恢复已软删除记录。audit::force_delete::<E>(&db, cond)与audit::prune_deleted::<E>(&db, older_than, batch_size):物理删除或按批清理超期回收站数据(见 审计字段文档)。- 查询未删除数据使用
ctx.list或audit::find_visible::<E>()(回收站用audit::find_deleted::<E>())。
变更历史#
标注 #[kxed::audit(history)] 后,单行更新、软删除、恢复、物理删除与批量 audit::update_many_recorded 会在同事务内自动将字段变更前后差异写入 kxed_audit_log(敏感字段标 #[audit(redact)] 或使用 Encrypted<T> 只记列名不记明文):
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
#[kxed_plugins::seaorm::audit(history)]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "customers")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub name: String,
#[audit(redact)]
pub id_number: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}启用变更历史时,把 audit::history_migrations() 放在应用 Migrator::migrations() 最前面,通过 audit::history::<Entity>(&db, id)(多租户用 audit::history_in)按时间倒序读取修改记录。
业务记录#
不对应单行实体修改的业务动作(如导出报表、手工调账),可调用 audit::record(&db, "orders", "export", payload) 写入同一张 kxed_audit_log(kind = "record"),并用 audit::records(&db, "orders") 查询。
只追加的审计表#
在 Migrator::migrations() 中紧跟 audit::history_migrations() 追加 audit::append_only_migrations(),即可在 PostgreSQL、MySQL 与 SQLite 上安装防篡改触发器,禁止任何 UPDATE / DELETE 修改历史审计日志(TiDB 无触发器,请在数据库账号权限层收回修改权限)。
业务表迁移#
开启 seaorm-migration 特性后,调用 SeaOrmPlugin::new().migrate::<Migrator>(MigrationLock::new("app.migrations")) 登记迁移:
- 服务进程自动串行迁移:服务启动时在建池后、对外暴露连接前获取跨进程迁移锁(PostgreSQL 用事务级 advisory lock,MySQL/TiDB 用
GET_LOCK,SQLite 用IMMEDIATE写事务,默认最多等待 60s)自动执行待跑迁移,失败立即关池退出。 - CLI 运维命令手动控制:运行
./app <command>时不触发自动迁移,而是提供以下六条子命令(支持--connection <name>指定具名库,后四条破坏性命令在非交互终端需加--force):
| CLI 命令 | 作用 |
|---|---|
migrate status | 查看所有迁移的 applied / pending 状态(只读) |
migrate up [--steps <n>] | 执行前 n 个(默认全部)待执行迁移 |
migrate down [--steps <n>] | 按逆序回滚最近 n 个(默认 1 个)迁移(无 down 实现报 migration_no_down) |
migrate reset | 回滚全部已执行迁移 |
migrate refresh [--seed] | 先 reset 再 up,加 --seed 时随后运行 Seeder |
migrate fresh [--seed] | 开发环境直接删掉所有非 kxed_ 前缀业务表后重跑全部迁移(保留 kxed_* 框架表,业务表命名请勿以 kxed_ 开头) |
多副本滚动发布兼容建议:数据库表结构变更遵循「先加可空/默认列 -> 下一版停用旧列 -> 再下一版删旧列」的分步演进,大表数据回填放入后台 Task 分批执行,避免长耗时迁移阻塞新副本启动。不注册插件的独立脚本可直接调用 migrate_serialized、down_serialized 或 SerializedMigration::begin。
Seeder#
演示与初始化开发数据实现 Seeder 并通过 .seed::<DemoSeeder>() 登记,仅在运行 db seed [--class <NAME>] [--connection <NAME>] 或 migrate fresh --seed 时在共享写事务内执行,服务启动绝不自动运行:
use kxed_core::AppErr;
use kxed_plugins::seaorm::sea_orm::ConnectionTrait;
use kxed_plugins::seaorm::{SeaOrmPlugin, Seed, Seeder};
struct DemoSeeder;
impl Seeder for DemoSeeder {
async fn run(seed: &Seed<'_>) -> Result<(), AppErr> {
let db = seed.db().await?;
db.execute_unprepared("INSERT INTO notes (title) VALUES ('hello')").await?;
Ok(())
}
}
fn plugin() -> SeaOrmPlugin {
SeaOrmPlugin::new().seed::<DemoSeeder>()
}具名连接#
除主库外,报表仓库或遗留系统数据库可配在 database.connections.<name> 下,代码中通过 ctx.db_of("analytics")? 访问(连接名未配置返 500 database_connection_missing):
[database]
url = "postgres://app@db/app"
[database.connections.analytics]
url = "postgres://report@warehouse/analytics"
max_connections = 5use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::ConnectionTrait;
use kxed_plugins::seaorm::AppCtxDatabase;
async fn refresh_report(ctx: AppCtx) -> Result<&'static str, AppErr> {
let analytics = ctx.db_of("analytics")?;
analytics.execute_unprepared("REFRESH MATERIALIZED VIEW daily_orders").await?;
Ok("refreshed")
}运行期具名从属库发生故障时只记告警并让访问它的请求返回 503 database_unavailable,不会摘除整个实例的 /readyz,避免报表库抖动拖垮核心主业务。
读写分离#
将只读副本配置为一个具名连接并设置 database.read_connection = "replica",只读查询调用 ctx.read_db()?(未配置 read_connection 时自动回退主库,代码零改动):
[database]
url = "postgres://app@primary/app"
read_connection = "replica"
[database.connections.replica]
url = "postgres://app@replica/app"同请求写后读防延迟(Sticky Read):同一个 HTTP 请求内只要调用过 ctx.db()、ctx.transaction 或提取过 Found<E>,后续的 ctx.read_db()? 自动切回主库,确保刚写入的数据立即可见;下一个请求恢复读副本(后台 Task 与 WebSocket 不在单次 HTTP 请求作用域内,写后需立即读最新值时直接调 ctx.db()?)。
具名连接的迁移与 Seeder#
通过 .migrate_of::<AnalyticsMigrator>("analytics", lock) 与 .seed_of::<VisitSeeder>("analytics") 即可为具名连接独立维护迁移表与演示数据,CLI 命令加上 --connection analytics 即可定向操作该库。
加密列#
手机号、证件号等敏感字段使用 Encrypted<T>(数据库列类型设为 TEXT),基于 app.key 进行带列用途绑定的 AEAD 加密(一列的密文复制到另一列无法解密):
use kxed_core::crypto::AppCtxCrypto;
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
use kxed_plugins::seaorm::Encrypted;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "customers")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(column_type = "Text")]
pub phone: Encrypted<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
fn phone_of(ctx: &AppCtx, customer: &Model) -> Result<String, AppErr> {
Ok(customer.phone.open(&ctx.crypto()?, "customers.phone")?)
}
fn sealed_phone(ctx: &AppCtx, phone: &str) -> Result<Encrypted<String>, AppErr> {
Ok(Encrypted::seal(&ctx.crypto()?, "customers.phone", &phone.to_owned())?)
}purpose 按 <表名>.<列名> 命名时,轮换主密钥后直接运行 ./app db rekey customers phone 即可在线分批将旧密钥(app.previous_keys)密文重加密为新密钥,直至 unreadable 0。
附件列#
开启主包 seaorm-object-store 特性后,实体可使用 JSON 列类型 Attachment 保存对象存储文件的元数据(key、mime、bytes、filename),配合 Multipart 一步完成流式上传与元数据构造:
use kxed_core::{AppCtx, AppErr, FileRule, FormPart, Multipart};
use kxed_plugins::object_store::{AppCtxObjectStore, ObjectPath};
use kxed_plugins::seaorm::sea_orm::{self, entity::prelude::*};
use kxed_plugins::seaorm::Attachment;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "documents")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(column_type = "Json")]
pub file: Attachment,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
async fn receive(ctx: AppCtx, mut form: Multipart, id: i64) -> Result<Attachment, AppErr> {
let rule = FileRule::new().max_bytes(5 << 20).max_fields(1);
let stores = ctx.object_store()?;
while let Some(part) = form.next_part(&rule).await? {
if let FormPart::File(file) = part {
return Attachment::store(&stores, &ObjectPath::from(format!("documents/{id}")), *file).await;
}
}
Err(AppErr::bad_request("file is required"))
}对象 path 须由服务端生成(勿拼接客户端文件名,详见 保存上传的文件);删除数据库行后可在后台 Task 中调用幂等的 attachment.delete(&stores) 回收底层存储对象。
测试数据#
在 [dev-dependencies] 开启主包 testing 特性后,kxed::plugins::seaorm::testing 提供实体数据工厂 Factory 与真实数据库单测隔离容器 TestDatabase:
use kxed::plugins::seaorm::sea_orm::ActiveValue::Set;
use kxed::plugins::seaorm::testing::{factory, Factory, TestDatabase};
use kxed::prelude::*;
struct UserFactory;
impl Factory for UserFactory {
type Entity = user::Entity;
fn definition(n: u64) -> user::ActiveModel {
user::ActiveModel {
name: Set(format!("user-{n}")),
suspended: Set(false),
..Default::default()
}
}
}
// 批量造测试数据(审计列自动盖章)
let users = factory::<UserFactory>().count(10).create(&db).await?;
// PostgreSQL / MySQL 单测创建独立临时库,作用域结束自动 DROP DATABASE
let temp_db = TestDatabase::create(&admin_url).await?;
let config = ConfigLoader::testing().with_override("database.url", temp_db.url())?;设置环境变量 KXED_TEST_SEAORM_KEEP_DATABASE=1 可在测试失败后保留临时库排查现场(SQLite 单测直接使用 sqlite::memory: 即可天然隔离)。
Config#
| key | default | contract |
|---|---|---|
database.url | "" | 主库连接串(SecretString,日志与 config show 自动脱敏,<= 8192 字节) |
database.max_connections | 20 | 业务连接池上限,范围 1..=256 |
database.min_connections | 1 | 最小保活连接数,范围 0..=max_connections |
database.startup_timeout | 10s | 启动建连与方言探测总预算,范围 1ms..=5m |
database.acquire_timeout | 5s | 借出连接及 SQLite 写锁 busy_timeout 等待上限,范围 1ms..=5m |
database.idle_timeout | 10m | 空闲连接回收时长,null 或 1s..=1year |
database.max_lifetime | 30m | 连接最大存活期,null 或 1s..=1year |
database.statement_timeout | 30s | 单语句超时(PG statement_timeout,MySQL/TiDB max_execution_time),null 或 1ms..=24h |
database.health_check_interval | 30s | 后台健康探测与连接池指标采样周期,范围 1s..=24h |
database.health_check_timeout | 2s | 单次健康探测超时,范围 1ms..=5m |
database.health_check_failure_threshold | 3 | 连续探测失败多少次后摘除 /readyz,范围 1..=100 |
database.release_ping_timeout | null | 连接归还回池检查上限,null 取 max(health_check_timeout, acquire_timeout) |
database.require_writable | false | 开启后探测与归还检查拦截 PG 备库或 MySQL/TiDB read_only 节点 |
database.sqlx_logging | false | 是否开启 SQLx 全量语句日志 |
database.slow_statement_threshold | 0s | 慢查询日志阈值,0s 关闭,或 1ms..=1m |
database.slow_statement_level | warn | 慢查询日志级别(trace/debug/info/warn/error) |
database.sqlite_journal_mode | null | SQLite 日志模式(同机多实例共享文件须设为 wal) |
database.read_connection | 无 | 只读副本对应的具名连接名,见 读写分离 |
database.connections.<name>.url | 无 | 具名数据库连接串(必填,<name> 由小写字母、数字与下划线组成) |
database.connections.<name>.max_connections | 沿用 database.max_connections | 该具名连接的最大连接数 |
database.connections.<name>.min_connections | 沿用 database.min_connections | 该具名连接的最小连接数 |
database.connections.<name>.require_writable | false | 该具名连接是否要求可写主节点 |
database.connections.<name>.sqlite_journal_mode | null | 该具名连接的 SQLite 日志模式 |
连接数估算与错误码自动映射:
- 每实例连接数预算:每个实例占用
database.max_connections + 1(含 1 条独立健康探测连接,同库启用 SQL Task 存储另加tasks.storage.max_connections默认 4,另加各具名连接的max_connections)。多主代理(如 Galera/ProxySQL 轮询多主)会导致库身份核对不一致,请固定连接同一主节点。 DbErr转AppErr状态码对照(基于ErrorCause::of(&DbErr)自动分类,日志脱敏不泄露参数):
| 数据库错误类别 | 映射状态码与错误码 | 重试分类 |
|---|---|---|
借池超时、建连失败、服务端关停或切换只读节点(connection == true) | 503 database_unavailable | NotExecuted(语句未发出,可安全重试) |
死锁、序列化冲突、锁等待超时、语句超时、SQLite BUSY/LOCKED(transient == true) | 503 database_busy | NotExecuted(ctx.transaction 自动重放) |
| 语句发出后网络中断(可能已在服务端落盘) | 504 database_connection_lost | Indeterminate(仅幂等操作可直接重发) |
| 唯一约束冲突 / 外键约束冲突 | 409 database_unique_violation / database_foreign_key_violation | Settled |
| 记录未找到 | 404 not_found | Settled |
| 方言不支持的操作 / 其他数据库报错 | 500 database_backend_unsupported / database_failed | Settled / Indeterminate |
后端#
生产一级支持 PostgreSQL、MySQL 8.0+ 与 TiDB,单机与测试支持打包内置的 SQLite:
- TiDB 自动识别与连接串:TiDB 复用
seaorm-mysql特性与mysql://协议,启动时自动识别为SqlDialect::TiDb(可通过ctx.db_dialect()?读取)。连接 TiDB Cloud 须保持默认悲观事务并开启证书校验:mysql://<prefix>.root:<password>@<host>:4000/<db>?ssl-mode=VERIFY_IDENTITY(Dedicated 集群追加ssl-ca=<path>)。 - TiDB 需避开的三类写法:
| 写法 | TiDB 行为 | 推荐替代写法 |
|---|---|---|
共享锁 LockType::Share / lock_shared() | 报错 1235 | 改用排他锁 LockType::Update / lock_exclusive() |
FOR UPDATE SKIP LOCKED | 语法通过但不跳过已锁行,导致重复领取 | 改用普通 FOR UPDATE、NOWAIT 或条件更新租约 |
只读事务 AccessMode::ReadOnly | 报错 1235 | 使用普通事务 |
State 与 lifecycle#
插件启动时建立连接池、探测方言并发布 DatabaseCapability 与 DatabaseConnection(启动前需自建连接池时调用 DatabaseConfig::connect 再传给 SeaOrmPlugin::from_connection):
use kxed_core::{AppCtx, AppErr};
use kxed_plugins::seaorm::sea_orm::ConnectionTrait;
use kxed_plugins::seaorm::AppCtxDatabase;
async fn archive_expired(ctx: AppCtx) -> Result<&'static str, AppErr> {
let db = ctx.db()?;
db.execute_unprepared("UPDATE tickets SET archived = 1 WHERE expires_at < CURRENT_TIMESTAMP")
.await?;
Ok("archived")
}- 双通道健康探测防误摘流:后台探测优先走业务池;若业务池被慢查询占满超时,自动切换单条独立探测连接复查,复查正常则保持实例
/readyz可用,仅递增kxed_database_pool_exhaustion_total告警。 - 归还回池防脏事务:连接归还连接池前在
release_ping_timeout内自动清理未提交残留事务并校验读写角色,异常或超时连接直接硬关闭(计入kxed_database_release_close_total{reason})。停机时按close_budget等待在途连接优雅归还后关池。
慢语句与数据库指标#
慢语句日志#
将 database.slow_statement_threshold 设为非零时长(如 "500ms")后,超出阈值的 SQL 由 sqlx::query 按 database.slow_statement_level 输出慢查询日志(记录带占位符的 SQL 模板、耗时与行数,绝不打印绑定参数明文)。
指标#
开启任一 seaorm-* 主包特性后,自动向 /metrics 导出以下数据库运行指标(并配套 deploy/observability/prometheus-overload.yaml 预置告警规则):
| 指标 | 类型 | 标签 | 含义 |
|---|---|---|---|
kxed_database_query_duration_seconds | histogram | operation(select/insert/update/delete/other)、outcome(ok/error) | 经 SeaORM 执行语句的耗时分布 |
kxed_database_pool_connections | gauge | state(in_use/idle) | 主库业务连接池当前借出与空闲连接数 |
kxed_database_pool_connection_limit | gauge | 无 | 主库业务连接池配置上限 database.max_connections |