Skip to main content

mariadb_cli/dispatch/
context.rs

1//! Assembling what each command family needs from the settings layer.
2//!
3//! Every ceiling a command obeys is built here from a named key. No family
4//! reads the configuration on its own, and no ceiling appears as a bare number
5//! inside the work.
6
7use crate::cli::globals::RowCountMode;
8use crate::cli::Cli;
9use crate::commands::data::DataSettings;
10use crate::commands::query::{Context, EphemeralNotice};
11use crate::commands::schema::{PolicyScope, Target};
12use crate::config::Config;
13use crate::conn::handshake::PacketCeiling;
14use crate::conn::options::ConnectionSettings;
15use crate::conn::profile::{Profile, SecretRef, SecretVault};
16use crate::conn::store::ProfileStore;
17use crate::datamove::export::ExportLock;
18use crate::error::Result;
19use crate::exec::{Policy, ReadOnlyProbe, WriteState};
20use crate::introspect::{map::Budget, Ceilings};
21use crate::serverinfo::ServerSettings;
22use crate::settings;
23use crate::sql::parse::ParseLimits;
24use secrecy::SecretString;
25use std::collections::HashMap;
26use std::time::Duration;
27
28/// Reads the port a destination falls back to when it names none.
29///
30/// The number used to sit here as a literal, which made the one port every
31/// destination inherits the only part of reaching a server that no command
32/// could change. A host whose servers all listen elsewhere had to repeat the
33/// port on every destination it wrote.
34///
35/// # Errors
36///
37/// Returns a configuration failure when the stored number is outside the range
38/// a port can occupy, which the registry's own domain cannot express.
39fn default_port(config: &Config) -> Result<u16> {
40    let stored = settings::integer(config, "conn.default_port")?;
41    u16::try_from(stored).map_err(|_| {
42        // The detail is the bare number, never a sentence. A sentence built
43        // here would be interpolated into the translated message as `$detail`
44        // and the reader would get one line of their language wrapped around
45        // one line of English.
46        crate::error::Failure::config("config.port_out_of_range", stored.to_string())
47            .with_detail("detail", stored.to_string())
48            .with_hint("choose a number from 1 to 65535")
49    })
50}
51
52// The two budgets the compact map is drawn under are `schema.map_tables` and
53// `schema.map_rows`. They were numbers here once, with the whole argument for
54// why they cannot be derived from the output row ceiling written beside them —
55// the map reads catalogue rows rather than table contents, so a caller asking
56// for few rows would silently empty it. That argument is sound and it argues
57// for a budget of their own, which is what they now have. It never argued for
58// a number nobody could see or change.
59
60/// Resolves the destination this invocation talks to, and its secret.
61///
62/// A destination written as one text wins over a stored profile, and carries
63/// its own secret. Reading the vault for it would answer with the secret of a
64/// profile the caller never named.
65///
66/// # Errors
67///
68/// Returns a configuration failure when the text cannot be read, when the named
69/// profile does not exist on this host, or when the vault cannot be read.
70pub fn destination(
71    config: &Config,
72    cli: &Cli,
73    store: &ProfileStore,
74    vault: &dyn SecretVault,
75) -> Result<(Profile, Option<SecretString>)> {
76    if let Some(text) = &cli.globals.destination.dsn {
77        let parsed = crate::conn::Dsn::parse(text)?;
78        return Ok((parsed.profile, parsed.secret));
79    }
80
81    let profile = store
82        .resolve(
83            cli.globals.destination.profile.as_deref(),
84            stored_default(config)?.as_deref(),
85        )?
86        .clone();
87    let secret = vault.load(&SecretRef::for_profile(&profile.name))?;
88    Ok((profile, secret))
89}
90
91/// Builds what the connection layer needs to open a destination.
92///
93/// The secret is handed in rather than looked up, because where it comes from
94/// depends on how the destination was named and that decision belongs to
95/// [`destination`].
96///
97/// # Errors
98///
99/// Returns a configuration failure when a stored value is outside its domain.
100pub fn connection(
101    config: &Config,
102    cli: &Cli,
103    profile: Option<&Profile>,
104    secret: Option<SecretString>,
105) -> Result<ConnectionSettings> {
106    // A destination that refuses change is put inside a read-only block, so the
107    // refusal comes from the server rather than from classifying text here.
108    let refuse_change = settings::read_only(config, &cli.globals)?
109        || profile.is_some_and(|profile| profile.read_only);
110
111    let keepalive = settings::integer(config, "conn.keepalive_secs")?;
112    let encryption = settings::encryption(config, &cli.globals)?;
113
114    Ok(ConnectionSettings {
115        secret,
116        default_port: default_port(config)?,
117        prefer_socket: settings::boolean(config, "conn.prefer_socket")?,
118        // The mark on the command line wins over the stored key here, like
119        // everywhere else. Reading only the key would have made `--compress`
120        // a flag the product accepts and ignores.
121        compress: settings::compress(config, &cli.globals)?,
122        max_allowed_packet: settings::optional_count(config, "conn.max_packet_bytes")?,
123        wait_timeout: settings::optional_count(config, "conn.idle_timeout_secs")?,
124        tcp_keepalive: (keepalive > 0).then(|| Duration::from_secs(keepalive)),
125        stmt_cache_size: settings::count(config, "conn.stmt_cache_size")?,
126        count_matched_rows: settings::row_count_matched(config, &cli.globals)?,
127        // The level is one setting read once. Writing the two checks out here,
128        // as this once did, made `tls.verify` a word the product stored, read
129        // back and reported as being in force while checking something else.
130        verification: encryption.verification,
131        encryption,
132        timezone: settings::optional_word(config, "conn.timezone")?,
133        charset: settings::optional_word(config, "conn.charset")?,
134        session_setup: settings::session_setup(config)?,
135        local_file_read: settings::boolean(config, "sql.local_file_read")?,
136        readable_local_files: files_this_invocation_named(cli),
137        connect_attributes: connect_attributes(),
138        refuse_change,
139        // Handing the budget to the server makes it the first line: it stops
140        // the statement itself, so the common case never opens a second
141        // connection to ask.
142        statement_budget: Some(settings::operation_timeout(config, &cli.globals)?),
143    })
144}
145
146/// The destination that applies when the caller names none.
147///
148/// Read from the registry and from nowhere else. The profile store used to keep
149/// a default of its own, which meant `config set conn.default` stored a value
150/// the work never consulted. One reader, in one place, is what keeps the two
151/// from disagreeing.
152///
153/// # Errors
154///
155/// Returns a configuration failure when the stored value is outside its domain.
156pub fn stored_default(config: &Config) -> Result<Option<String>> {
157    settings::optional_word(config, "conn.default")
158}
159
160/// The local files this invocation named for itself.
161///
162/// This is the whole list a server may ever ask for, and only when the local
163/// file permission is on. Bounding it by what the caller already named means
164/// that even a host which granted the permission has not granted a server the
165/// run of the filesystem.
166fn files_this_invocation_named(cli: &Cli) -> Vec<std::path::PathBuf> {
167    use crate::cli::data::DataCommand;
168    use crate::cli::Command;
169
170    match &cli.command {
171        Command::Data(DataCommand::Import(args)) => args.file.iter().cloned().collect(),
172        _ => Vec::new(),
173    }
174}
175
176/// What this tool tells the server about itself.
177///
178/// Naming the client in the server's connection list is what lets an operator
179/// tell an agent's session apart from a person's.
180fn connect_attributes() -> HashMap<String, String> {
181    HashMap::from([
182        ("_client_name".to_owned(), env!("CARGO_PKG_NAME").to_owned()),
183        (
184            "_client_version".to_owned(),
185            env!("CARGO_PKG_VERSION").to_owned(),
186        ),
187    ])
188}
189
190/// Builds the ceilings the structure commands obey.
191///
192/// # Errors
193///
194/// Returns a configuration failure when a stored value is outside its domain.
195pub fn schema_target(config: &Config, cli: &Cli, scope: Option<String>) -> Result<Target> {
196    // How far past the row ceiling an estimate may reach before an exact count
197    // is refused rather than started, read from `output.count_headroom`.
198    //
199    // It multiplies the row ceiling rather than standing on its own, and that
200    // relationship is the argument for it: counting rows is not returning them,
201    // so a caller who lowered the row ceiling to keep answers small never meant
202    // to make counting refuse a table a thousand times smaller than the one it
203    // refused yesterday. Deriving from the ceiling is right. Deriving by a
204    // factor written into this file, which the caller could neither read nor
205    // change, was not.
206    let headroom = settings::integer(config, "output.count_headroom")?;
207
208    // Settled here because this is the first point at which configuration and a
209    // target meet, and a hint built later has no way back to either.
210    crate::introspect::names::declare_near_name_count(settings::count(
211        config,
212        "output.near_name_count",
213    )?);
214
215    let max_rows = settings::count(config, "output.max_rows")?;
216    Ok(Target {
217        database: scope.or_else(|| cli.globals.destination.database.clone()),
218        read_only: settings::read_only(config, &cli.globals)?,
219        policy_scope: PolicyScope::parse(&settings::word(config, "sql.policy_scope")?)?,
220        index_advice: settings::boolean(config, "schema.index_advice")?,
221        ceilings: Ceilings {
222            map: Budget {
223                tables: settings::count(config, "schema.map_tables")?,
224                rows: settings::count(config, "schema.map_rows")?,
225            },
226            search_rows: max_rows,
227            ranked_objects: max_rows,
228            countable_rows: settings::integer(config, "output.max_rows")?.saturating_mul(headroom),
229        },
230    })
231}
232
233impl ParseLimits {
234    /// Builds the bounds a statement is read under for this destination.
235    ///
236    /// Two ceilings meet here and neither may be mistaken for the other. The
237    /// parser guard is this product's own and protects the thread the parser
238    /// runs on; the packet ceiling belongs to the destination and decides what
239    /// it will accept in one piece. What they share is that a statement larger
240    /// than the packet ceiling can never be sent, so reading it costs nothing
241    /// but time, and the smaller of the two is therefore what the parser is
242    /// entered with.
243    ///
244    /// The packet ceiling is settled here and nowhere else, and the order is
245    /// the requirement: the stored key wins when it was written, the server's
246    /// own answer applies when it was not, and no number in this source is ever
247    /// used. An invocation that has reached no server has neither, and then
248    /// nothing is settled at all — there is no send to measure, so a ceiling
249    /// invented here would refuse a command no server ever objected to.
250    ///
251    /// # The defect this shape was written to close
252    ///
253    /// The paragraph above said no number in this source is ever used, and a
254    /// number in this source was used: the smaller of the two ceilings was
255    /// taken against `DEFAULT_MAX_STATEMENT_BYTES`, one mebibyte written into
256    /// `crate::sql::parse`. A caller who raised the published
257    /// `conn.max_packet_bytes` to sixty-four mebibytes went on reading one, and
258    /// the invocation ended in zero with nothing said.
259    ///
260    /// That is the costliest shape hardcoding takes. A number standing where no
261    /// setting exists is merely invisible; a number ANNULLING a setting that
262    /// does exist makes the setting appear to work while it does not, and the
263    /// caller has no way to learn otherwise. Both ceilings are settings now, so
264    /// the smaller of the two is still taken and the caller can move either.
265    ///
266    /// # Errors
267    ///
268    /// Returns a configuration failure when a stored ceiling is outside its
269    /// domain.
270    pub fn from_server(config: &Config) -> Result<Self> {
271        let settled = settle_packet_ceiling(
272            settings::optional_count(config, "conn.max_packet_bytes")?,
273            PacketCeiling::observed(),
274        );
275        PacketCeiling::declare(settled);
276
277        let guard = settings::count(config, "limits.max_statement_bytes")?;
278        let read_at_most = settled.map_or(guard, |ceiling| ceiling.min(guard));
279        Ok(Self::new(
280            read_at_most,
281            settings::count(config, "limits.parser_stack_bytes")?,
282        ))
283    }
284}
285
286/// Which of the two answers decides the ceiling.
287///
288/// Kept apart from the reading so the order can be proved without a server and
289/// without a settings location, which is what makes it a rule rather than a
290/// remark in a comment.
291const fn settle_packet_ceiling(stored: Option<usize>, observed: Option<usize>) -> Option<usize> {
292    match stored {
293        Some(written) => Some(written),
294        None => observed,
295    }
296}
297
298/// Builds what the query commands obey.
299///
300/// # Errors
301///
302/// Returns a configuration failure when a stored value is outside its domain.
303pub fn query_context(
304    config: &Config,
305    cli: &Cli,
306    token: tokio_util::sync::CancellationToken,
307) -> Result<Context> {
308    let mode = if settings::row_count_matched(config, &cli.globals)? {
309        RowCountMode::Matched
310    } else {
311        RowCountMode::Changed
312    };
313
314    let mut policy = Policy::new(
315        ParseLimits::from_server(config)?,
316        cli.globals
317            .safety
318            .max_affected
319            .map_or_else(|| settings::integer(config, "limits.max_affected_rows"), Ok)?,
320        cli.globals
321            .output
322            .limit
323            .map_or_else(|| settings::count(config, "output.max_rows"), Ok)?,
324        mode,
325        settings::word(config, "sql.delimiter")?,
326        settings::operation_timeout(config, &cli.globals)?,
327    );
328    policy.max_input_bytes = settings::count(config, "limits.max_input_bytes")?;
329    policy.confirmed = cli.globals.safety.yes;
330    policy.dry_run = cli.globals.safety.dry_run;
331    policy.count_only = cli.globals.output.count_only;
332    policy.read_only = settings::read_only(config, &cli.globals)?;
333    policy.require_where = settings::boolean(config, "sql.require_where")?;
334    policy.require_unique_key = settings::boolean(config, "sql.require_unique_key")?;
335
336    Ok(Context {
337        token,
338        policy,
339        config_dir: crate::config::paths::config_dir(
340            cli.globals.diagnostics.config_dir.as_deref(),
341        )?,
342        write_state: WriteState::new(ReadOnlyProbe::parse(&settings::word(
343            config,
344            "server.readonly_probe",
345        )?)?),
346        ephemeral_notice: EphemeralNotice::parse(&settings::word(config, "sql.ephemeral_notice")?)?,
347        conversion: settings::conversion(config)?,
348        refuses_to_ask: settings::no_input(&cli.globals),
349        database: cli.globals.destination.database.clone(),
350        passed_over: cli.globals.pipeline(config)?.cursor.unwrap_or(0),
351    })
352}
353
354/// Builds what the server commands obey.
355///
356/// # Errors
357///
358/// Returns a configuration failure when a stored value is outside its domain.
359pub fn server_settings(config: &Config, cli: &Cli) -> Result<ServerSettings> {
360    /// Most rows a ranking answers with when the caller names no number.
361    ///
362    /// This is not a setting of its own. A ranking is meant to be read, and a
363    /// caller who raised the row ceiling to pull a large table did not thereby
364    /// ask for the thousand heaviest statements. The row ceiling still applies
365    /// below this, so lowering it still narrows the ranking.
366    const RANKING_WITHOUT_A_NUMBER: usize = 100;
367
368    Ok(ServerSettings {
369        status_interval_secs: settings::integer(config, "server.status_interval_secs")?,
370        default_top: settings::count(config, "output.max_rows")?.min(RANKING_WITHOUT_A_NUMBER),
371        confirmed: cli.globals.safety.yes,
372        observability_visible: settings::boolean(config, "server.observability_visible")?,
373        kill_foreign_requires_yes: settings::boolean(config, "server.kill_foreign_requires_yes")?,
374    })
375}
376
377/// Builds what the data movement commands obey.
378///
379/// # Errors
380///
381/// Returns a configuration failure when a stored value is outside its domain.
382pub fn data_settings(config: &Config, cli: &Cli) -> Result<DataSettings> {
383    Ok(DataSettings {
384        batch_size: settings::count(config, "import.batch_size")?,
385        rows_per_statement: settings::count(config, "data.rows_per_statement")?,
386        volume_ceiling: cli.globals.output.max_output_bytes.map_or_else(
387            || settings::count(config, "output.max_bytes").map(Some),
388            |value| Ok(Some(value)),
389        )?,
390        stop_on_refusal: settings::boolean(config, "data.stop_on_refusal")?,
391        database: cli.globals.destination.database.clone(),
392        export_lock: ExportLock::parse(&settings::word(config, "data.export_lock")?)?,
393    })
394}
395
396#[cfg(test)]
397mod tests {
398    // Imported here rather than beside the production imports at the head of
399    // this file. A `#[cfg(test)]` up there truncates the scan that proves every
400    // catalogue entry has an emitter — it reads a source file only as far as
401    // its first test marker — and the `config.port_out_of_range` failure raised
402    // forty lines below it silently stopped being visible.
403    use crate::sql::parse::{DEFAULT_MAX_STATEMENT_BYTES, DEFAULT_PARSER_STACK_BYTES};
404
405    use super::*;
406    use clap::Parser;
407
408    fn parse(args: &[&str]) -> Cli {
409        let command_line: Vec<String> = std::iter::once("mariadb-cli")
410            .chain(args.iter().copied())
411            .map(ToOwned::to_owned)
412            .collect();
413        Cli::try_parse_from(command_line).expect("the sample invocation parses")
414    }
415
416    fn empty() -> (tempfile::TempDir, Config) {
417        let scratch = tempfile::tempdir().expect("scratch directory");
418        let config = Config::load(Some(scratch.path())).expect("an empty location still loads");
419        (scratch, config)
420    }
421
422    #[test]
423    fn a_confirmation_mark_reaches_the_policy() {
424        let (_scratch, config) = empty();
425        let cli = parse(&["--yes", "query", "run", "SELECT 1"]);
426        let context = query_context(&config, &cli, tokio_util::sync::CancellationToken::new())
427            .expect("builds");
428        assert!(context.policy.confirmed);
429    }
430
431    /// The published default lets change through, and the mark is what turns
432    /// the blanket refusal on. The defence against an unintended change is the
433    /// confirmation, the required restriction and the ceiling on affected
434    /// rows, not a lock that made the change surface unreachable.
435    #[test]
436    fn the_blanket_refusal_is_asked_for_and_never_assumed() {
437        let (_scratch, config) = empty();
438        let silent = query_context(
439            &config,
440            &parse(&["query", "run", "SELECT 1"]),
441            tokio_util::sync::CancellationToken::new(),
442        )
443        .expect("builds");
444        assert!(!silent.policy.read_only);
445
446        let asked = query_context(
447            &config,
448            &parse(&["--read-only", "query", "run", "SELECT 1"]),
449            tokio_util::sync::CancellationToken::new(),
450        )
451        .expect("builds");
452        assert!(asked.policy.read_only);
453    }
454
455    #[test]
456    fn a_row_ceiling_on_the_command_line_beats_the_stored_one() {
457        let (_scratch, config) = empty();
458        let cli = parse(&["--limit", "7", "query", "run", "SELECT 1"]);
459        let context = query_context(&config, &cli, tokio_util::sync::CancellationToken::new())
460            .expect("builds");
461        assert_eq!(context.policy.max_rows, 7);
462    }
463
464    #[test]
465    fn both_certificate_checks_stay_on_by_default() {
466        let (_scratch, config) = empty();
467        let cli = parse(&["conn", "list"]);
468        let settings = connection(&config, &cli, None, None).expect("builds");
469        assert!(settings.verification.is_strict());
470    }
471
472    /// Asking for the blanket refusal must reach the server as a read-only
473    /// block, so the refusal comes from there rather than from classifying
474    /// text here.
475    #[test]
476    fn the_server_is_asked_to_refuse_change_when_the_caller_asks_for_it() {
477        let (_scratch, config) = empty();
478        assert!(
479            !connection(&config, &parse(&["query", "run", "SELECT 1"]), None, None)
480                .expect("builds")
481                .refuse_change
482        );
483        assert!(
484            connection(
485                &config,
486                &parse(&["--read-only", "query", "run", "SELECT 1"]),
487                None,
488                None
489            )
490            .expect("builds")
491            .refuse_change
492        );
493    }
494
495    /// The budget reaches the server, so it stops the statement itself instead
496    /// of leaving the work running after this process gave up.
497    #[test]
498    fn the_time_budget_reaches_the_connection_layer() {
499        let (_scratch, config) = empty();
500        let cli = parse(&["--timeout", "7", "query", "run", "SELECT 1"]);
501        assert_eq!(
502            connection(&config, &cli, None, None)
503                .expect("builds")
504                .statement_budget,
505            Some(Duration::from_secs(7))
506        );
507    }
508
509    /// A destination written as one text wins over the stored default, and
510    /// brings its own secret: reading the vault would answer with the secret of
511    /// a profile the caller never named.
512    #[test]
513    fn a_destination_written_as_text_wins_over_the_stored_one() {
514        let scratch = tempfile::tempdir().expect("scratch directory");
515        let config = Config::load(Some(scratch.path())).expect("an empty location loads");
516        let store = ProfileStore::open(scratch.path()).expect("opens");
517        let vault = crate::config::vault::FileVault::open(scratch.path()).expect("opens");
518        let cli = parse(&[
519            "--dsn",
520            "mariadb://reader:hunter2@10.255.255.1:3307/sales",
521            "query",
522            "run",
523            "SELECT 1",
524        ]);
525
526        let (profile, secret) = destination(&config, &cli, &store, &vault).expect("resolves");
527        assert_eq!(profile.host.as_deref(), Some("10.255.255.1"));
528        assert_eq!(profile.port, Some(3307));
529        assert_eq!(
530            secret.as_ref().map(secrecy::ExposeSecret::expose_secret),
531            Some("hunter2")
532        );
533    }
534
535    /// Without a text destination and without a stored default there is nothing
536    /// to reach, and that must be said rather than silently resolved.
537    #[test]
538    fn no_text_and_no_stored_default_is_a_configuration_failure() {
539        let scratch = tempfile::tempdir().expect("scratch directory");
540        let config = Config::load(Some(scratch.path())).expect("an empty location loads");
541        let store = ProfileStore::open(scratch.path()).expect("opens");
542        let vault = crate::config::vault::FileVault::open(scratch.path()).expect("opens");
543        let cli = parse(&["query", "run", "SELECT 1"]);
544
545        let failure = destination(&config, &cli, &store, &vault).expect_err("must refuse");
546        assert_eq!(failure.code(), "profile.no_default");
547    }
548
549    #[test]
550    fn the_counter_interval_comes_from_its_own_key() {
551        let (_scratch, config) = empty();
552        let cli = parse(&["server", "status"]);
553        assert_eq!(
554            server_settings(&config, &cli)
555                .expect("builds")
556                .status_interval_secs,
557            1
558        );
559    }
560
561    /// FR-084. The stored key wins when it was written and the server's own
562    /// answer applies when it was not, and with neither there is no ceiling at
563    /// all: an invocation that reached no server has no send to measure, and a
564    /// number invented here would refuse a command no destination objected to.
565    #[test]
566    fn the_stored_ceiling_wins_and_the_server_answers_when_it_is_absent() {
567        assert_eq!(
568            settle_packet_ceiling(Some(4096), Some(4 * 1024 * 1024)),
569            Some(4096)
570        );
571        assert_eq!(
572            settle_packet_ceiling(None, Some(4 * 1024 * 1024)),
573            Some(4 * 1024 * 1024)
574        );
575        assert_eq!(settle_packet_ceiling(None, None), None);
576    }
577
578    /// FR-084. A ceiling below the parser's own lowers what is read, because a
579    /// statement the destination cannot carry is never worth parsing. It never
580    /// raises it: the parser guard is this product's own and no destination
581    /// gets to widen it.
582    #[test]
583    fn the_ceiling_lowers_what_is_parsed_and_never_raises_it() {
584        settling(|| {
585            let (_scratch, config) = stored(&[("conn.max_packet_bytes", "4096")]);
586            let limits = ParseLimits::from_server(&config).expect("builds");
587            assert_eq!(limits.max_statement_bytes(), 4096);
588            assert_eq!(PacketCeiling::in_force(), Some(4096));
589            assert_eq!(limits.parser_stack_bytes(), DEFAULT_PARSER_STACK_BYTES);
590        });
591    }
592
593    /// Settling the packet ceiling writes a number the whole process shares, so
594    /// the tests that settle it run one at a time.
595    ///
596    /// This was not a precaution. The assertion on `PacketCeiling::in_force`
597    /// above passed for as long as it was the only test in this file calling
598    /// `from_server`, and failed the moment a second one did, reading the
599    /// ceiling a neighbour had just written. A proof whose result depends on
600    /// which other proofs happen to be running is not measuring the product.
601    static SETTLING: std::sync::Mutex<()> = std::sync::Mutex::new(());
602
603    /// Runs one body with the settled ceiling to itself.
604    fn settling<T>(body: impl FnOnce() -> T) -> T {
605        let guard = SETTLING
606            .lock()
607            .unwrap_or_else(std::sync::PoisonError::into_inner);
608        let outcome = body();
609        drop(guard);
610        outcome
611    }
612
613    /// Writes several settings into one scratch file and loads it.
614    fn stored(pairs: &[(&str, &str)]) -> (tempfile::TempDir, Config) {
615        let scratch = tempfile::tempdir().expect("scratch directory");
616        let file =
617            crate::config::paths::config_file(Some(scratch.path())).expect("a settings file");
618        for (key, value) in pairs {
619            crate::config::store::store(&file, key, value).expect("the value is stored");
620        }
621        let config = Config::load(Some(scratch.path())).expect("the stored values load");
622        (scratch, config)
623    }
624
625    /// The two ceilings are both settings, and the smaller of them decides.
626    ///
627    /// This is the proof the earlier shape could not have passed. One mebibyte
628    /// was written into `crate::sql::parse` and taken as the smaller of the two
629    /// unconditionally, so a caller who raised the packet ceiling alone read one
630    /// mebibyte and a caller who raised both read one mebibyte. Only the second
631    /// of those is still true, and it is true because the caller said so.
632    #[test]
633    fn raising_only_the_packet_ceiling_still_stops_at_the_statement_ceiling() {
634        settling(|| {
635            let (_scratch, config) = stored(&[("conn.max_packet_bytes", "67108864")]);
636            let limits = ParseLimits::from_server(&config).expect("builds");
637            assert_eq!(
638                limits.max_statement_bytes(),
639                DEFAULT_MAX_STATEMENT_BYTES,
640                "the statement ceiling was left at its default, so it decides"
641            );
642        });
643    }
644
645    #[test]
646    fn raising_both_ceilings_raises_what_is_read() {
647        settling(|| {
648            let (_scratch, config) = stored(&[
649                ("conn.max_packet_bytes", "67108864"),
650                ("limits.max_statement_bytes", "4194304"),
651            ]);
652            let limits = ParseLimits::from_server(&config).expect("builds");
653            assert_eq!(
654                limits.max_statement_bytes(),
655                4_194_304,
656                "both ceilings were raised, so neither may hold the reading down"
657            );
658            assert!(
659                limits.max_statement_bytes() > DEFAULT_MAX_STATEMENT_BYTES,
660                "a number written in this source is deciding again"
661            );
662        });
663    }
664
665    /// The stack the parser thread gets is a setting, and moving it moves.
666    #[test]
667    fn the_parser_stack_follows_its_setting() {
668        settling(|| {
669            let (_scratch, config) = stored(&[("limits.parser_stack_bytes", "8388608")]);
670            let limits = ParseLimits::from_server(&config).expect("builds");
671            assert_eq!(limits.parser_stack_bytes(), 8_388_608);
672        });
673    }
674
675    /// A default written in two places is two numbers that can drift apart.
676    ///
677    /// The registry carries the built-in as text and `crate::sql::parse` carries
678    /// it as an expression, and nothing but this makes them the same number. An
679    /// invocation with nothing stored reads the registry, so a drift here would
680    /// silently move every default install away from what the source says.
681    #[test]
682    fn the_published_default_is_the_number_this_source_names() {
683        settling(|| {
684            let (_scratch, config) = stored(&[]);
685            let limits = ParseLimits::from_server(&config).expect("builds");
686            assert_eq!(limits.max_statement_bytes(), DEFAULT_MAX_STATEMENT_BYTES);
687            assert_eq!(limits.parser_stack_bytes(), DEFAULT_PARSER_STACK_BYTES);
688        });
689    }
690
691    #[test]
692    fn a_refused_row_never_discards_the_whole_file() {
693        let (_scratch, config) = empty();
694        let cli = parse(&["data", "import", "--file", "rows.csv", "--table", "t"]);
695        assert!(
696            !data_settings(&config, &cli)
697                .expect("builds")
698                .stop_on_refusal
699        );
700    }
701}