web项目中,我们一般不直接拼接
sql
语句,而是选择一个orm来进行操作数据库,本文和大家一起学习sea-orm
的使用
添加依赖
使用 cargo new sea-orm-demo
新建项目,并在Cargo.toml
中添加sea-orm
依赖
sea-orm的features
有较多可选项,主要是根据你所使用的数据库类型和要使用的异步运行时进行选择,macros
也是个常用feature, 因为我们大概率会使用sea-orm-cli来生成实体和模型,macros feature 提供的宏可以帮我们节省很多代码
- runtime-tokio-native-tls,可以理解为使用
tokio
作为异步运行时,native-tls
表示使用原生的tls实现;其他可选feature还有- runtime-async-std-native-tls
- runtime-async-std-rustls
- runtime-tokio-rustls
- sqlx-mysql表示我们使用
mysql
作为数据库驱动,sea-orm还支持postgres
,sqlite
,只需激活相应的feature
即可- sqlx-postgres
- sqlx-sqlite
...
[dependencies.sea-orm]
version = "0.12.15"
features = ["runtime-tokio-native-tls", "macros", "debug-print", "sqlx-mysql"]
...
使用migrate创建数据表
创建数据表,我们可以通过原生sql创建,也可以通过sea-orm编写纯rust代码执行创建
安装sea-orm-cli
sea-orm-cli
是sea-orm
官方 提供的工具链,可以通过cargo
直接安装
cargo install sea-orm-cli
初始化 migrate目录
- 在项目根目录执行如下命令,会创建一个
migration
目录,该目录是一个完整的binary crate
sea-orm-cli migrate init
- 修改
migration/Cargo.toml
,将feature
配置为与项目一致
[dependencies.sea-orm-migration]
version = "0.12.15"
features = [
"runtime-tokio-native-tls",
"sqlx-mysql",
]
- 在
migration/src
目录下存在名称格式为m日期_时间_迁移名称.rs
的文件,这个文件就是sea-orm的迁移文件;新创建的migration默认包含一个迁移文件; 如果要新建一个迁移文件,执行如下命令
// 根目录执行
sea-orm-cli migrate generate create_user
此时migration/src
下会新建一个名称格式类似 m20240731_123456_create_user.rs
的文件,将其作为模块在 lib.rs
里导入,并按格式追加到lib.rs
的migrations
方法即可
pub use sea_orm_migration::prelude::*;
mod m20220101_000001_create_table;
mod m20240730_000001_create_user;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
Box::new(m20220101_000001_create_table::Migration),
**Box::new(m20240730_000001_create_user::Migration),**
]
}
}
本文仅为演示,将直接修改默认迁移文件
编辑迁移文件
我们将通过migration
创建一个user
表
原生sql表示为
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
编辑迁移文件
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(
ColumnDef::new(User::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(User::Username).string().not_null())
.col(ColumnDef::new(User::Password).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum User {
Table,
Id,
Username,
Password,
}
主要关注迁移文件里的 up
, down
方法,up是执行,down是回退
执行迁移命令
sea-orm-cli migrate up -u mysql://root:123456@localhost:3306/sea-demo
连接到sea-demo数据库可以看到创建了 user
表和 seaql_migrations
表,其中user
表是我们指定创建的表,seaql_migrations
是自动创建的记录迁移记录的表,以免迁移冲突;
下节我们将一起学习使用sea-orm执行增删改查