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
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::str::FromStr;

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct RefInline {
  pub rel: Relation,
  pub rhs: RefIdent,
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct RefBlock {
  pub rel: Relation,
  pub lhs: RefIdent,
  pub rhs: RefIdent,
  pub settings: Option<RefSettings>,
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub enum Relation {
  #[default]
  Undef,
  One2One,
  One2Many,
  Many2One,
  Many2Many,
}

impl FromStr for Relation {
  type Err = String;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    match s {
      "<" => Ok(Self::One2Many),
      ">" => Ok(Self::Many2One),
      "-" => Ok(Self::One2One),
      "<>" => Ok(Self::Many2Many),
      _ => Err(format!("incorrect relation symbol '{}'", s)),
    }
  }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct RefIdent {
  pub schema: Option<String>,
  pub table: String,
  pub compositions: Vec<String>,
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ReferentialAction {
  NoAction,
  Cascade,
  Restrict,
  SetNull,
  SetDefault,
}

impl FromStr for ReferentialAction {
  type Err = ();

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    match s {
      "no action" => Ok(Self::NoAction),
      "cascade" => Ok(Self::Cascade),
      "restrict" => Ok(Self::Restrict),
      "set null" => Ok(Self::SetNull),
      "set default" => Ok(Self::SetDefault),
      _ => Err(()),
    }
  }
}

impl ToString for ReferentialAction {
  fn to_string(&self) -> String {
    match self {
      Self::NoAction => {
        format!("no action")
      }
      Self::Cascade => format!("cascade"),
      Self::Restrict => format!("restrict"),
      Self::SetNull => format!("set null"),
      Self::SetDefault => {
        format!("set default")
      }
    }
  }
}

#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct RefSettings {
  pub on_delete: Option<ReferentialAction>,
  pub on_update: Option<ReferentialAction>,
}