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
//! Classification of a statement by its syntax tree.
//!
//! The reference implementations decide what a statement does by looking at its
//! first word. That is wrong in both directions: a leading comment moves the
//! first word, and a reserved word inside a literal is not the first word of
//! anything. This module parses the statement and decides from the tree.
//!
//! # Refusal is the default
//!
//! A statement whose shape this module does not recognise is refused. It is
//! never treated as a read, because a wrong guess in that direction is the one
//! that changes data.
//!
//! Reading the text into a tree, and the bounds that make that safe, belong to
//! [`mod@crate::sql::parse`]. This module only decides what the tree means.

use crate::error::{Failure, Result};
use crate::sql::parse::{parse, ParseLimits};
use sqlparser::ast::Statement;

/// What a statement does, as read from its syntax tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Classification {
    /// Returns rows and leaves the server unchanged.
    Read,
    /// Adds, alters or removes rows.
    Change,
    /// Adds, alters or removes an object.
    Definition,
    /// Acts on the session, the transaction, a privilege or the server itself.
    Administration,
}

impl Classification {
    /// The stable name used in output and in a refusal message.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Read => "read",
            Self::Change => "change",
            Self::Definition => "definition",
            Self::Administration => "administration",
        }
    }

    /// Whether the statement leaves the server unchanged.
    #[must_use]
    pub const fn is_read(self) -> bool {
        matches!(self, Self::Read)
    }
}

/// The outcome of reading one statement.
#[derive(Debug, Clone)]
pub struct Analysis {
    classification: Classification,
    kind: &'static str,
    statements: Vec<Statement>,
}

impl Analysis {
    /// What the statement does.
    #[must_use]
    pub const fn classification(&self) -> Classification {
        self.classification
    }

    /// The recognised statement shape, such as `select` or `create_table`.
    ///
    /// Simulation branches on this, so it is a stable identifier and not prose.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        self.kind
    }

    /// The parsed statements, in the order they were written.
    #[must_use]
    pub fn statements(&self) -> &[Statement] {
        &self.statements
    }
}

/// Reads a statement and says what it does.
///
/// # Errors
///
/// Returns a validation failure when the statement is empty, exceeds the size
/// ceiling, cannot be parsed, or has a shape this module does not recognise.
pub fn analyze(sql: &str, limits: ParseLimits) -> Result<Analysis> {
    if let Some(known) = recalled(sql, limits) {
        return Ok(known);
    }
    let fresh = read_fresh(sql, limits)?;
    remember(sql, limits, &fresh);
    Ok(fresh)
}

/// The one statement this invocation has already read, if it read one.
///
/// # Why anything is remembered at all
///
/// One invocation of `query run` reads the same text twice. The dispatch calls
/// [`classify`] before a session exists, to decide whether the answer can be
/// streamed, and the execution path then calls [`analyze`] again through
/// `guard::admit`. Each call reaches [`parse`], and [`parse`] spawns a thread
/// with an enlarged stack and joins it, so the second reading paid for a second
/// thread to reach a conclusion the first had already reached.
///
/// # Why one entry is the right size
///
/// This binary is born, runs one invocation and dies. There is one statement,
/// so a map would carry bookkeeping for a second entry that never arrives.
/// A miss costs exactly what the code cost before, which is why a call from
/// another thread is a lost saving rather than a defect.
///
/// Failures are deliberately not remembered: a refusal is answered once and the
/// invocation ends, so storing it would only widen what has to stay correct.
type Remembered = Option<(String, ParseLimits, Analysis)>;

thread_local! {
    static LAST_READ: core::cell::RefCell<Remembered> = const { core::cell::RefCell::new(None) };
}

/// The reading of this exact text under these exact limits, if it is held.
fn recalled(sql: &str, limits: ParseLimits) -> Option<Analysis> {
    LAST_READ.with_borrow(|held| {
        held.as_ref().and_then(|(text, held_limits, analysis)| {
            (text == sql && *held_limits == limits).then(|| analysis.clone())
        })
    })
}

/// Holds one reading, replacing whatever was held before.
fn remember(sql: &str, limits: ParseLimits, analysis: &Analysis) {
    LAST_READ.with_borrow_mut(|held| {
        *held = Some((sql.to_owned(), limits, analysis.clone()));
    });
}

/// Reads a statement without consulting or filling what is held.
fn read_fresh(sql: &str, limits: ParseLimits) -> Result<Analysis> {
    note_fresh_read();
    let statements = parse(sql, limits)?;
    let first = statements.first().ok_or_else(|| {
        Failure::validation("sql.empty", "the statement is empty").with_hint("send one statement")
    })?;
    let (classification, kind) = read_statement(first)?;
    Ok(Analysis {
        classification,
        kind,
        statements,
    })
}

/// Reads a statement and says what it does, discarding the tree.
///
/// # Errors
///
/// Same conditions as [`analyze`].
pub fn classify(sql: &str, limits: ParseLimits) -> Result<Classification> {
    analyze(sql, limits).map(|analysis| analysis.classification)
}

/// Decides what one statement does, or refuses it.
///
/// The categories are tried in order and the first match wins. A statement no
/// category claims is refused rather than assumed harmless.
fn read_statement(statement: &Statement) -> Result<(Classification, &'static str)> {
    // `EXPLAIN ANALYZE` runs the statement it wraps, so it inherits what that
    // statement does. Plain `EXPLAIN` only reports a plan.
    if let Statement::Explain {
        analyze: true,
        statement: inner,
        ..
    } = statement
    {
        return read_statement(inner);
    }

    if let Some(kind) = read_kind(statement) {
        return Ok((Classification::Read, kind));
    }
    if let Some(kind) = change_kind(statement) {
        return Ok((Classification::Change, kind));
    }
    if let Some(kind) = definition_kind(statement) {
        return Ok((Classification::Definition, kind));
    }
    if let Some(kind) = administration_kind(statement) {
        return Ok((Classification::Administration, kind));
    }

    Err(Failure::validation(
        "sql.unclassified",
        "the statement has a shape this tool does not recognise",
    )
    .with_hint("a statement that cannot be classified is refused rather than assumed to be a read"))
}

/// Statements that return rows and leave the server unchanged.
fn read_kind(statement: &Statement) -> Option<&'static str> {
    Some(match statement {
        Statement::Query(_) => "select",
        Statement::Explain { .. } => "explain",
        Statement::ExplainTable { .. } => "describe",
        Statement::ShowCatalogs { .. } => "show_catalogs",
        Statement::ShowCharset(_) => "show_charset",
        Statement::ShowCollation { .. } => "show_collation",
        Statement::ShowColumns { .. } => "show_columns",
        Statement::ShowCreate { .. } => "show_create",
        Statement::ShowDatabases { .. } => "show_databases",
        Statement::ShowFunctions { .. } => "show_functions",
        Statement::ShowObjects(_) => "show_objects",
        Statement::ShowProcessList { .. } => "show_process_list",
        Statement::ShowSchemas { .. } => "show_schemas",
        Statement::ShowStatus { .. } => "show_status",
        Statement::ShowTables { .. } => "show_tables",
        Statement::ShowVariable { .. } => "show_variable",
        Statement::ShowVariables { .. } => "show_variables",
        Statement::ShowViews { .. } => "show_views",
        _ => return None,
    })
}

/// Statements that add, alter or remove rows.
fn change_kind(statement: &Statement) -> Option<&'static str> {
    Some(match statement {
        Statement::Insert(_) => "insert",
        Statement::Update(_) => "update",
        Statement::Delete(_) => "delete",
        Statement::Merge(_) => "merge",
        Statement::Copy { .. } => "copy",
        Statement::Directory { .. } => "insert_into_directory",
        Statement::LoadData { .. } => "load_data",
        Statement::Unload { .. } => "unload",
        _ => return None,
    })
}

/// Statements that add, alter or remove an object.
///
/// `TRUNCATE` sits here and not with the row changes: on this server it commits
/// implicitly and a rollback does not undo it.
fn definition_kind(statement: &Statement) -> Option<&'static str> {
    Some(match statement {
        Statement::AlterFunction(_) => "alter_function",
        Statement::AlterIndex { .. } => "alter_index",
        Statement::AlterSchema(_) => "alter_schema",
        Statement::AlterTable(_) => "alter_table",
        Statement::AlterType(_) => "alter_type",
        Statement::AlterView { .. } => "alter_view",
        Statement::CreateDatabase { .. } => "create_database",
        Statement::CreateFunction(_) => "create_function",
        Statement::CreateIndex(_) => "create_index",
        Statement::CreateProcedure { .. } => "create_procedure",
        Statement::CreateSchema { .. } => "create_schema",
        Statement::CreateSequence { .. } => "create_sequence",
        Statement::CreateTable(_) => "create_table",
        Statement::CreateTrigger(_) => "create_trigger",
        Statement::CreateType { .. } => "create_type",
        Statement::CreateView(_) => "create_view",
        Statement::CreateVirtualTable { .. } => "create_virtual_table",
        Statement::Drop { .. } => "drop",
        Statement::DropFunction(_) => "drop_function",
        Statement::DropProcedure { .. } => "drop_procedure",
        Statement::DropTrigger(_) => "drop_trigger",
        Statement::RenameTable(_) => "rename_table",
        Statement::Truncate(_) => "truncate",
        _ => return None,
    })
}

/// Statements that act on the session, the transaction, a privilege or the
/// server itself.
fn administration_kind(statement: &Statement) -> Option<&'static str> {
    Some(match statement {
        Statement::Analyze(_) => "analyze",
        Statement::AlterRole { .. } => "alter_role",
        Statement::Call(_) => "call",
        Statement::Commit { .. } => "commit",
        Statement::CreateRole(_) => "create_role",
        Statement::Deallocate { .. } => "deallocate",
        Statement::Deny(_) => "deny",
        Statement::Execute { .. } => "execute",
        Statement::Flush { .. } => "flush",
        Statement::Grant(_) => "grant",
        Statement::Install { .. } => "install",
        Statement::Kill { .. } => "kill",
        Statement::Lock(_) => "lock",
        Statement::LockTables { .. } => "lock_tables",
        Statement::OptimizeTable { .. } => "optimize_table",
        Statement::Prepare { .. } => "prepare",
        Statement::ReleaseSavepoint { .. } => "release_savepoint",
        Statement::Revoke(_) => "revoke",
        Statement::Rollback { .. } => "rollback",
        Statement::Savepoint { .. } => "savepoint",
        Statement::Set(_) => "set",
        Statement::StartTransaction { .. } => "start_transaction",
        Statement::UnlockTables => "unlock_tables",
        Statement::Use(_) => "use",
        _ => return None,
    })
}

// Everything below is scaffolding for the proofs, and it is placed here rather
// than beside what it measures for a reason worth writing down: the catalogue
// proof decides where a file stops being the product by finding the first
// `#[cfg(test)]` in it, and treats every failure code after that point as one a
// reader can never reach. A counter written in the middle of this module moved
// that boundary above two live codes, and the catalogue prose for both was
// reported as words nothing could render. Test-only items belong next to the
// tests, and this is not a matter of taste here — the boundary is read.

// How many statements were read afresh, counted only while testing.
//
// What is saved by holding a reading cannot be seen in a result: a served
// reading and a fresh one return the same value, which is what makes holding
// one safe and also what makes it impossible to prove by looking at what comes
// back. The number of readings is the only difference there is to observe.
#[cfg(test)]
thread_local! {
    static FRESH_READS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}

/// Records that one statement was read afresh.
///
/// A call rather than an attribute at the one place it matters, so that no
/// `#[cfg(test)]` is written above the failures this module raises.
#[cfg(test)]
fn note_fresh_read() {
    FRESH_READS.with(|count| count.set(count.get() + 1));
}

/// Records nothing, and costs nothing, in every build that is not a test.
#[cfg(not(test))]
const fn note_fresh_read() {}

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

    fn kind_of(sql: &str) -> (Classification, &'static str) {
        let analysis = analyze(sql, ParseLimits::default()).expect("recognised statement");
        (analysis.classification(), analysis.kind())
    }

    /// How many statements were read afresh while the work ran.
    ///
    /// A difference rather than a total, because the harness is free to put two
    /// tests on one thread and what is held is per thread. Every test below
    /// also opens with text of its own, so an entry left by a neighbour is for
    /// a different statement and cannot be mistaken for a saving.
    fn readings_during(work: impl FnOnce()) -> usize {
        let before = FRESH_READS.with(core::cell::Cell::get);
        work();
        FRESH_READS.with(core::cell::Cell::get) - before
    }

    #[test]
    fn one_statement_read_twice_is_parsed_once() {
        let sql = "SELECT 1 /* read twice */";
        let readings = readings_during(|| {
            let first = analyze(sql, ParseLimits::default()).expect("read");
            let second = analyze(sql, ParseLimits::default()).expect("read");
            assert_eq!(first.classification(), second.classification());
            assert_eq!(first.kind(), second.kind());
        });
        assert_eq!(
            readings, 1,
            "the second reading of one statement must be served, not parsed again"
        );
    }

    #[test]
    fn what_is_held_is_one_statement_and_not_a_map() {
        let one = "SELECT 1 /* held first */";
        let other = "SELECT 2 /* held second */";
        let readings = readings_during(|| {
            analyze(one, ParseLimits::default()).expect("read");
            analyze(other, ParseLimits::default()).expect("read");
            analyze(one, ParseLimits::default()).expect("read");
        });
        assert_eq!(
            readings, 3,
            "a second statement replaces the first, so returning to it costs a reading"
        );
    }

    #[test]
    fn the_same_text_under_other_limits_is_read_again() {
        let sql = "SELECT 1 /* two ceilings */";
        let readings = readings_during(|| {
            analyze(sql, ParseLimits::default()).expect("read");
            analyze(sql, ParseLimits::new(4096, 0)).expect("read");
        });
        assert_eq!(
            readings, 2,
            "limits are part of what was asked, so a different ceiling is a different question"
        );
    }

    #[test]
    fn a_refusal_is_not_held() {
        let sql = "SELECT FROM WHERE /* refused twice */";
        let readings = readings_during(|| {
            analyze(sql, ParseLimits::default()).expect_err("refused");
            analyze(sql, ParseLimits::default()).expect_err("refused");
        });
        assert_eq!(
            readings, 2,
            "a refusal is answered once and the invocation ends, so nothing is stored for it"
        );
    }

    #[test]
    fn a_select_is_a_read() {
        assert_eq!(kind_of("SELECT 1").0, Classification::Read);
        assert_eq!(kind_of("SELECT * FROM t WHERE a = 1").1, "select");
    }

    #[test]
    fn the_row_changing_statements_are_changes() {
        for sql in [
            "INSERT INTO t (a) VALUES (1)",
            "UPDATE t SET a = 1",
            "DELETE FROM t",
        ] {
            assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
        }
    }

    #[test]
    fn the_object_changing_statements_are_definitions() {
        for sql in [
            "CREATE TABLE t (a INT)",
            "DROP TABLE t",
            "ALTER TABLE t ADD COLUMN b INT",
            "TRUNCATE TABLE t",
        ] {
            assert_eq!(kind_of(sql).0, Classification::Definition, "input {sql:?}");
        }
    }

    #[test]
    fn the_session_and_privilege_statements_are_administration() {
        for sql in [
            "SET autocommit = 1",
            "START TRANSACTION",
            "COMMIT",
            "ROLLBACK",
            "USE other",
        ] {
            assert_eq!(
                kind_of(sql).0,
                Classification::Administration,
                "input {sql:?}"
            );
        }
    }

    /// The reference implementations read the first word. A comment in front of
    /// it, or in the middle of it, must not move the decision.
    #[test]
    fn a_destructive_statement_hidden_behind_a_comment_is_still_a_change() {
        for sql in [
            "/* SELECT */ DELETE FROM users",
            "-- SELECT 1\nDELETE FROM users",
            "DELETE /* looks harmless */ FROM users",
            "# SELECT 1\nDELETE FROM users",
        ] {
            assert_eq!(kind_of(sql).0, Classification::Change, "input {sql:?}");
        }
    }

    #[test]
    fn a_reserved_word_inside_a_literal_does_not_change_the_decision() {
        for sql in [
            "SELECT 'DROP TABLE users' AS note",
            "SELECT * FROM t WHERE note = 'DELETE FROM users'",
            "SELECT \"CREATE TABLE x\" AS note",
        ] {
            assert_eq!(kind_of(sql).0, Classification::Read, "input {sql:?}");
        }
    }

    #[test]
    fn letter_case_does_not_change_the_decision() {
        assert_eq!(kind_of("select 1").0, Classification::Read);
        assert_eq!(kind_of("SeLeCt 1").0, Classification::Read);
        assert_eq!(kind_of("delete from t").0, Classification::Change);
        assert_eq!(kind_of("DeLeTe FrOm t").0, Classification::Change);
    }

    #[test]
    fn a_plain_explain_is_a_read_even_over_a_destructive_statement() {
        assert_eq!(kind_of("EXPLAIN DELETE FROM t").0, Classification::Read);
    }

    /// `EXPLAIN ANALYZE` runs the statement it wraps, so it cannot be read as a
    /// plan request.
    #[test]
    fn an_explain_that_runs_the_statement_inherits_what_that_statement_does() {
        assert_eq!(
            kind_of("EXPLAIN ANALYZE DELETE FROM t").0,
            Classification::Change
        );
        assert_eq!(kind_of("EXPLAIN ANALYZE SELECT 1").0, Classification::Read);
    }

    #[test]
    fn an_unparsable_statement_is_refused_and_never_read_as_a_query() {
        let failure = analyze("SELECT FROM WHERE", ParseLimits::default())
            .expect_err("unparsable text is refused");
        assert_eq!(failure.code(), "sql.unparsable");
    }

    #[test]
    fn an_empty_statement_is_refused() {
        let failure =
            analyze("   ", ParseLimits::default()).expect_err("an empty statement is refused");
        assert!(matches!(failure.code(), "sql.empty" | "sql.unparsable"));
    }

    // The bounds are exercised in the module tests.
    #[test]
    fn the_parsed_tree_is_exposed_for_the_guards_and_for_simulation() {
        let analysis = analyze("SELECT 1", ParseLimits::default()).expect("read");
        assert_eq!(analysis.statements().len(), 1);
        assert!(analysis.classification().is_read());
    }
}