[Rust]SeaORMで基本的なInsert,Delete,Update操作を行う方法

Rust

はじめに

今回は、RustのORMライブラリSeaORMを使って、Insert(追加)Update(更新)Delete(削除)の基本的な操作方法を紹介します。

SeaORMの導入方法については、こちらを参考にしてください。

Rust×SeaORMで学ぶORM入門:セットアップと基本操作を解説
はじめに今回は、Rustの人気ORMパッケージであるSeaORMをインストールから、簡単なデータベース操作までを解説します。なお、今回紹介するソースコードはこちらにあります。また、Rustのデスクトッ...

また、selectでの検索方法はこちらを参考にしてください

[Rust]SeaORMで基本的なSelect操作を行う方法
はじめに今回は、SeaORMのselect処理において、頻繁に使用するような処理を紹介します。なお、SeaORMの導入方法については、こちらを参考にしてくださいテーブルすべてのレコードを取得するuse...

新規データを追加する(Insert)

1レコードを追加


pub mod entities;
// 新しいユーザーデータを作成
let user = entities::user::ActiveModel {
   id: sea_orm::ActiveValue::Set(1),
   name: sea_orm::ActiveValue::Set("Alice".to_owned()),
   email: sea_orm::ActiveValue::Set("...".to_owned()),
};
// データベースに挿入
entities::user::Entity::insert(user).exec(&db).await?;

// 新しいユーザーデータを作成 name,email以外のフィールドはデフォルト値
let user = entities::user::ActiveModel {
    name: sea_orm::ActiveValue::Set("Alice".to_owned()),
    email: sea_orm::ActiveValue::Set("...".to_owned()),
    ..Default::default()
};
// データベースに挿入
entities::user::Entity::insert(user).exec(&db).await?;
  

複数レコードを追加


pub mod entities;
let user = entities::user::ActiveModel {
    name: sea_orm::ActiveValue::Set("Alice".to_owned()),
    email: sea_orm::ActiveValue::Set("...".to_owned()),
    ..Default::default()
};
let user2 = entities::user::ActiveModel {
    name: sea_orm::ActiveValue::Set("Tom".to_owned()),
    email: sea_orm::ActiveValue::Set("...".to_owned()),
    ..Default::default()
};
// 複数レコードをデータベースに挿入
entities::user::Entity::insert_many([user, user2]).exec(&db).await?;
  

既存データを更新する(Update)

1レコードを更新


// ID=1のユーザーを取得して名前を更新
let user: Option = entities::user::Entity::find_by_id(1).one(&db).await?;

let mut changed_user: entities::user::ActiveModel = user.unwrap().into();

// ユーザー名を変更
changed_user.name = sea_orm::ActiveValue::Set("Changed User".to_owned());

// Update実行
changed_user.update(&db).await?;
  

条件を指定して複数レコードを更新


// Nameカラムに"Sample"を含むユーザーの名前を"Updated Name"に更新
entities::user::Entity::update_many()
    .col_expr(entities::user::Column::Name, Expr::value("Updated Name"))
    .filter(entities::user::Column::Name.contains("Sample"))
    .exec(&db)
    .await?;
  

データを削除する(Delete)

idをもとに1件データを削除


// ID=1のユーザーを削除
entities::user::Entity::delete_by_id(1).exec(&db).await?;
  

全レコード削除


entities::user::Entity:: delete_many().exec(&db).await?;
  

条件を指定してレコード削除


entities::user::Entity:: delete_many()
    .filter(entities::user::Column::Name.contains("Sample")) // nameカラムがSampleのユーザを指定
    .exec(&db).await?;
  

参考リンク

タイトルとURLをコピーしました