use sea_orm::{ ActiveValue::{NotSet, Set}, entity::prelude::*, sea_query::Expr, sqlx::types::chrono::{self, Utc}, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)] #[sea_orm(table_name = "stream_session")] pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub stream_key_id: i32, pub started_at: DateTimeUtc, pub ended_at: Option, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation { #[sea_orm( belongs_to = "super::stream_key::Entity", from = "Column::StreamKeyId", to = "super::stream_key::Column::Id" )] StreamKey, } impl Related for Entity { fn to() -> RelationDef { Relation::StreamKey.def() } } impl ActiveModelBehavior for ActiveModel {} impl Model { pub async fn create_stream_session( db: &DatabaseConnection, stream_key_id: i32, started_at: chrono::DateTime, ) -> Result { ActiveModel { id: NotSet, stream_key_id: Set(stream_key_id), started_at: Set(started_at), ended_at: NotSet, ..Default::default() } .insert(db) .await } pub async fn get_all_active_sessions(db: &DatabaseConnection) -> Result, DbErr> { Entity::find() .filter(Column::EndedAt.is_null()) .all(db) .await } pub async fn get_active_by_stream_key_id( db: &DatabaseConnection, stream_key_id: i32, ) -> Result, DbErr> { Entity::find() .filter(Column::StreamKeyId.eq(stream_key_id)) .filter(Column::EndedAt.is_null()) .one(db) .await } pub async fn clean_unended_streams(db: &DatabaseConnection) -> Result { let result = Entity::update_many() .filter(Column::EndedAt.is_null()) .col_expr(Column::EndedAt, Expr::col(Column::StartedAt).into()) .exec(db) .await?; Ok(result.rows_affected) } } impl ActiveModel { pub async fn finish_stream_session( mut self, db: &DatabaseConnection, ended_at: chrono::DateTime, ) -> Result { self.ended_at = Set(Some(ended_at)); self.update(db).await } }