Skip to main content

fjall_cli/command/keyspace_command/
contains_command.rs

1use crate::{ByteEncoding, ByteEncodingDecodeError};
2use errgonomic::{handle, handle_bool};
3use fjall::{Database, KeyspaceCreateOptions};
4use std::process::ExitCode;
5use thiserror::Error;
6
7#[derive(clap::Parser, Clone, Debug)]
8#[command(long_about = "Exit codes: 0 = key exists, 127 = key not found, 1 = error.")]
9pub struct ContainsCommand {
10    #[arg(value_name = "KEY")]
11    key: String,
12
13    #[arg(long, value_enum, default_value_t = ByteEncoding::String)]
14    key_encoding: ByteEncoding,
15}
16
17impl ContainsCommand {
18    pub async fn run(self, db: &Database, keyspace: impl Into<String>) -> Result<ExitCode, ContainsCommandRunError> {
19        use ContainsCommandRunError::*;
20        let keyspace = keyspace.into();
21        let Self {
22            key,
23            key_encoding,
24        } = self;
25        let key_bytes = handle!(key_encoding.decode(&key), DecodeKeyBytesFailed, key, key_encoding);
26        handle_bool!(!db.keyspace_exists(&keyspace), KeyspaceNotFound, keyspace);
27        let keyspace_handle = handle!(db.keyspace(&keyspace, KeyspaceCreateOptions::default), KeyspaceFailed, keyspace);
28        let exists = handle!(keyspace_handle.contains_key(&key_bytes), ContainsKeyFailed, keyspace);
29        let exit_code = if exists { ExitCode::SUCCESS } else { ExitCode::from(127) };
30        Ok(exit_code)
31    }
32}
33
34#[derive(Error, Debug)]
35pub enum ContainsCommandRunError {
36    #[error("failed to decode key '{key}' with encoding '{key_encoding}'")]
37    DecodeKeyBytesFailed { source: ByteEncodingDecodeError, key: String, key_encoding: ByteEncoding },
38
39    #[error("keyspace '{keyspace}' not found")]
40    KeyspaceNotFound { keyspace: String },
41
42    #[error("failed to open keyspace '{keyspace}'")]
43    KeyspaceFailed { source: fjall::Error, keyspace: String },
44
45    #[error("failed to check key presence in keyspace '{keyspace}'")]
46    ContainsKeyFailed { source: fjall::Error, keyspace: String },
47}