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
//! The stable shape every command answers with.
//!
//! One shape serves the whole surface, so a caller learns it once. Commands
//! fill the payload; they never invent envelope fields of their own.

use indexmap::IndexMap;
use serde::Serialize;
use serde_json::Value;

/// A gap: something the caller asked for that could not be delivered.
///
/// A shrunken answer without a declared gap is a defect. Gaps do not change
/// the exit number, because the request was partly served.
#[derive(Debug, Clone, Serialize)]
pub struct Gap {
    /// The object that could not be delivered.
    pub object: String,
    /// Why it could not be delivered, in stable snake_case.
    pub cause: String,
    /// What was missing, in human prose.
    pub detail: String,
}

impl Gap {
    /// Records one undelivered object with its cause.
    #[must_use]
    pub fn new(
        object: impl Into<String>,
        cause: impl Into<String>,
        detail: impl Into<String>,
    ) -> Self {
        Self {
            object: object.into(),
            cause: cause.into(),
            detail: detail.into(),
        }
    }
}

/// What the output pipeline did to the payload, when it did anything.
///
/// Emitted only when at least one operation was active, so an untouched answer
/// carries no extra weight.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Applied {
    /// Elements the pipeline received.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_count: Option<usize>,
    /// Elements the pipeline emitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_count: Option<usize>,
    /// Whether any cell was shortened.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub content_truncated: bool,
    /// Whether credential-shaped text inside any cell was replaced by the mark.
    ///
    /// Reported rather than left silent for the reason the shortening is: a
    /// caller comparing two answers has to be able to tell a value that was
    /// never there from one this product took out.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub content_redacted: bool,
    /// Whether whole rows were dropped to fit the volume ceiling.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub output_truncated: bool,
    /// How many elements were dropped.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dropped: Option<usize>,
    /// The mark that asks for the page after this one.
    ///
    /// A plain offset, and deliberately not an encoded blob. A caller has to be
    /// able to predict and construct the next mark from what it already knows,
    /// which is why the opaque cursor was dropped from the design: a reader
    /// that cannot build the mark cannot page without this answer in hand.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<usize>,
    /// Whether anything remains after this page.
    ///
    /// Absent means the question was not asked. Present and false is the answer
    /// that lets a caller stop, which is the whole reason paging is worth
    /// declaring rather than leaving to be inferred from a short page.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_more: Option<bool>,
    /// The operations that needed the whole set gathered before answering.
    ///
    /// A read is served as a continuous flow, whose memory cost does not grow
    /// with the number of rows. Ordering the whole result and counting the
    /// whole result cannot be: the answer is a property of the set and not of
    /// any row in it. Naming them here is what keeps that from happening in
    /// silence, so a caller who asked for a flow and got a gathered answer is
    /// told which operation cost it.
    #[serde(skip_serializing_if = "no_operation_gathered")]
    pub accumulated_for: &'static [&'static str],
}

/// Whether no operation needed the whole set, so nothing has to be declared.
fn no_operation_gathered(names: &&'static [&'static str]) -> bool {
    names.is_empty()
}

/// The name the signature is declared under, matching the mark that asks for it.
pub const SIGNATURE_OPERATION: &str = "checksum";

impl Applied {
    /// Adds the signature to what this answer had to be gathered for.
    ///
    /// The names are a fixed slice rather than a list built at run time, so
    /// that the same set of operations always yields the same bytes and costs
    /// no allocation. Adding one is therefore a choice among the combinations
    /// that exist, and there are only these four.
    #[must_use]
    pub fn also_gathered_for_the_signature(mut self) -> Self {
        let gathered = self.accumulated_for;
        self.accumulated_for = match (gathered.contains(&"sort"), gathered.contains(&"count-only"))
        {
            (true, true) => &["sort", "count-only", SIGNATURE_OPERATION],
            (true, false) => &["sort", SIGNATURE_OPERATION],
            (false, true) => &["count-only", SIGNATURE_OPERATION],
            (false, false) => &[SIGNATURE_OPERATION],
        };
        self
    }

    /// Whether anything worth reporting happened.
    #[must_use]
    pub const fn is_silent(&self) -> bool {
        self.input_count.is_none()
            && self.output_count.is_none()
            && !self.content_truncated
            // A report carrying only the redaction was silently dropped here
            // while the redaction itself worked, so an answer came back altered
            // and said nothing about it. Every field of this record has to be
            // named in this list, or the record reports only the fields
            // somebody remembered.
            && !self.content_redacted
            && !self.output_truncated
            && self.dropped.is_none()
            && self.accumulated_for.is_empty()
    }
}

/// Where the destination of this invocation was decided.
///
/// A closed domain, because a caller reading it back has to be able to tell
/// "I chose this" from "something chose it for me" without a second lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TargetSource {
    /// Written on the call, as a profile name.
    Argv,
    /// Written on the call, as one text carrying the whole destination.
    Dsn,
    /// Written on the call, as a rule that chooses several destinations at once.
    ///
    /// `--all-profiles` used to report `config`, which read as "something chose
    /// this for me" about a call that had said which destinations it wanted.
    /// The distinction this domain exists to make was the one it got wrong: the
    /// caller was explicit, and about more than one destination, and the answer
    /// described them as inherited.
    Selector,
    /// Inherited from the stored default, and named by nobody on the call.
    Config,
}

/// The destination an answer came from, and how it was chosen.
///
/// # Why an answer carries its own question back
///
/// Everything else in the envelope describes the result. This describes an
/// input, which looks redundant until the input was never written down: a call
/// that names no profile is served by whichever one the stored default points
/// at, and the answer used to say nothing about which that was. The one
/// decision the product made on the caller's behalf was the only one it did not
/// declare.
#[derive(Debug, Clone, Serialize)]
pub struct Target {
    /// The profile that served this call, when a stored profile did.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    /// The address reached, when the destination is reached over a network.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
    /// The port reached, when the destination is reached over a network.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// The local channel reached, when the destination is reached without one.
    ///
    /// Present instead of the address and the port rather than beside them, so
    /// an answer never describes a network hop that did not happen.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub socket: Option<String>,
    /// The database the call was scoped to, when it was scoped to one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
}

/// The answer of one command.
///
/// Field order is fixed by construction, so the same input yields the same
/// bytes on every platform.
#[derive(Debug, Clone, Serialize)]
pub struct Envelope {
    /// The command that produced this answer, as published in the surface map.
    pub command: &'static str,
    /// Version of this envelope shape.
    pub schema_version: u32,
    /// The destination this answer came from, when one was reached.
    ///
    /// Absent for the commands that answer without a destination, because
    /// naming one there would be inventing a fact.
    ///
    /// Spelled `target_resolved` on the wire, beside `target_source`, so a
    /// reader finds the destination and the reason it was that destination as
    /// two facts at the same level rather than one nested inside the other.
    #[serde(rename = "target_resolved", skip_serializing_if = "Option::is_none")]
    pub target: Option<Target>,
    /// How the destination above was chosen.
    ///
    /// Beside the destination rather than within it, because a caller checking
    /// that a change was aimed and not inherited asks only this, and a check
    /// that has to walk into a nested object to find its answer is a check
    /// somebody writes wrongly once.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_source: Option<TargetSource>,
    /// The command's own result.
    pub data: Value,
    /// Objects the caller asked for and did not get, with the cause of each.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub gaps: Vec<Gap>,
    /// What the output pipeline did, when it did anything.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub applied: Option<Applied>,
    /// Signature of the result, when the caller asked for one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
    /// The field of `data` that is a document in its own right, when one is.
    ///
    /// Almost every answer is data the envelope describes, and writing it to a
    /// file means writing the envelope. A few answers are not: a manual page is
    /// a document with a format of its own, and a reader of manual pages cannot
    /// open an envelope with the page inside a field.
    ///
    /// Naming the field rather than carrying a second copy of it keeps the
    /// primary channel exactly as it was — the envelope still travels whole,
    /// with the page in it — and lets the one place that writes to a file know
    /// there is something inside worth writing on its own.
    ///
    /// Never serialised. It is an instruction to the writer, not part of the
    /// answer, and a caller reading the envelope must not find it there.
    #[serde(skip)]
    pub raw_field: Option<&'static str>,
}

/// The current envelope shape version.
pub const SCHEMA_VERSION: u32 = 1;

impl Envelope {
    /// Builds an answer for the given command.
    #[must_use]
    pub fn new(command: &'static str, data: Value) -> Self {
        Self {
            command,
            schema_version: SCHEMA_VERSION,
            target: None,
            target_source: None,
            data,
            gaps: Vec::new(),
            applied: None,
            checksum: None,
            raw_field: None,
        }
    }

    /// Records the destination this answer came from.
    ///
    /// Applied at the one place a destination is opened, rather than by each
    /// command, because no command owns this fact and every one of them that
    /// reaches a server has it.
    ///
    /// Takes the two facts together, so an answer can never carry a
    /// destination without saying who chose it.
    #[must_use]
    pub fn from_destination(mut self, target: Target, source: TargetSource) -> Self {
        self.target = Some(target);
        self.target_source = Some(source);
        self
    }

    /// Declares which field of the payload is a document in its own right.
    ///
    /// The envelope is unchanged for every caller that reads it. What changes
    /// is what reaches a file when the caller asked for one: the named field's
    /// text, and not the envelope around it.
    #[must_use]
    pub fn with_raw_field(mut self, field: &'static str) -> Self {
        self.raw_field = Some(field);
        self
    }

    /// The document this answer carries in its own right, when it carries one.
    ///
    /// Answers `None` when the named field is absent or is not text, so a
    /// declaration that stopped being true writes the envelope rather than
    /// writing nothing at all.
    #[must_use]
    pub fn raw_document(&self) -> Option<&str> {
        self.data.get(self.raw_field?)?.as_str()
    }

    /// Declares one object the caller asked for and did not get.
    #[must_use]
    pub fn with_gap(mut self, gap: Gap) -> Self {
        self.gaps.push(gap);
        self
    }

    /// Records what the output pipeline did, unless it did nothing.
    #[must_use]
    pub fn with_applied(mut self, applied: Applied) -> Self {
        if !applied.is_silent() {
            self.applied = Some(applied);
        }
        self
    }

    /// Attaches the signature of the result.
    #[must_use]
    pub fn with_checksum(mut self, checksum: impl Into<String>) -> Self {
        self.checksum = Some(checksum.into());
        self
    }

    /// The field that lists the columns of the payload rows, when one does.
    ///
    /// A payload may carry a list of names beside a list of rows without the
    /// two being about each other: a report of rejected lines names the columns
    /// of the file it read, not the fields of a rejection. The list is read as a
    /// description of the rows only when every key the rows carry is named in
    /// it, which is what makes it safe to narrow when a projection drops fields.
    #[must_use]
    pub fn payload_columns_key(&self) -> Option<&'static str> {
        const COLUMNS: &str = "columns";
        let map = self.data.as_object()?;
        let declared: Vec<&str> = map
            .get(COLUMNS)?
            .as_array()?
            .iter()
            .map(Value::as_str)
            .collect::<Option<Vec<&str>>>()?;
        if declared.is_empty() {
            return None;
        }
        let rows = map.get(self.payload_array_key()?)?.as_array()?;
        rows.iter()
            .all(|row| {
                row.as_object()
                    .is_some_and(|fields| fields.keys().all(|key| declared.contains(&key.as_str())))
            })
            .then_some(COLUMNS)
    }

    /// Borrows the array the output pipeline should act on, if there is one.
    ///
    /// The payload key is found by trying the published names in a fixed
    /// order, so the same payload always resolves to the same array.
    #[must_use]
    pub fn payload_array_key(&self) -> Option<&'static str> {
        const CANDIDATES: [&str; 6] = ["rows", "items", "objects", "results", "entries", "records"];
        let map = self.data.as_object()?;
        CANDIDATES
            .into_iter()
            .find(|key| map.get(*key).is_some_and(Value::is_array))
    }
}

/// A row as it travels through the output pipeline.
///
/// An ordered map keeps column order stable without paying for a hash, and
/// makes the same query produce the same bytes on every run.
pub type Row = IndexMap<String, Value>;

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

    #[test]
    fn a_clean_answer_carries_no_optional_weight() {
        let envelope = Envelope::new("schema tables", json!({"rows": []}));
        let line = serde_json::to_string(&envelope).expect("serialises");
        assert!(!line.contains("gaps"), "empty gaps must not appear: {line}");
        assert!(!line.contains("applied"), "silent pipeline must not appear");
        assert!(
            !line.contains("checksum"),
            "absent checksum must not appear"
        );
    }

    #[test]
    fn a_declared_gap_appears_without_changing_the_shape() {
        let envelope =
            Envelope::new("schema databases", json!({"rows": ["a"]})).with_gap(Gap::new(
                "restricted_db",
                "permission",
                "the credential may not list this database",
            ));
        let parsed = serde_json::to_value(&envelope).expect("serialises");
        assert_eq!(parsed["gaps"][0]["cause"], "permission");
        assert_eq!(parsed["gaps"][0]["object"], "restricted_db");
    }

    #[test]
    fn a_silent_pipeline_is_not_reported() {
        let envelope =
            Envelope::new("query run", json!({"rows": []})).with_applied(Applied::default());
        assert!(envelope.applied.is_none());
    }

    #[test]
    fn the_payload_array_is_found_by_published_order() {
        let envelope = Envelope::new("query run", json!({"rows": [1, 2], "count": 2}));
        assert_eq!(envelope.payload_array_key(), Some("rows"));

        let no_array = Envelope::new("meta version", json!({"version": "0.1.0"}));
        assert_eq!(no_array.payload_array_key(), None);
    }
}