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

71 lines
2.1 KiB
Rust
Raw Normal View History

2024-05-06 07:09:40 +00:00
use rusqlite::{named_params, Connection, Row};
2024-05-02 16:10:29 +00:00
use serde::Serialize;
2024-05-01 14:21:07 +00:00
use super::{
error::DataStoreError,
pagination::{Pagination, SortOrder},
};
2024-05-02 16:10:29 +00:00
#[derive(Debug, Serialize)]
2024-05-01 14:21:07 +00:00
pub struct Author {
2024-05-06 07:09:40 +00:00
pub id: u64,
2024-05-01 14:21:07 +00:00
pub name: String,
pub sort: String,
}
impl Author {
fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get(0)?,
name: row.get(1)?,
sort: row.get(2)?,
})
}
2024-05-06 07:09:40 +00:00
pub fn multiple(
2024-05-01 14:21:07 +00:00
conn: &Connection,
limit: u64,
cursor: Option<&str>,
2024-05-06 11:51:49 +00:00
sort_order: &SortOrder,
2024-05-06 07:09:40 +00:00
) -> Result<Vec<Self>, DataStoreError> {
2024-05-06 11:51:49 +00:00
let pagination = Pagination::new("sort", cursor, limit, *sort_order);
2024-05-01 14:21:07 +00:00
pagination.paginate(
conn,
"SELECT id, name, sort FROM authors",
&[],
Self::from_row,
)
}
2024-05-06 07:09:40 +00:00
pub fn book_author(conn: &Connection, id: u64) -> Result<Self, DataStoreError> {
let mut stmt = conn.prepare(
"SELECT authors.id, authors.name, authors.sort FROM authors \
INNER JOIN books_authors_link ON authors.id = books_authors_link.author \
WHERE books_authors_link.book = (:id)",
)?;
let params = named_params! { ":id": id };
Ok(stmt.query_row(params, Self::from_row)?)
}
2024-05-06 11:51:49 +00:00
pub fn has_previous_authors(
conn: &Connection,
sort_name: &str,
) -> Result<bool, DataStoreError> {
let mut stmt = conn
.prepare("SELECT Count(1) FROM authors WHERE sort < (:sort_name) ORDER BY sort DESC")?;
let params = named_params! { ":sort_name": sort_name };
let count: u64 = stmt.query_row(params, |x| x.get(0))?;
Ok(count > 0)
}
pub fn has_more_authors(conn: &Connection, sort_name: &str) -> Result<bool, DataStoreError> {
let mut stmt = conn
.prepare("SELECT Count(1) FROM authors WHERE sort > (:sort_name) ORDER BY sort ASC")?;
let params = named_params! { ":sort_name": sort_name };
let count: u64 = stmt.query_row(params, |x| x.get(0))?;
Ok(count > 0)
}
2024-05-01 14:21:07 +00:00
}