use crate::error::{Error, Result};
use rocksdb::{Options, DB};
use std::time::Duration;
pub trait OptionsExt {
fn set_ttl(&mut self, ttl: Duration) -> &mut Self;
fn disable_ttl(&mut self) -> &mut Self;
}
impl OptionsExt for Options {
fn set_ttl(&mut self, _ttl: Duration) -> &mut Self {
self
}
fn disable_ttl(&mut self) -> &mut Self {
self
}
}
pub mod ttl_utils {
use super::*;
use std::path::Path;
pub fn open_db_with_ttl<P: AsRef<Path>>(path: P, ttl: Duration) -> Result<DB> {
let mut options = Options::default();
options.create_if_missing(true);
options.create_missing_column_families(true);
options.set_ttl(ttl);
DB::open(&options, path).map_err(Error::from)
}
pub fn create_cf_with_ttl(db: &mut DB, name: &str, ttl: Duration) -> Result<()> {
let mut options = Options::default();
options.set_ttl(ttl);
db.create_cf(name, &options).map_err(Error::from)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn test_ttl_expiration() {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let path = temp_dir.path();
let ttl = Duration::from_secs(2);
let db = ttl_utils::open_db_with_ttl(path, ttl).unwrap();
db.put(b"test_key", b"test_value").unwrap();
let value = db.get(b"test_key").unwrap().unwrap();
assert_eq!(value, b"test_value");
let value_after = db.get(b"test_key").unwrap();
assert!(
value_after.is_some(),
"Key should still exist in placeholder implementation"
);
}
}