feat: start migration other models to diesel

image-uploads
Jef Roosens 2025-01-16 09:08:33 +01:00
parent 77995ebec9
commit daead2116b
No known key found for this signature in database
GPG Key ID: 21FD3D77D56BAF49
3 changed files with 80 additions and 0 deletions

View File

@ -1 +1,3 @@
mod plant;
mod session;
mod user;

View File

@ -0,0 +1,41 @@
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use crate::db::schema::*;
#[derive(Serialize, Queryable, Selectable)]
#[diesel(table_name = plants)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Plant {
id: i64,
name: String,
species: String,
description: String,
}
#[derive(Deserialize, Insertable)]
#[diesel(table_name = plants)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct NewPlant {
name: String,
species: String,
description: String,
}
impl NewPlant {
pub fn insert(self, conn: &mut SqliteConnection) -> QueryResult<Plant> {
self.insert_into(plants::table)
.returning(Plant::as_returning())
.get_result(conn)
}
}
impl Plant {
pub fn by_id(conn: &mut SqliteConnection, id: i64) -> QueryResult<Option<Self>> {
plants::table
.find(id)
.select(Self::as_select())
.first(conn)
.optional()
}
}

View File

@ -0,0 +1,37 @@
use diesel::prelude::*;
use rand::Rng;
use super::user::User;
use crate::db::schema::*;
#[derive(Clone, Queryable, Selectable, Insertable, Associations)]
#[diesel(belongs_to(super::user::User))]
#[diesel(table_name = sessions)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Session {
pub id: i64,
pub user_id: i64,
}
impl Session {
pub fn new_for_user(conn: &mut SqliteConnection, user_id: i64) -> QueryResult<Self> {
let id: i64 = rand::thread_rng().gen();
Self { id, user_id }
.insert_into(sessions::table)
.returning(Self::as_returning())
.get_result(conn)
}
pub fn user_from_id(
conn: &mut SqliteConnection,
id: i64,
) -> QueryResult<Option<super::user::User>> {
sessions::dsl::sessions
.inner_join(users::table)
.filter(sessions::id.eq(id))
.select(User::as_select())
.get_result(conn)
.optional()
}
}