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
//! Statements that alter data, and every ceiling that guards them.
//!
//! # The ceiling on affected rows is checked before the change, always
//!
//! The obvious implementation runs the change inside an atomic block, counts
//! what it touched and undoes the block when the count is too high. That works
//! only while a block exists, and a statement that defines an object confirms
//! itself on this server, so no block can undo it. Worse, without a block there
//! is nothing to undo at all, which is precisely when a caller most needs a
//! ceiling.
//!
//! So the count is derived from the statement's own restriction by
//! [`crate::exec::plan::estimate`], run first, and the change is refused before
//! it is sent. That costs one extra round trip on every change. The cost was
//! accepted deliberately, because a ceiling that only works inside a block is a
//! ceiling that fails in the case it exists for.
//!
//! When no count can be derived, the answer declares a gap rather than
//! pretending the ceiling was applied.
//!
//! # A table with no unique key
//!
//! A row of such a table cannot be named again afterwards, so the change cannot
//! be repeated safely. That makes a repeat unsafe; it does not make this change
//! wrong. The absence is therefore reported on the auxiliary channel and the
//! change proceeds, unless `sql.require_unique_key` asks for the stricter rule.

use super::plan::{self, Estimate, Target};
use super::prepare::{self, Gated};
use super::{ChangeCounts, Policy, WriteState};
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::envelope::Gap;
use mysql_async::prelude::Queryable;
use mysql_async::Conn;
use serde_json::{json, Value};
use sqlparser::ast::Statement;

/// Refuses a change that would reach every row of its table.
///
/// The decision comes from the syntax tree and never from the text, so a
/// restriction hidden behind a comment still counts as one.
///
/// # Errors
///
/// Returns a validation failure naming the table the change would have reached
/// in full.
pub fn refuse_without_restriction(gated: &Gated) -> Result<()> {
    let Some(statement) = gated.admission().analysis().statements().first() else {
        return Ok(());
    };
    if !matches!(statement, Statement::Delete(_) | Statement::Update(_))
        || plan::restriction_of(statement).is_some()
    {
        return Ok(());
    }
    let named =
        plan::target_of(statement).map_or_else(|| "the target table".to_owned(), |t| t.table);
    Err(Failure::validation(
        "safety.no_restriction",
        format!("this change would reach every row of `{named}`"),
    )
    .with_detail("detail", named)
    .with_hint("add a restriction, or set sql.require_where to false to allow the whole table"))
}

/// The refusal a change over the ceiling produces, before it is sent.
#[must_use]
pub fn over_ceiling(would_affect: u64, ceiling: u64) -> Failure {
    Failure::limit(
        "limit.affected_rows",
        format!("this change would affect {would_affect} rows and the ceiling is {ceiling}"),
    )
    .with_detail("detail", format!("{would_affect} > {ceiling}"))
    .with_hint("narrow the restriction, or raise --max-affected")
}

/// Decides, before the change is sent, whether the ceiling admits it.
///
/// Returns the predicted count when one could be established, and a declared
/// gap when none could.
///
/// # Errors
///
/// Returns a limit failure when the prediction exceeds the ceiling, and the
/// mapped driver failure when the derived count could not be run.
pub async fn admit_scale(
    conn: &mut Conn,
    gated: &Gated,
    ceiling: u64,
) -> Result<(Option<u64>, Option<Gap>)> {
    let Some(statement) = gated.admission().analysis().statements().first() else {
        return Ok((None, None));
    };

    let predicted = match plan::estimate(statement) {
        Estimate::Known(rows) => rows,
        Estimate::Unavailable(reason) => return Ok((None, Some(plan::undecidable_gap(reason)))),
        Estimate::Derived(count_sql) => {
            let values = plan::count_values(&count_sql, gated.values());
            prepare::exec_count(conn, &count_sql, prepare::bind(values)).await?
        }
    };

    if predicted > ceiling {
        return Err(over_ceiling(predicted, ceiling));
    }
    Ok((Some(predicted), None))
}

/// Whether the target table can name a row again afterwards.
///
/// Answers `None` when the question itself could not be asked, which is not the
/// same as a table without a key and is never reported as one.
///
/// # Errors
///
/// Returns the mapped driver failure when the channel is lost.
pub async fn has_unique_key(conn: &mut Conn, target: &Target) -> Result<Option<bool>> {
    const QUERY: &str = "SELECT COUNT(*) FROM information_schema.table_constraints \
         WHERE table_schema = COALESCE(NULLIF(?, ''), DATABASE()) \
           AND table_name = ? \
           AND constraint_type IN ('PRIMARY KEY', 'UNIQUE')";
    let values = vec![
        target.database.clone().unwrap_or_default(),
        target.table.clone(),
    ];
    match prepare::exec_count(conn, QUERY, prepare::bind(&values)).await {
        Ok(count) => Ok(Some(count > 0)),
        // The question itself failing must not be read as an answer of "no".
        Err(failure) if failure.category() == crate::error::Category::Server => Ok(None),
        Err(other) => Err(other),
    }
}

/// Applies the rule for a table that cannot name its rows again.
///
/// # Errors
///
/// Returns a validation failure only when the stricter rule was asked for.
pub fn report_missing_unique_key(target: &Target, policy: &Policy) -> Result<()> {
    if policy.require_unique_key {
        return Err(Failure::validation(
            "safety.no_unique_key",
            format!(
                "`{}` has no primary or unique key, so this change cannot be repeated safely",
                target.table
            ),
        )
        .with_detail("detail", target.table.clone())
        .with_hint("set sql.require_unique_key to false to proceed with a warning instead"));
    }
    crate::i18n::report::safety_no_unique_key(&target.table);
    Ok(())
}

/// Every condition the server reported for the statement, not only the first.
///
/// The server may report several conditions for one statement, and returning
/// only the first hides from the caller the very one they have to fix. When the
/// conditions cannot be read at all, an empty list is returned: inventing one
/// would be worse than reporting none.
pub async fn conditions(conn: &mut Conn) -> Vec<String> {
    let Ok(result) = conn.query_iter("SHOW WARNINGS").await else {
        return Vec::new();
    };
    let collected: std::result::Result<Vec<(String, u32, String)>, _> =
        result.collect_and_drop().await;
    collected.map_or_else(
        |_| Vec::new(),
        |rows| {
            rows.into_iter()
                .map(|(level, code, text)| format!("{level} {code}: {text}"))
                .collect()
        },
    )
}

/// Attaches every condition beyond the first to a failure.
///
/// The first one is already the failure's own message, so repeating it would
/// make the caller read the same line twice.
#[must_use]
pub fn with_conditions(failure: Failure, conditions: &[String]) -> Failure {
    conditions
        .iter()
        .skip(1)
        .fold(failure, |carried, condition| {
            carried.with_extra_condition(condition.clone())
        })
}

/// What one change produced.
#[derive(Debug, Default)]
pub struct ChangeOutcome {
    /// The two counts and the mark of which was asked for.
    pub counts: Option<ChangeCounts>,
    /// The rows the change was predicted to touch, before it was sent.
    pub predicted: Option<u64>,
    /// The identifier the server generated, when it generated one.
    pub last_insert_id: Option<u64>,
    /// Every condition the server reported.
    pub conditions: Vec<String>,
    /// What the caller asked for and did not get.
    pub gaps: Vec<Gap>,
    /// Whether the change was described rather than caused.
    pub simulated: bool,
}

impl ChangeOutcome {
    /// The answer this outcome carries.
    ///
    /// A simulation carries the prediction and no measured count, because it
    /// measured nothing; claiming otherwise would be inventing a result.
    #[must_use]
    pub fn as_value(&self) -> Value {
        let mut data = json!({ "simulated": self.simulated });
        if let Some(counts) = self.counts {
            data["rows"] = counts.as_value();
        }
        if let Some(predicted) = self.predicted {
            data["predicted_rows"] = json!(predicted);
        }
        if let Some(identifier) = self.last_insert_id {
            data["generated_id"] = json!(identifier);
        }
        if !self.conditions.is_empty() {
            data["conditions"] = json!(self.conditions);
        }
        data
    }
}

/// Puts one change through every ceiling that guards it, then applies it.
///
/// The order is the design: refuse outright, then confirm, then ask the
/// destination whether it accepts a change at all, then the restriction, then
/// the key, then the scale. Only the last two cost a round trip, and they are
/// asked last so every refusal that costs nothing comes first.
///
/// # Errors
///
/// Returns the first refusal any of those layers produced, or the mapped driver
/// failure when the change itself was refused by the server.
pub async fn apply(
    gated: &Gated,
    conn: &mut Conn,
    policy: &Policy,
    write_state: &mut WriteState,
    server_read_only: bool,
) -> Result<ChangeOutcome> {
    policy.admit_change(gated.kind())?;
    write_state.admit(server_read_only)?;
    if policy.require_where {
        refuse_without_restriction(gated)?;
    }

    let mut gaps = Vec::new();
    if let Some(target) = gated
        .admission()
        .analysis()
        .statements()
        .first()
        .and_then(plan::target_of)
    {
        match has_unique_key(conn, &target).await? {
            Some(false) => report_missing_unique_key(&target, policy)?,
            Some(true) => {}
            None => gaps.push(Gap::new(
                "unique_key_check",
                "unreadable",
                "whether the target table can name a row again could not be established",
            )),
        }
    }

    let (predicted, gap) = admit_scale(conn, gated, policy.max_affected).await?;
    gaps.extend(gap);

    if policy.dry_run {
        return Ok(ChangeOutcome {
            predicted,
            gaps,
            simulated: true,
            ..ChangeOutcome::default()
        });
    }

    let mut outcome = send(conn, gated, policy).await?;
    outcome.predicted = predicted;
    outcome.gaps.extend(gaps);
    Ok(outcome)
}

/// Describes what one change did, with any notice the invocation earned.
///
/// The notice about state that dies with the process is raised only where the
/// statement actually created such state, so a plain change carries none.
#[must_use]
pub fn describe(gated: &Gated, outcome: &ChangeOutcome) -> Value {
    let mut data = outcome.as_value();
    if let Some(state) = super::Ephemeral::detect(gated.kind(), gated.admission().stripped().text())
    {
        data["ephemeral"] = json!({"state": state.as_str(), "notice": state.notice()});
        crate::i18n::report::ephemeral_state(state.as_str());
    }
    data
}

/// Raises the notice about session state on an answer that carries none.
///
/// The notice a statement earned by actually creating state is more precise
/// than this one and is never overwritten by it. This is the blanket form, for
/// the caller who asked to be reminded on every invocation that opens a
/// session rather than only on the ones that left something behind.
pub fn note_session_is_ephemeral(data: &mut Value) {
    let Some(map) = data.as_object_mut() else {
        return;
    };
    if map.contains_key("ephemeral") {
        return;
    }
    map.insert(
        "ephemeral".to_owned(),
        json!({
            "state": "session",
            "notice": "this invocation holds its own session, and every piece of \
                       state in it dies when the process ends",
        }),
    );
}

/// Sends one change and reads back everything the server said about it.
///
/// # Errors
///
/// Returns the mapped driver failure, carrying every condition the server
/// reported rather than only the first.
pub async fn send(conn: &mut Conn, gated: &Gated, policy: &Policy) -> Result<ChangeOutcome> {
    // Said here because this is the one place that holds all three: the text
    // that leaves, how many values travel with it, and what the statement was
    // admitted as. The diagnostic was written and published and nothing ever
    // called it, which made it a promise to a caller reading the auxiliary
    // channel that the channel never kept.
    crate::i18n::report::statement_sending(
        gated.sql(),
        gated.values().len(),
        gated.classification().as_str(),
    );

    // The prepared protocol, so the server itself refuses a multiple command.
    let outcome = conn.exec_iter(gated.sql(), gated.params()).await;
    let result = match outcome {
        Ok(result) => result,
        Err(error) => {
            let failure = crate::conn::map_driver_error(&error);
            let reported = conditions(conn).await;
            return Err(with_conditions(failure, &reported));
        }
    };
    result.drop_result().await.or_failure()?;

    let counts = ChangeCounts::read(conn.affected_rows(), &conn.info(), policy.row_count_mode);
    let last_insert_id = conn.last_insert_id();
    Ok(ChangeOutcome {
        counts: Some(counts),
        last_insert_id,
        conditions: conditions(conn).await,
        ..ChangeOutcome::default()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::globals::RowCountMode;
    use crate::exec::prepare;
    use crate::sql::ParseLimits;
    use std::time::Duration;

    fn policy() -> Policy {
        let mut policy = Policy::new(
            ParseLimits::default(),
            100,
            50,
            RowCountMode::Changed,
            ";".to_owned(),
            Duration::from_secs(30),
        );
        policy.read_only = false;
        policy.confirmed = true;
        policy
    }

    fn gated(sql: &str) -> Gated {
        prepare::gate(sql, &[], &policy()).expect("admitted")
    }

    /// A change with no restriction reaches every row, and one hidden behind a
    /// comment is still a restriction, because the decision comes from the tree
    /// and never from the text.
    #[test]
    fn a_change_reaching_every_row_is_refused_and_the_table_is_named() {
        for sql in ["DELETE FROM pedidos", "UPDATE pedidos SET pago = 1"] {
            let failure = refuse_without_restriction(&gated(sql)).expect_err("must refuse");
            assert_eq!(failure.code(), "safety.no_restriction", "input {sql:?}");
            assert!(failure.message().contains("pedidos"), "input {sql:?}");
            assert_eq!(failure.exit_number().code(), 3);
        }
        for sql in [
            "DELETE FROM pedidos WHERE id = 7",
            "INSERT INTO t (a) VALUES (1)",
            "DELETE /* note */ FROM t WHERE a = 1",
        ] {
            assert!(
                refuse_without_restriction(&gated(sql)).is_ok(),
                "input {sql:?}"
            );
        }
    }

    #[test]
    fn a_change_over_the_ceiling_is_a_limit_failure_naming_both_numbers() {
        let failure = over_ceiling(5000, 100);
        assert_eq!(failure.code(), "limit.affected_rows");
        assert_eq!(failure.exit_number().code(), 10);
        assert!(failure.message().contains("5000") && failure.message().contains("100"));
    }

    #[test]
    fn a_table_without_a_unique_key_warns_by_default_and_refuses_only_on_request() {
        let target = Target {
            database: None,
            table: "eventos".to_owned(),
        };
        assert!(
            report_missing_unique_key(&target, &policy()).is_ok(),
            "the default warns, so a legitimate change is not blocked"
        );

        let mut strict = policy();
        strict.require_unique_key = true;
        let failure =
            report_missing_unique_key(&target, &strict).expect_err("the stricter rule refuses");
        assert_eq!(failure.code(), "safety.no_unique_key");
        assert!(failure.message().contains("eventos"));
    }

    /// Reporting only the first condition hides the one the caller must fix.
    #[test]
    fn every_condition_the_server_reported_reaches_the_caller() {
        let reported = vec![
            "Warning 1264: out of range for column `a`".to_owned(),
            "Warning 1264: out of range for column `b`".to_owned(),
            "Warning 1265: data truncated for column `c`".to_owned(),
        ];
        let failure = with_conditions(
            Failure::server("server.condition", reported[0].clone()),
            &reported,
        );
        assert_eq!(failure.extra_conditions().len(), 2);
        assert!(failure.extra_conditions()[1].contains("1265"));

        // The first condition is already the failure's own message, so it is
        // never repeated as an extra one.
        let only = vec!["Warning 1264: out of range".to_owned()];
        let single = with_conditions(Failure::server("server.condition", "x"), &only);
        assert!(single.extra_conditions().is_empty());
    }

    /// The blanket notice never overwrites the precise one a statement earned,
    /// and never lands on anything that is not an answer object.
    #[test]
    fn the_blanket_notice_yields_to_the_one_the_statement_earned() {
        let mut plain = json!({"simulated": false});
        note_session_is_ephemeral(&mut plain);
        assert_eq!(plain["ephemeral"]["state"], "session");
        assert!(plain["ephemeral"]["notice"]
            .as_str()
            .is_some_and(|notice| notice.contains("process ends")));

        let mut earned = json!({"ephemeral": {"state": "temporary_table"}});
        note_session_is_ephemeral(&mut earned);
        assert_eq!(earned["ephemeral"]["state"], "temporary_table");

        let mut not_an_object = json!([1, 2]);
        note_session_is_ephemeral(&mut not_an_object);
        assert_eq!(not_an_object, json!([1, 2]));
    }

    /// A simulation measured nothing, so it must never report a measurement; a
    /// completed change reports both counts and anything the server generated.
    #[test]
    fn a_simulation_reports_its_prediction_and_a_change_reports_its_measurement() {
        let simulated = ChangeOutcome {
            simulated: true,
            predicted: Some(12),
            ..ChangeOutcome::default()
        }
        .as_value();
        assert_eq!(simulated["simulated"], true);
        assert_eq!(simulated["predicted_rows"], 12);
        assert!(simulated.get("rows").is_none());

        let applied = ChangeOutcome {
            counts: Some(ChangeCounts::read(
                1,
                "Rows matched: 2  Changed: 1  Warnings: 0",
                RowCountMode::Changed,
            )),
            last_insert_id: Some(77),
            ..ChangeOutcome::default()
        }
        .as_value();
        assert_eq!(applied["rows"]["matched"], 2);
        assert_eq!(applied["rows"]["changed"], 1);
        assert_eq!(applied["generated_id"], 77);
        assert_eq!(applied["simulated"], false);
    }
}