webcomment/server/src/db.rs
2023-07-13 11:36:31 +02:00

71 lines
1.8 KiB
Rust

use webcomment_common::types::*;
use std::{net::IpAddr, path::Path};
pub use sled::transaction::{
ConflictableTransactionError, ConflictableTransactionResult, TransactionError,
};
pub use typed_sled::Tree;
const DB_DIR: &str = "db";
#[derive(Clone)]
pub struct Dbs {
pub comment: Tree<CommentId, (Comment, CommentStatus)>,
pub comment_approved: Tree<(TopicHash, Time, CommentId), ()>,
/// -> (client_addr, is_edit)
pub comment_pending: Tree<(TopicHash, Time, CommentId), (Option<IpAddr>, bool)>,
/// client_addr -> (last_mutation, mutation_count)
pub client_mutation: Tree<IpAddr, (Time, u32)>,
}
pub fn load_dbs(path: Option<&Path>) -> Dbs {
let db = sled::Config::new();
let db = if let Some(path) = path {
db.path(path.join(DB_DIR))
} else {
db.temporary(true)
}
.open()
.expect("Cannot open db");
Dbs {
comment: Tree::open(&db, "comment"),
comment_approved: Tree::open(&db, "comment_approved"),
comment_pending: Tree::open(&db, "comment_pending"),
client_mutation: Tree::open(&db, "client_mutation"),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_typed_sled() {
let db = sled::Config::new().temporary(true).open().unwrap();
let tree = typed_sled::Tree::<(u32, u32), ()>::open(&db, "test");
tree.insert(&(123, 456), &()).unwrap();
tree.flush().unwrap();
let mut iter = tree.range((123, 0)..(124, 0));
//let mut iter = tree.iter();
assert_eq!(iter.next(), Some(Ok(((123, 456), ()))));
}
#[test]
fn test_comment_id_base64() {
for _ in 0..10 {
let comment_id = CommentId::new();
assert_eq!(
CommentId::from_base64(&comment_id.to_base64()),
Ok(comment_id)
);
}
}
#[test]
fn test_from_base64_dont_panic() {
assert_eq!(CommentId::from_base64("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), Err(base64::DecodeError::InvalidLength));
}
}