mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Where each column of a result physically comes from.
//!
//! # Nothing here opens a connection
//!
//! The answer is read from the statement's own syntax tree. That is what makes
//! it usable before the statement is run, which is the whole point: a caller
//! decides whether to run a query by knowing what it touches.
//!
//! # A guess is worse than a refusal
//!
//! An unqualified column over a join belongs to whichever table declares it,
//! and the tree cannot say which. Answering anyway would hand the caller a
//! confident wrong answer, so the whole answer is refused instead, naming the
//! column that could not be resolved. The same holds for a wildcard, whose
//! columns are not written down anywhere in the statement, and for a derived
//! table, whose columns are produced rather than stored.
//!
//! # The server outranks the syntax
//!
//! When a result is at hand the server has already declared, column by column,
//! which stored table and which stored column produced it. That declaration is
//! the origin itself, not an opinion about it, so [`resolve_declared`] prefers
//! it and keeps reading the syntax back only as the reserve for the columns the
//! server left blank, which are the ones it produced rather than stored.

use crate::error::{Failure, Result};
use core::ops::ControlFlow;
use mysql_async::Column as Declared;
use serde_json::{json, Value};
use sqlparser::ast::{
    Expr, Query, Select, SelectItem, SetExpr, Statement, TableFactor, Visit, Visitor,
};
use std::collections::BTreeMap;

/// One physical column a result column was produced from.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Source {
    /// The table it lives in, as the statement named it.
    pub table: String,
    /// The column itself.
    pub column: String,
}

/// One column of the result and everything that produced it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
    /// The name the result carries it under.
    pub name: String,
    /// Every physical column that fed it, in a fixed order.
    pub sources: Vec<Source>,
}

/// Resolves every result column of a query to its physical origin.
///
/// # Errors
///
/// Returns a validation failure when the text is not a single query, when it
/// carries a wildcard, when a column cannot be attributed to one table, or when
/// it reads from something that is not a stored table.
pub fn resolve(statements: &[Statement]) -> Result<Vec<Column>> {
    let [Statement::Query(query)] = statements else {
        return Err(Failure::validation(
            "lineage.not_a_single_query",
            "origins can only be resolved for a single statement that returns rows",
        )
        .with_hint("send one statement that returns rows"));
    };
    let select = only_select(query)?;
    let tables = sources_of(select)?;
    select
        .projection
        .iter()
        .map(|item| column_of(item, &tables))
        .collect()
}

/// Resolves every result column, preferring what the server itself declared.
///
/// Reading the statement back can only infer an origin, and an expression, a
/// subquery or a function call is exactly where that inference goes wrong. The
/// metadata of a result carries no inference: the server names the stored table
/// and the stored column each result column came from. So the metadata answers
/// first, and the syntax tree is consulted only for the columns the server left
/// blank, which are the ones it produced rather than read from a table.
///
/// A syntax tree the reserve cannot resolve does not sink the answer here: the
/// server already resolved the stored columns, and a column it declared as
/// produced is answered as produced, which is what it is.
///
/// The labels come from the same place the header of a result comes from, so
/// the origins of a query line up with the columns it returns even when two of
/// them carry the same name.
///
/// # Errors
///
/// Returns whatever [`resolve`] refuses with when the server declared no
/// columns at all, because then there is nothing to prefer over the syntax.
pub fn resolve_declared(statements: &[Statement], declared: &[Declared]) -> Result<Vec<Column>> {
    if declared.is_empty() {
        return resolve(statements);
    }
    // The reserve costs a full parse, so it is only paid for when some column
    // actually needs it.
    let reserve = if declared
        .iter()
        .any(|column| declared_origin(column).is_none())
    {
        resolve(statements).unwrap_or_default()
    } else {
        Vec::new()
    };

    Ok(crate::exec::read::column_names(declared)
        .into_iter()
        .enumerate()
        .map(|(index, name)| Column {
            sources: declared_origin(&declared[index])
                .map_or_else(|| reserve_sources(&reserve, index), |source| vec![source]),
            name,
        })
        .collect())
}

/// The stored origin the server declared for one column, when it declared one.
///
/// A blank table or a blank name is the server saying the column is not stored,
/// which is a statement about the column and not a gap in the metadata.
///
/// Published rather than kept private, because the origin is also the only way
/// to learn the type the catalogue declares for a value. The result packet of
/// this server does not distinguish a universal identifier or a network address
/// from ordinary text, so the family of those has to be read from the stored
/// column, and this is what names it. See [`crate::types::map::family_for`].
#[must_use]
pub fn declared_origin(column: &Declared) -> Option<Source> {
    let table = column.org_table_str();
    let name = column.org_name_str();
    if table.is_empty() || name.is_empty() {
        return None;
    }
    Some(Source {
        table: table.into_owned(),
        column: name.into_owned(),
    })
}

/// What the syntax tree offered for the column at this position, if anything.
///
/// The reserve is matched by position because that is the one thing the two
/// readings of the same statement always agree on.
fn reserve_sources(reserve: &[Column], index: usize) -> Vec<Source> {
    reserve
        .get(index)
        .map(|column| column.sources.clone())
        .unwrap_or_default()
}

/// The one plain selection a query is built from.
fn only_select(query: &Query) -> Result<&Select> {
    match query.body.as_ref() {
        SetExpr::Select(select) => Ok(select),
        _ => Err(Failure::validation(
            "lineage.compound_query",
            "the query combines several selections, so a column has no single origin",
        )
        .with_hint("resolve each selection of the combination on its own")),
    }
}

/// The tables a selection reads from, by the name each is referred to under.
fn sources_of(select: &Select) -> Result<BTreeMap<String, String>> {
    let mut tables = BTreeMap::new();
    for reference in &select.from {
        add_table(&reference.relation, &mut tables)?;
        for join in &reference.joins {
            add_table(&join.relation, &mut tables)?;
        }
    }
    if tables.is_empty() {
        return Ok(tables);
    }
    Ok(tables)
}

/// Records one table reference under the name columns refer to it by.
fn add_table(relation: &TableFactor, tables: &mut BTreeMap<String, String>) -> Result<()> {
    let TableFactor::Table { name, alias, .. } = relation else {
        return Err(Failure::validation(
            "lineage.not_a_stored_table",
            "the query reads from something that is not a stored table",
        )
        .with_hint("resolve the origins of the inner query on its own"));
    };
    let real = name.to_string().replace('`', "");
    let referred = alias
        .as_ref()
        .map_or_else(|| last_part(&real), |alias| alias.name.value.clone());
    tables.insert(referred, real);
    Ok(())
}

/// The last part of a possibly qualified name.
fn last_part(name: &str) -> String {
    name.rsplit('.').next().unwrap_or(name).to_owned()
}

/// Resolves one item of the projection.
fn column_of(item: &SelectItem, tables: &BTreeMap<String, String>) -> Result<Column> {
    let (expr, name) = match item {
        SelectItem::UnnamedExpr(expr) => (expr, rendered_name(expr)),
        SelectItem::ExprWithAlias { expr, alias } => (expr, alias.value.clone()),
        SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(..) => {
            return Err(Failure::validation(
                "lineage.wildcard",
                "the query asks for every column, and which those are is not written in it",
            )
            .with_hint("name the columns the result should carry"));
        }
        // An item this tool does not recognise is refused rather than resolved
        // by guesswork, which is the rule this whole command exists for. The
        // shape is named rather than caught by a wildcard, so a shape the
        // parser gains later stops the build here instead of arriving as this
        // message about an item nobody has looked at.
        other @ SelectItem::ExprWithAliases { .. } => {
            return Err(Failure::validation(
                "lineage.unrecognised_item",
                format!("`{other}` has a shape whose origin this tool cannot resolve"),
            )
            .with_detail("detail", other.to_string())
            .with_hint("name the columns the result should carry, one by one"));
        }
    };

    let mut sources = Vec::new();
    for reference in references(expr) {
        sources.push(resolve_reference(&reference, tables, &name)?);
    }
    sources.sort();
    sources.dedup();
    Ok(Column { name, sources })
}

/// The name a result carries a column under when no other name was given.
fn rendered_name(expr: &Expr) -> String {
    match expr {
        Expr::Identifier(ident) => ident.value.clone(),
        Expr::CompoundIdentifier(parts) => parts
            .last()
            .map_or_else(|| expr.to_string(), |ident| ident.value.clone()),
        other => other.to_string(),
    }
}

/// One column mentioned in an expression, as it was written.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Reference {
    qualifier: Option<String>,
    column: String,
}

/// Every column an expression mentions, in the order they appear.
fn references(expr: &Expr) -> Vec<Reference> {
    let mut collector = Collector::default();
    let _ = expr.visit(&mut collector);
    collector.found
}

/// Walks an expression collecting every column it mentions.
#[derive(Debug, Default)]
struct Collector {
    found: Vec<Reference>,
}

impl Visitor for Collector {
    type Break = ();

    fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
        match expr {
            Expr::Identifier(ident) => self.found.push(Reference {
                qualifier: None,
                column: ident.value.clone(),
            }),
            Expr::CompoundIdentifier(parts) => {
                if let [qualifier @ .., column] = parts.as_slice() {
                    self.found.push(Reference {
                        qualifier: qualifier.last().map(|part| part.value.clone()),
                        column: column.value.clone(),
                    });
                }
            }
            _ => {}
        }
        ControlFlow::Continue(())
    }
}

/// Attributes one mentioned column to the table it lives in.
///
/// An unqualified column over more than one table cannot be attributed from the
/// tree alone, and a guess there is exactly what this command exists to avoid.
fn resolve_reference(
    reference: &Reference,
    tables: &BTreeMap<String, String>,
    column_name: &str,
) -> Result<Source> {
    if let Some(qualifier) = &reference.qualifier {
        let table = tables.get(qualifier).ok_or_else(|| {
            Failure::validation(
                "lineage.unknown_qualifier",
                format!("`{qualifier}` is not a table this query reads from"),
            )
            .with_detail("detail", qualifier.clone())
            .with_hint("check the name the column is qualified with")
        })?;
        return Ok(Source {
            table: table.clone(),
            column: reference.column.clone(),
        });
    }

    let mut named = tables.values();
    match (named.next(), named.next()) {
        (Some(only), None) => Ok(Source {
            table: only.clone(),
            column: reference.column.clone(),
        }),
        (None, _) => Err(Failure::validation(
            "lineage.no_table",
            format!("`{}` is not read from any table this query names", reference.column),
        )
        .with_detail("detail", reference.column.clone())
        .with_hint("name the table the column comes from")),
        (Some(_), Some(_)) => Err(Failure::validation(
            "lineage.ambiguous_column",
            format!(
                "`{}` in the result column `{column_name}` is not qualified, and the query reads from more than one table",
                reference.column
            ),
        )
        .with_detail("detail", reference.column.clone())
        .with_hint("qualify the column with the table it comes from")),
    }
}

/// The answer this command carries.
#[must_use]
pub fn as_value(columns: &[Column]) -> Value {
    json!({
        "rows": columns
            .iter()
            .map(|column| json!({
                "column": column.name,
                "sources": column
                    .sources
                    .iter()
                    .map(|source| json!({"table": source.table, "column": source.column}))
                    .collect::<Vec<_>>(),
                "computed": column.sources.is_empty(),
            }))
            .collect::<Vec<_>>(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sql::ParseLimits;

    fn parsed(sql: &str) -> Vec<Statement> {
        crate::sql::parse(sql, ParseLimits::default()).expect("parses")
    }

    fn columns(sql: &str) -> Vec<Column> {
        resolve(&parsed(sql)).expect("every column must resolve")
    }

    fn refusal(sql: &str) -> Failure {
        resolve(&parsed(sql)).expect_err("the answer must be refused")
    }

    #[test]
    fn a_qualified_column_resolves_to_the_table_it_lives_in() {
        let resolved = columns(
            "SELECT pedidos.total FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente",
        );
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].name, "total");
        assert_eq!(
            resolved[0].sources,
            vec![Source {
                table: "pedidos".to_owned(),
                column: "total".to_owned()
            }]
        );
    }

    #[test]
    fn an_alias_resolves_to_the_real_table_behind_it() {
        let resolved = columns("SELECT p.total FROM pedidos AS p");
        assert_eq!(resolved[0].sources[0].table, "pedidos");
    }

    /// The refusal that matters: over a join, an unqualified column has no
    /// answer in the tree, and a guess is worse than saying so.
    #[test]
    fn an_unqualified_column_over_a_join_refuses_the_whole_answer() {
        let failure =
            refusal("SELECT total FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente");
        assert_eq!(failure.code(), "lineage.ambiguous_column");
        assert_eq!(failure.exit_number().code(), 3);
        assert!(failure.message().contains("total"));
    }

    /// One bad column refuses everything, so a caller never reads a partly
    /// guessed answer as a whole one.
    #[test]
    fn one_column_that_cannot_be_attributed_refuses_the_other_columns_too() {
        let failure = refusal(
            "SELECT pedidos.total, cliente FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente",
        );
        assert_eq!(failure.code(), "lineage.ambiguous_column");
    }

    #[test]
    fn an_unqualified_column_over_one_table_resolves_without_a_guess() {
        let resolved = columns("SELECT total FROM pedidos");
        assert_eq!(resolved[0].sources[0].table, "pedidos");
        assert_eq!(resolved[0].sources[0].column, "total");
    }

    #[test]
    fn a_computed_column_lists_every_physical_column_that_fed_it() {
        let resolved = columns("SELECT p.total + p.frete AS bruto FROM pedidos AS p");
        assert_eq!(resolved[0].name, "bruto");
        assert_eq!(
            resolved[0].sources,
            vec![
                Source {
                    table: "pedidos".to_owned(),
                    column: "frete".to_owned()
                },
                Source {
                    table: "pedidos".to_owned(),
                    column: "total".to_owned()
                }
            ]
        );
    }

    #[test]
    fn a_column_that_is_a_constant_says_so_rather_than_naming_a_table() {
        let resolved = columns("SELECT 1 AS um FROM pedidos");
        assert!(resolved[0].sources.is_empty());
        assert_eq!(as_value(&resolved)["rows"][0]["computed"], true);
    }

    /// A wildcard names no columns anywhere in the statement, so answering
    /// would mean inventing the list.
    #[test]
    fn a_wildcard_is_refused_rather_than_expanded_by_guesswork() {
        assert_eq!(refusal("SELECT * FROM pedidos").code(), "lineage.wildcard");
        assert_eq!(
            refusal("SELECT p.* FROM pedidos AS p").code(),
            "lineage.wildcard"
        );
    }

    #[test]
    fn a_derived_table_is_refused_because_its_columns_are_produced_and_not_stored() {
        assert_eq!(
            refusal("SELECT s.a FROM (SELECT a FROM t) AS s").code(),
            "lineage.not_a_stored_table"
        );
    }

    #[test]
    fn a_qualifier_that_names_no_table_of_the_query_is_refused() {
        let failure = refusal("SELECT outra.total FROM pedidos");
        assert_eq!(failure.code(), "lineage.unknown_qualifier");
        assert!(failure.message().contains("outra"));
    }

    #[test]
    fn a_column_with_no_table_at_all_is_refused() {
        assert_eq!(refusal("SELECT a").code(), "lineage.no_table");
    }

    #[test]
    fn a_statement_that_does_not_return_rows_has_no_origins_to_resolve() {
        for sql in ["DELETE FROM t WHERE a = 1", "CREATE TABLE t (a INT)"] {
            assert_eq!(
                refusal(sql).code(),
                "lineage.not_a_single_query",
                "input {sql:?}"
            );
        }
    }

    #[test]
    fn a_combination_of_selections_is_refused_rather_than_merged() {
        assert_eq!(
            refusal("SELECT a FROM t UNION SELECT b FROM u").code(),
            "lineage.compound_query"
        );
    }

    /// Builds one column the way the server declares it in a result.
    fn declared(table: &str, name: &str, org_table: &str, org_name: &str) -> Declared {
        Declared::new(mysql_async::consts::ColumnType::MYSQL_TYPE_LONG)
            .with_table(table.as_bytes())
            .with_name(name.as_bytes())
            .with_org_table(org_table.as_bytes())
            .with_org_name(org_name.as_bytes())
    }

    /// FR-073: the server declares the stored column behind an alias, and the
    /// syntax tree only sees the alias. The declaration wins.
    #[test]
    fn fr_073_the_declared_origin_outranks_the_name_written_in_the_statement() {
        let resolved = resolve_declared(
            &parsed("SELECT p.total AS bruto FROM pedidos AS p"),
            &[declared("p", "bruto", "pedidos", "total")],
        )
        .expect("the server already resolved it");
        assert_eq!(resolved[0].name, "bruto");
        assert_eq!(
            resolved[0].sources,
            vec![Source {
                table: "pedidos".to_owned(),
                column: "total".to_owned()
            }]
        );
    }

    /// FR-073: an unqualified column over a join has no answer in the syntax
    /// tree, and reading it back refuses the whole answer. The server names the
    /// table, so with the declaration at hand there is nothing left to refuse.
    #[test]
    fn fr_073_a_column_the_syntax_cannot_attribute_is_answered_from_the_declaration() {
        let sql = "SELECT total FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente";
        assert_eq!(
            refusal(sql).code(),
            "lineage.ambiguous_column",
            "the syntax alone still refuses"
        );

        let resolved = resolve_declared(
            &parsed(sql),
            &[declared("pedidos", "total", "pedidos", "total")],
        )
        .expect("the declaration leaves nothing ambiguous");
        assert_eq!(resolved[0].sources[0].table, "pedidos");
    }

    /// FR-073: a blank origin is the server saying the column was produced, so
    /// the syntax tree is read back for exactly those columns and no others.
    #[test]
    fn fr_073_a_produced_column_falls_back_to_the_syntax_tree() {
        let resolved = resolve_declared(
            &parsed("SELECT p.total + p.frete AS bruto FROM pedidos AS p"),
            &[declared("", "bruto", "", "")],
        )
        .expect("the reserve answers the produced column");
        assert_eq!(
            resolved[0].sources,
            vec![
                Source {
                    table: "pedidos".to_owned(),
                    column: "frete".to_owned()
                },
                Source {
                    table: "pedidos".to_owned(),
                    column: "total".to_owned()
                }
            ]
        );
    }

    /// FR-073: a syntax tree the reserve refuses must not sink the columns the
    /// server already declared in full.
    #[test]
    fn fr_073_a_refused_reserve_does_not_sink_a_declared_answer() {
        let resolved = resolve_declared(
            &parsed("SELECT *, 1 FROM pedidos"),
            &[
                declared("pedidos", "total", "pedidos", "total"),
                declared("", "1", "", ""),
            ],
        )
        .expect("the wildcard refusal stays inside the reserve");
        assert_eq!(resolved[0].sources[0].column, "total");
        assert!(resolved[1].sources.is_empty(), "a produced column says so");
    }

    /// FR-073 with FR-102: two homonymous columns keep two origins, each under
    /// the label the result itself carries.
    #[test]
    fn fr_073_two_homonymous_columns_keep_two_distinct_origins() {
        let resolved = resolve_declared(
            &parsed("SELECT pedidos.id, clientes.id FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente"),
            &[
                declared("pedidos", "id", "pedidos", "id"),
                declared("clientes", "id", "clientes", "id"),
            ],
        )
        .expect("both columns resolve");
        assert_eq!(resolved.len(), 2);
        assert_eq!(resolved[0].name, "pedidos.id");
        assert_eq!(resolved[1].name, "clientes.id");
        assert_eq!(resolved[0].sources[0].table, "pedidos");
        assert_eq!(resolved[1].sources[0].table, "clientes");
    }

    /// FR-073: with no declaration at hand the command is exactly what it was,
    /// which is what keeps it answerable without opening a connection.
    #[test]
    fn fr_073_without_a_declaration_the_syntax_tree_answers_alone() {
        let resolved =
            resolve_declared(&parsed("SELECT p.total FROM pedidos AS p"), &[]).expect("resolves");
        assert_eq!(resolved, columns("SELECT p.total FROM pedidos AS p"));
        assert_eq!(
            resolve_declared(
                &parsed("SELECT total FROM pedidos JOIN clientes ON clientes.id = pedidos.cliente"),
                &[]
            )
            .expect_err("the refusal is kept")
            .code(),
            "lineage.ambiguous_column"
        );
    }

    #[test]
    fn the_answer_keeps_a_fixed_order_so_two_runs_agree() {
        let first = as_value(&columns("SELECT p.total, p.frete FROM pedidos AS p"));
        let second = as_value(&columns("SELECT p.total, p.frete FROM pedidos AS p"));
        assert_eq!(first, second);
        assert_eq!(first["rows"][0]["column"], "total");
        assert_eq!(first["rows"][1]["column"], "frete");
    }
}