mod regions;
mod resources;
mod schema;
use std::collections::BTreeMap;
use mln_style::error::{Error, ErrorKind};
use rusqlite::types::FromSqlError;
use rusqlite::{Connection, Row, ffi};
use crate::log_target;
use crate::storage::constants::DEFAULT_MAX_CACHE_SIZE;
use crate::storage::resource::{Kind, Resource, TileData};
pub(crate) const MAX_PENDING_ACCESSED: usize = 4096;
#[derive(Clone, Debug, thiserror::Error)]
pub enum DatabaseError {
#[error("{message}")]
Sqlite { code: i32, message: String },
#[error("{message}")]
Io { code: i32, message: String },
#[error("{0}")]
Failed(String),
#[error("{0}")]
InvalidArgument(String),
#[error("no offline region has ID {0}")]
RegionNotFound(i64),
}
impl From<rusqlite::Error> for DatabaseError {
fn from(e: rusqlite::Error) -> Self {
let code = e.sqlite_error().map_or(ffi::SQLITE_ERROR, |error| error.extended_code);
DatabaseError::Sqlite { code, message: e.to_string() }
}
}
impl From<FromSqlError> for DatabaseError {
fn from(e: FromSqlError) -> Self {
DatabaseError::Sqlite { code: ffi::SQLITE_ERROR, message: e.to_string() }
}
}
impl From<Error> for DatabaseError {
fn from(e: Error) -> Self {
match e.kind {
ErrorKind::InvalidArgument => DatabaseError::InvalidArgument(e.message),
_ => DatabaseError::Failed(e.message),
}
}
}
impl From<DatabaseError> for Error {
fn from(error: DatabaseError) -> Self {
let kind = match error {
DatabaseError::InvalidArgument(_) => ErrorKind::InvalidArgument,
DatabaseError::RegionNotFound(_) => ErrorKind::NotFound,
_ => ErrorKind::Failed,
};
Error::new(kind, error.to_string())
}
}
type DbResult<T> = Result<T, DatabaseError>;
fn delete_file(filename: &str) -> DbResult<()> {
match std::fs::remove_file(filename) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => {
let code = e.raw_os_error().unwrap_or(0);
let what = e.to_string();
let what = what.split(" (os error").next().unwrap_or(&what).to_owned();
Err(DatabaseError::Io { code, message: format!("Could not delete file {filename}: {what}") })
}
}
}
pub struct OfflineDatabase {
path: String,
db: Option<Connection>,
maximum_ambient_cache_size: u64,
current_ambient_cache_size: Option<u64>,
autopack: bool,
read_only: bool,
pending_resource_accessed: BTreeMap<i64, i64>,
pending_tile_accessed: BTreeMap<i64, i64>,
pending_applied_for_eviction: bool,
accessed_flush_failed: bool,
accessed_callback: Option<Box<dyn FnMut() + Send>>,
}
impl Drop for OfflineDatabase {
fn drop(&mut self) {
self.cleanup();
}
}
impl OfflineDatabase {
pub fn new(path: impl Into<String>) -> Self {
let mut db = OfflineDatabase {
path: path.into(),
db: None,
maximum_ambient_cache_size: DEFAULT_MAX_CACHE_SIZE,
current_ambient_cache_size: None,
autopack: true,
read_only: false,
pending_resource_accessed: BTreeMap::new(),
pending_tile_accessed: BTreeMap::new(),
pending_applied_for_eviction: false,
accessed_flush_failed: false,
accessed_callback: None,
};
if let Err(e) = db.initialize() {
db.handle_error(&e, "open database");
}
db
}
#[cfg(test)]
pub(crate) fn change_path(&mut self, path: &str) {
tracing::info!(target: log_target::DATABASE, "Changing the database path.");
self.cleanup();
self.path = path.to_owned();
if let Err(e) = self.initialize() {
self.handle_error(&e, "open database");
}
}
fn cleanup(&mut self) {
self.flush_accessed();
self.discard_pending_accessed();
self.db = None;
}
fn disabled(&mut self) -> bool {
if self.maximum_ambient_cache_size != 0 {
return false;
}
let regions = self.list_regions();
regions.map_or(true, |regions| regions.is_empty())
}
fn handle_error(&mut self, error: &DatabaseError, action: &str) {
match error {
DatabaseError::Sqlite { code, message } => {
let primary_code = code & 0xff;
if primary_code == ffi::SQLITE_NOTADB
|| primary_code == ffi::SQLITE_CORRUPT
|| *code == ffi::SQLITE_READONLY_DBMOVED
{
tracing::error!(
target: log_target::DATABASE,
code = i64::from(primary_code),
action,
error = %message,
"Offline database operation failed"
);
if let Err(io_ex) = self.remove_existing() {
self.handle_error(&io_ex, action);
}
} else {
tracing::warn!(
target: log_target::DATABASE,
code = i64::from(primary_code),
action,
error = %message,
"Offline database operation failed"
);
}
}
DatabaseError::Io { code, message } => {
tracing::error!(
target: log_target::DATABASE,
code = i64::from(*code),
action,
error = %message,
"Offline database operation failed"
);
}
DatabaseError::Failed(message) => {
tracing::error!(target: log_target::DATABASE, action, error = %message, "Offline database operation failed");
}
DatabaseError::InvalidArgument(_) => {
tracing::error!(target: log_target::DATABASE, action, "Offline database operation failed");
}
DatabaseError::RegionNotFound(_) => {}
}
}
fn report<T>(&mut self, result: DbResult<T>, action: &str) -> DbResult<T> {
if let Err(e) = &result {
self.handle_error(e, action);
}
result
}
fn remove_existing(&mut self) -> DbResult<()> {
tracing::warn!(target: log_target::DATABASE, "Removing existing incompatible offline database");
self.discard_pending_accessed();
let filename = match &self.db {
Some(db) => db.path().unwrap_or("").to_owned(),
None => self.path.clone(),
};
self.db = None;
if !filename.is_empty() {
delete_file(&filename)?;
}
Ok(())
}
fn check_flags(&self) -> DbResult<()> {
if self.read_only {
return Err(DatabaseError::Failed("Cannot modify database in read-only mode".to_owned()));
}
Ok(())
}
fn db(&mut self) -> DbResult<&Connection> {
if self.db.is_none() {
self.initialize()?;
}
self.db.as_ref().ok_or_else(|| DatabaseError::Failed("Database not initialized".to_owned()))
}
fn execute(&mut self, sql: &str, params: impl rusqlite::Params) -> DbResult<u64> {
let conn = self.db()?;
let mut stmt = conn.prepare_cached(sql)?;
Ok(stmt.execute(params)? as u64)
}
fn query_row<T>(
&mut self,
sql: &str,
params: impl rusqlite::Params,
f: impl FnOnce(&Row<'_>) -> DbResult<T>,
) -> DbResult<Option<T>> {
let conn = self.db()?;
let mut stmt = conn.prepare_cached(sql)?;
let mut rows = stmt.query(params)?;
match rows.next()? {
None => Ok(None),
Some(row) => f(row).map(Some),
}
}
fn last_insert_row_id(&mut self) -> DbResult<i64> {
let conn = self.db()?;
Ok(conn.last_insert_rowid())
}
fn with_transaction<T>(&mut self, begin: Begin, f: impl FnOnce(&mut Self) -> DbResult<T>) -> DbResult<T> {
exec(self.db()?, begin.sql())?;
match f(self) {
Ok(value) => {
exec(self.db()?, "COMMIT TRANSACTION")?;
Ok(value)
}
Err(e) => {
if let Some(db) = &self.db {
let _ = exec(db, "ROLLBACK TRANSACTION");
}
Err(e)
}
}
}
fn pragma_i64(&mut self, sql: &str) -> DbResult<i64> {
Ok(self.query_row(sql, [], |row| Ok(row.get(0)?))?.unwrap_or(0))
}
pub(crate) fn pack(&mut self) -> DbResult<()> {
let result = (|| -> DbResult<()> {
if self.db.is_none() {
self.initialize()?;
}
self.vacuum()
})();
self.report(result, "pack storage")
}
#[cfg(test)]
pub(crate) fn run_pack_database_automatically(&mut self, autopack: bool) {
self.autopack = autopack;
}
pub(crate) fn reopen_database_read_only(&mut self, read_only: bool) {
if self.read_only == read_only {
return;
}
self.cleanup();
self.read_only = read_only;
if let Err(e) = self.initialize() {
self.handle_error(&e, "reopen database read-only");
}
}
pub(crate) fn reset_database(&mut self) -> DbResult<()> {
let result = self.remove_existing().and_then(|()| self.initialize());
self.report(result, "reset database")
}
}
#[derive(Clone, Copy)]
enum Begin {
Deferred,
Immediate,
}
impl Begin {
fn sql(self) -> &'static str {
match self {
Begin::Deferred => "BEGIN DEFERRED TRANSACTION",
Begin::Immediate => "BEGIN IMMEDIATE TRANSACTION",
}
}
}
fn exec(conn: &Connection, sql: &str) -> rusqlite::Result<()> {
use rusqlite::fallible_iterator::FallibleIterator as _;
let mut batch = rusqlite::Batch::new(conn, sql);
while let Some(mut stmt) = batch.next()? {
let mut rows = stmt.raw_query();
while rows.next()?.is_some() {}
}
Ok(())
}
fn tile_data(resource: &Resource) -> Option<&TileData> {
resource.tile_data.as_ref().filter(|_| resource.kind == Kind::Tile)
}
#[derive(Clone, Copy)]
enum Table {
Tiles,
Resources,
}
impl Table {
fn name(self) -> &'static str {
match self {
Table::Tiles => "tiles",
Table::Resources => "resources",
}
}
fn regions(self) -> (&'static str, &'static str) {
match self {
Table::Tiles => ("region_tiles", "tile_id"),
Table::Resources => ("region_resources", "resource_id"),
}
}
}
enum Stored<'a> {
Tile(&'a TileData),
Resource { url: String, kind: i32 },
}
impl<'a> Stored<'a> {
fn of(resource: &'a Resource) -> Self {
match tile_data(resource) {
Some(tile) => Stored::Tile(tile),
None => Stored::Resource { url: OfflineDatabase::cache_key(resource), kind: resource.kind as i32 },
}
}
fn is_tile(&self) -> bool {
matches!(self, Stored::Tile(_))
}
}