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;
fn default_port(config: &Config) -> Result<u16> {
let stored = settings::integer(config, "conn.default_port")?;
u16::try_from(stored).map_err(|_| {
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")
})
}
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))
}
pub fn connection(
config: &Config,
cli: &Cli,
profile: Option<&Profile>,
secret: Option<SecretString>,
) -> Result<ConnectionSettings> {
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")?,
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)?,
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,
statement_budget: Some(settings::operation_timeout(config, &cli.globals)?),
})
}
pub fn stored_default(config: &Config) -> Result<Option<String>> {
settings::optional_word(config, "conn.default")
}
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(),
}
}
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(),
),
])
}
pub fn schema_target(config: &Config, cli: &Cli, scope: Option<String>) -> Result<Target> {
let headroom = settings::integer(config, "output.count_headroom")?;
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 {
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")?,
))
}
}
const fn settle_packet_ceiling(stored: Option<usize>, observed: Option<usize>) -> Option<usize> {
match stored {
Some(written) => Some(written),
None => observed,
}
}
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),
})
}
pub fn server_settings(config: &Config, cli: &Cli) -> Result<ServerSettings> {
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")?,
})
}
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 {
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);
}
#[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());
}
#[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
);
}
#[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))
);
}
#[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")
);
}
#[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
);
}
#[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);
}
#[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);
});
}
static SETTLING: std::sync::Mutex<()> = std::sync::Mutex::new(());
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
}
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)
}
#[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"
);
});
}
#[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);
});
}
#[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
);
}
}