1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use crate::db::{ChannelId, ChannelVisibility};
use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, Default, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "channels")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: ChannelId,
    pub name: String,
    pub visibility: ChannelVisibility,
    pub parent_path: String,
}

impl Model {
    pub fn parent_id(&self) -> Option<ChannelId> {
        self.ancestors().last()
    }

    pub fn ancestors(&self) -> impl Iterator<Item = ChannelId> + '_ {
        self.parent_path
            .trim_end_matches('/')
            .split('/')
            .filter_map(|id| Some(ChannelId::from_proto(id.parse().ok()?)))
    }

    pub fn ancestors_including_self(&self) -> impl Iterator<Item = ChannelId> + '_ {
        self.ancestors().chain(Some(self.id))
    }

    pub fn path(&self) -> String {
        format!("{}{}/", self.parent_path, self.id)
    }
}

impl ActiveModelBehavior for ActiveModel {}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    #[sea_orm(has_one = "super::room::Entity")]
    Room,
    #[sea_orm(has_one = "super::buffer::Entity")]
    Buffer,
    #[sea_orm(has_many = "super::channel_member::Entity")]
    Member,
    #[sea_orm(has_many = "super::channel_buffer_collaborator::Entity")]
    BufferCollaborators,
    #[sea_orm(has_many = "super::channel_chat_participant::Entity")]
    ChatParticipants,
}

impl Related<super::channel_member::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Member.def()
    }
}

impl Related<super::room::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Room.def()
    }
}

impl Related<super::buffer::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::Buffer.def()
    }
}

impl Related<super::channel_buffer_collaborator::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::BufferCollaborators.def()
    }
}

impl Related<super::channel_chat_participant::Entity> for Entity {
    fn to() -> RelationDef {
        Relation::ChatParticipants.def()
    }
}