persist command

This commit is contained in:
2025-06-17 21:11:09 +02:00
parent c51c90b597
commit 0a9c8f81aa
5 changed files with 106 additions and 3 deletions

View File

@@ -2,6 +2,7 @@ mod delete;
mod expire;
mod get;
mod has;
mod persist;
mod set;
mod ttl;
@@ -12,6 +13,7 @@ use delete::Delete;
use expire::Expire;
use get::Get;
use has::Has;
use persist::Persist;
use set::Set;
use ttl::Ttl;
@@ -25,6 +27,7 @@ pub enum Command {
Has(Has),
Ttl(Ttl),
Expire(Expire),
Persist(Persist),
}
impl Command {
@@ -36,6 +39,7 @@ impl Command {
Command::Has(has) => has.execute(db, connection).await,
Command::Ttl(ttl) => ttl.execute(db, connection).await,
Command::Expire(expire) => expire.execute(db, connection).await,
Command::Persist(persist) => persist.execute(db, connection).await,
}
}
@@ -61,6 +65,7 @@ impl Command {
"has" => Self::Has(Has::parse(bytes)?),
"ttl" => Self::Ttl(Ttl::parse(bytes)?),
"expire" => Self::Expire(Expire::parse(bytes)?),
"persist" => Self::Persist(Persist::parse(bytes)?),
_ => return Err(AppError::UnknownCommand(command_name)),
};

34
src/commands/persist.rs Normal file
View File

@@ -0,0 +1,34 @@
use std::io::Cursor;
use bytes::{Buf as _, Bytes};
use crate::{Result, connection::Connection, database::Database, errors::AppError};
#[derive(Debug, Clone)]
pub struct Persist {
key: String,
}
impl Persist {
pub async fn execute(self, db: &Database, connection: &mut Connection) -> Result<()> {
let value = db.persist(&self.key).await?;
connection
.write(Bytes::from_static(if value { &[1] } else { &[0] }))
.await?;
Ok(())
}
pub fn parse(bytes: &mut Cursor<&[u8]>) -> Result<Self> {
let key_length = bytes.try_get_u16()? as usize;
if bytes.remaining() < key_length {
return Err(AppError::IncompleteCommandBuffer);
}
let key = String::from_utf8(bytes.copy_to_bytes(key_length).to_vec())?;
Ok(Self { key })
}
}