1. はじめに
以前の記事で Rust を使って MySQL へ接続 を試しました。
今回は、その続きで MySQL の upsert を使ってみます。
単純な挿入や更新は Diesel で簡単にできますが、upsert は Diesel には用意されておらず、SQL を直接書く必要があります。
2. Schema と Model の準備
まずは、前に作成した schema.rs
と models.rs
を使い拡張していきます。
schema.rs はそのままで、models.rs を以下に変更します。
#[derive(Insertable, AsChangeset, Debug, Serialize, Deserialize)]
#[diesel(table_name = task)]
pub struct Task {
pub id: i32,
pub title: String,
}
3. MySQL の upsert を実装
PostgreSQL では diesel に upsert が用意されていますが、MySQL にはなさそうで、SQL を直接書く方法を使います。
use diesel::query_dsl::RunQueryDsl;
use diesel::sql_query;
let query = format!(
"INSERT INTO stock (title) VALUES ('{}') ON DUPLICATE KEY UPDATE title = '{}'",
task.title
task.title
);
let result = sql_query(query).execute(&mut connection);
match result {
Ok(_) => println!("Inserted"),
Err(e) => println!("Error: {:?}", e),
}
4. まとめ
最初は MySQL でも diesel で upsert が使えると思いやり方を調べていましたがどうしてもうまくいかず・・・
結局、SQL を直接書く方法に落ち着きました。
今回の記事は、Github Copilot が5割くらい書いてくれました。
A. 参考サイト
All About Inserts
Module diesel::upsert
Function diesel::replace_into
dieselでbatch upsertをするには
SQL 挿入する際に既存のレコードがある場合は更新する「upsert」の使い方と注意点
コメント