create table todo_list (
id serial primary key,
title varchar(150) not null
);
create table todo_item (
id serial primary key,
title varchar(150) not null,
checked boolean not null default false,
list_id integer not null,
foreign key (list_id) references todo_list(id)
);
down.sql:
drop table if exists todo_item;
drop table if exists todo_list;
由于之前已经有对应的数据表结构,需要将原来的表结构删除,再运行数据库变更:
# 删除原有的数据表之后
diesel migrations run
其中,对应生成的 schema 为:
table! {
todo_item (id) {
id -> Int4,
title -> Varchar,
checked -> Bool,
list_id -> Int4,
}
}
table! {
todo_list (id) {
id -> Int4,
title -> Varchar,
}
}
joinable!(todo_item -> todo_list (list_id));
allow_tables_to_appear_in_same_query!(
todo_item,
todo_list,
);
使用 diesel 管理数据库变化
diesel 是一个用 rust 写的 ORM 库,支持多种数据库,同时 diesel 提供了对数据库结构的管理功能。我们将使用 diesel 对我们的数据库结构变化进行管理。
首先,安装命令行工具
diesel_cli
,并初始化数据库设置在生成的
migrations
目录中,填入数据库变化的 sql 语句,up.sql
用于修改,down.sql
用于撤销修改。up.sql
:down.sql
:由于之前已经有对应的数据表结构,需要将原来的表结构删除,再运行数据库变更:
其中,对应生成的 schema 为:
此时,数据库中的表机构就和我们之前是一样的,同时增加了一个用于记录已经做过的 migrations 的数据库。
ORM
鉴于 diesel 没有 async 版本,以及 quaint 不是 type-safe,不做 ORM 的支持。
错误处理
自定义错误,并将常见的错误统一处理。
新增
errors.rs
:修改
db.rs
:修改
handlers.rs
,其中一个请求处理小结
参考文档和项目