-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookDatabaseSQLiteTemp.rs
More file actions
64 lines (54 loc) · 1.45 KB
/
BookDatabaseSQLiteTemp.rs
File metadata and controls
64 lines (54 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use dotenv::dotenv;
use std::env;
pub fn establish_connection() -> SqliteConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
SqliteConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}
table! {
books (id) {
id -> Integer,
title -> Text,
author -> Text,
publication_year -> Integer,
}
}
#[derive(Queryable)]
pub struct Book {
pub id: i32,
pub title: String,
pub author: String,
pub publication_year: i32,
}
#[derive(Insertable)]
#[table_name="books"]
pub struct NewBook<'a> {
pub title: &'a str,
pub author: &'a str,
pub publication_year: &'a i32,
}
pub fn create_book<'a>(conn: &SqliteConnection, title: &'a str, author: &'a str, publication_year: &'a i32) -> Book {
use diesel::insert_into;
let new_book = NewBook {
title,
author,
publication_year,
};
insert_into(books::table)
.values(&new_book)
.execute(conn)
.expect("Error saving new book");
books::table
.order(books::id.desc())
.first(conn)
.unwrap()
}
pub fn all_books(conn: &SqliteConnection) -> Vec<Book> {
books::table
.order(books::id)
.load::<Book>(conn)
.unwrap()
}