building db support with diesel.rs
This commit is contained in:
23
cookbook/src/bin/show_recipes.rs
Normal file
23
cookbook/src/bin/show_recipes.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
extern crate cookbook;
|
||||
extern crate diesel;
|
||||
|
||||
use self::cookbook::*;
|
||||
use self::models::*;
|
||||
use self::diesel::prelude::*;
|
||||
|
||||
fn main() {
|
||||
use cookbook::schema::recipes::dsl::*;
|
||||
|
||||
let conn = establish_connection();
|
||||
let result = recipes
|
||||
.limit(5)
|
||||
.load::<Recipe>(&conn)
|
||||
.expect("Error loading recipes");
|
||||
|
||||
println!("Here are {} recipes :", result.len());
|
||||
for rec in result {
|
||||
println!("{}", rec.title);
|
||||
println!("-------------\n");
|
||||
println!("{}", rec.ingredients);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,28 @@
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
extern crate dotenv;
|
||||
|
||||
pub mod schema;
|
||||
pub mod models;
|
||||
|
||||
mod recipe;
|
||||
mod storage;
|
||||
mod importer;
|
||||
|
||||
use diesel::prelude::*;
|
||||
use dotenv::dotenv;
|
||||
use std::env;
|
||||
|
||||
pub fn establish_connection() -> SqliteConnection {
|
||||
dotenv().ok();
|
||||
|
||||
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set !");
|
||||
SqliteConnection::establish(&db_url)
|
||||
.expect(&format!("Error connecting to {}", db_url))
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
|
||||
8
cookbook/src/models.rs
Normal file
8
cookbook/src/models.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
#[derive(Queryable)]
|
||||
pub struct Recipe {
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub category: i32,
|
||||
pub ingredients: String,
|
||||
pub preparation: String,
|
||||
}
|
||||
@@ -40,8 +40,7 @@ impl Ingredient {
|
||||
pub(super) fn new(name: String) -> Ingredient {
|
||||
Ingredient {
|
||||
alias: vec![name],
|
||||
..
|
||||
Default::default()
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
9
cookbook/src/schema.rs
Normal file
9
cookbook/src/schema.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
table! {
|
||||
recipes (id) {
|
||||
id -> Integer,
|
||||
title -> Text,
|
||||
category -> Integer,
|
||||
ingredients -> Text,
|
||||
preparation -> Text,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user