use std::fmt;
use std::time::Duration;
use surrealdb_kvs::config::{AolMode, SnapshotMode};
use crate::engine::local::Db;
use crate::{Connect, Error};
fn format_duration(d: Duration) -> String {
let micros = d.as_micros() as u64;
if micros == 0 {
return "0".to_string();
}
let secs = d.as_secs();
if secs > 0 && secs.is_multiple_of(86400) && d.subsec_nanos() == 0 {
return format!("{}d", secs / 86400);
}
if secs > 0 && secs.is_multiple_of(3600) && d.subsec_nanos() == 0 {
return format!("{}h", secs / 3600);
}
if secs > 0 && secs.is_multiple_of(60) && d.subsec_nanos() == 0 {
return format!("{}m", secs / 60);
}
if d.subsec_nanos() == 0 {
return format!("{secs}s");
}
if micros.is_multiple_of(1000) {
return format!("{}ms", micros / 1000);
}
format!("{micros}us")
}
impl<R> Connect<Db, R> {
pub fn versioned(mut self) -> Self {
self.address = self.address.map(|mut endpoint| {
endpoint.append_query_param("versioned", "true");
endpoint
});
self
}
pub fn retention(mut self, duration: Duration) -> Self {
self.address = self.address.map(|mut endpoint| {
endpoint.append_query_param("retention", &format_duration(duration));
endpoint
});
self
}
pub fn sync(mut self, mode: impl fmt::Display) -> Self {
self.address = self.address.map(|mut endpoint| {
endpoint.append_query_param("sync", &mode.to_string());
endpoint
});
self
}
pub fn aol(mut self, mode: AolMode) -> Self {
self.address = self.address.and_then(|mut endpoint| match endpoint.url.scheme() {
"mem" => {
endpoint.append_query_param("aol", &mode.to_string());
Ok(endpoint)
}
scheme => Err(Error::internal(format!(
"The 'aol' option is only supported by the 'mem' engine, not '{scheme}'"
))),
});
self
}
pub fn snapshot(mut self, mode: SnapshotMode) -> Self {
self.address = self.address.and_then(|mut endpoint| match endpoint.url.scheme() {
"mem" => {
endpoint.append_query_param("snapshot", &mode.to_string());
Ok(endpoint)
}
scheme => Err(Error::internal(format!(
"The 'snapshot' option is only supported by the 'mem' engine, not '{scheme}'"
))),
});
self
}
}