use crate::error::Result;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode},
SqlitePool,
};
use std::path::PathBuf;
pub fn get_file() -> PathBuf {
crate::path::get_home().join(".script_info.db")
}
pub async fn get_pool(need_journal: &mut bool) -> Result<(SqlitePool, bool)> {
let file = get_file();
if !file.exists() {
*need_journal = true;
let pool = crate::migration::do_migrate(file).await?;
return Ok((pool, true));
}
let mut opt = SqliteConnectOptions::new().filename(&file);
if !*need_journal {
opt = opt.journal_mode(SqliteJournalMode::Off);
}
let res = SqlitePool::connect_with(opt).await;
let pool = match res {
Err(err) => {
log::warn!("資料庫錯誤 {},嘗試用 journal 再開一次", err);
*need_journal = true;
let opt = SqliteConnectOptions::new().filename(&file);
SqlitePool::connect_with(opt).await?
}
Ok(pool) => pool,
};
Ok((pool, false))
}