doido_model/
association.rs1use doido_core::Inflector;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum AssociationKind {
12 BelongsTo,
13 HasOne,
14 HasMany,
15 HasAndBelongsToMany,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Association {
21 pub name: String,
22 pub kind: AssociationKind,
23 pub foreign_key: String,
24 pub table: String,
25}
26
27impl Association {
28 pub fn belongs_to(name: &str) -> Self {
30 Self {
31 name: name.to_string(),
32 kind: AssociationKind::BelongsTo,
33 foreign_key: Inflector::foreign_key(name),
34 table: Inflector::tableize(name),
35 }
36 }
37
38 pub fn has_one(owner: &str, name: &str) -> Self {
40 Self {
41 name: name.to_string(),
42 kind: AssociationKind::HasOne,
43 foreign_key: Inflector::foreign_key(owner),
44 table: Inflector::tableize(name),
45 }
46 }
47
48 pub fn has_many(owner: &str, name: &str) -> Self {
51 Self {
52 name: name.to_string(),
53 kind: AssociationKind::HasMany,
54 foreign_key: Inflector::foreign_key(owner),
55 table: Inflector::tableize(&Inflector::singularize(name)),
56 }
57 }
58
59 pub fn has_and_belongs_to_many(name: &str) -> Self {
61 Self {
62 name: name.to_string(),
63 kind: AssociationKind::HasAndBelongsToMany,
64 foreign_key: Inflector::foreign_key(&Inflector::singularize(name)),
65 table: Inflector::tableize(&Inflector::singularize(name)),
66 }
67 }
68}
69
70pub fn join_table(a: &str, b: &str) -> String {
73 let mut tables = [Inflector::tableize(a), Inflector::tableize(b)];
74 tables.sort();
75 format!("{}_{}", tables[0], tables[1])
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct PolymorphicAssociation {
82 pub name: String,
83 pub type_column: String,
84 pub id_column: String,
85}
86
87impl PolymorphicAssociation {
88 pub fn belongs_to(name: &str) -> Self {
89 Self {
90 name: name.to_string(),
91 type_column: format!("{name}_type"),
92 id_column: format!("{name}_id"),
93 }
94 }
95}
96
97pub fn sti_type_column() -> &'static str {
99 "type"
100}