//! Series data. use rusqlite::{named_params, Connection, Row}; use serde::Serialize; use super::{ error::DataStoreError, pagination::{Pagination, SortOrder}, }; /// Series in calibre. #[derive(Debug, Clone, Serialize)] pub struct Series { /// Id in database. pub id: u64, /// Series name. pub name: String, /// Series name for sorting. pub sort: String, } impl Series { fn from_row(row: &Row<'_>) -> Result { Ok(Self { id: row.get(0)?, name: row.get(1)?, sort: row.get(2)?, }) } /// Fetch series data from calibre, starting at `cursor`, fetching up to an amount of `limit` and /// ordering by `sort_order`. pub fn multiple( conn: &Connection, limit: u64, cursor: Option<&str>, sort_order: &SortOrder, ) -> Result, DataStoreError> { let pagination = Pagination::new("sort", cursor, limit, *sort_order); pagination.paginate( conn, "SELECT id, name, sort FROM series", &[], Self::from_row, ) } /// Fetch a single series with id `id`. pub fn scalar_series(conn: &Connection, id: u64) -> Result { let mut stmt = conn.prepare("SELECT id, name, sort FROM series WHERE id = (:id)")?; let params = named_params! { ":id": id }; Ok(stmt.query_row(params, Self::from_row)?) } /// Get the series a book with id `id` is in, as well as the book's position within the series. pub fn book_series( conn: &Connection, book_id: u64, ) -> Result, DataStoreError> { let mut stmt = conn.prepare( "SELECT series.id, series.name, series.sort, books.series_index FROM series \ INNER JOIN books_series_link ON series.id = books_series_link.series \ INNER JOIN books ON books.id = books_series_link.book \ WHERE books_series_link.book = (:id)", )?; let params = named_params! { ":id": book_id }; let from_row = |row: &Row<'_>| { let series = Self::from_row(row)?; let series_idx = row.get(3)?; Ok((series, series_idx)) }; match stmt.query_row(params, from_row) { Ok(series) => Ok(Some(series)), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(e) => Err(DataStoreError::SqliteError(e)), } } /// Check if there are more series before the specified cursor. pub fn has_previous_series(conn: &Connection, sort_name: &str) -> Result { Pagination::has_prev_or_more(conn, "series", sort_name, &SortOrder::DESC) } /// Check if there are more series after the specified cursor. pub fn has_more_series(conn: &Connection, sort_name: &str) -> Result { Pagination::has_prev_or_more(conn, "series", sort_name, &SortOrder::ASC) } }