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
use std::{
    rc::Rc,
    ops::Deref,
    fmt::Display,
};
use super::{
    table::{
        Table,
    },
    field::Field,
};

#[derive(Clone, Eq, PartialEq, Hash, Debug, PartialOrd, Ord)]
pub struct SchemaConstraintId(pub String);

impl Display for SchemaConstraintId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

#[derive(Clone, PartialEq)]
pub struct PrimaryKeyDef {
    pub fields: Vec<Field>,
}

#[derive(Clone, PartialEq)]
pub struct ForeignKeyDef {
    pub fields: Vec<(Field, Field)>,
}

#[derive(Clone, PartialEq)]
pub enum ConstraintType {
    PrimaryKey(PrimaryKeyDef),
    ForeignKey(ForeignKeyDef),
}

pub struct Constraint_ {
    pub table: Table,
    pub schema_id: SchemaConstraintId,
    pub id: String,
    pub type_: ConstraintType,
}

#[derive(Clone)]
pub struct Constraint(pub Rc<Constraint_>);

impl Display for Constraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(
            &format!("{}.{} ({}.{})", self.0.table.id, self.0.id, self.0.table.schema_id, self.0.schema_id),
            f,
        )
    }
}

impl PartialEq for Constraint {
    fn eq(&self, other: &Self) -> bool {
        self.table == other.table && self.schema_id == other.schema_id
    }
}

impl Eq for Constraint { }

impl Deref for Constraint {
    type Target = Constraint_;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}