spacejam/sled

contains_key returns true even if key does not exist.

vsabavat opened this issue · 3 comments

I tried to prototype with sled db and the contains_key API always returns true even though the key does not exist.

use random_string::generate;
use sled;

static ENCODE_CHARSET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

struct SledCli {
    db: sled::Db,
}

impl SledCli {
    fn new(db: sled::Db) -> Self {
        SledCli { db }
    }
    fn contains_key(&self, key: &str) -> bool {
        match self.db.contains_key(key) {
           Err(e) => false,
           Ok(v) => true,
        }
    }
    fn put(&self, key: &str, value: &str) -> bool {
        match self.db.insert(key, value) {
            Ok(_) => true,
            Err(e) => {
                println!("Failed to insert {} err {:?}", key, e);
                false
            }
        }
    }
    fn get(&self, key: &str) -> Option<String> {
        match self.db.get(key) {
            Err(e) => {
                println!("Cannot find the tiny_url {} err {:?}", key, e);
                None
            }
            Ok(v) => {
                if let Some(url) = v {
                    match String::from_utf8(url.to_vec()) {
                        Ok(value) => Some(value),
                        Err(e) => {
                            println!("Unable to decode utf8 string {:?}", e);
                            None
                        }
                    }
                } else {
                    None
                }
            }
        }
    }
}
fn main() {
    println!("Hello, world!");
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_sled() {
        let db = sled::open("test_db").unwrap();
        let sled_cli = SledCli::new(db);
        for _ in 0..10 {
            let url = generate(200, ENCODE_CHARSET);
            let tiny_url = generate(6, ENCODE_CHARSET);
            sled_cli.put(&tiny_url, &url);
            assert!(sled_cli.contains_key(&tiny_url));
            let found = sled_cli.get(&tiny_url).unwrap();
            assert_eq!(url, found);
            let tiny_url = generate(6, ENCODE_CHARSET);
            assert!(!sled_cli.contains_key(&tiny_url), false);
        }
    }
}

db.contains_key(key)

fn contains_key(&self, key: &str) -> bool {
        match self.db.contains_key(key) {
           Err(e) => false,
           Ok(v) => v,
        }
    }

Sorry, you can change that to match the actual API, it will still return true for both cases. whether key exists or does not exist. I tried to simplify code that I copied here and I forgot to change it for match. I am using .get() to be able to determine if key exists or not.

fn contains_key(&self, key: &str) -> bool {
        match self.db.contains_key(key) {
           Err(e) => false,
           Ok(v) => v, // attention here 
        }
    }