Skip to content

Commit

Permalink
Update review idea
Browse files Browse the repository at this point in the history
Signed-off-by: Manjusaka <[email protected]>
  • Loading branch information
Zheaoli committed Sep 29, 2023
1 parent da12c5a commit 196c09f
Showing 1 changed file with 43 additions and 29 deletions.
72 changes: 43 additions & 29 deletions core/src/services/sqlite/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use std::fmt::Formatter;

use async_trait::async_trait;
use rusqlite::{params, Connection};
use tokio::task;

use crate::raw::adapters::kv;
use crate::raw::*;
Expand Down Expand Up @@ -56,12 +57,11 @@ impl SqliteBuilder {
///
/// ## Url
///
/// This format resembles the url format of the sqlite client. The format is: [scheme://][user[:[password]]@]host[:port][/schema][?attribute1=value1&attribute2=value2...
/// This format resembles the url format of the sqlite client. The format is: file://[path]?flag
///
/// - `file://data.db`
///
/// For more information, please refer to [Opening A New Database Connection](http://www.sqlite.org/c3ref/open.html)
///
pub fn connection_string(&mut self, v: &str) -> &mut Self {
if !v.is_empty() {
self.connection_string = Some(v.to_string());
Expand Down Expand Up @@ -204,54 +204,68 @@ impl kv::Adapter for Adapter {
}

async fn get(&self, path: &str) -> Result<Option<Vec<u8>>> {
task::spawn_blocking(move || {
self.blocking_get(path);
})
.await
.unwrap();
}

fn blocking_get(&self, path: &str) -> Result<Option<Vec<u8>>> {
let query = format!(
"SELECT {} FROM {} WHERE `{}` = $1 LIMIT 1",
self.value_field, self.table, self.key_field
);
let conn = Connection::open(self.connection_string.clone()).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite open error").set_source(err)
})?;
let mut statement = conn.prepare(&query).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite prepared query error").set_source(err)
})?;
let conn = Connection::open(self.connection_string.clone()).map_err(|err| Error::from)?;
let mut statement = conn.prepare(&query).map_err(|err| Error::from)?;
let result = statement.query_row(&[path], |row| Ok(row.get(0)?));
match result {
Ok(v) => Ok(Some(v)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(err) => {
Err(Error::new(ErrorKind::Unexpected, "Sqlite query error").set_source(err))
}
Err(err) => Error::from,
}
}

async fn set(&self, path: &str, value: &[u8]) -> Result<()> {
task::spawn_blocking(move || {
self.blocking_set(path, value);
})
.await
.unwrap();
}

fn blocking_set(&self, path: &str, value: &[u8]) -> Result<()> {
let query = format!(
"INSERT OR REPLACE INTO `{}` (`{}`, `{}`) VALUES ($1, $2)",
self.table, self.key_field, self.value_field
);
let conn = Connection::open(self.connection_string.clone()).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite open error").set_source(err)
})?;
let mut statement = conn.prepare(&query).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite prepared query error").set_source(err)
})?;
statement.execute(params![path, value]).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite qupdate error").set_source(err)
})?;
let conn = Connection::open(self.connection_string.clone()).map_err(|err| Error::from)?;
let mut statement = conn.prepare(&query).map_err(|err| Error::from)?;
statement
.execute(params![path, value])
.map_err(|err| Error::from)?;
Ok(())
}

async fn delete(&self, path: &str) -> Result<()> {
let conn = Connection::open(self.connection_string.clone()).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite open error").set_source(err)
})?;
task::spawn_blocking(move || {
self.blocking_delete(path);
})
.await
.unwrap();
}

fn blocking_delete(&self, path: &str) -> Result<()> {
let conn = Connection::open(self.connection_string.clone()).map_err(|err| Error::from)?;
let query = format!("DELETE FROM {} WHERE `{}` = $1", self.table, self.key_field);
let mut statement = conn.prepare(&query).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite prepared error").set_source(err)
})?;
statement.execute(&[path]).map_err(|err| {
Error::new(ErrorKind::Unexpected, "Sqlite delete error").set_source(err)
})?;
let mut statement = conn.prepare(&query).map_err(|err| Error::from)?;
statement.execute(&[path]).map_err(|err| Error::from)?;
Ok(())
}
}

impl From<rusqlite::Error> for Error {
fn from(err: rusqlite::Error) -> Self {
Error::new(ErrorKind::Unexpected, "Sqlite error").set_source(err)
}
}

0 comments on commit 196c09f

Please sign in to comment.