1
0
mirror of https://github.com/actix/examples synced 2025-01-23 14:24:35 +01:00

42 lines
1.4 KiB
Rust
Raw Normal View History

2018-08-27 10:56:26 +01:00
use std::ops::Deref;
use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection};
2019-03-10 18:23:44 -07:00
use crate::model::{NewTask, Task};
2018-08-27 10:56:26 +01:00
2019-03-10 18:23:44 -07:00
pub type PgPool = Pool<ConnectionManager<PgConnection>>;
2018-08-27 10:56:26 +01:00
type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub fn init_pool(database_url: &str) -> Result<PgPool, PoolError> {
let manager = ConnectionManager::<PgConnection>::new(database_url);
Pool::builder().build(manager)
}
2019-03-10 18:23:44 -07:00
fn get_conn(pool: &PgPool) -> Result<PgPooledConnection, &'static str> {
pool.get().map_err(|_| "Can't get connection")
2018-08-27 10:56:26 +01:00
}
2019-03-10 18:23:44 -07:00
pub fn get_all_tasks(pool: &PgPool) -> Result<Vec<Task>, &'static str> {
Task::all(get_conn(pool)?.deref()).map_err(|_| "Error retrieving tasks")
2018-08-27 10:56:26 +01:00
}
2019-03-10 18:23:44 -07:00
pub fn create_task(todo: String, pool: &PgPool) -> Result<(), &'static str> {
let new_task = NewTask { description: todo };
Task::insert(new_task, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error inserting task")
2018-08-27 10:56:26 +01:00
}
2019-03-10 18:23:44 -07:00
pub fn toggle_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
Task::toggle_with_id(id, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error toggling task completion")
2018-08-27 10:56:26 +01:00
}
2019-03-10 18:23:44 -07:00
pub fn delete_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
Task::delete_with_id(id, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error deleting task")
2018-08-27 10:56:26 +01:00
}