This commit is contained in:
2022-09-18 08:26:41 +00:00
committed by GitHub
parent 4d587b459e
commit 7670d13405
2 changed files with 40 additions and 7 deletions

View File

@@ -2,30 +2,56 @@ use super::super::{
PixivDownloaderDb, PixivDownloaderDbConfig, PixivDownloaderDbError, PixivDownloaderSqliteConfig,
};
use super::SqliteError;
use rusqlite::{Connection, OpenFlags};
use std::sync::Mutex;
use futures_util::lock::Mutex;
use rusqlite::{Connection, OpenFlags, OptionalExtension};
use std::collections::HashMap;
const TAGS_TABLE: &'static str = "CREATE TABLE tags (
id INT,
name TEXT,
PRIMARY KEY (id)
);";
const VERSION_TABLE: &'static str = "CREATE TABLE version (
id TEXT,
v1 INT,
v2 INT,
v3 INT,
v4 INT,
PRIMARY KEY (id)
);";
const VERSION: [u8; 4] = [1, 0, 0, 0];
pub struct PixivDownloaderSqlite {
db: Mutex<Connection>,
}
impl PixivDownloaderSqlite {
/// Get all exists tables
async fn _get_exists_table(&self) -> Result<HashMap<String, ()>, SqliteError> {
let con = self.db.lock().await;
let mut tables = HashMap::new();
let mut stmt = con.prepare("SELECT name FROM main.sqlite_master WHERE type='table';")?;
let mut rows = stmt.query([])?;
while let Some(row) = rows.next()? {
tables.insert(row.get(0)?, ());
}
Ok(tables)
}
fn _new(cfg: &PixivDownloaderSqliteConfig) -> Result<Self, SqliteError> {
let con = Connection::open_with_flags(
let db = Connection::open_with_flags(
&cfg.path,
OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_FULL_MUTEX
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_URI,
)?;
Ok(Self {
db: Mutex::new(con),
})
Ok(Self { db: Mutex::new(db) })
}
}
#[async_trait]
impl PixivDownloaderDb for PixivDownloaderSqlite {
#[allow(unreachable_patterns)]
fn new<R: AsRef<PixivDownloaderDbConfig> + ?Sized>(
cfg: &R,
) -> Result<Self, PixivDownloaderDbError> {
@@ -37,4 +63,8 @@ impl PixivDownloaderDb for PixivDownloaderSqlite {
_ => panic!("Config mismatched."),
}
}
async fn init(&self) -> Result<(), PixivDownloaderDbError> {
Ok(())
}
}

View File

@@ -1,6 +1,7 @@
use super::PixivDownloaderDbConfig;
use super::PixivDownloaderDbError;
#[async_trait]
pub trait PixivDownloaderDb {
/// Create a new instance of database
fn new<R: AsRef<PixivDownloaderDbConfig> + ?Sized>(
@@ -8,4 +9,6 @@ pub trait PixivDownloaderDb {
) -> Result<Self, PixivDownloaderDbError>
where
Self: Sized + Send + Sync;
/// Initialize the database (create tables, migrate data, etc.)
async fn init(&self) -> Result<(), PixivDownloaderDbError>;
}