pub mod factory;
pub mod serialization;
use std::sync::OnceLock;
use sea_orm::{
ActiveModelTrait, Condition, DatabaseConnection, DeleteResult, EntityTrait, IntoActiveModel,
LoaderTrait, ModelTrait, PrimaryKeyTrait, QueryFilter, Related,
};
static GLOBAL_DB: OnceLock<DatabaseConnection> = OnceLock::new();
pub fn set_global_database(db: DatabaseConnection) -> Result<(), sea_orm::DbErr> {
GLOBAL_DB.set(db).map_err(|_| {
tracing::warn!("Global database connection already initialized. Ignoring duplicate.");
sea_orm::DbErr::Custom("Global database connection already initialized".to_string())
})
}
pub fn database() -> &'static DatabaseConnection {
GLOBAL_DB
.get()
.expect("Global database connection not initialized. Call set_global_database() first.")
}
#[async_trait::async_trait]
pub trait DbModel: Send + Sync + Sized + 'static {
type Entity: EntityTrait;
fn db() -> &'static DatabaseConnection {
database()
}
fn scope_filter() -> Condition {
Condition::all()
}
fn query() -> sea_orm::Select<Self::Entity> {
Self::Entity::find().filter(Self::scope_filter())
}
async fn find(
id: impl Into<<<Self::Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType> + Send,
) -> Result<Option<<Self::Entity as EntityTrait>::Model>, sea_orm::DbErr> {
Self::Entity::find_by_id(id)
.filter(Self::scope_filter())
.one(Self::db())
.await
}
async fn all() -> Result<Vec<<Self::Entity as EntityTrait>::Model>, sea_orm::DbErr> {
Self::Entity::find()
.filter(Self::scope_filter())
.all(Self::db())
.await
}
async fn insert(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<<Self::Entity as EntityTrait>::Model, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
<Self::Entity as EntityTrait>::Model:
IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
{
active_model.insert(Self::db()).await
}
async fn update(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<<Self::Entity as EntityTrait>::Model, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
<Self::Entity as EntityTrait>::Model:
IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
{
active_model.update(Self::db()).await
}
async fn delete(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<DeleteResult, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
{
active_model.delete(Self::db()).await
}
async fn has_many<R>(
model: &<Self::Entity as EntityTrait>::Model,
related_entity: R,
) -> Result<Vec<<R as EntityTrait>::Model>, sea_orm::DbErr>
where
R: EntityTrait,
Self::Entity: Related<R>,
<Self::Entity as EntityTrait>::Model: ModelTrait + Send + Sync,
<R as EntityTrait>::Model: Send + Sync,
{
model.find_related(related_entity).all(Self::db()).await
}
async fn belongs_to<R>(
model: &<Self::Entity as EntityTrait>::Model,
related_entity: R,
) -> Result<Option<<R as EntityTrait>::Model>, sea_orm::DbErr>
where
R: EntityTrait,
Self::Entity: Related<R>,
<Self::Entity as EntityTrait>::Model: ModelTrait + Send + Sync,
<R as EntityTrait>::Model: Send + Sync,
{
model.find_related(related_entity).one(Self::db()).await
}
async fn load_many<R>(
models: &[<Self::Entity as EntityTrait>::Model],
related_entity: R,
) -> Result<Vec<Vec<<R as EntityTrait>::Model>>, sea_orm::DbErr>
where
R: EntityTrait,
Self::Entity: Related<R>,
<Self::Entity as EntityTrait>::Model: ModelTrait + Send + Sync,
<R as EntityTrait>::Model: Send + Sync,
{
models.load_many(related_entity, Self::db()).await
}
async fn load_one<R>(
models: &[<Self::Entity as EntityTrait>::Model],
related_entity: R,
) -> Result<Vec<Option<<R as EntityTrait>::Model>>, sea_orm::DbErr>
where
R: EntityTrait,
Self::Entity: Related<R>,
<Self::Entity as EntityTrait>::Model: ModelTrait + Send + Sync,
<R as EntityTrait>::Model: Send + Sync,
{
models.load_one(related_entity, Self::db()).await
}
}
#[async_trait::async_trait]
pub trait SoftDeletes: DbModel {
async fn soft_delete(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<<Self::Entity as EntityTrait>::Model, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
<Self::Entity as EntityTrait>::Model:
IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
{
active_model.update(Self::db()).await
}
async fn force_delete(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<DeleteResult, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
{
active_model.delete(Self::db()).await
}
fn with_trashed() -> sea_orm::Select<Self::Entity> {
Self::Entity::find()
}
fn only_trashed() -> sea_orm::Select<Self::Entity>;
fn trashed(model: &<Self::Entity as EntityTrait>::Model) -> bool;
}
#[async_trait::async_trait]
pub trait Timestamps: DbModel {
fn fresh_timestamp() -> chrono::NaiveDateTime {
chrono::Utc::now().naive_utc()
}
async fn touch(
active_model: <Self::Entity as EntityTrait>::ActiveModel,
) -> Result<<Self::Entity as EntityTrait>::Model, sea_orm::DbErr>
where
<Self::Entity as EntityTrait>::ActiveModel: Send,
<Self::Entity as EntityTrait>::Model:
IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
{
active_model.update(Self::db()).await
}
}
#[cfg(test)]
mod tests {
use super::{DbModel, SoftDeletes, Timestamps};
use sea_orm::entity::prelude::*;
use sea_orm::Condition;
use sea_orm::IntoActiveModel;
mod category {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "categories")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
pub struct Category;
impl DbModel for Category {
type Entity = category::Entity;
}
mod post {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub title: String,
pub deleted_at: Option<chrono::NaiveDateTime>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
pub struct Post;
impl DbModel for Post {
type Entity = post::Entity;
fn scope_filter() -> Condition {
Condition::all().add(post::Column::DeletedAt.is_null())
}
}
impl SoftDeletes for Post {
fn only_trashed() -> sea_orm::Select<post::Entity> {
<post::Entity as EntityTrait>::find().filter(post::Column::DeletedAt.is_not_null())
}
fn trashed(model: &post::Model) -> bool {
model.deleted_at.is_some()
}
}
#[test]
fn test_db_model_impl_compiles() {
fn _assert<T: DbModel>() {}
_assert::<Category>();
_assert::<Post>();
}
#[test]
fn test_find_accepts_primary_key() {
let _ = Category::find(42);
let _ = Post::find(1);
}
#[test]
fn test_query_method_exists() {
let _cat_select = Category::query();
let _post_select = Post::query();
}
#[test]
fn test_scope_filter_compiles_for_both() {
let _cat_cond = Category::scope_filter();
let _post_cond = Post::scope_filter();
}
#[test]
fn test_query_applies_global_scope_for_soft_deletes() {
let _post_select: sea_orm::Select<post::Entity> = Post::query();
let _cat_select: sea_orm::Select<category::Entity> = Category::query();
}
#[test]
fn test_with_trashed_bypasses_global_scope() {
let _select: sea_orm::Select<post::Entity> = Post::with_trashed();
}
#[test]
fn test_only_trashed_returns_only_trashed() {
let _select: sea_orm::Select<post::Entity> = Post::only_trashed();
}
#[test]
fn test_all_uses_global_scope() {
let _fut = Post::all();
let _fut = Category::all();
}
#[test]
fn test_find_uses_global_scope() {
let _fut = Post::find(1);
let _fut = Category::find(42);
}
#[test]
fn test_query_uses_scope_filter() {
let _select: sea_orm::Select<post::Entity> = Post::query();
let _select: sea_orm::Select<category::Entity> = Category::query();
}
#[test]
fn test_has_many_method_exists() {
fn _assert<T: DbModel>() {}
_assert::<Category>();
}
#[test]
fn test_soft_deletes_trait_compiles() {
fn _assert<T: SoftDeletes>() {}
_assert::<Post>();
}
#[test]
fn test_soft_deletes_trashed() {
let post = post::Model {
id: 1,
title: "Test".to_string(),
deleted_at: Some(chrono::Local::now().naive_local()),
};
assert!(Post::trashed(&post));
let post = post::Model {
id: 2,
title: "Active".to_string(),
deleted_at: None,
};
assert!(!Post::trashed(&post));
}
#[test]
fn test_soft_deletes_with_trashed_compiles() {
let _select = Post::with_trashed();
}
#[test]
fn test_soft_deletes_only_trashed_compiles() {
let _select = Post::only_trashed();
}
#[test]
fn test_soft_delete_method_signature_compiles() {
fn _check<M>()
where
M: SoftDeletes,
<M::Entity as EntityTrait>::ActiveModel: Send,
<M::Entity as EntityTrait>::Model:
IntoActiveModel<<M::Entity as EntityTrait>::ActiveModel>,
{
}
_check::<Post>();
}
#[test]
fn test_force_delete_method_signature_compiles() {
fn _check<M>()
where
M: SoftDeletes,
<M::Entity as EntityTrait>::ActiveModel: Send,
{
}
_check::<Post>();
}
#[test]
fn test_soft_deletes_impl_requires_only_trashed_and_trashed() {
fn _check_required_methods<T>()
where
T: SoftDeletes,
{
fn _has_only_trashed<U: SoftDeletes>() {
let _ = U::only_trashed();
}
fn _has_trashed<U: SoftDeletes>(model: &<U::Entity as EntityTrait>::Model) -> bool {
U::trashed(model)
}
}
_check_required_methods::<Post>();
}
mod article {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "articles")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub title: String,
pub created_at: chrono::NaiveDateTime,
pub updated_at: chrono::NaiveDateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
pub struct Article;
impl DbModel for Article {
type Entity = article::Entity;
}
impl Timestamps for Article {}
#[test]
fn test_timestamps_trait_compiles() {
fn _assert<T: Timestamps>() {}
_assert::<Article>();
}
#[test]
fn test_fresh_timestamp_returns_naive_datetime() {
let ts: chrono::NaiveDateTime = Article::fresh_timestamp();
let now = chrono::Utc::now().naive_utc();
let diff = now - ts;
assert!(
diff.num_seconds().abs() < 10,
"fresh_timestamp should return a recent timestamp"
);
}
#[test]
fn test_timestamps_with_db_model() {
fn _assert<T: DbModel>() {}
_assert::<Article>();
}
#[test]
fn test_timestamp_touch_method_signature_compiles() {
fn _check<M>()
where
M: Timestamps,
<M::Entity as EntityTrait>::ActiveModel: Send,
<M::Entity as EntityTrait>::Model:
IntoActiveModel<<M::Entity as EntityTrait>::ActiveModel>,
{
}
_check::<Article>();
}
#[test]
fn test_timestamps_and_soft_deletes_are_independent() {
fn _assert_timestamps<T: Timestamps>() {}
fn _assert_soft_deletes<T: SoftDeletes>() {}
_assert_timestamps::<Article>();
_assert_soft_deletes::<Post>();
}
#[test]
fn test_all_traits_available() {
fn _assert_db<T: DbModel>() {}
fn _assert_ts<T: Timestamps>() {}
fn _assert_sd<T: SoftDeletes>() {}
_assert_db::<Category>();
_assert_db::<Post>();
_assert_db::<Article>();
_assert_ts::<Article>();
_assert_sd::<Post>();
}
}