toql_core 0.4.2

Library with core functionality for Toql
Documentation
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Turns an [SqlExpr] into [Sql]
use super::{resolver_error::ResolverError, PredicateColumn};
use crate::{
    alias_translator::AliasTranslator,
    parameter_map::ParameterMap,
    sql::Sql,
    sql_arg::SqlArg,
    sql_expr::{SqlExpr, SqlExprToken},
};
use std::{borrow::Cow, collections::HashMap};

/// The resolver may hold values for placeholder tokens from [SqlExpr] and replace those.
///
/// It will replace placeholder tokens from [SqlExpr] with concret values as good as it can.
///
/// This is a typical use:
/// ```rust
/// use toql_core::{sql_expr::SqlExpr, alias_format::AliasFormat};
/// use toql_core::{alias_translator::AliasTranslator, sql_expr::resolver::Resolver};
///
/// let sql_expr = SqlExpr::self_alias();
/// let mut alias_translator = AliasTranslator::new(AliasFormat::TinyIndex);
/// let resolver = Resolver::new().with_self_alias("t1");
///
/// let sql = resolver.to_sql(&sql_expr, &mut alias_translator).unwrap();
/// assert_eq!("t1", sql.to_unsafe_string());
/// ```
pub struct Resolver<'a> {
    self_alias: Option<&'a str>,
    other_alias: Option<&'a str>,
    arguments: Option<&'a [SqlArg]>,
    aux_params: Option<&'a ParameterMap<'a>>,
}

impl<'a> Resolver<'a> {
    // Create new resolver.
    pub fn new() -> Self {
        Self {
            self_alias: None,
            other_alias: None,
            arguments: None,
            aux_params: None,
            // alias_translator: None
        }
    }

    /// Replace self alias placeholders with this alias.
    pub fn with_self_alias(mut self, alias: &'a str) -> Self {
        self.self_alias = Some(alias);
        self
    }
    /// Replace other alias placeholders with this alias.
    pub fn with_other_alias(mut self, alias: &'a str) -> Self {
        self.other_alias = Some(alias);
        self
    }
    /// Replace aux param placeholders with values from this map.
    pub fn with_aux_params(mut self, aux_params: &'a ParameterMap<'a>) -> Self {
        self.aux_params = Some(aux_params);
        self
    }
    /// Replace argument placeholder with values from this argument list.
    pub fn with_arguments(mut self, arguments: &'a [SqlArg]) -> Self {
        self.arguments = Some(arguments);
        self
    }

    /// Replace aux param palceholders with SQL expressions.
    /// Skips placeholders that can't be replaced.
    pub fn replace_aux_params(
        sql_expr: SqlExpr,
        aux_params_exprs: &HashMap<String, SqlExpr>,
    ) -> SqlExpr {
        let mut tokens = Vec::new();

        for token in sql_expr.tokens {
            if let SqlExprToken::AuxParam(ref name) = token {
                if let Some(expr) = aux_params_exprs.get(name) {
                    tokens.extend_from_slice(&expr.tokens);
                } else {
                    tokens.push(token);
                }
            } else {
                tokens.push(token);
            }
        }
        SqlExpr::from(tokens)
    }

    /// Resolve aux params placeholders with value from parameter map.
    /// Skips placeholders that cannot be resolved.
    pub fn resolve_aux_params(sql_expr: SqlExpr, aux_params: &ParameterMap) -> SqlExpr {
        let mut tokens = Vec::new();

        for token in sql_expr.tokens {
            if let SqlExprToken::AuxParam(ref name) = token {
                if let Some(arg) = aux_params.get(name) {
                    // Resolve if possible, copy SQL argument
                    tokens.push(SqlExprToken::Arg(arg.clone()));
                } else {
                    tokens.push(token); // Copy unresolved aux param
                }
            } else {
                tokens.push(token); // Copy any not aux params
            }
        }
        SqlExpr::from(tokens) // Return resolved string
    }

    // Resolve all placeholder tokens from sql_expr.
    pub fn resolve(&self, sql_expr: &'a SqlExpr) -> std::result::Result<SqlExpr, ResolverError> {
        let mut tokens = Vec::new();

        for token in sql_expr.tokens() {
            tokens.push(self.resolve_token(token)?.into_owned())
        }

        Ok(SqlExpr::from(tokens))
    }

    /// Resolve all aliases to literal strings.
    pub fn alias_to_literals(
        &self,
        sql_expr: &'a SqlExpr,
    ) -> std::result::Result<SqlExpr, ResolverError> {
        let mut tokens = Vec::new();

        for token in sql_expr.tokens() {
            tokens.push(self.resolve_alias_to_literals(token).into_owned())
        }

        Ok(SqlExpr::from(tokens))
    }

    /// Resolve all placeholder tokens and translate aliases with the [AliasTranslator].
    /// This turns an [SqlExpr] into [Sql], if all placeholder tokens can be resolved
    /// and fail otherwise.
    pub fn to_sql(
        &self,
        sql_expr: &SqlExpr,
        alias_translator: &mut AliasTranslator,
    ) -> Result<Sql, ResolverError> {
        let mut stmt = String::new();
        let mut args: Vec<SqlArg> = Vec::new();

        for unresolved_token in &sql_expr.tokens {
            let mut token = self.resolve_token(unresolved_token)?;
            Self::token_to_sql(token.to_mut(), alias_translator, &mut stmt, &mut args)?;
        }

        Ok(Sql(stmt, args))
    }

    fn resolve_alias_to_literals(&self, token: &'a SqlExprToken) -> Cow<'a, SqlExprToken> {
        match token {
            SqlExprToken::SelfAlias if self.self_alias.is_some() => {
                Cow::Owned(SqlExprToken::Literal(self.self_alias.unwrap().to_string()))
            }
            SqlExprToken::OtherAlias if self.other_alias.is_some() => {
                Cow::Owned(SqlExprToken::Literal(self.other_alias.unwrap().to_string()))
            }
            tok => Cow::Borrowed(tok),
        }
    }

    fn resolve_token(
        &self,
        token: &'a SqlExprToken,
    ) -> Result<Cow<'a, SqlExprToken>, ResolverError> {
        let arg_iter = if self.arguments.is_some() {
            Some(self.arguments.unwrap())
        } else {
            None
        };

        match token {
            SqlExprToken::SelfAlias if self.self_alias.is_some() => Ok(Cow::Owned(
                SqlExprToken::Alias(self.self_alias.unwrap().to_string()),
            )),
            SqlExprToken::OtherAlias if self.other_alias.is_some() => Ok(Cow::Owned(
                SqlExprToken::Alias(self.other_alias.unwrap().to_string()),
            )),
            SqlExprToken::AuxParam(name) if self.aux_params.is_some() => {
                let arg = self
                    .aux_params
                    .unwrap()
                    .get(&name)
                    .ok_or_else(|| ResolverError::AuxParamMissing(name.to_string()))?
                    .to_owned();
                Ok(Cow::Owned(SqlExprToken::Arg(arg)))
            }
            SqlExprToken::UnresolvedArg if arg_iter.is_some() => {
                let arg = arg_iter
                    .unwrap()
                    .iter()
                    .next()
                    .ok_or(ResolverError::ArgumentMissing)?;

                Ok(Cow::Owned(SqlExprToken::Arg(arg.to_owned())))
            }
            SqlExprToken::Predicate { columns, args }
                if self.self_alias.is_some() || self.other_alias.is_some() =>
            {
                // TODO optimise so that arguments are not copied
                // maybe take self instead of &self

                let mut changed_columns: Vec<PredicateColumn> = Vec::new();
                let mut changed = false;

                for c in columns {
                    changed_columns.push(match c {
                        PredicateColumn::SelfAliased(a) => {
                            changed = true;
                            if self.self_alias.is_some() {
                                PredicateColumn::Aliased(
                                    self.self_alias.unwrap().to_owned(),
                                    a.to_owned(),
                                )
                            } else {
                                PredicateColumn::SelfAliased(a.to_owned())
                            }
                        }
                        PredicateColumn::OtherAliased(a) => {
                            changed = true;
                            if self.other_alias.is_some() {
                                PredicateColumn::Aliased(
                                    self.other_alias.unwrap().to_owned(),
                                    a.to_owned(),
                                )
                            } else {
                                PredicateColumn::OtherAliased(a.to_owned())
                            }
                        }
                        PredicateColumn::Literal(l) => PredicateColumn::Literal(l.to_owned()),
                        PredicateColumn::Aliased(a, c) => {
                            PredicateColumn::Aliased(a.to_owned(), c.to_owned())
                        }
                    });
                }

                if changed {
                    Ok(Cow::Owned(SqlExprToken::Predicate {
                        columns: changed_columns,
                        args: args.to_owned(),
                    }))
                } else {
                    // Pattern bindings are unstable, so we can't return Cow::Borrowed(token)
                    Ok(Cow::Owned(SqlExprToken::Predicate {
                        columns: columns.to_owned(),
                        args: args.to_owned(),
                    }))
                }
            }
            tok => Ok(Cow::Borrowed(tok)),
        }
    }

    pub fn token_to_sql(
        token: &SqlExprToken,
        alias_translator: &mut AliasTranslator,
        stmt: &mut String,
        args: &mut Vec<SqlArg>,
    ) -> std::result::Result<(), ResolverError> {
        match token {
            SqlExprToken::SelfAlias => return Err(ResolverError::UnresolvedSelfAlias),
            SqlExprToken::OtherAlias => return Err(ResolverError::UnresolvedOtherAlias),
            SqlExprToken::UnresolvedArg => return Err(ResolverError::UnresolvedArgument),
            SqlExprToken::AuxParam(name) => {
                return Err(ResolverError::UnresolvedAuxParameter(name.to_owned()))
            }

            SqlExprToken::Literal(lit) => stmt.push_str(&lit),

            SqlExprToken::Alias(canonical_alias) => {
                let alias = alias_translator.translate(canonical_alias);
                stmt.push_str(&alias);
            }

            SqlExprToken::Arg(arg) => {
                stmt.push('?');
                args.push(arg.to_owned());
            }

            SqlExprToken::Predicate { columns, args: a } => match columns.len() {
                0 => { /* Omit statement if no columns are provied */ }
                1 => {
                    match columns.get(0).unwrap() {
                        PredicateColumn::SelfAliased(_) => {
                            return Err(ResolverError::UnresolvedSelfAlias)
                        }
                        PredicateColumn::OtherAliased(_) => {
                            return Err(ResolverError::UnresolvedOtherAlias)
                        }
                        PredicateColumn::Literal(l) => stmt.push_str(l),
                        PredicateColumn::Aliased(canonical_alias, col) => {
                            let alias = alias_translator.translate(canonical_alias);
                            stmt.push_str(&alias);
                            stmt.push('.');
                            stmt.push_str(col);
                        }
                    };

                    match a.len() {
                        0 => return Err(ResolverError::ArgumentMissing),
                        1 => {
                            stmt.push_str(" = ?");
                            args.push(a.get(0).unwrap().to_owned());
                        }
                        _ => {
                            stmt.push_str(" IN (?");
                            for _ in 1..a.len() {
                                stmt.push_str(", ?");
                            }
                            stmt.push(')');
                            args.extend(a.to_owned());
                        }
                    }
                }
                _ => {
                    let mut nc = 1;
                    for (ar, c) in a.iter().zip(columns.iter().cycle()) {
                        match c {
                            PredicateColumn::SelfAliased(_) => {
                                return Err(ResolverError::UnresolvedSelfAlias)
                            }
                            PredicateColumn::OtherAliased(_) => {
                                return Err(ResolverError::UnresolvedOtherAlias)
                            }
                            PredicateColumn::Literal(lit) => stmt.push_str(lit),
                            PredicateColumn::Aliased(canonical_alias, col) => {
                                let alias = alias_translator.translate(canonical_alias);
                                stmt.push_str(&alias);
                                stmt.push('.');
                                stmt.push_str(col);
                            }
                        };

                        stmt.push_str(" = ?");
                        args.push(ar.to_owned());
                        if nc < columns.len() {
                            nc += 1;
                            stmt.push_str(" AND ");
                        } else {
                            nc = 1;
                            stmt.push_str(" OR ");
                        }
                    }

                    if nc == 1 {
                        // Remove ' OR '
                        stmt.pop();
                        stmt.pop();
                        stmt.pop();
                        stmt.pop();
                    } else {
                        // Remove ' AND '
                        stmt.pop();
                        stmt.pop();
                        stmt.pop();
                        stmt.pop();
                        stmt.pop();
                    }
                }
            },
        }
        Ok(())
    }
}

impl Default for Resolver<'_> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use super::Resolver;
    use crate::{
        parameter_map::ParameterMap,
        sql_arg::SqlArg,
        sql_expr::{SqlExpr, SqlExprToken},
    };
    use std::collections::HashMap;
    #[test]
    fn create() {
        let expr = SqlExpr::self_alias();
        let resolver = Resolver::new().with_self_alias("a");
        let expr = resolver.resolve(&expr).unwrap();
        assert_eq!(expr.to_string(), "a");

        let expr = SqlExpr::other_alias();
        let resolver = Resolver::new().with_other_alias("a");
        let expr = resolver.resolve(&expr).unwrap();
        assert_eq!(expr.to_string(), "a");

        let expr = SqlExpr::unresolved_arg();
        let args = [SqlArg::Str("a".to_string())];
        let resolver = Resolver::new().with_arguments(&args);
        let expr = resolver.resolve(&expr).unwrap();
        assert_eq!(expr.to_string(), "'a'");

        let tokens = vec![SqlExprToken::AuxParam("param".to_string())];
        let expr = SqlExpr::from(tokens);
        let mut params = HashMap::new();
        params.insert("param".to_string(), SqlArg::Str("a".to_string()));
        let map = [&params];
        let map = ParameterMap::new(&map);
        let resolver = Resolver::new().with_aux_params(&map);
        let expr = resolver.resolve(&expr).unwrap();
        assert_eq!(expr.to_string(), "'a'");
    }

    #[test]
    fn replace_aux_params() {
        let tokens = vec![SqlExprToken::AuxParam("param".to_string())];
        let expr = SqlExpr::from(tokens);

        let mut replace = HashMap::new();
        replace.insert("param".to_string(), SqlExpr::literal("a".to_string()));

        let expr = Resolver::replace_aux_params(expr, &replace);
        assert_eq!(expr.to_string(), "a");
    }
    #[test]
    fn alias_to_literals() {
        // resolve all aliases
        let tokens = vec![
            SqlExprToken::SelfAlias,
            SqlExprToken::Literal(" ".to_string()),
            SqlExprToken::OtherAlias,
        ];
        let expr = SqlExpr::from(tokens);

        let resolver = Resolver::default()
            .with_self_alias("a")
            .with_other_alias("b");
        let expr = resolver.alias_to_literals(&expr).unwrap();
        assert_eq!(expr.to_string(), "a b");
    }
}