little-hesinde/calibre-db/src/data/book.rs

75 lines
2.2 KiB
Rust
Raw Normal View History

2024-05-02 18:10:29 +02:00
use rusqlite::{named_params, Connection, Row};
use serde::Serialize;
2024-05-01 16:21:07 +02:00
use super::{
error::DataStoreError,
pagination::{Pagination, SortOrder},
};
2024-05-02 18:10:29 +02:00
#[derive(Debug, Serialize)]
2024-05-01 16:21:07 +02:00
pub struct Book {
pub id: i32,
pub title: String,
pub sort: String,
2024-05-02 18:10:29 +02:00
pub path: String,
2024-05-01 16:21:07 +02:00
}
impl Book {
fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get(0)?,
title: row.get(1)?,
sort: row.get(2)?,
2024-05-02 18:10:29 +02:00
path: row.get(3)?,
2024-05-01 16:21:07 +02:00
})
}
pub fn books(
conn: &Connection,
limit: u64,
cursor: Option<&str>,
sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> {
let pagination = Pagination::new("sort", cursor, limit, sort_order);
pagination.paginate(
conn,
2024-05-02 18:10:29 +02:00
"SELECT id, title, sort, path FROM books",
2024-05-01 16:21:07 +02:00
&[],
Self::from_row,
)
}
pub fn author_books(
conn: &Connection,
author_id: u64,
limit: u64,
cursor: Option<&str>,
sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> {
let pagination = Pagination::new("books.sort", cursor, limit, sort_order);
pagination.paginate(
conn,
2024-05-02 18:10:29 +02:00
"SELECT books.id, books.title, books.sort, books.path FROM books \
2024-05-01 16:21:07 +02:00
INNER JOIN books_authors_link ON books.id = books_authors_link.book \
WHERE books_authors_link.author = (:author_id) AND",
&[(":author_id", &author_id)],
Self::from_row,
)
}
2024-05-02 18:10:29 +02:00
pub fn recents(conn: &Connection, limit: u64) -> Result<Vec<Book>, DataStoreError> {
let mut stmt = conn.prepare(
"SELECT id, title, sort, path FROM books ORDER BY timestamp DESC LIMIT (:limit)",
)?;
let params = named_params! { ":limit": limit };
let iter = stmt.query_map(params, Self::from_row)?;
Ok(iter.filter_map(Result::ok).collect())
}
pub fn scalar_book(conn: &Connection, id: u64) -> Result<Book, DataStoreError> {
let mut stmt = conn.prepare("SELECT id, title, sort, path FROM books WHERE id = (:id)")?;
let params = named_params! { ":id": id };
Ok(stmt.query_row(params, Self::from_row)?)
}
2024-05-01 16:21:07 +02:00
}