zoodex/src/persist/sqlite_manager.rs

203 lines
6.6 KiB
Rust
Raw Normal View History

use std::ffi::OsStr;
use std::fmt;
use std::fmt::{Debug, Formatter};
use async_sqlite::rusqlite::fallible_iterator::FallibleIterator;
use async_sqlite::rusqlite::{OpenFlags, Row};
use async_sqlite::{Client, ClientBuilder, rusqlite};
use crate::persist::common::{ResultExt, concat_os_str};
use crate::persist::data_manager::DataManagerError;
use crate::views::overview::{FilmOverview, SeriesOverview};
pub struct SqliteManager {
client: Client,
}
impl SqliteManager {
pub async fn new(data_dir: &OsStr) -> Result<SqliteManager, DataManagerError> {
let client = create_client(data_dir).await?;
Ok(SqliteManager { client })
}
// The order of the items is undefined.
pub async fn films_overview(&self) -> Result<Vec<FilmOverview>, DataManagerError> {
let overview = self
.client
.conn(|connection| {
connection
.prepare(
"
select uuid, name, original_name, release_date, runtime_minutes
from films
",
)
.expect("films overview statement should be valid SQL")
.query(())
.expect("parameters in films overview query should match those in its statement")
.map(row_to_film_overview)
.collect()
})
.await;
overview.map_err(|async_sqlite_error| match async_sqlite_error {
async_sqlite::Error::Closed => {
panic!("database connection should remain open as long as the application is running")
}
async_sqlite::Error::Rusqlite(rusqlite_error) => match rusqlite_error {
rusqlite::Error::InvalidColumnIndex(_) => {
panic!("column indices obtained from films overview query should exist")
}
rusqlite::Error::InvalidColumnName(_) => {
panic!("column names obtained from films overview query should exist")
}
rusqlite::Error::InvalidColumnType(..) => panic!(
"values obtained from films overview query should have a type matching their column"
),
_ => DataManagerError::UnknownDBError,
},
_ => DataManagerError::UnknownDBError,
})
}
// The order of the items is undefined.
pub async fn series_overview(&self) -> Result<Vec<SeriesOverview>, DataManagerError> {
let overview = self
.client
.conn(|connection| {
connection
.prepare(
"
select series.uuid, series.name, series.original_name,
min(episodes.release_date) as first_release_date
from series, seasons, episodes
where series.uuid = seasons.series and seasons.uuid = episodes.season
group by series.uuid
",
)
.expect("series overview statement should be valid SQL")
.query(())
.expect("parameters in series overview query should match those in its statement")
.map(row_to_series_overview)
.collect()
})
.await;
overview.map_err(|async_sqlite_error| match async_sqlite_error {
async_sqlite::Error::Closed => {
panic!("database connection should remain open as long as the application is running")
}
async_sqlite::Error::Rusqlite(rusqlite_error) => match rusqlite_error {
rusqlite::Error::InvalidColumnIndex(_) => {
panic!("column indices obtained from series overview query should exist")
}
rusqlite::Error::InvalidColumnName(_) => {
panic!("column names obtained from series overview query should exist")
}
rusqlite::Error::InvalidColumnType(..) => panic!(
"values obtained from series overview query should have a type matching their column"
),
_ => DataManagerError::UnknownDBError,
},
_ => DataManagerError::UnknownDBError,
})
}
}
impl Debug for SqliteManager {
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("SqliteManager { Client, Client }")
}
}
async fn create_client(data_dir: &OsStr) -> Result<Client, DataManagerError> {
let client = ClientBuilder::new()
.path("")
.flags(OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX)
.open()
.await;
let data_dir = data_dir.to_os_string();
let client = client
.and_then_async(async move |client| {
client
.conn(move |connection| {
let shared_path_os_str = concat_os_str!(&data_dir, "/shared.sqlite");
let shared_path = shared_path_os_str
.to_str()
.expect("shared database path should be valid Unicode");
connection
.execute("attach database :path as shared", &[(":path", shared_path)])
.expect(
"shared database attaching statement should be valid SQL with matching parameters",
);
let local_path_os_str = concat_os_str!(&data_dir, "/local.sqlite");
let local_path = local_path_os_str
.to_str()
.expect("local database path should be valid Unicode");
connection
.execute("attach database :path as local", &[(":path", local_path)])
.expect(
"local database attaching statement should be valid SQL with matching parameters",
);
Ok(())
})
.await
.map(|_| client)
})
.await;
client.map_err(|async_sqlite_error| match async_sqlite_error {
async_sqlite::Error::Closed => {
panic!("database connection should remain open as long as the application is running")
}
async_sqlite::Error::Rusqlite(rusqlite_error) => match rusqlite_error {
rusqlite::Error::SqliteFailure(sqlite_error, _) => match sqlite_error.code {
rusqlite::ffi::ErrorCode::CannotOpen => DataManagerError::CannotOpenDB,
_ => DataManagerError::UnknownDBError,
},
_ => DataManagerError::UnknownDBError,
},
_ => DataManagerError::UnknownDBError,
})
}
fn row_to_film_overview(row: &Row) -> rusqlite::Result<FilmOverview> {
let uuid = row.get("uuid")?;
let name = row.get("name")?;
let original_name = row.get("original_name")?;
let release_date = row.get("release_date")?;
let runtime = row.get("runtime_minutes")?;
Ok(FilmOverview {
uuid,
name,
original_name,
release_date,
runtime,
})
}
fn row_to_series_overview(row: &Row) -> rusqlite::Result<SeriesOverview> {
let uuid = row.get("uuid")?;
let name = row.get("name")?;
let original_name = row.get("original_name")?;
let first_release_date = row.get("first_release_date")?;
Ok(SeriesOverview {
uuid,
name,
original_name,
first_release_date,
})
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DBType {
Shared,
Local,
}