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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use {
crate::{
ast::{ColumnDef, ColumnOption},
data::{Key, Row, Value},
result::Result,
store::Store,
},
im_rc::HashSet,
serde::Serialize,
std::{fmt::Debug, rc::Rc},
thiserror::Error as ThisError,
utils::Vector,
};
#[derive(ThisError, Debug, PartialEq, Serialize)]
pub enum ValidateError {
#[error("conflict! storage row has no column on index {0}")]
ConflictOnStorageColumnIndex(usize),
#[error("duplicate entry '{0:?}' for unique column '{1}'")]
DuplicateEntryOnUniqueField(Value, String),
}
pub enum ColumnValidation {
All(Rc<[ColumnDef]>),
SpecifiedColumns(Rc<[ColumnDef]>, Vec<String>),
}
#[derive(Debug)]
struct UniqueConstraint {
column_index: usize,
column_name: String,
keys: HashSet<Key>,
}
impl UniqueConstraint {
fn new(column_index: usize, column_name: String) -> Self {
Self {
column_index,
column_name,
keys: HashSet::new(),
}
}
fn add(self, value: &Value) -> Result<Self> {
let new_key = self.check(value)?;
if matches!(new_key, Key::None) {
return Ok(self);
}
let keys = self.keys.update(new_key);
Ok(Self {
column_index: self.column_index,
column_name: self.column_name,
keys,
})
}
fn check(&self, value: &Value) -> Result<Key> {
let key = Key::try_from(value)?;
if !self.keys.contains(&key) {
Ok(key)
} else {
Err(ValidateError::DuplicateEntryOnUniqueField(
value.clone(),
self.column_name.to_owned(),
)
.into())
}
}
}
pub async fn validate_unique(
storage: &impl Store,
table_name: &str,
column_validation: ColumnValidation,
row_iter: impl Iterator<Item = &Row> + Clone,
) -> Result<()> {
let columns = match column_validation {
ColumnValidation::All(column_defs) => fetch_all_unique_columns(&column_defs),
ColumnValidation::SpecifiedColumns(column_defs, specified_columns) => {
fetch_specified_unique_columns(&column_defs, &specified_columns)
}
};
let unique_constraints: Vec<_> = create_unique_constraints(columns, row_iter)?.into();
if unique_constraints.is_empty() {
return Ok(());
}
let unique_constraints = Rc::new(unique_constraints);
storage.scan_data(table_name).await?.try_for_each(|result| {
let (_, row) = result?;
Rc::clone(&unique_constraints)
.iter()
.try_for_each(|constraint| {
let col_idx = constraint.column_index;
let val = row
.get_value(col_idx)
.ok_or(ValidateError::ConflictOnStorageColumnIndex(col_idx))?;
constraint.check(val)?;
Ok(())
})
})
}
fn create_unique_constraints<'a>(
unique_columns: Vec<(usize, String)>,
row_iter: impl Iterator<Item = &'a Row> + Clone,
) -> Result<Vector<UniqueConstraint>> {
unique_columns
.into_iter()
.try_fold(Vector::new(), |constraints, col| {
let (col_idx, col_name) = col;
let new_constraint = UniqueConstraint::new(col_idx, col_name);
let new_constraint = row_iter
.clone()
.try_fold(new_constraint, |constraint, row| {
let val = row
.get_value(col_idx)
.ok_or(ValidateError::ConflictOnStorageColumnIndex(col_idx))?;
constraint.add(val)
})?;
Ok(constraints.push(new_constraint))
})
}
fn fetch_all_unique_columns(column_defs: &[ColumnDef]) -> Vec<(usize, String)> {
column_defs
.iter()
.enumerate()
.filter_map(|(i, table_col)| {
if table_col
.options
.iter()
.any(|opt_def| matches!(opt_def.option, ColumnOption::Unique { .. }))
{
Some((i, table_col.name.to_owned()))
} else {
None
}
})
.collect()
}
fn fetch_specified_unique_columns(
all_column_defs: &[ColumnDef],
specified_columns: &[String],
) -> Vec<(usize, String)> {
all_column_defs
.iter()
.enumerate()
.filter_map(|(i, table_col)| {
if table_col
.options
.iter()
.any(|opt_def| match opt_def.option {
ColumnOption::Unique { .. } => specified_columns
.iter()
.any(|specified_col| specified_col == &table_col.name),
_ => false,
})
{
Some((i, table_col.name.to_owned()))
} else {
None
}
})
.collect()
}