やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

Rust自習(diesel 2 SQLite3 ORM)

 データを挿入する。

成果物

コード

 前回のコードに以下を追記する。

models.rs

models.rs

use super::schema::posts;

#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost<'a> {
    pub title: &'a str,
    pub body: &'a str,
}

lib.rs

pub fn create_post(conn: &SqliteConnection, title: &str, body: &str) -> usize {
    use schema::posts;

    let new_post = crate::models::NewPost { title, body };

    diesel::insert_into(posts::table)
        .values(&new_post)
        .execute(conn)
        .expect("Error saving new post")
}

 ビルドできることを確認する。

$ cargo build

src/bin/write.rs

extern crate diesel_hello;
extern crate diesel;

use self::diesel_hello::*;
use std::io::{stdin, Read};

fn main() {
    let connection = establish_connection();

    println!("タイトル> ");
    let mut title = String::new();
    stdin().read_line(&mut title).unwrap();
    let title = &title[..(title.len() - 1)]; // Drop the newline character
    println!("\n本文(終了:{})\n", EOF);
    let mut body = String::new();
    stdin().read_to_string(&mut body).unwrap();

    let post_id = create_post(&connection, title, &body);
    println!("\n保存した。ドラフト「{}」 id: {}", title, post_id);
}

#[cfg(not(windows))]
const EOF: &'static str = "CTRL+D";

#[cfg(windows)]
const EOF: &'static str = "CTRL+Z";

実行

cargo run --bin write_post

 ターミナルにタイトルと本文を入力する。本文はEnterを押しても終了せず次の行を入力する。終了するには書いてある通りCTRL+Dキーを押下する。

タイトル> 
記事のタイトル

本文(終了:CTRL+D)

記事の本文。
複数行を書く。
Ctrl+dキーで終了。
最終行。

保存した。ドラフト「記事のタイトル」 id: 1

確認

 DBファイルの中身を確認してみる。

$ sqlite3 ./db.sqlite3
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite> select * from posts;
1|記事のタイトル|記事の本文。
複数行を書く。
Ctrl+dキーで終了。
最終行。
|f

 データが挿入されている。成功!

対象環境

$ uname -a
Linux raspberrypi 4.19.42-v7+ #1219 SMP Tue May 14 21:20:58 BST 2019 armv7l GNU/Linux

前回まで