Skip to content

Commit

Permalink
Refactor database adapter methods
Browse files Browse the repository at this point in the history
Standardized handling of database results in MySQL and Postgres adapters by using `and_then` instead of a combination of `map` and `flatten`. Shifted position of `clear` method in InMemory adapter for consistency. Also, removed unnecessary reference in Postgres adapter's delete query binding.
  • Loading branch information
chrisllontop committed Apr 18, 2024
1 parent 06dae11 commit 25ff41e
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 11 deletions.
12 changes: 6 additions & 6 deletions src/store/adapter/inmemory/inmemory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,17 @@ impl Store for InMemoryStore {
Ok(())
}

async fn clear(&self) -> Result<(), StoreError> {
let mut db_lock = self.db.lock().await;
db_lock.clear();
Ok(())
}

async fn remove_many(&self, keys: &[&str]) -> Result<(), StoreError> {
let mut db_lock = self.db.lock().await;
for key in keys {
db_lock.remove(&key.to_string());
}
Ok(())
}

async fn clear(&self) -> Result<(), StoreError> {
let mut db_lock = self.db.lock().await;
db_lock.clear();
Ok(())
}
}
3 changes: 1 addition & 2 deletions src/store/adapter/mysql/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ impl Store for MySqlStore {
.map_err(|_| StoreError::QueryError("Failed to fetch the value".to_string()))?;

Ok(result
.map(|row| serde_json::from_str(row.get("value")).ok())
.flatten())
.and_then(|row| serde_json::from_str(row.get("value")).ok()))
}

async fn set(&self, key: &str, value: Value, ttl: Option<u64>) -> Result<(), StoreError> {
Expand Down
5 changes: 2 additions & 3 deletions src/store/adapter/postgres/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ impl Store for PostgresStore {
.map_err(|_| StoreError::QueryError("Failed to fetch the value".to_string()))?;

Ok(result
.map(|row| serde_json::from_str(row.get("value")).ok())
.flatten())
.and_then(|row| serde_json::from_str(row.get("value")).ok()))
}

async fn set(&self, key: &str, value: Value, ttl: Option<u64>) -> Result<(), StoreError> {
Expand Down Expand Up @@ -105,7 +104,7 @@ impl Store for PostgresStore {
let query = format!("DELETE FROM {} WHERE key = ANY($1)", self.get_table_name());

sqlx::query(&query)
.bind(&keys)
.bind(keys)
.execute(&*self.pool)
.await
.map_err(|_| StoreError::QueryError("Failed to remove the keys".to_string()))?;
Expand Down

0 comments on commit 25ff41e

Please sign in to comment.