Skip to content

Commit

Permalink
run cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
PumPum7 committed Oct 30, 2024
1 parent 9d3e173 commit a7c2e7c
Show file tree
Hide file tree
Showing 11 changed files with 99 additions and 57 deletions.
46 changes: 25 additions & 21 deletions src/bin/client.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use database::protocol::{Command, Response, connection::Connection};
use database::protocol::{connection::Connection, Command, Response};
use database::storage::Value;
use rustyline::completion::Completer;
use rustyline::error::ReadlineError;
use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
use rustyline::hint::Hinter;
use rustyline::validate::{Validator, MatchingBracketValidator};
use rustyline::validate::{MatchingBracketValidator, Validator};
use rustyline::{CompletionType, Config, Editor};
use std::net::TcpStream;

Expand Down Expand Up @@ -86,7 +86,7 @@ impl Client {
fn execute_command(&mut self, input: &str) -> Result<String, Box<dyn std::error::Error>> {
let command = parse_command(input)?;
self.conn.send_command(command)?;

match self.conn.receive_response()? {
Response::Ok => Ok("OK\n".into()),
Response::Value(Some(value)) => Ok(format!("{:?}\n", value)),
Expand All @@ -97,7 +97,7 @@ impl Client {
output.push_str(&format!("{}: {:?}\n", key, value));
}
Ok(output)
},
}
Response::Error(err) => Ok(format!("ERROR: {}\n", err)),
Response::Pong => Ok("PONG\n".into()),
Response::Size(size) => Ok(format!("{}\n", size)),
Expand Down Expand Up @@ -132,8 +132,10 @@ fn parse_command(input: &str) -> Result<Command, Box<dyn std::error::Error>> {
if parts.len() != 2 {
return Err("Usage: GET <key>".into());
}
Ok(Command::Get { key: parts[1].parse()? })
},
Ok(Command::Get {
key: parts[1].parse()?,
})
}
"SET" => {
if parts.len() < 3 {
return Err("Usage: SET <key> <value>".into());
Expand All @@ -143,7 +145,7 @@ fn parse_command(input: &str) -> Result<Command, Box<dyn std::error::Error>> {
key: parts[1].parse()?,
value: parse_value(&value)?,
})
},
}
"UPDATE" => {
if parts.len() < 3 {
return Err("Usage: SET <key> <value>".into());
Expand All @@ -153,20 +155,24 @@ fn parse_command(input: &str) -> Result<Command, Box<dyn std::error::Error>> {
key: parts[1].parse()?,
value: parse_value(&value)?,
})
},
}
"DEL" => {
if parts.len() != 2 {
return Err("Usage: DEL <key>".into());
}
Ok(Command::Delete { key: parts[1].parse()? })
},
Ok(Command::Delete {
key: parts[1].parse()?,
})
}
"ALL" => Ok(Command::All),
"STRLEN" => {
if parts.len() != 2 {
return Err("Usage: STRLEN <key>".into());
}
Ok(Command::Strlen { key: parts[1].parse()? })
},
Ok(Command::Strlen {
key: parts[1].parse()?,
})
}
"STRCAT" => {
if parts.len() < 3 {
return Err("Usage: STRCAT <key> <value>".into());
Expand All @@ -176,7 +182,7 @@ fn parse_command(input: &str) -> Result<Command, Box<dyn std::error::Error>> {
key: parts[1].parse()?,
value: parse_value(&value)?,
})
},
}
"SUBSTR" => {
if parts.len() != 4 {
return Err("Usage: SUBSTR <key> <start> <length>".into());
Expand All @@ -186,7 +192,7 @@ fn parse_command(input: &str) -> Result<Command, Box<dyn std::error::Error>> {
start: parts[2].parse()?,
length: parts[3].parse()?,
})
},
}
"EXIT" => Ok(Command::Exit),
_ => Err("Unknown command".into()),
}
Expand Down Expand Up @@ -272,14 +278,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
continue;
}
"exit" => break,
cmd => {
match client.execute_command(cmd) {
Ok(response) => print!("{}", response),
Err(e) => println!("Error: {}", e),
}
}
cmd => match client.execute_command(cmd) {
Ok(response) => print!("{}", response),
Err(e) => println!("Error: {}", e),
},
}
}

Ok(())
}
}
5 changes: 3 additions & 2 deletions src/index/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ impl BTree {
let mut root_page_id_write = self.root_page_id.write().unwrap();
*root_page_id_write = new_root.page_id;
// Insert into new root

drop(root_page_id_write);
self.insert_non_full(new_root.page_id, key, value, buffer_pool)?;
} else {
Expand Down Expand Up @@ -351,7 +351,8 @@ impl BTree {

pub fn delete(&mut self, key: i32, buffer_pool: &mut BufferPool) -> Result<()> {
let root_page_id = *self.root_page_id.read().unwrap();
self.delete_key(root_page_id, key, buffer_pool).map_err(|_| DatabaseError::KeyNotFound(key))
self.delete_key(root_page_id, key, buffer_pool)
.map_err(|_| DatabaseError::KeyNotFound(key))
}

fn delete_key(&mut self, page_id: u32, key: i32, buffer_pool: &mut BufferPool) -> Result<()> {
Expand Down
2 changes: 1 addition & 1 deletion src/protocol/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::storage::Value;
use serde::{Deserialize, Serialize};

mod tests;
pub mod connection;
mod tests;

#[derive(Debug, Serialize, Deserialize)]
pub enum Command {
Expand Down
16 changes: 13 additions & 3 deletions src/protocol/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(test)]
mod tests {
use crate::protocol::{Command, Response};
use crate::protocol::connection::Connection;
use crate::protocol::{Command, Response};
use crate::Value;
use std::net::{TcpListener, TcpStream};
use std::thread;
Expand Down Expand Up @@ -41,15 +41,25 @@ mod tests {
let mut conn = Connection::new(stream);

let command = conn.receive_command().unwrap();
assert!(matches!(command, Command::Update { key: 1, value: Value::String(_) }));
assert!(matches!(
command,
Command::Update {
key: 1,
value: Value::String(_)
}
));

conn.send_response(Response::Ok).unwrap();
});

let stream = TcpStream::connect(addr).unwrap();
let mut conn = Connection::new(stream);

conn.send_command(Command::Update { key: 1, value: Value::String("Hello, world!".to_string()) }).unwrap();
conn.send_command(Command::Update {
key: 1,
value: Value::String("Hello, world!".to_string()),
})
.unwrap();
let response = conn.receive_response().unwrap();
assert!(matches!(response, Response::Ok));
}
Expand Down
2 changes: 1 addition & 1 deletion src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use protocol::{Command, Response, connection::Connection};
use database::{protocol, Database};
use protocol::{connection::Connection, Command, Response};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use threadpool::ThreadPool;
Expand Down
4 changes: 3 additions & 1 deletion src/storage/disk_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ impl DiskManager {

// Overwrite the page with zeros
let zeros = vec![0u8; PAGE_SIZE];
self.heap_file.write_all(&zeros).map_err(|_| DatabaseError::PageNotFound(page_id))?;
self.heap_file
.write_all(&zeros)
.map_err(|_| DatabaseError::PageNotFound(page_id))?;

// Flush changes to disk
self.heap_file.flush()?;
Expand Down
4 changes: 2 additions & 2 deletions src/storage/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
pub mod buffer_pool;
pub mod disk_manager;
pub mod error;
pub mod operations;
pub mod page;
pub mod slotted_page;
pub mod transaction;
pub mod value;
pub mod wal;
pub mod operations;

mod tests;
pub use value::Value;
pub use wal::{WriteAheadLog, LogRecord};
pub use wal::{LogRecord, WriteAheadLog};

pub use transaction::{Transaction, TransactionManager};

Expand Down
62 changes: 44 additions & 18 deletions src/storage/operations.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use std::sync::{Arc, Mutex};

use super::{Transaction, Value, LogRecord};
use crate::DatabaseError;
use super::{LogRecord, Transaction, Value};
use crate::index::BTree;
use crate::storage::BufferPool;
use crate::DatabaseError;

pub fn insert(
txn: &mut Transaction,
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32,
value: &Value
value: &Value,
) -> Result<(), Box<dyn std::error::Error>> {
let mut btree = btree.lock().unwrap();
match btree.insert(key, value.clone(), buffer_pool) {
Expand All @@ -24,7 +24,7 @@ pub fn insert(
})?;
}
Ok(())
},
}
Err(e) => {
eprintln!("Error inserting key {}: {}", key, e);
Err(Box::new(e))
Expand All @@ -36,7 +36,7 @@ pub fn delete(
txn: &mut Transaction,
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32
key: i32,
) -> Result<(), Box<dyn std::error::Error>> {
let mut btree = btree.lock().unwrap();
match btree.delete(key, buffer_pool) {
Expand All @@ -50,7 +50,7 @@ pub fn delete(
})?;
}
Ok(())
},
}
Err(e) => {
eprintln!("Error deleting key {}: {}", key, e);
Err(Box::new(e))
Expand All @@ -61,7 +61,7 @@ pub fn delete(
pub fn get(
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32
key: i32,
) -> Result<Option<Value>, Box<dyn std::error::Error>> {
let btree = btree.lock().unwrap();
match btree.search(key, buffer_pool) {
Expand All @@ -78,7 +78,7 @@ pub fn update(
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32,
value: &Value
value: &Value,
) -> Result<(), Box<dyn std::error::Error>> {
let mut btree = btree.lock().unwrap();
match btree.update(key, value.clone(), buffer_pool) {
Expand All @@ -92,48 +92,74 @@ pub fn update(
})?;
}
Ok(())
},
}
Err(e) => {
eprintln!("Error updating key {}: {}", key, e);
Err(Box::new(e))
}
}
}
}

pub fn all(btree: &Arc<Mutex<BTree>>, buffer_pool: &mut BufferPool) -> Result<Vec<(i32, Value)>, Box<dyn std::error::Error>> {
pub fn all(
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
) -> Result<Vec<(i32, Value)>, Box<dyn std::error::Error>> {
let btree = btree.lock().unwrap();
btree.all(buffer_pool).map_err(|e| e.into())
}

pub fn strlen(btree: &Arc<Mutex<BTree>>, buffer_pool: &mut BufferPool, key: i32) -> Result<Option<usize>, Box<dyn std::error::Error>> {
pub fn strlen(
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32,
) -> Result<Option<usize>, Box<dyn std::error::Error>> {
let btree = btree.lock().unwrap();
match btree.search(key, buffer_pool) {
Ok(Some(value)) => Ok(Some(value.to_string().len())),
_ => Err(DatabaseError::KeyNotFound(key).into()),
}
}

pub fn strcat(txn: &mut Transaction, btree: &Arc<Mutex<BTree>>, buffer_pool: &mut BufferPool, key: i32, value: &Value) -> Result<(), Box<dyn std::error::Error>> {
pub fn strcat(
txn: &mut Transaction,
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32,
value: &Value,
) -> Result<(), Box<dyn std::error::Error>> {
let btree_unlocked = btree.lock().unwrap();
match btree_unlocked.search(key, buffer_pool) {
Ok(Some(old_value)) => {
let concatenated = old_value.add(value)?;
update(txn, btree, buffer_pool, key, &concatenated)?;
Ok(())
},
}
_ => Err(DatabaseError::KeyNotFound(key).into()),
}
}

pub fn substr(txn: &mut Transaction, btree: &Arc<Mutex<BTree>>, buffer_pool: &mut BufferPool, key: i32, start: usize, length: usize) -> Result<(), Box<dyn std::error::Error>> {
pub fn substr(
txn: &mut Transaction,
btree: &Arc<Mutex<BTree>>,
buffer_pool: &mut BufferPool,
key: i32,
start: usize,
length: usize,
) -> Result<(), Box<dyn std::error::Error>> {
let btree_unlocked = btree.lock().unwrap();
match btree_unlocked.search(key, buffer_pool) {
Ok(Some(value)) => {
let substr = value.to_string();
let substr = substr.get(start..start + length).unwrap_or("");
update(txn, btree, buffer_pool, key, &Value::String(substr.to_string()))?;
update(
txn,
btree,
buffer_pool,
key,
&Value::String(substr.to_string()),
)?;
Ok(())
},
}
_ => Err(DatabaseError::KeyNotFound(key).into()),
}
}
}
1 change: 0 additions & 1 deletion src/storage/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ pub struct Transaction {
pub wal: Option<Arc<Mutex<WriteAheadLog>>>,
}


pub struct TransactionManager {
next_txn_id: AtomicU64,
active_txns: Mutex<Vec<TransactionId>>,
Expand Down
Loading

0 comments on commit a7c2e7c

Please sign in to comment.