关系数据库

本篇连接本地 SQLite 数据库实现笔记增删改查服务,包含自动建表、分页查询、参数校验与角色保护。跑通后访客可匿名翻页阅读笔记,editor 角色用户可新增、修改与删除记录。

配置数据库与默认访问策略#

首先开启 SQLite 数据库驱动、迁移支持和登录认证三个 feature(参数校验宏 Validate 已由 prelude 默认提供)。

新建 Cargo.toml:

TOML
[package]
name = "guide-database"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"

[dependencies]
kxed = { version = "0.0.5-alpha", features = ["seaorm-sqlite", "seaorm-migration", "auth"] }

接着指定本地 SQLite 数据库文件路径,?mode=rwc 表示库文件不存在时自动创建(请把运行生成的 notes.sqlite、-wal 与 -shm 加入 .gitignore)。

新建 config/database.toml:

TOML
url = "sqlite://notes.sqlite?mode=rwc"

由于笔记列表和详情允许未登录访客直接阅读,我们先把全局默认策略设为允许匿名访问,稍后单独给 /admin 写路由组加上角色要求。

新建 config/auth.toml:

TOML
default_policy = "anonymous"

定义数据表与建表迁移#

在 SeaORM 里,Model 结构体的每个字段直接对应数据库 notes 表的一列,派生宏 DeriveEntityModel 会自动生成查询用的 Entity、Column 和写入用的 ActiveModel。下面的 CreateNotes 迁移直接根据实体定义生成建表语句,以后想从 SQLite 换成 PostgreSQL 或 MySQL 时,只需替换 Cargo.toml 里的驱动 feature,业务代码一行都不用改。

新建 src/note.rs:

Rust
use kxed::plugins::seaorm::async_trait;
use kxed::plugins::seaorm::sea_orm::entity::prelude::*;
use kxed::plugins::seaorm::sea_orm::sea_query::Table;
use kxed::plugins::seaorm::sea_orm::{self, DbErr, Schema};
use kxed::plugins::seaorm::sea_orm_migration::{MigrationName, MigrationTrait, MigratorTrait, SchemaManager};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "notes")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub title: String,
    pub body: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

impl kxed::plugins::seaorm::RouteBinding for Entity {}

pub(crate) struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![Box::new(CreateNotes)]
    }
}

struct CreateNotes;

impl MigrationName for CreateNotes {
    fn name(&self) -> &str {
        "m20261013_000001_create_notes"
    }
}

#[async_trait]
impl MigrationTrait for CreateNotes {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let schema = Schema::new(manager.get_database_backend());
        manager.create_table(schema.create_table_from_entity(Entity)).await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(Entity).to_owned()).await
    }
}

增删改查与分页#

处理请求时通过 ctx.db()? 拿到数据库连接池,数据库报错用 ? 会自动转换成标准 HTTP 错误响应(连不上库时返回 503,底层 SQL 报错详情只写服务端日志不暴露给前端)。下面的 src/notes.rs 用到了三个省代码的提取器:

  • 分页参数 PageQuery:自动读取 URL 里的 ?page=1&per_page=15(默认每页 15 条,最大 100 条,越界返回 400 invalid_page),配合带排序的 .paginate_json(&db, &page) 直接生成带 data、meta 和上下页 links 的标准列表响应(大表深翻页可改用 CursorQuery 游标分页,见 SeaORM plugin 的分页)。
  • 按路径主键查记录 Found<note::Entity>:实体实现了 RouteBinding 后,参数写 Found(current) 就会自动按 URL 里的 {id} 查出那一行;查不到返回 404,传了非整数返回 400 invalid_path(多参数路径绑定见 路由模型绑定)。
  • JSON 参数校验 Valid<Json<NoteInput>>:在进函数前检查标题不能为空且不超过 200 字,不满足时直接返回 422 validation_failed(见 HTTP 参考的返回错误)。对外单独定义 NoteView 返回结构体,能防止以后往表里加内部字段时不小心返回给前端。

新建 src/notes.rs:

Rust
use crate::note;
use kxed::http::extract::Valid;
use kxed::plugins::seaorm::sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait, QueryOrder};
use kxed::prelude::*;

#[derive(Serialize)]
pub(crate) struct NoteView {
    id: i64,
    title: String,
    body: String,
}

impl From<note::Model> for NoteView {
    fn from(model: note::Model) -> Self {
        Self { id: model.id, title: model.title, body: model.body }
    }
}

#[derive(Deserialize, Validate)]
pub(crate) struct NoteInput {
    #[garde(length(min = 1, max = 200))]
    title: String,
    #[garde(length(max = 10000))]
    body: String,
}

pub(crate) async fn index(ctx: AppCtx, page: PageQuery) -> Result<Collection<NoteView>, AppErr> {
    let db = ctx.db()?;
    let notes = note::Entity::find().order_by_asc(note::Column::Id);
    Ok(notes.paginate_json(&db, &page).await?.map(NoteView::from))
}

pub(crate) async fn show(Found(current): Found<note::Entity>) -> Json<NoteView> {
    Json(current.into())
}

pub(crate) async fn store(ctx: AppCtx, Valid(Json(input)): Valid<Json<NoteInput>>) -> Result<(StatusCode, Json<NoteView>), AppErr> {
    let db = ctx.db()?;
    let created = note::ActiveModel {
        title: Set(input.title),
        body: Set(input.body),
        ..Default::default()
    }
    .insert(&*db)
    .await?;
    Ok((StatusCode::CREATED, Json(created.into())))
}

pub(crate) async fn update(ctx: AppCtx, Found(current): Found<note::Entity>, Valid(Json(input)): Valid<Json<NoteInput>>) -> Result<Json<NoteView>, AppErr> {
    let mut changes = note::ActiveModel::from(current);
    changes.title = Set(input.title);
    changes.body = Set(input.body);
    let db = ctx.db()?;
    Ok(Json(changes.update(&*db).await?.into()))
}

pub(crate) async fn destroy(ctx: AppCtx, Path(id): Path<i64>) -> Result<StatusCode, AppErr> {
    let db = ctx.db()?;
    let deleted = note::Entity::delete_by_id(id).exec(&*db).await?;
    if deleted.rows_affected == 0 {
        return Err(AppErr::not_found());
    }
    Ok(StatusCode::NO_CONTENT)
}

接入登录并挂载路由#

为了测试写接口的角色保护,我们准备 alice(拥有 editor 角色)和 bob(无角色普通用户)两个账号,密码都是 correct horse battery(真实数据库项目在登录成功时顺手升级旧密码哈希参数的写法见 auth README 的登录时升级哈希)。新建 src/auth.rs:

Rust
use kxed::access::{AccessError, GuardAccess};
use kxed::config::SecretString;
use kxed::identity::Identity;
use kxed::plugins::auth::{AuthError, AuthPrincipal, AuthSessionValidator, LoginOptions, StoredAuthSession};
use kxed::prelude::*;

const PASSWORD_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$mJfhhg2fcfZQEdxdBPkEWg$KVeOODDsOGTKIEa8avz/Q0fvdUhm+Yc5+gHIYc1ZpRw";
const ACCOUNTS: [(&str, &str); 2] = [("1", "alice"), ("2", "bob")];

pub(crate) struct Accounts;

impl AuthSessionValidator for Accounts {
    async fn is_valid(&self, session: &StoredAuthSession) -> Result<bool, AuthError> {
        Ok(ACCOUNTS.iter().any(|(id, _)| *id == session.principal.subject))
    }
}

pub(crate) struct Roles;

impl GuardAccess for Roles {
    async fn grants(&self, identity: &Identity) -> Result<Grants, AccessError> {
        Ok(Grants::roles_only((identity.subject() == "1").then_some("editor"))?)
    }
}

#[derive(Deserialize)]
pub(crate) struct Login {
    name: String,
    password: SecretString,
}

pub(crate) async fn login(ctx: AppCtx, Json(login): Json<Login>) -> Result<String, AppErr> {
    let account = ACCOUNTS.iter().find(|(_, name)| *name == login.name);
    let hash = account.map(|_| PASSWORD_HASH.to_owned());
    let matched = ctx.password_verifier()?.verify_and_upgrade(login.password, hash).await?.is_valid();
    let Some((id, _)) = account.filter(|_| matched) else {
        return Err(AppErr::new(StatusCode::UNAUTHORIZED, "invalid credentials").with_code("invalid_credentials"));
    };
    let issued = ctx.auth_sessions()?.issue_token(AuthPrincipal::new(*id), LoginOptions::default()).await?;
    Ok(issued.token.expose_secret().to_owned())
}

最后在入口挂载 SeaOrmPlugin(启动时自动运行 Migrator 建表)与 AuthPlugin,把写操作放进挂了 require_role("editor") 的 /admin 路由组。新建 src/main.rs:

Rust
mod auth;
mod note;
mod notes;

use kxed::plugins::auth::{AuthPlugin, MemoryAuthStore};
use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<note::Migrator>(MigrationLock::new("notes.migrations")))
        .plugin(
            AuthPlugin::new()
                .with_store(MemoryAuthStore::new(1024)?, auth::Accounts)
                .with_access(auth::Roles),
        )
        .routes(|router| {
            router
                .route("/login", post(auth::login))
                .route("/notes", get(notes::index))
                .route("/notes/{id}", get(notes::show))
                .group("/admin", |admin| {
                    admin
                        .layer(require_role("editor"))
                        .route("/notes", post(notes::store))
                        .route("/notes/{id}", put(notes::update).delete(notes::destroy));
                });
        })
        .run()
        .await
}

验证#

在空库状态下启动 cargo run(操作约定见 怎么读),另开终端测试未登录拦截、缺角色拦截、空标题校验,再用 alice 身份创建三条笔记:

Shell
ALICE=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/login)
BOB=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"bob","password":"correct horse battery"}' http://127.0.0.1:8080/login)
curl --silent --output /dev/null --write-out '%{http_code}\n' -H 'content-type: application/json' -d '{"title":"Plan","body":"Plan the release."}' http://127.0.0.1:8080/admin/notes
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $BOB" -H 'content-type: application/json' -d '{"title":"Plan","body":"Plan the release."}' http://127.0.0.1:8080/admin/notes
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"title":"","body":""}' http://127.0.0.1:8080/admin/notes
curl --fail --silent -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"title":"Plan","body":"Plan the release."}' http://127.0.0.1:8080/admin/notes; echo
curl --fail --silent -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"title":"Build","body":"Build the release."}' http://127.0.0.1:8080/admin/notes; echo
curl --fail --silent -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"title":"Ship","body":"Ship the release."}' http://127.0.0.1:8080/admin/notes; echo

预期输出(依次对应未登录 401、bob 无 editor 角色 403、空标题校验不通过 422 以及成功创建的三条记录):

输出
401
403
422
{"id":1,"title":"Plan","body":"Plan the release."}
{"id":2,"title":"Build","body":"Build the release."}
{"id":3,"title":"Ship","body":"Ship the release."}

接着不带令牌直接匿名请求分页列表、单条详情与越界分页参数:

Shell
curl --fail --silent 'http://127.0.0.1:8080/notes?per_page=2'; echo
curl --fail --silent 'http://127.0.0.1:8080/notes?page=2&per_page=2'; echo
curl --fail --silent http://127.0.0.1:8080/notes/2; echo
curl --silent --output /dev/null --write-out '%{http_code}\n' 'http://127.0.0.1:8080/notes?per_page=500'

预期输出:

输出
{"data":[{"id":1,"title":"Plan","body":"Plan the release."},{"id":2,"title":"Build","body":"Build the release."}],"meta":{"page":1,"per_page":2,"total":3,"last_page":2},"links":{"first":"/notes?per_page=2&page=1","last":"/notes?per_page=2&page=2","prev":null,"next":"/notes?per_page=2&page=2"}}
{"data":[{"id":3,"title":"Ship","body":"Ship the release."}],"meta":{"page":2,"per_page":2,"total":3,"last_page":2},"links":{"first":"/notes?per_page=2&page=1","last":"/notes?per_page=2&page=2","prev":"/notes?per_page=2&page=1","next":null}}
{"id":2,"title":"Build","body":"Build the release."}
400

最后更新第 3 条笔记并删掉第 1 条,验证已删记录读取和重复删除均返回 404:

Shell
ALICE=$(curl --fail --silent -H 'content-type: application/json' -d '{"name":"alice","password":"correct horse battery"}' http://127.0.0.1:8080/login)
curl --fail --silent -X PUT -H "authorization: Bearer $ALICE" -H 'content-type: application/json' -d '{"title":"Ship","body":"Ship on Friday."}' http://127.0.0.1:8080/admin/notes/3; echo
curl --silent --output /dev/null --write-out '%{http_code}\n' -X DELETE -H "authorization: Bearer $ALICE" http://127.0.0.1:8080/admin/notes/1
curl --silent --output /dev/null --write-out '%{http_code}\n' http://127.0.0.1:8080/notes/1
curl --silent --output /dev/null --write-out '%{http_code}\n' -X DELETE -H "authorization: Bearer $ALICE" http://127.0.0.1:8080/admin/notes/1

预期输出:

输出
{"id":3,"title":"Ship","body":"Ship on Friday."}
204
404
404

用 Procedure 简化读写接口#

上面为了展示底层 HTTP 提取器使用了 App::routes 手写路由。日常写业务接口时,同一张 SeaORM 表可以直接搭配 #[query] 和 #[mutation] 编写,省掉手写 Valid<Json<..>>、状态码元组和路由表,还能同时获得 /_rpc 接口与前端 SDK 生成(详见 Procedure):

Rust
#[query(name = "notes.get", public, get = "/notes/{id}")]
pub async fn get_note(ctx: &AppCtx, input: Id<i64>) -> Result<NoteView, AppErr> {
    let row = note::Entity::find_by_id(input.into_inner()).one(&*ctx.db()?).await?.ok_or_else(AppErr::not_found)?;
    Ok(row.into())
}

#[mutation(name = "notes.store", post = "/admin/notes", status = 201, role = "editor")]
pub async fn store_note(ctx: &AppCtx, input: NoteInput) -> Result<NoteView, AppErr> {
    let created = note::ActiveModel { title: Set(input.title), body: Set(input.body), ..Default::default() }
        .insert(&*ctx.db()?)
        .await?;
    Ok(created.into())
}

按租户隔离数据#

做多租户 SaaS 系统时,给 Model 加上 #[kxed::tenant](默认按 tenant_id 列隔离)。查询与修改方法在编译期强制要求首参传入租户来源(Entity::find(&ctx)?、model.insert(&ctx, &db)),漏传直接编译失败,跨租户访问统一返回 404。UPSERT 请调 .on_conflict_update([..], [..])? 或 .on_conflict_do_nothing()(见 冲突结局);路径带 {tenant} 时在路由组加 tenant_route("tenant")(见 多租户作用域)。

自动审计列与软删除#

给 Model 加上 #[kxed::audit] 会自动生成创建人、修改人与软删除等 9 个标准列(加 #[kxed::audit(history)] 额外记录字段级变更历史,见 变更历史)。insert 与 update 自动填入当前操作者;直接物理 delete 会被禁用,改调 audit::soft_delete::<E>(&db, cond)、audit::restore、audit::force_delete 与 audit::find_visible::<E>()(详见 审计字段 与 审计实体)。

事务、第二个数据库与乐观锁#

场景需求推荐写法关键行为
冲突自动重试事务ctx.transaction(3, |txn| async move { .. })死锁、序列化冲突或 SQLite 写锁繁忙(503 database_busy)自动回滚重跑最多 3 次,外部调用放事务外(见 事务与冲突重试)
第二个库与读写分离ctx.db_of("analytics")?、ctx.read_db()?配 database.connections.analytics 后按名取连接(漏配返 500 database_connection_missing),只读查询调 read_db(见 具名连接、读写分离、第二个数据库的迁移)
乐观锁防并发覆盖#[kxed::lock_version] + model.update_checked(&db)版本号落后时返回 409 database_version_conflict(多租户实体传 (&ctx, &db),见 乐观锁)

常见排错#

现象原因解决方法
.insert(&db) 或 .exec(&db) 编译类型不匹配ctx.db()? 返回智能包装句柄,SeaORM 原生方法要求传底层连接引用kxed 封装方法(如 paginate_json、audit::soft_delete)传 &db,SeaORM 原生方法解引用传 &*db
DeriveEntityModel 展开提示找不到 sea_orm模块只导入了子项,未把 sea_orm 模块名本身引入当前作用域导入时保留 use kxed::plugins::seaorm::sea_orm::{self, ..};
SQLite 并发写入偶发 503 database_busy手工调 db.begin() 开了延迟读事务,升级写锁时撞锁写事务统一改用 db.begin_write().await? 或 ctx.transaction(3, ..)
租户实体 Entity::find() 编译缺参数#[kxed::tenant] 实体要求显式绑定租户上下文改为 Entity::find(&ctx)?,写操作首参同样传 &ctx

参考#