Skip to content

Commit

Permalink
update naming and imports
Browse files Browse the repository at this point in the history
  • Loading branch information
giuseppe-g-gelardi committed Dec 13, 2024
1 parent a403dff commit 2c1f2ab
Show file tree
Hide file tree
Showing 6 changed files with 250 additions and 252 deletions.
80 changes: 40 additions & 40 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ use tracing;
use crate::{query::Operation, DatabaseError, Query, Table, View};

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct DatabaseAsync {
pub struct Database {
pub(crate) name: String,
pub(crate) file_name: String,
pub(crate) tables: Vec<Table>,
}

impl DatabaseAsync {
pub async fn new_async(name: &str) -> Self {
impl Database {
pub async fn new(name: &str) -> Self {
let name = name.to_string();
let file_name = format!("{name}.json");

if tokio::fs::metadata(&file_name).await.is_ok() {
tracing::info!("Database already exists: {name}, loading database");

// Load the database from the file
match DatabaseAsync::load_from_file_async(&file_name).await {
match Database::load_from_file(&file_name).await {
Ok(db) => return db,
Err(e) => {
tracing::error!("Failed to load database from file: {file_name}, error: {e}");
Expand All @@ -33,14 +33,14 @@ impl DatabaseAsync {
}
}

DatabaseAsync {
Database {
name,
file_name,
tables: Vec::new(),
}
}

pub async fn drop_database_async(&self) -> Result<(), DatabaseError> {
pub async fn drop_database(&self) -> Result<(), DatabaseError> {
if tokio::fs::remove_file(&self.file_name).await.is_err() {
tracing::error!(
"{}",
Expand All @@ -52,7 +52,7 @@ impl DatabaseAsync {
Ok(())
}

pub async fn add_table_async(&mut self, table: &mut Table) -> Result<(), DatabaseError> {
pub async fn add_table(&mut self, table: &mut Table) -> Result<(), DatabaseError> {
if self.tables.iter().any(|t| t.name == table.name) {
tracing::warn!(
"{}",
Expand All @@ -62,21 +62,21 @@ impl DatabaseAsync {
}

self.tables.push(table.clone());
self.save_to_file_async()
self.save_to_file()
.await
.map_err(|e| DatabaseError::SaveError(e))?;
Ok(())
}

pub async fn drop_table_async(&mut self, table_name: &str) -> Result<(), DatabaseError> {
let mut db = DatabaseAsync::load_from_file_async(&self.file_name)
pub async fn drop_table(&mut self, table_name: &str) -> Result<(), DatabaseError> {
let mut db = Database::load_from_file(&self.file_name)
.await
.map_err(|e| DatabaseError::LoadError(e))?;

if let Some(index) = db.tables.iter().position(|t| t.name == table_name) {
let removed_table = db.tables.remove(index);
tracing::info!("Table `{}` dropped successfully", removed_table.name);
db.save_to_file_async()
db.save_to_file()
.await
.map_err(|e| DatabaseError::SaveError(e))?;

Expand All @@ -88,16 +88,16 @@ impl DatabaseAsync {
}
}

pub(crate) async fn save_to_file_async(&self) -> Result<(), tokio::io::Error> {
pub(crate) async fn save_to_file(&self) -> Result<(), tokio::io::Error> {
let json_data = serde_json::to_string_pretty(&self)?;
tokio::fs::write(&self.file_name, json_data).await?;
tracing::info!("Database saved to file: {}", self.file_name);
Ok(())
}

pub(crate) async fn load_from_file_async(file_name: &str) -> Result<Self, tokio::io::Error> {
pub(crate) async fn load_from_file(file_name: &str) -> Result<Self, tokio::io::Error> {
let json_data = tokio::fs::read_to_string(file_name).await?;
let db: DatabaseAsync = serde_json::from_str(&json_data)?;
let db: Database = serde_json::from_str(&json_data)?;
tracing::info!("Database loaded from file: {}", file_name);
Ok(db)
}
Expand Down Expand Up @@ -172,7 +172,7 @@ mod tests {
use tracing_test::traced_test;

use super::*;
use crate::{setup_temp_db_async, Columns, Table};
use crate::{setup_temp_db, Columns, Table};

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)]
struct TestData {
Expand All @@ -181,8 +181,8 @@ mod tests {
}

#[tokio::test]
async fn test_database_new_async() {
let db = setup_temp_db_async().await;
async fn test_database_new() {
let db = setup_temp_db().await;

let db_name = &db.name.to_string();
let fnn = format!("{db_name}.json");
Expand All @@ -193,24 +193,24 @@ mod tests {
}

#[tokio::test]
async fn test_drop_database_async() {
let db = setup_temp_db_async().await;
let result = db.drop_database_async().await;
async fn test_drop_database() {
let db = setup_temp_db().await;
let result = db.drop_database().await;

assert!(result.is_ok());
assert!(!std::path::Path::new(&db.file_name).exists());
}

#[tokio::test]
async fn test_add_table_success_async() {
async fn test_add_table_success() {
// this test does not use the setup_temp_db function
// because it needs to test the creation of a new database and table
tokio::fs::remove_file("test_db.json").await.ok();
let mut db = DatabaseAsync::new_async("test_db").await;
let mut db = Database::new("test_db").await;
let test_columns = Columns::from_struct::<TestData>(true);
let mut test_table = Table::new("TestTable".to_string(), test_columns);

let result = db.add_table_async(&mut test_table).await;
let result = db.add_table(&mut test_table).await;

assert!(result.is_ok());
assert_eq!(db.tables.len(), 1);
Expand All @@ -221,13 +221,13 @@ mod tests {

#[traced_test]
#[tokio::test]
async fn test_add_table_already_exists_async() {
let mut db = setup_temp_db_async().await;
async fn test_add_table_already_exists() {
let mut db = setup_temp_db().await;

// Create a duplicate table
let columns = Columns::from_struct::<TestData>(true);
let mut duplicate_table = Table::new("TestTable".to_string(), columns);
let result = db.add_table_async(&mut duplicate_table).await;
let result = db.add_table(&mut duplicate_table).await;

// Assert that the result is Ok(()) even when the table already exists
assert!(result.is_ok());
Expand All @@ -241,19 +241,19 @@ mod tests {
}

#[tokio::test]
async fn test_drop_table_success_async() {
let mut db = setup_temp_db_async().await;
let result = db.drop_table_async("TestTable").await;
async fn test_drop_table_success() {
let mut db = setup_temp_db().await;
let result = db.drop_table("TestTable").await;

assert!(result.is_ok());
assert_eq!(db.tables.len(), 0);
}

#[traced_test]
#[tokio::test]
async fn test_drop_table_not_found_async() {
let mut db = setup_temp_db_async().await;
let result = db.drop_table_async("NonExistentTable").await;
async fn test_drop_table_not_found() {
let mut db = setup_temp_db().await;
let result = db.drop_table("NonExistentTable").await;

assert!(result.is_ok());

Expand All @@ -267,45 +267,45 @@ mod tests {
}

#[tokio::test]
async fn test_save_to_file_async() {
async fn test_save_to_file() {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();

let db = DatabaseAsync {
let db = Database {
name: "test_db".to_string(),
file_name: db_path.clone(),
tables: vec![],
};

db.save_to_file_async()
db.save_to_file()
.await
.expect("Failed to save database");
let loaded_db = DatabaseAsync::load_from_file_async(&db_path)
let loaded_db = Database::load_from_file(&db_path)
.await
.expect("Failed to load database");
assert_eq!(db, loaded_db);
}

#[tokio::test]
async fn test_load_from_file_async() {
async fn test_load_from_file() {
use tempfile::NamedTempFile;

let temp_file = NamedTempFile::new().expect("Failed to create a temporary file");
let db_path = temp_file.path().to_str().unwrap().to_string();

let db = DatabaseAsync {
let db = Database {
name: "test_db".to_string(),
file_name: db_path.to_string(),
tables: vec![],
};

db.save_to_file_async()
db.save_to_file()
.await
.expect("Failed to save database");

let loaded_db = DatabaseAsync::load_from_file_async(&db_path)
let loaded_db = Database::load_from_file(&db_path)
.await
.expect("Failed to load database");

Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ pub use columns::{Column, Columns};
pub use errors::DatabaseError;
pub use row::Row;

pub use database::DatabaseAsync;
pub use database::Database;
pub use query::Query;
pub use table::Table;
pub use util::setup_temp_db_async;
pub use util::setup_temp_db;
pub use view::View;
Loading

0 comments on commit 2c1f2ab

Please sign in to comment.