use super::{query_change, query_read};
use crate::cli::query::{NamedAction, QueryCommand, RunArgs, StatementArgs};
use crate::conn::Session;
use crate::error::{Failure, Result};
use crate::exec::{change, named, prepare, Policy, WriteState};
use crate::output::{Envelope, Gap};
use mysql_async::Conn;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EphemeralNotice {
OnCreate,
Always,
}
impl EphemeralNotice {
pub fn parse(word: &str) -> Result<Self> {
match word {
"on_create" => Ok(Self::OnCreate),
"always" => Ok(Self::Always),
other => Err(Failure::config(
"config.unknown_ephemeral_notice",
format!("`{other}` is not a moment the notice can be raised at"),
)
.with_detail("detail", other)
.with_hint("set sql.ephemeral_notice to on_create or to always")),
}
}
}
#[derive(Debug)]
pub struct Context {
pub policy: Policy,
pub config_dir: PathBuf,
pub write_state: WriteState,
pub ephemeral_notice: EphemeralNotice,
pub database: Option<String>,
pub passed_over: usize,
pub refuses_to_ask: bool,
pub conversion: crate::types::Conversion,
pub token: tokio_util::sync::CancellationToken,
}
#[must_use]
pub fn execute_offline(command: &QueryCommand, context: &Context) -> Option<Result<Envelope>> {
match command {
QueryCommand::Lineage(args) => Some(query_read::origins(args, context)),
QueryCommand::Named(args) if !matches!(args.action, NamedAction::Run { .. }) => {
Some(catalogue(&args.action, context))
}
_ => None,
}
}
pub async fn execute(
command: &QueryCommand,
session: &mut Session,
context: &mut Context,
) -> Result<Envelope> {
let server_read_only = session.facts().read_only;
let conn = session.connection();
let mut envelope = served(command, conn, context, server_read_only).await?;
apply_ephemeral_notice(&mut envelope, context.ephemeral_notice);
Ok(envelope)
}
pub fn apply_ephemeral_notice(envelope: &mut Envelope, notice: EphemeralNotice) {
if matches!(notice, EphemeralNotice::Always) {
change::note_session_is_ephemeral(&mut envelope.data);
}
}
async fn served(
command: &QueryCommand,
conn: &mut Conn,
context: &mut Context,
server_read_only: bool,
) -> Result<Envelope> {
match command {
QueryCommand::Run(args) => run(args, conn, context, server_read_only).await,
QueryCommand::Sample(args) => query_read::sample(args, conn, context).await,
QueryCommand::Explain(args) => query_read::explain(args, conn, context).await,
QueryCommand::Analyze(args) => {
query_change::measure(args, conn, context, server_read_only).await
}
QueryCommand::Plan(args) => query_read::running_plan(args, conn, context).await,
QueryCommand::File(args) => query_change::file(args, conn, context, server_read_only).await,
QueryCommand::Tx(args) => query_change::block(args, conn, context, server_read_only).await,
QueryCommand::Call(args) => query_change::call(args, conn, context, server_read_only).await,
QueryCommand::Named(args) => query_read::named_run(args, conn, context).await,
QueryCommand::Lineage(_) => Err(offline_only("query lineage")),
}
}
pub(super) fn offline_only(name: &str) -> Failure {
Failure::usage(
"usage.served_without_a_connection",
format!("`{name}` is served without a connection"),
)
.with_detail("detail", name)
.with_hint("route it through the path that opens no connection")
}
pub fn statement_text(
args: &StatementArgs,
refuses_to_ask: bool,
ceiling: usize,
) -> Result<String> {
if let Some(text) = &args.statement {
return Ok(text.clone());
}
if !args.stdin {
return Err(
Failure::usage("usage.no_statement", "no statement was given").with_hint(
"write the statement, or pass --stdin to read it from the standard input",
),
);
}
read_standard_input(refuses_to_ask, ceiling)
}
pub(super) fn kept_name(given: &str) -> Result<&str> {
if given.trim().is_empty() {
return Err(Failure::usage(
"query.name_missing",
"this action needs the name of a kept statement",
)
.with_hint(
"give one as the first word, as in `query named run pedidos`; \
`query named list` shows the kept names",
));
}
Ok(given)
}
pub(super) fn read_standard_input(refuses_to_ask: bool, ceiling: usize) -> Result<String> {
crate::settings::refuse_a_read_that_would_wait(refuses_to_ask, "the statement")?;
super::input::standard_input_within(ceiling)
}
pub(super) fn envelope(command: &'static str, data: serde_json::Value, gaps: Vec<Gap>) -> Envelope {
gaps.into_iter()
.fold(Envelope::new(command, data), Envelope::with_gap)
}
async fn run(
args: &RunArgs,
conn: &mut Conn,
context: &mut Context,
server_read_only: bool,
) -> Result<Envelope> {
let text = statement_text(
&args.statement,
context.refuses_to_ask,
context.policy.max_input_bytes,
)?;
let gated = prepare::gate(&text, &args.statement.params, &context.policy)?;
prepare::echo(&gated);
if gated.classification().is_read() {
let ceiling = context.policy.max_rows;
return query_read::reading(
"query run",
gated,
conn,
&context.policy,
ceiling,
&context.conversion,
context.passed_over,
)
.await;
}
let outcome = change::apply(
&gated,
conn,
&context.policy,
&mut context.write_state,
server_read_only,
)
.await?;
if !outcome.simulated {
crate::exec::script::confirm_changes(conn).await?;
}
let data = change::describe(&gated, &outcome);
Ok(envelope("query run", data, outcome.gaps))
}
fn catalogue(action: &NamedAction, context: &Context) -> Result<Envelope> {
match action {
NamedAction::Save {
name, statement, ..
} => {
kept_name(name)?;
if statement.trim().is_empty() {
return Err(Failure::usage(
"query.statement_missing",
"keeping a statement under a name needs the statement itself",
)
.with_hint(
"give it as the second word, as in \
`query named save pedidos 'SELECT * FROM pedidos'`",
));
}
}
NamedAction::Remove { name } | NamedAction::Run { name, .. } => {
kept_name(name)?;
}
NamedAction::List => {}
}
let data = named::serve(action, &context.config_dir, &context.policy)?;
Ok(Envelope::new("query named", data))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::globals::RowCountMode;
use crate::cli::query::{NamedArgs, PlanArgs};
use crate::sql::ParseLimits;
use std::time::Duration;
fn context() -> Context {
Context {
token: tokio_util::sync::CancellationToken::new(),
policy: Policy::new(
ParseLimits::default(),
100,
50,
RowCountMode::Changed,
";".to_owned(),
Duration::from_secs(30),
),
config_dir: std::env::temp_dir(),
write_state: WriteState::default(),
ephemeral_notice: EphemeralNotice::OnCreate,
conversion: crate::types::Conversion::stable(),
refuses_to_ask: false,
database: None,
passed_over: 0,
}
}
#[test]
fn the_moment_of_the_notice_is_read_from_its_own_word() {
assert_eq!(
EphemeralNotice::parse("on_create").expect("published"),
EphemeralNotice::OnCreate
);
assert_eq!(
EphemeralNotice::parse("always").expect("published"),
EphemeralNotice::Always
);
assert_eq!(
EphemeralNotice::parse("never")
.expect_err("outside the domain")
.code(),
"config.unknown_ephemeral_notice"
);
}
fn statement(text: &str) -> StatementArgs {
StatementArgs {
statement: Some(text.to_owned()),
stdin: false,
params: Vec::new(),
}
}
#[test]
fn only_the_commands_that_need_no_server_are_served_without_one() {
let context = context();
let lineage = QueryCommand::Lineage(statement("SELECT p.a FROM t AS p"));
let envelope = execute_offline(&lineage, &context)
.expect("served offline")
.expect("resolves");
assert_eq!(envelope.command, "query lineage");
assert_eq!(envelope.data["rows"][0]["sources"][0]["table"], "t");
for command in [
QueryCommand::Run(RunArgs {
statement: statement("SELECT 1"),
}),
QueryCommand::Analyze(statement("SELECT 1")),
QueryCommand::Plan(PlanArgs { id: Some(1) }),
QueryCommand::Named(NamedArgs {
action: NamedAction::Run {
name: "pedidos".to_owned(),
args: Vec::new(),
},
}),
] {
assert!(execute_offline(&command, &context).is_none());
}
}
#[test]
fn a_command_given_no_statement_is_refused_without_touching_anything() {
let none = StatementArgs {
statement: None,
stdin: false,
params: Vec::new(),
};
let missing = statement_text(&none, false, crate::exec::DEFAULT_MAX_INPUT_BYTES)
.expect_err("must refuse");
assert_eq!(missing.code(), "usage.no_statement");
assert_eq!(missing.exit_number().code(), 2);
}
fn save(name: &str, statement: &str) -> NamedAction {
NamedAction::Save {
name: name.to_owned(),
statement: statement.to_owned(),
params: Vec::new(),
max_rows: Some(10),
}
}
#[test]
fn the_catalogue_is_served_on_disk_and_never_keeps_a_refused_statement() {
let directory = tempfile::tempdir().expect("scratch");
let mut context = context();
context.config_dir = directory.path().to_owned();
let saved = catalogue(&save("pedidos", "SELECT * FROM pedidos"), &context).expect("stored");
assert_eq!(saved.data["stored"], true);
assert_eq!(
catalogue(&NamedAction::List, &context).expect("lists").data["rows"][0]["name"],
"pedidos"
);
let refused = catalogue(&save("duas", "SELECT 1; DROP TABLE users"), &context)
.expect_err("must refuse");
assert_eq!(refused.code(), "sql.multiple_statements");
let reopened = named::Catalogue::open(directory.path()).expect("opens");
assert!(
reopened.get("duas").is_err(),
"a refused statement is never left in the catalogue"
);
let gone = NamedAction::Remove {
name: "pedidos".to_owned(),
};
assert_eq!(
catalogue(&gone, &context).expect("removes").data["removed"],
true
);
}
#[test]
fn an_action_without_a_name_is_refused_with_a_code() {
let context = context();
for action in [
NamedAction::Remove {
name: String::new(),
},
NamedAction::Run {
name: String::new(),
args: Vec::new(),
},
save("", "SELECT 1"),
] {
let failure = catalogue(&action, &context).expect_err("must refuse");
assert_eq!(failure.code(), "query.name_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("query named")));
}
}
#[test]
fn keeping_a_statement_without_the_statement_is_refused_with_a_code() {
let context = context();
let failure = catalogue(&save("pedidos", ""), &context).expect_err("must refuse");
assert_eq!(failure.code(), "query.statement_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("query named save")));
}
}