web項目中坯台,我們一般不直接拼接
sql
語句扣蜻,而是選擇一個orm來進行操作數(shù)據庫,本文和大家一起學習sea-orm
的使用
添加依賴
使用 cargo new sea-orm-demo
新建項目对人,并在Cargo.toml
中添加sea-orm
依賴
sea-orm的features
有較多可選項暂筝,主要是根據你所使用的數(shù)據庫類型和要使用的異步運行時進行選擇,macros
也是個常用feature, 因為我們大概率會使用sea-orm-cli來生成實體和模型右遭,macros feature 提供的宏可以幫我們節(jié)省很多代碼
- runtime-tokio-native-tls做盅,可以理解為使用
tokio
作為異步運行時,native-tls
表示使用原生的tls實現(xiàn)窘哈;其他可選feature還有- runtime-async-std-native-tls
- runtime-async-std-rustls
- runtime-tokio-rustls
- sqlx-mysql表示我們使用
mysql
作為數(shù)據庫驅動吹榴,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創(chuàng)建數(shù)據表
創(chuàng)建數(shù)據表滚婉,我們可以通過原生sql創(chuàng)建图筹,也可以通過sea-orm編寫純rust代碼執(zhí)行創(chuàng)建
安裝sea-orm-cli
sea-orm-cli
是sea-orm
官方 提供的工具鏈,可以通過cargo
直接安裝
cargo install sea-orm-cli
初始化 migrate目錄
- 在項目根目錄執(zhí)行如下命令,會創(chuàng)建一個
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的遷移文件瓜晤;新創(chuàng)建的migration默認包含一個遷移文件锥余; 如果要新建一個遷移文件,執(zhí)行如下命令
// 根目錄執(zhí)行
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
創(chuàng)建一個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是執(zhí)行雄驹,down是回退
執(zhí)行遷移命令
sea-orm-cli migrate up -u mysql://root:123456@localhost:3306/sea-demo
連接到sea-demo數(shù)據庫可以看到創(chuàng)建了 user
表和 seaql_migrations
表,其中user
表是我們指定創(chuàng)建的表淹辞,seaql_migrations
是自動創(chuàng)建的記錄遷移記錄的表医舆,以免遷移沖突;
下節(jié)我們將一起學習使用sea-orm執(zhí)行增刪改查