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
93
94
95
96
97
98
99
use crate::mysql::def::*;
use crate::mysql::query::ConstraintQueryResult;
use crate::Name;
pub struct ConstraintQueryResultParser {
curr: Option<ForeignKeyInfo>,
results: Box<dyn Iterator<Item = ConstraintQueryResult>>,
}
pub fn parse_constraint_query_results(
results: Box<dyn Iterator<Item = ConstraintQueryResult>>,
) -> impl Iterator<Item = ForeignKeyInfo> {
ConstraintQueryResultParser {
curr: None,
results,
}
}
impl Iterator for ConstraintQueryResultParser {
type Item = ForeignKeyInfo;
fn next(&mut self) -> Option<Self::Item> {
while let Some(result) = self.results.next() {
let mut constraint = parse_constraint_query_result(result);
if let Some(curr) = &mut self.curr {
if curr.name == constraint.name {
curr.columns.push(constraint.columns.pop().unwrap());
curr.referenced_columns
.push(constraint.referenced_columns.pop().unwrap());
} else {
let prev = self.curr.take();
self.curr = Some(constraint);
return prev;
}
} else {
self.curr = Some(constraint);
}
}
self.curr.take()
}
}
pub fn parse_constraint_query_result(result: ConstraintQueryResult) -> ForeignKeyInfo {
ForeignKeyInfo {
name: result.constraint_name,
columns: vec![result.column_name],
referenced_table: result.referenced_table_name,
referenced_columns: vec![result.referenced_column_name],
on_update: parse_foreign_key_action(result.update_rule.as_str()),
on_delete: parse_foreign_key_action(result.delete_rule.as_str()),
}
}
pub fn parse_foreign_key_action(string: &str) -> ForeignKeyAction {
ForeignKeyAction::from_str(string).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert_eq!(
parse_constraint_query_results(Box::new(
vec![
ConstraintQueryResult {
constraint_name: "fk-cat-dog".to_owned(),
column_name: "d1".to_owned(),
referenced_table_name: "cat".to_owned(),
referenced_column_name: "c1".to_owned(),
update_rule: "CASCADE".to_owned(),
delete_rule: "NO ACTION".to_owned(),
},
ConstraintQueryResult {
constraint_name: "fk-cat-dog".to_owned(),
column_name: "d2".to_owned(),
referenced_table_name: "cat".to_owned(),
referenced_column_name: "c2".to_owned(),
update_rule: "CASCADE".to_owned(),
delete_rule: "NO ACTION".to_owned(),
},
]
.into_iter()
))
.collect::<Vec<ForeignKeyInfo>>(),
vec![ForeignKeyInfo {
name: "fk-cat-dog".to_owned(),
columns: vec!["d1".to_owned(), "d2".to_owned()],
referenced_table: "cat".to_owned(),
referenced_columns: vec!["c1".to_owned(), "c2".to_owned()],
on_update: ForeignKeyAction::Cascade,
on_delete: ForeignKeyAction::NoAction,
}]
);
}
}