feat: implement image db pagination

image-uploads
Jef Roosens 2025-01-24 13:20:57 +01:00
parent 51fa92ba3b
commit 39a15bb094
No known key found for this signature in database
GPG Key ID: 21FD3D77D56BAF49
2 changed files with 37 additions and 1 deletions

View File

@ -7,6 +7,7 @@ use diesel::{
SqliteConnection, SqliteConnection,
}; };
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use serde::Deserialize;
use std::{error::Error, fmt, path::Path}; use std::{error::Error, fmt, path::Path};
@ -67,3 +68,19 @@ pub fn initialize_db(path: impl AsRef<Path>, run_migrations: bool) -> Result<DbP
Ok(pool) Ok(pool)
} }
#[derive(Deserialize, Copy, Clone)]
#[serde(default)]
pub struct Pagination {
page: u32,
per_page: u32,
}
impl Default for Pagination {
fn default() -> Self {
Self {
page: 0,
per_page: 10,
}
}
}

View File

@ -2,7 +2,7 @@ use chrono::NaiveDate;
use diesel::prelude::*; use diesel::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::db::{schema::*, DbPool, DbResult}; use crate::db::{schema::*, DbPool, DbResult, Pagination};
#[derive(Serialize, Queryable, Selectable)] #[derive(Serialize, Queryable, Selectable)]
#[diesel(table_name = images)] #[diesel(table_name = images)]
@ -25,6 +25,11 @@ pub struct NewImage {
note: Option<String>, note: Option<String>,
} }
#[derive(Deserialize, Clone, Copy)]
pub struct ImageFilter {
pub plant_id: Option<i32>,
}
impl NewImage { impl NewImage {
pub fn new( pub fn new(
plant_id: i32, plant_id: i32,
@ -56,4 +61,18 @@ impl Image {
.first(&mut pool.get()?) .first(&mut pool.get()?)
.optional()?) .optional()?)
} }
pub fn page(pool: &DbPool, page: Pagination, filter: ImageFilter) -> DbResult<Vec<Self>> {
let mut query = images::table.select(Self::as_select()).into_boxed();
if let Some(plant_id) = filter.plant_id {
query = query.filter(images::dsl::plant_id.eq(plant_id));
}
Ok(query
.order_by((images::dsl::date_taken.desc(), images::dsl::id.desc()))
.offset((page.page * page.per_page).into())
.limit(page.per_page.into())
.get_results(&mut pool.get()?)?)
}
} }