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
//! The language of messages written for a person.
//!
//! # What is translated and what never is
//!
//! Only prose addressed to a person is translated, and that prose only ever
//! travels on the auxiliary channel. The primary channel is read by another
//! program, so everything it carries stays in one fixed form on every host:
//! command names, flag names, payload keys and the stable failure codes are
//! identifiers, not sentences, and translating an identifier would break the
//! caller that branches on it.
//!
//! Because of that split, this module is deliberately unreachable from the
//! primary channel: nothing here returns a value that the output layer emits.

pub mod active;
pub mod negotiate;
pub mod report;

pub use active::{active, install};
pub use negotiate::{negotiate, SUPPORTED};

use crate::error::{Failure, Result};
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
use unic_langid::LanguageIdentifier;

/// The message set carried for each language this build serves.
///
/// Held as source text and read at start-up rather than generated, so adding a
/// language is one file and no code. One language names several files, because
/// a single file per language would grow past the size this product allows.
const CATALOGUES: [(&str, &str); 12] = [
    ("en", include_str!("locales/en.ftl")),
    ("en", include_str!("locales/errors-usage.en.ftl")),
    ("en", include_str!("locales/errors-sql.en.ftl")),
    ("en", include_str!("locales/errors-config.en.ftl")),
    ("en", include_str!("locales/errors-server.en.ftl")),
    ("en", include_str!("locales/errors-data.en.ftl")),
    ("pt-BR", include_str!("locales/pt-BR.ftl")),
    ("pt-BR", include_str!("locales/errors-usage.pt-BR.ftl")),
    ("pt-BR", include_str!("locales/errors-sql.pt-BR.ftl")),
    ("pt-BR", include_str!("locales/errors-config.pt-BR.ftl")),
    ("pt-BR", include_str!("locales/errors-server.pt-BR.ftl")),
    ("pt-BR", include_str!("locales/errors-data.pt-BR.ftl")),
];

/// The name under which a failure code carries its message.
const FAILURE_MESSAGE_PREFIX: &str = "err-";

/// The name under which a failure code carries its next action.
const FAILURE_HINT_PREFIX: &str = "hint-";

/// The message name a failure code answers to.
///
/// A code separates its parts with a dot and an underscore, and a message name
/// carries neither, so both become a hyphen: `sql.multiple_statements` is
/// named `err-sql-multiple-statements`.
fn failure_id(prefix: &str, code: &str) -> String {
    let mut id = String::with_capacity(prefix.len() + code.len());
    id.push_str(prefix);
    id.extend(code.chars().map(|part| match part {
        '.' | '_' => '-',
        other => other,
    }));
    id
}

/// The messages in force for one invocation.
pub struct Messages {
    language: LanguageIdentifier,
    bundle: FluentBundle<FluentResource>,
}

impl std::fmt::Debug for Messages {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Closed as incomplete on purpose: the bundle beside the language is a
        // parsed message catalogue with no readable rendering of its own, and
        // printing it would be pages of syntax tree in place of one tag.
        f.debug_struct("Messages")
            .field("language", &self.language.to_string())
            .finish_non_exhaustive()
    }
}

impl Messages {
    /// Loads the message set of one language.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when this build carries no messages for
    /// the language, or when the carried source does not parse, which is a
    /// defect in this build rather than caller input.
    pub fn load(language: LanguageIdentifier) -> Result<Self> {
        let tag = language.to_string();
        let sources: Vec<&str> = CATALOGUES
            .iter()
            .filter(|(name, _)| *name == tag)
            .map(|(_, source)| *source)
            .collect();
        if sources.is_empty() {
            return Err(
                Failure::config("i18n.missing_catalogue", format!("`{tag}`"))
                    .with_detail("detail", tag)
                    .with_detail("languages", SUPPORTED.join(", "))
                    .with_hint(format!("carried languages: {}", SUPPORTED.join(", "))),
            );
        }

        let mut bundle = FluentBundle::new(vec![language.clone()]);
        // Directional marks around a substituted value are for a text renderer
        // that understands them. A terminal does not, so they would show up as
        // stray characters in the middle of a diagnostic.
        bundle.set_use_isolating(false);
        for source in sources {
            add_catalogue(&mut bundle, source, &tag)?;
        }

        Ok(Self { language, bundle })
    }

    /// A set that carries no messages at all, and cannot fail to be built.
    ///
    /// Exists for the one case where even the built-in language will not load,
    /// which is a defect in this build rather than caller input. Every failure
    /// then reports in the words its source already wrote, so the reader still
    /// gets a diagnosis; losing the invocation instead would give them none.
    #[must_use]
    pub fn empty(language: LanguageIdentifier) -> Self {
        let mut bundle = FluentBundle::new(vec![language.clone()]);
        bundle.set_use_isolating(false);
        Self { language, bundle }
    }

    /// Loads the message set the four layers of negotiation settled on.
    ///
    /// # Errors
    ///
    /// Returns the negotiation failure when a language was asked for and this
    /// build does not carry it.
    pub fn resolve(requested: Option<&str>, stored: Option<&str>) -> Result<Self> {
        Self::load(negotiate::negotiate(requested, stored)?)
    }

    /// The language these messages are written in.
    #[must_use]
    pub const fn language(&self) -> &LanguageIdentifier {
        &self.language
    }

    /// One message with no substitutions.
    #[must_use]
    pub fn get(&self, id: &str) -> String {
        self.format(id, &[])
    }

    /// One message with the named values substituted into it.
    ///
    /// A message this build does not carry renders as its own name, and a value
    /// that was not supplied is left as its own placeholder. Neither is allowed
    /// to stop the work: the diagnostic exists to explain what happened, and
    /// losing the invocation to explain it would be worse than an unpolished
    /// line.
    #[must_use]
    pub fn format(&self, id: &str, arguments: &[(&str, &str)]) -> String {
        let Some(pattern) = self.bundle.get_message(id).and_then(|found| found.value()) else {
            return id.to_owned();
        };

        let mut args = FluentArgs::new();
        for (name, value) in arguments {
            args.set(*name, *value);
        }

        let mut ignored = Vec::new();
        self.bundle
            .format_pattern(pattern, Some(&args), &mut ignored)
            .into_owned()
    }

    /// Whether this build carries a message of that name.
    #[must_use]
    pub fn carries(&self, id: &str) -> bool {
        self.bundle
            .get_message(id)
            .is_some_and(|found| found.value().is_some())
    }

    /// The message of a failure code in this language, when one is carried.
    ///
    /// `details` are the measured values the source recorded by name, and they
    /// arrive under those names, so a catalogue words the sentence around them
    /// instead of repeating a sentence the source built in one language.
    ///
    /// # Why the sentence the source built is not passed in here
    ///
    /// It used to be, bound to `detail`, as a convenience for the call sites
    /// that pass a bare identifier as their message. It was measured doing the
    /// opposite of its purpose. Sixty-seven of the ninety-two catalogue entries
    /// that name `$detail` are worded as a complete generic sentence with the
    /// measurement appended in parentheses, and their call sites build a
    /// complete English sentence as the message. The convenience substituted
    /// that whole English sentence into the parenthesis, so a reader of
    /// Portuguese got a translated sentence trailed by an untranslated one, and
    /// a reader of English got the same sentence twice.
    ///
    /// Nothing failed. The category, the code and the exit number were correct
    /// throughout, and those are what the proofs read. The defect lived in the
    /// one field nothing measured, which is exactly what a silent default buys.
    ///
    /// So there is no default now. A catalogue entry that names `$detail` gets
    /// it from an explicit `with_detail` at the call site or not at all, and
    /// `every_catalogue_frame_gets_the_detail_it_names` refuses the build when
    /// a site forgets. A forgotten value is now a red proof rather than a
    /// plausible sentence in the wrong language.
    #[must_use]
    pub fn failure_message(
        &self,
        code: &str,
        details: &[(&'static str, String)],
    ) -> Option<String> {
        self.carried(&failure_id(FAILURE_MESSAGE_PREFIX, code), details)
    }

    /// The next action of a failure code in this language, when one is carried.
    #[must_use]
    pub fn failure_hint(&self, code: &str, details: &[(&'static str, String)]) -> Option<String> {
        self.carried(&failure_id(FAILURE_HINT_PREFIX, code), details)
    }

    /// One message, or nothing at all when this build does not carry it.
    ///
    /// Distinct from [`Self::format`], which renders an absent message as its
    /// own name: a failure being reported must fall back to the sentence the
    /// source built, never to a bare message name.
    fn carried(&self, id: &str, details: &[(&'static str, String)]) -> Option<String> {
        if !self.carries(id) {
            return None;
        }
        let arguments: Vec<(&str, &str)> = details
            .iter()
            .map(|(name, value)| (*name, value.as_str()))
            .collect();
        Some(self.format(id, &arguments))
    }
}

/// Adds the messages of one source file to a bundle.
///
/// # Errors
///
/// Returns a configuration failure when the source does not parse, or when it
/// names a message another file of the same language already named. Both are
/// defects in this build rather than caller input.
fn add_catalogue(bundle: &mut FluentBundle<FluentResource>, source: &str, tag: &str) -> Result<()> {
    let resource = FluentResource::try_new(source.to_owned()).map_err(|(_, errors)| {
        Failure::config(
            "i18n.malformed_catalogue",
            format!("the messages carried for `{tag}` do not parse"),
        )
        .with_detail("detail", tag)
        .with_cause(format!("{} problem(s) in the source", errors.len()))
    })?;

    bundle.add_resource(resource).map_err(|errors| {
        Failure::config(
            "i18n.duplicate_message",
            format!("the messages carried for `{tag}` name the same message twice"),
        )
        .with_detail("detail", tag)
        .with_cause(format!("{} duplicate(s)", errors.len()))
    })
}

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

    fn messages(tag: &str) -> Messages {
        let language = negotiate::parse(tag).expect("a language");
        Messages::load(language).expect("carried by this build")
    }

    #[test]
    fn every_carried_language_loads() {
        for tag in SUPPORTED {
            let loaded = messages(tag);
            assert_eq!(loaded.language().to_string(), tag);
        }
    }

    /// The names one language carries, read from the source rather than from
    /// the bundle, because a bundle answers only about a name already known.
    fn named(tag: &str) -> std::collections::BTreeSet<&'static str> {
        CATALOGUES
            .iter()
            .filter(|(name, _)| *name == tag)
            .flat_map(|(_, source)| source.lines())
            .filter(|line| !line.starts_with('#') && !line.starts_with(' '))
            .filter_map(|line| line.split_once(" ="))
            .map(|(id, _)| id)
            .collect()
    }

    /// Every message named in one language is named in all of them, so a
    /// reader never gets a line half in one language and half in another.
    #[test]
    fn every_carried_language_names_the_same_messages() {
        let reference = named(SUPPORTED[0]);
        assert!(
            !reference.is_empty(),
            "the reference language names nothing"
        );
        for tag in SUPPORTED {
            let here = named(tag);
            let missing: Vec<_> = reference.difference(&here).collect();
            let extra: Vec<_> = here.difference(&reference).collect();
            assert!(missing.is_empty(), "`{tag}` is missing {missing:?}");
            assert!(
                extra.is_empty(),
                "`{tag}` names {extra:?} and no other does"
            );
        }
    }

    /// Every name the source carries loads, so a message that parses in one
    /// file is never shadowed or dropped when several files are joined.
    #[test]
    fn every_named_message_loads() {
        for tag in SUPPORTED {
            let loaded = messages(tag);
            for id in named(tag) {
                assert!(loaded.carries(id), "`{id}` is missing from `{tag}`");
            }
        }
    }

    /// A code reaches its prose under the name the catalogues use, and one the
    /// catalogues do not name falls back to the sentence the source built.
    #[test]
    fn a_failure_code_reaches_its_prose() {
        let loaded = messages("pt-BR");
        let translated = loaded
            .failure_message("sql.multiple_statements", &[])
            .expect("carried");
        assert!(translated.contains("mais de um"));
        assert!(loaded.failure_message("no.such_code", &[]).is_none());
    }

    /// A measured value survives translation because the call site records it
    /// under the name the catalogue substitutes, and never because the sentence
    /// the source built was carried through whole.
    ///
    /// This test asserted the second thing until it was measured. Passing it
    /// that way is what made the defect look like the design: the catalogue
    /// wording ended in a parenthesis, the English sentence went into the
    /// parenthesis, the measurement was somewhere inside that sentence, and the
    /// assertion below was satisfied. A reader of Portuguese got the English
    /// sentence with it. Asserting that a number appears somewhere in a string
    /// says nothing about the language of the words around it.
    #[test]
    fn a_measured_value_survives_translation() {
        let recorded = [("detail", "900000 > 65536".to_owned())];
        let translated = messages("pt-BR")
            .failure_message("sql.too_large", &recorded)
            .expect("carried");
        assert!(
            translated.contains("65536"),
            "the measurement was dropped: {translated}"
        );
        assert!(
            !translated.contains("the statement"),
            "the Portuguese wording carries English: {translated}"
        );
    }

    #[test]
    fn a_value_that_was_not_supplied_never_stops_the_work() {
        let rendered = messages("en").get("copy-table");
        assert!(!rendered.is_empty());
        assert!(rendered.starts_with("copying"));
    }

    #[test]
    fn a_substituted_value_arrives_without_stray_marks() {
        let rendered = messages("en").format("copy-table", &[("table", "orders")]);
        assert_eq!(rendered, "copying orders");
    }

    #[test]
    fn the_two_languages_really_differ() {
        let english = messages("en").format("copy-table", &[("table", "orders")]);
        let portuguese = messages("pt-BR").format("copy-table", &[("table", "orders")]);
        assert_ne!(english, portuguese);
        assert!(portuguese.starts_with("copiando"));
    }

    #[test]
    fn a_message_this_build_does_not_carry_never_stops_the_work() {
        assert_eq!(messages("en").get("no-such-message"), "no-such-message");
    }

    #[test]
    fn a_language_this_build_does_not_carry_is_refused_plainly() {
        let language = negotiate::parse("de-DE").expect("a language");
        let failure = Messages::load(language).expect_err("must refuse");
        assert_eq!(failure.code(), "i18n.missing_catalogue");
    }

    #[test]
    fn a_diagnostic_rendering_never_carries_the_whole_catalogue() {
        let rendered = format!("{:?}", messages("pt-BR"));
        assert!(rendered.contains("pt-BR"));
        assert!(!rendered.contains("copiando"));
    }
}