1use 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
28fn default_port(config: &Config) -> Result<u16> {
40 let stored = settings::integer(config, "conn.default_port")?;
41 u16::try_from(stored).map_err(|_| {
42 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
52pub 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
91pub fn connection(
101 config: &Config,
102 cli: &Cli,
103 profile: Option<&Profile>,
104 secret: Option<SecretString>,
105) -> Result<ConnectionSettings> {
106 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 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 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 statement_budget: Some(settings::operation_timeout(config, &cli.globals)?),
143 })
144}
145
146pub fn stored_default(config: &Config) -> Result<Option<String>> {
157 settings::optional_word(config, "conn.default")
158}
159
160fn 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
176fn 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
190pub fn schema_target(config: &Config, cli: &Cli, scope: Option<String>) -> Result<Target> {
196 let headroom = settings::integer(config, "output.count_headroom")?;
207
208 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 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
286const 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
298pub 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
354pub fn server_settings(config: &Config, cli: &Cli) -> Result<ServerSettings> {
360 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
377pub 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 static SETTLING: std::sync::Mutex<()> = std::sync::Mutex::new(());
602
603 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 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 #[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 #[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 #[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}