//
// Copyright (c) 2025-2026 rustmailer.com (https://rustmailer.com)
//
// This file is part of the Bichon Email Archiving Project
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
use crate::common::paginated::Paginated;
use crate::error::code::ErrorCode;
use crate::error::BichonResult;
use crate::raise_error;
use bichon_memdb::{MemDb, Transaction};
use serde::de::DeserializeOwned;
use serde::Serialize;
pub mod manager;
/// Trait for models that can be stored in MemDb collections.
pub trait MemDbModel: Serialize + DeserializeOwned + Clone + Send + 'static {
/// The collection name this model is stored under.
fn collection() -> &'static str;
/// The primary key as a string for MemDb storage.
fn key(&self) -> String;
}
// ─── Insert ───────────────────────────────────────────────────────────────
pub fn insert_impl(db: &MemDb, item: M) -> BichonResult<()> {
let coll = db.collection(M::collection());
let key = item.key();
coll.insert(key, &item)
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))
}
pub fn batch_insert_impl(db: &MemDb, items: Vec) -> BichonResult<()> {
let txn = db.transaction();
let mut txn = txn;
for item in &items {
txn = txn
.insert(M::collection(), item.key(), item)
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))?;
}
txn.commit()
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))
}
// ─── Upsert ────────────────────────────────────────────────────────────────
pub fn upsert_impl(db: &MemDb, item: M) -> BichonResult<()> {
let coll = db.collection(M::collection());
coll.upsert(item.key(), &item)
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))
}
pub fn batch_upsert_impl(db: &MemDb, items: Vec) -> BichonResult<()> {
let txn = db.transaction();
let mut txn = txn;
for item in &items {
txn = txn
.upsert(M::collection(), item.key(), item)
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))?;
}
txn.commit()
.map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError))
}
// ─── Find ──────────────────────────────────────────────────────────────────
pub fn find_impl(db: &MemDb, key: &str) -> BichonResult