Browse Source

Moved stuff around

main
Diane 7 months ago
parent
commit
eeb5747e36
No known key found for this signature in database GPG Key ID: 2D0649E76A7C8D25
  1. 12
      src/main.rs
  2. 32
      src/store/db.rs

12
src/main.rs

@ -1,22 +1,16 @@
use crate::store::db::connect;
use crate::store::models::Recipe;
#[macro_use]
extern crate diesel;
use store::schema::recipes::dsl::*;
use diesel::prelude::*;
use std::env;
mod store;
fn main() {
let db = connect();
let res = recipes
.limit(10)
.load::<Recipe>(&db)
.unwrap();
let db = connect(env::var("DATABASE_URL").unwrap().as_str());
let res = db.list_recipes();
println!("{} recipes", res.len());
for recipe in res {
println!("{}: {}", recipe.id, recipe.title);

32
src/store/db.rs

@ -1,9 +1,29 @@
use diesel::{Connection, SqliteConnection};
use std::env;
use crate::store::models::Recipe;
pub fn connect() -> SqliteConnection {
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
SqliteConnection::establish(&database_url)
.unwrap_or_else(|err| panic!("Error connecting to {}: {}", database_url, err))
use super::schema::recipes::dsl::*;
use diesel::prelude::*;
pub struct DataStore {
database: SqliteConnection
}
pub fn connect(url: &str) -> DataStore {
DataStore {
database: SqliteConnection::establish(url)
.unwrap_or_else(|err| panic!("Error connecting to {}: {}", url, err))
}
}
impl DataStore {
pub fn list_recipes(&self) -> Vec<Recipe> {
self.list_recipes(10)
}
pub fn list_recipes(&self, limit: i64) -> Vec<Recipe> {
recipes
.limit(limit)
.load::<Recipe>(&self.database)
.unwrap()
}
}
Loading…
Cancel
Save