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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Assembling what each command family needs from the settings layer.
//!
//! Every ceiling a command obeys is built here from a named key. No family
//! reads the configuration on its own, and no ceiling appears as a bare number
//! inside the work.

use crate::cli::globals::RowCountMode;
use crate::cli::Cli;
use crate::commands::data::DataSettings;
use crate::commands::query::{Context, EphemeralNotice};
use crate::commands::schema::{PolicyScope, Target};
use crate::config::Config;
use crate::conn::handshake::PacketCeiling;
use crate::conn::options::ConnectionSettings;
use crate::conn::profile::{Profile, SecretRef, SecretVault};
use crate::conn::store::ProfileStore;
use crate::datamove::export::ExportLock;
use crate::error::Result;
use crate::exec::{Policy, ReadOnlyProbe, WriteState};
use crate::introspect::{map::Budget, Ceilings};
use crate::serverinfo::ServerSettings;
use crate::settings;
use crate::sql::parse::ParseLimits;
use secrecy::SecretString;
use std::collections::HashMap;
use std::time::Duration;

/// Reads the port a destination falls back to when it names none.
///
/// The number used to sit here as a literal, which made the one port every
/// destination inherits the only part of reaching a server that no command
/// could change. A host whose servers all listen elsewhere had to repeat the
/// port on every destination it wrote.
///
/// # Errors
///
/// Returns a configuration failure when the stored number is outside the range
/// a port can occupy, which the registry's own domain cannot express.
fn default_port(config: &Config) -> Result<u16> {
    let stored = settings::integer(config, "conn.default_port")?;
    u16::try_from(stored).map_err(|_| {
        // The detail is the bare number, never a sentence. A sentence built
        // here would be interpolated into the translated message as `$detail`
        // and the reader would get one line of their language wrapped around
        // one line of English.
        crate::error::Failure::config("config.port_out_of_range", stored.to_string())
            .with_detail("detail", stored.to_string())
            .with_hint("choose a number from 1 to 65535")
    })
}

// The two budgets the compact map is drawn under are `schema.map_tables` and
// `schema.map_rows`. They were numbers here once, with the whole argument for
// why they cannot be derived from the output row ceiling written beside them —
// the map reads catalogue rows rather than table contents, so a caller asking
// for few rows would silently empty it. That argument is sound and it argues
// for a budget of their own, which is what they now have. It never argued for
// a number nobody could see or change.

/// Resolves the destination this invocation talks to, and its secret.
///
/// A destination written as one text wins over a stored profile, and carries
/// its own secret. Reading the vault for it would answer with the secret of a
/// profile the caller never named.
///
/// # Errors
///
/// Returns a configuration failure when the text cannot be read, when the named
/// profile does not exist on this host, or when the vault cannot be read.
pub fn destination(
    config: &Config,
    cli: &Cli,
    store: &ProfileStore,
    vault: &dyn SecretVault,
) -> Result<(Profile, Option<SecretString>)> {
    if let Some(text) = &cli.globals.destination.dsn {
        let parsed = crate::conn::Dsn::parse(text)?;
        return Ok((parsed.profile, parsed.secret));
    }

    let profile = store
        .resolve(
            cli.globals.destination.profile.as_deref(),
            stored_default(config)?.as_deref(),
        )?
        .clone();
    let secret = vault.load(&SecretRef::for_profile(&profile.name))?;
    Ok((profile, secret))
}

/// Builds what the connection layer needs to open a destination.
///
/// The secret is handed in rather than looked up, because where it comes from
/// depends on how the destination was named and that decision belongs to
/// [`destination`].
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain.
pub fn connection(
    config: &Config,
    cli: &Cli,
    profile: Option<&Profile>,
    secret: Option<SecretString>,
) -> Result<ConnectionSettings> {
    // A destination that refuses change is put inside a read-only block, so the
    // refusal comes from the server rather than from classifying text here.
    let refuse_change = settings::read_only(config, &cli.globals)?
        || profile.is_some_and(|profile| profile.read_only);

    let keepalive = settings::integer(config, "conn.keepalive_secs")?;
    let encryption = settings::encryption(config, &cli.globals)?;

    Ok(ConnectionSettings {
        secret,
        default_port: default_port(config)?,
        prefer_socket: settings::boolean(config, "conn.prefer_socket")?,
        // The mark on the command line wins over the stored key here, like
        // everywhere else. Reading only the key would have made `--compress`
        // a flag the product accepts and ignores.
        compress: settings::compress(config, &cli.globals)?,
        max_allowed_packet: settings::optional_count(config, "conn.max_packet_bytes")?,
        wait_timeout: settings::optional_count(config, "conn.idle_timeout_secs")?,
        tcp_keepalive: (keepalive > 0).then(|| Duration::from_secs(keepalive)),
        stmt_cache_size: settings::count(config, "conn.stmt_cache_size")?,
        count_matched_rows: settings::row_count_matched(config, &cli.globals)?,
        // The level is one setting read once. Writing the two checks out here,
        // as this once did, made `tls.verify` a word the product stored, read
        // back and reported as being in force while checking something else.
        verification: encryption.verification,
        encryption,
        timezone: settings::optional_word(config, "conn.timezone")?,
        charset: settings::optional_word(config, "conn.charset")?,
        session_setup: settings::session_setup(config)?,
        local_file_read: settings::boolean(config, "sql.local_file_read")?,
        readable_local_files: files_this_invocation_named(cli),
        connect_attributes: connect_attributes(),
        refuse_change,
        // Handing the budget to the server makes it the first line: it stops
        // the statement itself, so the common case never opens a second
        // connection to ask.
        statement_budget: Some(settings::operation_timeout(config, &cli.globals)?),
    })
}

/// The destination that applies when the caller names none.
///
/// Read from the registry and from nowhere else. The profile store used to keep
/// a default of its own, which meant `config set conn.default` stored a value
/// the work never consulted. One reader, in one place, is what keeps the two
/// from disagreeing.
///
/// # Errors
///
/// Returns a configuration failure when the stored value is outside its domain.
pub fn stored_default(config: &Config) -> Result<Option<String>> {
    settings::optional_word(config, "conn.default")
}

/// The local files this invocation named for itself.
///
/// This is the whole list a server may ever ask for, and only when the local
/// file permission is on. Bounding it by what the caller already named means
/// that even a host which granted the permission has not granted a server the
/// run of the filesystem.
fn files_this_invocation_named(cli: &Cli) -> Vec<std::path::PathBuf> {
    use crate::cli::data::DataCommand;
    use crate::cli::Command;

    match &cli.command {
        Command::Data(DataCommand::Import(args)) => args.file.iter().cloned().collect(),
        _ => Vec::new(),
    }
}

/// What this tool tells the server about itself.
///
/// Naming the client in the server's connection list is what lets an operator
/// tell an agent's session apart from a person's.
fn connect_attributes() -> HashMap<String, String> {
    HashMap::from([
        ("_client_name".to_owned(), env!("CARGO_PKG_NAME").to_owned()),
        (
            "_client_version".to_owned(),
            env!("CARGO_PKG_VERSION").to_owned(),
        ),
    ])
}

/// Builds the ceilings the structure commands obey.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain.
pub fn schema_target(config: &Config, cli: &Cli, scope: Option<String>) -> Result<Target> {
    // How far past the row ceiling an estimate may reach before an exact count
    // is refused rather than started, read from `output.count_headroom`.
    //
    // It multiplies the row ceiling rather than standing on its own, and that
    // relationship is the argument for it: counting rows is not returning them,
    // so a caller who lowered the row ceiling to keep answers small never meant
    // to make counting refuse a table a thousand times smaller than the one it
    // refused yesterday. Deriving from the ceiling is right. Deriving by a
    // factor written into this file, which the caller could neither read nor
    // change, was not.
    let headroom = settings::integer(config, "output.count_headroom")?;

    // Settled here because this is the first point at which configuration and a
    // target meet, and a hint built later has no way back to either.
    crate::introspect::names::declare_near_name_count(settings::count(
        config,
        "output.near_name_count",
    )?);

    let max_rows = settings::count(config, "output.max_rows")?;
    Ok(Target {
        database: scope.or_else(|| cli.globals.destination.database.clone()),
        read_only: settings::read_only(config, &cli.globals)?,
        policy_scope: PolicyScope::parse(&settings::word(config, "sql.policy_scope")?)?,
        index_advice: settings::boolean(config, "schema.index_advice")?,
        ceilings: Ceilings {
            map: Budget {
                tables: settings::count(config, "schema.map_tables")?,
                rows: settings::count(config, "schema.map_rows")?,
            },
            search_rows: max_rows,
            ranked_objects: max_rows,
            countable_rows: settings::integer(config, "output.max_rows")?.saturating_mul(headroom),
        },
    })
}

impl ParseLimits {
    /// Builds the bounds a statement is read under for this destination.
    ///
    /// Two ceilings meet here and neither may be mistaken for the other. The
    /// parser guard is this product's own and protects the thread the parser
    /// runs on; the packet ceiling belongs to the destination and decides what
    /// it will accept in one piece. What they share is that a statement larger
    /// than the packet ceiling can never be sent, so reading it costs nothing
    /// but time, and the smaller of the two is therefore what the parser is
    /// entered with.
    ///
    /// The packet ceiling is settled here and nowhere else, and the order is
    /// the requirement: the stored key wins when it was written, the server's
    /// own answer applies when it was not, and no number in this source is ever
    /// used. An invocation that has reached no server has neither, and then
    /// nothing is settled at all — there is no send to measure, so a ceiling
    /// invented here would refuse a command no server ever objected to.
    ///
    /// # The defect this shape was written to close
    ///
    /// The paragraph above said no number in this source is ever used, and a
    /// number in this source was used: the smaller of the two ceilings was
    /// taken against `DEFAULT_MAX_STATEMENT_BYTES`, one mebibyte written into
    /// `crate::sql::parse`. A caller who raised the published
    /// `conn.max_packet_bytes` to sixty-four mebibytes went on reading one, and
    /// the invocation ended in zero with nothing said.
    ///
    /// That is the costliest shape hardcoding takes. A number standing where no
    /// setting exists is merely invisible; a number ANNULLING a setting that
    /// does exist makes the setting appear to work while it does not, and the
    /// caller has no way to learn otherwise. Both ceilings are settings now, so
    /// the smaller of the two is still taken and the caller can move either.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when a stored ceiling is outside its
    /// domain.
    pub fn from_server(config: &Config) -> Result<Self> {
        let settled = settle_packet_ceiling(
            settings::optional_count(config, "conn.max_packet_bytes")?,
            PacketCeiling::observed(),
        );
        PacketCeiling::declare(settled);

        let guard = settings::count(config, "limits.max_statement_bytes")?;
        let read_at_most = settled.map_or(guard, |ceiling| ceiling.min(guard));
        Ok(Self::new(
            read_at_most,
            settings::count(config, "limits.parser_stack_bytes")?,
        ))
    }
}

/// Which of the two answers decides the ceiling.
///
/// Kept apart from the reading so the order can be proved without a server and
/// without a settings location, which is what makes it a rule rather than a
/// remark in a comment.
const fn settle_packet_ceiling(stored: Option<usize>, observed: Option<usize>) -> Option<usize> {
    match stored {
        Some(written) => Some(written),
        None => observed,
    }
}

/// Builds what the query commands obey.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain.
pub fn query_context(
    config: &Config,
    cli: &Cli,
    token: tokio_util::sync::CancellationToken,
) -> Result<Context> {
    let mode = if settings::row_count_matched(config, &cli.globals)? {
        RowCountMode::Matched
    } else {
        RowCountMode::Changed
    };

    let mut policy = Policy::new(
        ParseLimits::from_server(config)?,
        cli.globals
            .safety
            .max_affected
            .map_or_else(|| settings::integer(config, "limits.max_affected_rows"), Ok)?,
        cli.globals
            .output
            .limit
            .map_or_else(|| settings::count(config, "output.max_rows"), Ok)?,
        mode,
        settings::word(config, "sql.delimiter")?,
        settings::operation_timeout(config, &cli.globals)?,
    );
    policy.max_input_bytes = settings::count(config, "limits.max_input_bytes")?;
    policy.confirmed = cli.globals.safety.yes;
    policy.dry_run = cli.globals.safety.dry_run;
    policy.count_only = cli.globals.output.count_only;
    policy.read_only = settings::read_only(config, &cli.globals)?;
    policy.require_where = settings::boolean(config, "sql.require_where")?;
    policy.require_unique_key = settings::boolean(config, "sql.require_unique_key")?;

    Ok(Context {
        token,
        policy,
        config_dir: crate::config::paths::config_dir(
            cli.globals.diagnostics.config_dir.as_deref(),
        )?,
        write_state: WriteState::new(ReadOnlyProbe::parse(&settings::word(
            config,
            "server.readonly_probe",
        )?)?),
        ephemeral_notice: EphemeralNotice::parse(&settings::word(config, "sql.ephemeral_notice")?)?,
        conversion: settings::conversion(config)?,
        refuses_to_ask: settings::no_input(&cli.globals),
        database: cli.globals.destination.database.clone(),
        passed_over: cli.globals.pipeline(config)?.cursor.unwrap_or(0),
    })
}

/// Builds what the server commands obey.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain.
pub fn server_settings(config: &Config, cli: &Cli) -> Result<ServerSettings> {
    /// Most rows a ranking answers with when the caller names no number.
    ///
    /// This is not a setting of its own. A ranking is meant to be read, and a
    /// caller who raised the row ceiling to pull a large table did not thereby
    /// ask for the thousand heaviest statements. The row ceiling still applies
    /// below this, so lowering it still narrows the ranking.
    const RANKING_WITHOUT_A_NUMBER: usize = 100;

    Ok(ServerSettings {
        status_interval_secs: settings::integer(config, "server.status_interval_secs")?,
        default_top: settings::count(config, "output.max_rows")?.min(RANKING_WITHOUT_A_NUMBER),
        confirmed: cli.globals.safety.yes,
        observability_visible: settings::boolean(config, "server.observability_visible")?,
        kill_foreign_requires_yes: settings::boolean(config, "server.kill_foreign_requires_yes")?,
    })
}

/// Builds what the data movement commands obey.
///
/// # Errors
///
/// Returns a configuration failure when a stored value is outside its domain.
pub fn data_settings(config: &Config, cli: &Cli) -> Result<DataSettings> {
    Ok(DataSettings {
        batch_size: settings::count(config, "import.batch_size")?,
        rows_per_statement: settings::count(config, "data.rows_per_statement")?,
        volume_ceiling: cli.globals.output.max_output_bytes.map_or_else(
            || settings::count(config, "output.max_bytes").map(Some),
            |value| Ok(Some(value)),
        )?,
        stop_on_refusal: settings::boolean(config, "data.stop_on_refusal")?,
        database: cli.globals.destination.database.clone(),
        export_lock: ExportLock::parse(&settings::word(config, "data.export_lock")?)?,
    })
}

#[cfg(test)]
mod tests {
    // Imported here rather than beside the production imports at the head of
    // this file. A `#[cfg(test)]` up there truncates the scan that proves every
    // catalogue entry has an emitter — it reads a source file only as far as
    // its first test marker — and the `config.port_out_of_range` failure raised
    // forty lines below it silently stopped being visible.
    use crate::sql::parse::{DEFAULT_MAX_STATEMENT_BYTES, DEFAULT_PARSER_STACK_BYTES};

    use super::*;
    use clap::Parser;

    fn parse(args: &[&str]) -> Cli {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .map(ToOwned::to_owned)
            .collect();
        Cli::try_parse_from(command_line).expect("the sample invocation parses")
    }

    fn empty() -> (tempfile::TempDir, Config) {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = Config::load(Some(scratch.path())).expect("an empty location still loads");
        (scratch, config)
    }

    #[test]
    fn a_confirmation_mark_reaches_the_policy() {
        let (_scratch, config) = empty();
        let cli = parse(&["--yes", "query", "run", "SELECT 1"]);
        let context = query_context(&config, &cli, tokio_util::sync::CancellationToken::new())
            .expect("builds");
        assert!(context.policy.confirmed);
    }

    /// The published default lets change through, and the mark is what turns
    /// the blanket refusal on. The defence against an unintended change is the
    /// confirmation, the required restriction and the ceiling on affected
    /// rows, not a lock that made the change surface unreachable.
    #[test]
    fn the_blanket_refusal_is_asked_for_and_never_assumed() {
        let (_scratch, config) = empty();
        let silent = query_context(
            &config,
            &parse(&["query", "run", "SELECT 1"]),
            tokio_util::sync::CancellationToken::new(),
        )
        .expect("builds");
        assert!(!silent.policy.read_only);

        let asked = query_context(
            &config,
            &parse(&["--read-only", "query", "run", "SELECT 1"]),
            tokio_util::sync::CancellationToken::new(),
        )
        .expect("builds");
        assert!(asked.policy.read_only);
    }

    #[test]
    fn a_row_ceiling_on_the_command_line_beats_the_stored_one() {
        let (_scratch, config) = empty();
        let cli = parse(&["--limit", "7", "query", "run", "SELECT 1"]);
        let context = query_context(&config, &cli, tokio_util::sync::CancellationToken::new())
            .expect("builds");
        assert_eq!(context.policy.max_rows, 7);
    }

    #[test]
    fn both_certificate_checks_stay_on_by_default() {
        let (_scratch, config) = empty();
        let cli = parse(&["conn", "list"]);
        let settings = connection(&config, &cli, None, None).expect("builds");
        assert!(settings.verification.is_strict());
    }

    /// Asking for the blanket refusal must reach the server as a read-only
    /// block, so the refusal comes from there rather than from classifying
    /// text here.
    #[test]
    fn the_server_is_asked_to_refuse_change_when_the_caller_asks_for_it() {
        let (_scratch, config) = empty();
        assert!(
            !connection(&config, &parse(&["query", "run", "SELECT 1"]), None, None)
                .expect("builds")
                .refuse_change
        );
        assert!(
            connection(
                &config,
                &parse(&["--read-only", "query", "run", "SELECT 1"]),
                None,
                None
            )
            .expect("builds")
            .refuse_change
        );
    }

    /// The budget reaches the server, so it stops the statement itself instead
    /// of leaving the work running after this process gave up.
    #[test]
    fn the_time_budget_reaches_the_connection_layer() {
        let (_scratch, config) = empty();
        let cli = parse(&["--timeout", "7", "query", "run", "SELECT 1"]);
        assert_eq!(
            connection(&config, &cli, None, None)
                .expect("builds")
                .statement_budget,
            Some(Duration::from_secs(7))
        );
    }

    /// A destination written as one text wins over the stored default, and
    /// brings its own secret: reading the vault would answer with the secret of
    /// a profile the caller never named.
    #[test]
    fn a_destination_written_as_text_wins_over_the_stored_one() {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = Config::load(Some(scratch.path())).expect("an empty location loads");
        let store = ProfileStore::open(scratch.path()).expect("opens");
        let vault = crate::config::vault::FileVault::open(scratch.path()).expect("opens");
        let cli = parse(&[
            "--dsn",
            "mariadb://reader:hunter2@10.255.255.1:3307/sales",
            "query",
            "run",
            "SELECT 1",
        ]);

        let (profile, secret) = destination(&config, &cli, &store, &vault).expect("resolves");
        assert_eq!(profile.host.as_deref(), Some("10.255.255.1"));
        assert_eq!(profile.port, Some(3307));
        assert_eq!(
            secret.as_ref().map(secrecy::ExposeSecret::expose_secret),
            Some("hunter2")
        );
    }

    /// Without a text destination and without a stored default there is nothing
    /// to reach, and that must be said rather than silently resolved.
    #[test]
    fn no_text_and_no_stored_default_is_a_configuration_failure() {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let config = Config::load(Some(scratch.path())).expect("an empty location loads");
        let store = ProfileStore::open(scratch.path()).expect("opens");
        let vault = crate::config::vault::FileVault::open(scratch.path()).expect("opens");
        let cli = parse(&["query", "run", "SELECT 1"]);

        let failure = destination(&config, &cli, &store, &vault).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_default");
    }

    #[test]
    fn the_counter_interval_comes_from_its_own_key() {
        let (_scratch, config) = empty();
        let cli = parse(&["server", "status"]);
        assert_eq!(
            server_settings(&config, &cli)
                .expect("builds")
                .status_interval_secs,
            1
        );
    }

    /// FR-084. The stored key wins when it was written and the server's own
    /// answer applies when it was not, and with neither there is no ceiling at
    /// all: an invocation that reached no server has no send to measure, and a
    /// number invented here would refuse a command no destination objected to.
    #[test]
    fn the_stored_ceiling_wins_and_the_server_answers_when_it_is_absent() {
        assert_eq!(
            settle_packet_ceiling(Some(4096), Some(4 * 1024 * 1024)),
            Some(4096)
        );
        assert_eq!(
            settle_packet_ceiling(None, Some(4 * 1024 * 1024)),
            Some(4 * 1024 * 1024)
        );
        assert_eq!(settle_packet_ceiling(None, None), None);
    }

    /// FR-084. A ceiling below the parser's own lowers what is read, because a
    /// statement the destination cannot carry is never worth parsing. It never
    /// raises it: the parser guard is this product's own and no destination
    /// gets to widen it.
    #[test]
    fn the_ceiling_lowers_what_is_parsed_and_never_raises_it() {
        settling(|| {
            let (_scratch, config) = stored(&[("conn.max_packet_bytes", "4096")]);
            let limits = ParseLimits::from_server(&config).expect("builds");
            assert_eq!(limits.max_statement_bytes(), 4096);
            assert_eq!(PacketCeiling::in_force(), Some(4096));
            assert_eq!(limits.parser_stack_bytes(), DEFAULT_PARSER_STACK_BYTES);
        });
    }

    /// Settling the packet ceiling writes a number the whole process shares, so
    /// the tests that settle it run one at a time.
    ///
    /// This was not a precaution. The assertion on `PacketCeiling::in_force`
    /// above passed for as long as it was the only test in this file calling
    /// `from_server`, and failed the moment a second one did, reading the
    /// ceiling a neighbour had just written. A proof whose result depends on
    /// which other proofs happen to be running is not measuring the product.
    static SETTLING: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Runs one body with the settled ceiling to itself.
    fn settling<T>(body: impl FnOnce() -> T) -> T {
        let guard = SETTLING
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let outcome = body();
        drop(guard);
        outcome
    }

    /// Writes several settings into one scratch file and loads it.
    fn stored(pairs: &[(&str, &str)]) -> (tempfile::TempDir, Config) {
        let scratch = tempfile::tempdir().expect("scratch directory");
        let file =
            crate::config::paths::config_file(Some(scratch.path())).expect("a settings file");
        for (key, value) in pairs {
            crate::config::store::store(&file, key, value).expect("the value is stored");
        }
        let config = Config::load(Some(scratch.path())).expect("the stored values load");
        (scratch, config)
    }

    /// The two ceilings are both settings, and the smaller of them decides.
    ///
    /// This is the proof the earlier shape could not have passed. One mebibyte
    /// was written into `crate::sql::parse` and taken as the smaller of the two
    /// unconditionally, so a caller who raised the packet ceiling alone read one
    /// mebibyte and a caller who raised both read one mebibyte. Only the second
    /// of those is still true, and it is true because the caller said so.
    #[test]
    fn raising_only_the_packet_ceiling_still_stops_at_the_statement_ceiling() {
        settling(|| {
            let (_scratch, config) = stored(&[("conn.max_packet_bytes", "67108864")]);
            let limits = ParseLimits::from_server(&config).expect("builds");
            assert_eq!(
                limits.max_statement_bytes(),
                DEFAULT_MAX_STATEMENT_BYTES,
                "the statement ceiling was left at its default, so it decides"
            );
        });
    }

    #[test]
    fn raising_both_ceilings_raises_what_is_read() {
        settling(|| {
            let (_scratch, config) = stored(&[
                ("conn.max_packet_bytes", "67108864"),
                ("limits.max_statement_bytes", "4194304"),
            ]);
            let limits = ParseLimits::from_server(&config).expect("builds");
            assert_eq!(
                limits.max_statement_bytes(),
                4_194_304,
                "both ceilings were raised, so neither may hold the reading down"
            );
            assert!(
                limits.max_statement_bytes() > DEFAULT_MAX_STATEMENT_BYTES,
                "a number written in this source is deciding again"
            );
        });
    }

    /// The stack the parser thread gets is a setting, and moving it moves.
    #[test]
    fn the_parser_stack_follows_its_setting() {
        settling(|| {
            let (_scratch, config) = stored(&[("limits.parser_stack_bytes", "8388608")]);
            let limits = ParseLimits::from_server(&config).expect("builds");
            assert_eq!(limits.parser_stack_bytes(), 8_388_608);
        });
    }

    /// A default written in two places is two numbers that can drift apart.
    ///
    /// The registry carries the built-in as text and `crate::sql::parse` carries
    /// it as an expression, and nothing but this makes them the same number. An
    /// invocation with nothing stored reads the registry, so a drift here would
    /// silently move every default install away from what the source says.
    #[test]
    fn the_published_default_is_the_number_this_source_names() {
        settling(|| {
            let (_scratch, config) = stored(&[]);
            let limits = ParseLimits::from_server(&config).expect("builds");
            assert_eq!(limits.max_statement_bytes(), DEFAULT_MAX_STATEMENT_BYTES);
            assert_eq!(limits.parser_stack_bytes(), DEFAULT_PARSER_STACK_BYTES);
        });
    }

    #[test]
    fn a_refused_row_never_discards_the_whole_file() {
        let (_scratch, config) = empty();
        let cli = parse(&["data", "import", "--file", "rows.csv", "--table", "t"]);
        assert!(
            !data_settings(&config, &cli)
                .expect("builds")
                .stop_on_refusal
        );
    }
}