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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::marker::PhantomData;
use itertools::Itertools;
use super::tags::{CompareOp, ConjunctionOp, TagName, TagQueryEncoder};
use crate::error::Error;
pub struct TagSqlEncoder<'e, EN, EV> {
pub enc_name: EN,
pub enc_value: EV,
pub arguments: Vec<Vec<u8>>,
_pd: PhantomData<&'e ()>,
}
impl<'e, EN, EV> TagSqlEncoder<'e, EN, EV>
where
EN: Fn(&str) -> Result<Vec<u8>, Error> + 'e,
EV: Fn(&str) -> Result<Vec<u8>, Error> + 'e,
{
pub fn new(enc_name: EN, enc_value: EV) -> Self {
Self {
enc_name,
enc_value,
arguments: vec![],
_pd: PhantomData,
}
}
}
impl<'e, EN, EV> TagQueryEncoder for TagSqlEncoder<'e, EN, EV>
where
EN: Fn(&str) -> Result<Vec<u8>, Error> + 'e,
EV: Fn(&str) -> Result<Vec<u8>, Error> + 'e,
{
type Arg = Vec<u8>;
type Clause = String;
fn encode_name(&mut self, name: &TagName) -> Result<Self::Arg, Error> {
Ok(match name {
TagName::Encrypted(name) | TagName::Plaintext(name) => (&self.enc_name)(name)?,
})
}
fn encode_value(&mut self, value: &String, is_plaintext: bool) -> Result<Self::Arg, Error> {
Ok(if is_plaintext {
value.as_bytes().to_vec()
} else {
(&self.enc_value)(value)?
})
}
fn encode_op_clause(
&mut self,
op: CompareOp,
enc_name: Self::Arg,
enc_value: Self::Arg,
is_plaintext: bool,
) -> Result<Option<Self::Clause>, Error> {
let idx = self.arguments.len();
let (op_prefix, match_prefix) = match (is_plaintext, op.as_sql_str_for_prefix()) {
(false, Some(pfx_op)) if enc_value.len() > 12 => {
let match_prefix = enc_value[..12].to_vec();
(
format!(" AND SUBSTR(value, 1, 12) {} ${}", pfx_op, idx + 3),
Some(match_prefix),
)
}
_ => (String::new(), None),
};
self.arguments.push(enc_name);
self.arguments.push(enc_value);
if let Some(v) = match_prefix {
self.arguments.push(v);
}
let query = format!(
"i.id IN (SELECT item_id FROM items_tags WHERE name = ${} AND value {} ${}{} AND plaintext = {})",
idx + 1,
op.as_sql_str(),
idx + 2,
op_prefix.as_str(),
if is_plaintext { 1 } else { 0 }
);
Ok(Some(query))
}
fn encode_in_clause(
&mut self,
enc_name: Self::Arg,
enc_values: Vec<Self::Arg>,
is_plaintext: bool,
negate: bool,
) -> Result<Option<Self::Clause>, Error> {
let args_in = Itertools::intersperse(std::iter::repeat("$$").take(enc_values.len()), ", ")
.collect::<String>();
let query = format!(
"i.id IN (SELECT item_id FROM items_tags WHERE name = $$ AND value {} ({}) AND plaintext = {})",
if negate { "NOT IN" } else { "IN" },
args_in,
if is_plaintext { 1 } else { 0 }
);
self.arguments.push(enc_name);
self.arguments.extend(enc_values);
Ok(Some(query))
}
fn encode_exist_clause(
&mut self,
enc_name: Self::Arg,
is_plaintext: bool,
negate: bool,
) -> Result<Option<Self::Clause>, Error> {
let query = format!(
"i.id {} (SELECT item_id FROM items_tags WHERE name = $$ AND plaintext = {})",
if negate { "NOT IN" } else { "IN" },
if is_plaintext { 1 } else { 0 }
);
self.arguments.push(enc_name);
Ok(Some(query))
}
fn encode_conj_clause(
&mut self,
op: ConjunctionOp,
clauses: Vec<Self::Clause>,
) -> Result<Option<Self::Clause>, Error> {
let qc = clauses.len();
if qc == 0 {
if op == ConjunctionOp::Or {
return Ok(Some("0".to_string()));
} else {
return Ok(None);
}
}
let mut s = String::new();
if qc > 1 {
s.push('(');
}
for (index, clause) in clauses.into_iter().enumerate() {
if index > 0 {
s.push_str(op.as_sql_str());
}
s.push_str(&clause);
}
if qc > 1 {
s.push(')');
}
Ok(Some(s))
}
}
#[cfg(test)]
mod tests {
use super::super::tags::TagQuery;
use super::*;
#[test]
fn tag_query_encode() {
let condition_1 = TagQuery::And(vec![
TagQuery::Eq(
TagName::Encrypted("enctag".to_string()),
"noncenonce12encval".to_string(),
),
TagQuery::Eq(
TagName::Plaintext("plaintag".to_string()),
"plainval".to_string(),
),
]);
let condition_2 = TagQuery::And(vec![
TagQuery::Eq(
TagName::Encrypted("enctag".to_string()),
"noncenonce12encval".to_string(),
),
TagQuery::Not(Box::new(TagQuery::Eq(
TagName::Plaintext("plaintag".to_string()),
"eggs".to_string(),
))),
]);
let query = TagQuery::Or(vec![condition_1, condition_2]);
let mut enc = TagSqlEncoder::new(
|name: &str| Ok(format!("--{}--", name).into_bytes()),
|value: &str| Ok(value.to_uppercase().into_bytes()),
);
let query_str = enc.encode_query(&query).unwrap().unwrap();
assert_eq!(query_str, "((i.id IN (SELECT item_id FROM items_tags WHERE name = $1 AND value = $2 AND SUBSTR(value, 1, 12) = $3 AND plaintext = 0) AND i.id IN (SELECT item_id FROM items_tags WHERE name = $4 AND value = $5 AND plaintext = 1)) OR (i.id IN (SELECT item_id FROM items_tags WHERE name = $6 AND value = $7 AND SUBSTR(value, 1, 12) = $8 AND plaintext = 0) AND i.id IN (SELECT item_id FROM items_tags WHERE name = $9 AND value != $10 AND plaintext = 1)))");
let args = enc.arguments;
assert_eq!(
args,
vec![
b"--enctag--".to_vec(),
b"NONCENONCE12ENCVAL".to_vec(),
b"NONCENONCE12".to_vec(),
b"--plaintag--".to_vec(),
b"plainval".to_vec(),
b"--enctag--".to_vec(),
b"NONCENONCE12ENCVAL".to_vec(),
b"NONCENONCE12".to_vec(),
b"--plaintag--".to_vec(),
b"eggs".to_vec()
]
);
}
}