sql/schema/
constraint.rs

1use crate::{Dialect, ToSql};
2use crate::util::SqlExtension;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct ForeignKey {
7    pub table: String,
8    pub columns: Vec<String>,
9}
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13#[cfg_attr(feature = "serde", serde(tag = "type"))]
14pub enum Constraint {
15    ForeignKey(ForeignKey),
16}
17
18impl Constraint {
19    pub fn foreign_key(table: String, columns: Vec<String>) -> Self {
20        Constraint::ForeignKey(ForeignKey { table, columns })
21    }
22
23    pub fn name(&self) -> &str {
24        match self {
25            Constraint::ForeignKey(fk) => &fk.table,
26        }
27    }
28}
29
30impl ToSql for ForeignKey {
31    fn write_sql(&self, buf: &mut String, _dialect: Dialect) {
32        buf.push_str("REFERENCES ");
33        buf.push_quoted(&self.table);
34        if !self.columns.is_empty() {
35            buf.push('(');
36            buf.push_quoted_sequence(&self.columns, ", ");
37            buf.push(')');
38        }
39    }
40}
41
42impl ToSql for Constraint {
43    fn write_sql(&self, buf: &mut String, dialect: Dialect) {
44        match self {
45            Constraint::ForeignKey(fk) => fk.write_sql(buf, dialect),
46        }
47    }
48}