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
//! The two commands that move data in and out of the server.
//!
//! Both need an open session, so both are handed one rather than opening their
//! own: the invocation opens exactly one connection and these commands work
//! inside it, like every other command that reaches the server.

use crate::cli::data::{DataCommand, ExportArgs, ImportArgs};
use crate::conn::Session;
use crate::datamove::export::ExportLock;
use crate::datamove::{export, import, ExportReport, ExportRequest, ImportReport, ImportRequest};
use crate::error::{Failure, Result};
use crate::output::Envelope;
use serde_json::{json, Value};
use tokio_util::sync::CancellationToken;

/// The settings these two commands read, already resolved.
///
/// Passed in rather than read here, so the layer that owns the settings file
/// stays the only one that reads it.
#[derive(Debug, Clone)]
pub struct DataSettings {
    /// Rows one committed batch of a load carries.
    pub batch_size: usize,
    /// Rows one statement of a copy carries.
    pub rows_per_statement: usize,
    /// The largest a copy may become.
    pub volume_ceiling: Option<usize>,
    /// Whether a refused row stops the whole load.
    pub stop_on_refusal: bool,
    /// The database this invocation works on, when one was named.
    ///
    /// Read from the one global `--database` rather than from a copy declared
    /// on each command. Sixteen commands used to declare their own, and the
    /// argument layer matched each against the global as ONE argument, so the
    /// value arrived in two fields and two readers acted on it.
    pub database: Option<String>,
    /// What a copy holds still while it is taken.
    pub export_lock: ExportLock,
}

impl DataSettings {
    /// The published defaults, read from the setting registry.
    ///
    /// Written out as numbers here they would be a second place a ceiling
    /// lives, and the one that wins wherever nothing was stored, which is how
    /// a stored key comes to have no effect at all.
    ///
    /// This is not [`Default::default`], because it can fail and that signature
    /// cannot say so. A registry that disagrees with this file is a defect, and
    /// a defect still has to leave through the published table: ending the
    /// process on a panic would surface a number Annex D does not contain.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the registry carries no entry for a
    /// name read here, carries no built-in value for it, or carries one of a
    /// kind this file does not expect.
    pub fn published() -> Result<Self> {
        Ok(Self {
            batch_size: builtin_count("import.batch_size")?,
            rows_per_statement: builtin_count("data.rows_per_statement")?,
            volume_ceiling: None,
            stop_on_refusal: builtin_truth("data.stop_on_refusal")?,
            // Not a setting: it is what this invocation named, and an
            // invocation that named nothing works on the destination's own.
            database: None,
            export_lock: builtin_lock("data.export_lock")?,
        })
    }
}

/// Reports a registry that does not carry what this file reads from it.
///
/// One shape for all four disagreements, so the caller sees a single stable
/// identifier and the name of the setting is always in the message.
fn registry_defect(name: &str, what: &str) -> Failure {
    Failure::config("config.registry_defect", format!("`{name}` {what}"))
        .with_detail("detail", name)
        .with_hint("this is a defect in the built-in setting registry, not in the call")
}

/// The built-in number of one published setting.
///
/// # Errors
///
/// Returns a configuration failure when the registry carries no number for the
/// name.
fn builtin_count(name: &str) -> Result<usize> {
    match builtin(name)? {
        crate::config::keys::Value::Integer(value) => {
            Ok(usize::try_from(value).unwrap_or(usize::MAX))
        }
        other => Err(registry_defect(
            name,
            &format!("is not a number in the registry: {other}"),
        )),
    }
}

/// The built-in truth value of one published setting.
///
/// # Errors
///
/// Returns a configuration failure when the registry carries no truth value for
/// the name.
fn builtin_truth(name: &str) -> Result<bool> {
    match builtin(name)? {
        crate::config::keys::Value::Boolean(value) => Ok(value),
        other => Err(registry_defect(
            name,
            &format!("is not a truth value in the registry: {other}"),
        )),
    }
}

/// The built-in choice of what a copy holds still.
///
/// # Errors
///
/// Returns a configuration failure when the registry carries no word for the
/// name, or carries one outside the published domain.
fn builtin_lock(name: &str) -> Result<ExportLock> {
    match builtin(name)? {
        crate::config::keys::Value::Enumeration(word) => ExportLock::parse(word)
            .map_err(|_| registry_defect(name, "publishes a word outside its own domain")),
        other => Err(registry_defect(
            name,
            &format!("is not a word in the registry: {other}"),
        )),
    }
}

/// The built-in value of one published setting.
///
/// # Errors
///
/// Returns a configuration failure when the name is not a published setting,
/// when its built-in value is outside its own domain, or when it carries none.
fn builtin(name: &str) -> Result<crate::config::keys::Value> {
    crate::config::keys::spec(name)
        .ok_or_else(|| registry_defect(name, "is not a published setting"))?
        .default_value()
        .map_err(|_| registry_defect(name, "carries a built-in value outside its own domain"))?
        .ok_or_else(|| registry_defect(name, "carries no built-in value"))
}

/// Serves one data movement command.
///
/// # Errors
///
/// Returns a limit failure when a copy goes past its volume ceiling, a
/// validation failure when a load was told to stop at the first refused row
/// and one was refused, and the mapped server failure otherwise.
pub async fn execute(
    command: &DataCommand,
    session: &mut Session,
    settings: &DataSettings,
    token: &CancellationToken,
) -> Result<Envelope> {
    match command {
        DataCommand::Export(args) => {
            let request = export_request(args, settings)?;
            let report = export::run(session.connection(), &request, token).await?;
            Ok(export_envelope(&report))
        }
        DataCommand::Import(args) => {
            let request = import_request(args, settings)?;
            let report = import::run(session.connection(), &request, token).await?;
            Ok(import_envelope(&report))
        }
    }
}

/// Takes the database out of the table names a copy was given.
///
/// Every name may carry its own database, which is the form `schema map`
/// writes, and that database wins over the one in force. A copy writes one
/// database, so names disagreeing about which one are refused here rather than
/// quietly reduced to the first of them.
///
/// # Errors
///
/// Returns a usage failure when two names carry different databases.
fn tables_of(named: &[String], in_force: Option<String>) -> Result<(Option<String>, Vec<String>)> {
    let mut carried: Option<String> = None;
    let mut bare = Vec::with_capacity(named.len());

    for name in named {
        let split = crate::introspect::names::split(name);
        if let Some(database) = split.database {
            match &carried {
                Some(first) if !first.eq_ignore_ascii_case(&database) => {
                    return Err(Failure::usage(
                        "data.databases_disagree",
                        format!("`{first}` and `{database}`"),
                    )
                    .with_detail("detail", format!("`{first}` and `{database}`"))
                    .with_hint("run one copy for each database"));
                }
                Some(_) => {}
                None => carried = Some(database),
            }
        }
        bare.push(split.name);
    }

    Ok((carried.or(in_force), bare))
}

/// The copy the marks and the settings describe.
///
/// # Errors
///
/// Returns a usage failure when no destination was named, and when the tables
/// named carry databases that disagree. The argument layer lets the mark be
/// absent so that publishing the contract costs nothing, which makes this the
/// place the requirement is actually enforced.
fn export_request(args: &ExportArgs, settings: &DataSettings) -> Result<ExportRequest> {
    let output = args.to.clone().ok_or_else(|| {
        Failure::usage(
            "data.output_missing",
            "the copy needs a destination to write to",
        )
        .with_hint("name one with --to")
    })?;
    let (database, tables) = tables_of(&args.table, settings.database.clone())?;

    Ok(ExportRequest {
        database,
        tables,
        structure_only: args.structure_only,
        output,
        ceiling: args.max_bytes.or(settings.volume_ceiling),
        rows_per_statement: settings.rows_per_statement,
        lock: settings.export_lock,
    })
}

/// The load the marks and the settings describe.
///
/// # Errors
///
/// Returns a usage failure when no file or no table was named, and when the
/// separator given is not a single byte, because a separator wider than a byte
/// is not a separator this reader can use.
fn import_request(args: &ImportArgs, settings: &DataSettings) -> Result<ImportRequest> {
    /// The form a caller is shown when the file or the table is missing.
    const FORM: &str = "data import --file clientes.csv --table clientes";

    let file = args.file.clone().ok_or_else(|| {
        Failure::usage("data.file_missing", "the load needs a file to read")
            .with_hint(format!("name one with --file, as in `{FORM}`"))
    })?;
    let table = args.table.clone().ok_or_else(|| {
        Failure::usage("data.table_missing", "the load needs a table to write into")
            .with_hint(format!("name one with --table, as in `{FORM}`"))
    })?;

    let separator = match args.separator {
        None => b',',
        Some(character) => {
            let mut buffer = [0_u8; 4];
            let encoded = character.encode_utf8(&mut buffer);
            match encoded.len() {
                1 => encoded.as_bytes()[0],
                _ => {
                    return Err(crate::error::Failure::usage(
                        "datamove.separator_too_wide",
                        format!(
                            "`{character}` is wider than one byte, so it cannot separate fields"
                        ),
                    )
                    .with_detail("detail", character.to_string())
                    .with_hint("use a separator that is one byte, such as a comma or a tab"))
                }
            }
        }
    };

    // The table may name its own database, which is the form `schema map`
    // writes, and that database wins over the one in force.
    let split = crate::introspect::names::split(&table);

    Ok(ImportRequest {
        file,
        table: split.name.clone(),
        database: split.database_or(settings.database.clone()),
        batch_size: args.batch_size.unwrap_or(settings.batch_size),
        resume_from: args.resume_from.unwrap_or(0),
        separator,
        header: args.header,
        stop_on_refusal: args
            .on_error
            .map_or(settings.stop_on_refusal, crate::cli::data::OnError::stops),
    })
}

/// The answer of a copy.
#[must_use]
pub fn export_envelope(report: &ExportReport) -> Envelope {
    let envelope = Envelope::new(
        "data export",
        json!({
            "path": report.path.display().to_string(),
            "objects": report.objects,
            "rows": report.rows,
            "bytes": report.bytes,
            "content_checksum": report.content_checksum,
            "consistent": report.consistent,
        }),
    );
    report
        .gaps
        .iter()
        .fold(envelope, |carried, gap| carried.with_gap(gap.clone()))
}

/// The answer of a load.
///
/// Every refused row travels with its own reason, under the published payload
/// key, so the caller reads them the same way it reads any other set of rows.
#[must_use]
pub fn import_envelope(report: &ImportReport) -> Envelope {
    let rows: Vec<Value> = report
        .rejected
        .iter()
        .map(|rejection| json!({"row": rejection.row, "reason": rejection.reason}))
        .collect();

    Envelope::new(
        "data import",
        json!({
            "rows_read": report.rows_read,
            "rows_written": report.rows_written,
            "rows_rejected": rows.len(),
            "offset": report.offset,
            "columns": report.columns,
            "rows": rows,
        }),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::envelope::Gap;

    /// The published settings, which the built-in registry always carries.
    fn defaults() -> DataSettings {
        DataSettings::published().expect("the registry publishes these settings")
    }

    fn export_args() -> ExportArgs {
        ExportArgs {
            max_bytes: None,
            to: Some(std::path::PathBuf::from("copy.sql")),
            table: vec!["orders".to_owned()],
            structure_only: false,
        }
    }

    fn import_args() -> ImportArgs {
        ImportArgs {
            on_error: None,
            file: Some(std::path::PathBuf::from("rows.csv")),
            table: Some("customers".to_owned()),
            batch_size: None,
            resume_from: None,
            separator: None,
            header: true,
        }
    }

    #[test]
    fn the_stored_batch_size_applies_when_no_mark_was_given() {
        let settings = defaults();
        let request = import_request(&import_args(), &settings).expect("legal");
        assert_eq!(request.batch_size, settings.batch_size);
        assert_eq!(request.separator, b',');
        assert_eq!(request.resume_from, 0);
    }

    #[test]
    fn a_mark_outranks_the_stored_batch_size() {
        let mut args = import_args();
        args.batch_size = Some(50);
        args.resume_from = Some(800_000);
        let request = import_request(&args, &defaults()).expect("legal");
        assert_eq!(request.batch_size, 50);
        assert_eq!(request.resume_from, 800_000);
    }

    #[test]
    fn a_separator_of_one_byte_is_taken_as_given() {
        let mut args = import_args();
        args.separator = Some('\t');
        assert_eq!(
            import_request(&args, &defaults()).expect("legal").separator,
            b'\t'
        );
    }

    /// FR-145. A load takes the name `schema map` wrote, which carries the
    /// database with it, so a caller chaining the two hands it straight over.
    #[test]
    fn a_load_takes_the_qualified_name_a_map_wrote() {
        let mut args = import_args();
        args.table = Some("shop.customers".to_owned());
        let request = import_request(&args, &defaults()).expect("legal");
        assert_eq!(request.table, "customers");
        assert_eq!(request.database.as_deref(), Some("shop"));
    }

    /// FR-145. The database the name carries wins over the one in force, which
    /// is the rule this server applies to its own statements.
    #[test]
    fn the_database_a_loaded_name_carries_wins_over_the_one_in_force() {
        let settings = DataSettings {
            database: Some("other".to_owned()),
            ..defaults()
        };
        let mut args = import_args();
        args.table = Some("shop.customers".to_owned());
        assert_eq!(
            import_request(&args, &settings)
                .expect("legal")
                .database
                .as_deref(),
            Some("shop")
        );

        // And a bare name still takes the one in force, unchanged.
        assert_eq!(
            import_request(&import_args(), &settings)
                .expect("legal")
                .database
                .as_deref(),
            Some("other")
        );
    }

    /// FR-145. A copy writes one database, so names that disagree about which
    /// one are refused rather than quietly reduced to the first of them.
    ///
    /// Refusing matters more than it looks: taking the first would write a copy
    /// naming tables that were never read, and the caller would find that out
    /// from the copy rather than from the command.
    #[test]
    fn a_copy_of_tables_from_two_databases_is_refused_where_it_is_asked_for() {
        let mut args = export_args();
        args.table = vec!["shop.orders".to_owned(), "other.clients".to_owned()];
        let failure = export_request(&args, &defaults()).expect_err("must refuse");
        assert_eq!(failure.code(), "data.databases_disagree");
        assert_eq!(failure.exit_number().code(), 2);

        // The same database written in another case is not a disagreement.
        let mut agreeing = export_args();
        agreeing.table = vec!["shop.orders".to_owned(), "SHOP.clients".to_owned()];
        let request = export_request(&agreeing, &defaults()).expect("one database");
        assert_eq!(request.database.as_deref(), Some("shop"));
        assert_eq!(
            request.tables,
            vec!["orders".to_owned(), "clients".to_owned()]
        );
    }

    #[test]
    fn a_separator_wider_than_a_byte_is_refused_before_the_file_is_opened() {
        let mut args = import_args();
        args.separator = Some('—');
        let failure = import_request(&args, &defaults()).expect_err("must refuse");
        assert_eq!(failure.code(), "datamove.separator_too_wide");
        assert_eq!(failure.exit_number().code(), 2);
    }

    /// The marks of a copy reach the request unchanged, and the database comes
    /// from the settings rather than from a second declaration on the command.
    #[test]
    fn the_marks_of_a_copy_reach_the_request_unchanged() {
        let settings = DataSettings {
            database: Some("shop".to_owned()),
            ..defaults()
        };
        let request = export_request(&export_args(), &settings).expect("a destination is set");
        assert_eq!(
            request.database.as_deref(),
            Some("shop"),
            "the one global --database reaches the copy"
        );
        assert_eq!(request.tables, vec!["orders".to_owned()]);
        assert!(!request.structure_only);
    }

    /// Publishing the contract must cost nothing, so the destination is optional
    /// to the argument layer. That moves the requirement here, where a missing
    /// destination has to be refused with a code rather than silently accepted.
    #[test]
    fn a_copy_without_a_destination_is_refused_with_a_code() {
        let mut args = export_args();
        args.to = None;
        let failure = export_request(&args, &defaults()).expect_err("must refuse");
        assert_eq!(failure.code(), "data.output_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(failure.hint().is_some());
    }

    #[test]
    fn a_copy_that_is_not_a_snapshot_declares_the_shortfall() {
        let report = ExportReport {
            path: std::path::PathBuf::from("/tmp/copy.sql"),
            objects: 2,
            rows: 10,
            bytes: 512,
            content_checksum: "sha256:abc".to_owned(),
            consistent: false,
            gaps: vec![Gap::new(
                "sessions",
                "no_consistent_snapshot",
                "the engine keeps no versions",
            )],
        };
        let parsed = serde_json::to_value(export_envelope(&report)).expect("serialises");
        assert_eq!(parsed["command"], "data export");
        assert_eq!(parsed["data"]["consistent"], false);
        assert_eq!(parsed["gaps"][0]["cause"], "no_consistent_snapshot");
    }

    #[test]
    fn a_whole_copy_carries_no_shortfall_at_all() {
        let report = ExportReport {
            path: std::path::PathBuf::from("/tmp/copy.sql"),
            objects: 1,
            rows: 3,
            bytes: 64,
            content_checksum: "sha256:abc".to_owned(),
            consistent: true,
            gaps: Vec::new(),
        };
        let line = serde_json::to_string(&export_envelope(&report)).expect("serialises");
        assert!(!line.contains("gaps"));
        assert!(line.contains("content_checksum"));
    }

    #[test]
    fn a_load_reports_the_reason_of_every_refusal_and_where_to_resume() {
        let report = ImportReport {
            rows_read: 5,
            rows_written: 3,
            rejected: vec![
                crate::datamove::Rejection {
                    row: 1,
                    reason: "the line carries 1 field where the header names 2".to_owned(),
                },
                crate::datamove::Rejection {
                    row: 4,
                    reason: "the column will not take this value".to_owned(),
                },
            ],
            offset: 5,
            columns: vec!["id".to_owned(), "name".to_owned()],
        };
        let parsed = serde_json::to_value(import_envelope(&report)).expect("serialises");

        assert_eq!(parsed["command"], "data import");
        assert_eq!(parsed["data"]["rows_written"], 3);
        assert_eq!(parsed["data"]["rows_rejected"], 2);
        assert_eq!(parsed["data"]["offset"], 5);
        assert_eq!(parsed["data"]["rows"][0]["row"], 1);
        assert!(parsed["data"]["rows"][1]["reason"]
            .as_str()
            .is_some_and(|reason| !reason.is_empty()));
    }

    #[test]
    fn the_refusals_sit_under_the_published_payload_key() {
        let report = ImportReport {
            rows_read: 1,
            rows_written: 1,
            rejected: Vec::new(),
            offset: 1,
            columns: Vec::new(),
        };
        assert_eq!(import_envelope(&report).payload_array_key(), Some("rows"));
    }
}