feat(explain): add plan canvas with actual execution plans
This commit is contained in:
1 parent
cc7b2b17c5
commit
ed1e36912c
28 files changed
+2281
-43
No files matched your search
@@ -776,8 +776,12 @@ async fn execute_explain_query(
|
||||
}
|
||||
|
||||
// Build the database-specific EXPLAIN SQL
|
||||
let explain_result =
|
||||
build_explain_sql(ExplainSqlOptions { database_type: Some(*db_type), format: None, sql: sql.to_string() });
|
||||
let explain_result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(*db_type),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: sql.to_string(),
|
||||
});
|
||||
|
||||
let explain_sql = match (explain_result.ok, explain_result.sql) {
|
||||
(true, Some(sql)) => sql,
|
||||
|
||||
@@ -3132,6 +3132,7 @@ pub(crate) enum PostgresSearchPathContext {
|
||||
Query,
|
||||
Transaction,
|
||||
LocalTransaction,
|
||||
LocalQueryTransaction,
|
||||
}
|
||||
|
||||
pub(crate) fn postgres_set_search_path_sql(schema: &str, context: PostgresSearchPathContext) -> String {
|
||||
@@ -3141,6 +3142,7 @@ pub(crate) fn postgres_set_search_path_sql(schema: &str, context: PostgresSearch
|
||||
PostgresSearchPathContext::Query => ("", ", pg_catalog, public"),
|
||||
PostgresSearchPathContext::Transaction => ("", ", pg_catalog"),
|
||||
PostgresSearchPathContext::LocalTransaction => (" LOCAL", ", pg_catalog"),
|
||||
PostgresSearchPathContext::LocalQueryTransaction => (" LOCAL", ", pg_catalog, public"),
|
||||
};
|
||||
// PostgreSQL otherwise searches pg_catalog before every explicit path item.
|
||||
format!("SET{scope} search_path TO {}{suffix}", pg_quote_ident(schema))
|
||||
@@ -3305,6 +3307,88 @@ pub async fn execute_query_with_max_rows_and_cancel(
|
||||
.await
|
||||
}
|
||||
|
||||
fn postgres_read_only_transaction_setup(schema: Option<&str>) -> Vec<(String, &'static str)> {
|
||||
let mut statements = vec![("BEGIN READ ONLY".to_string(), "explain_analyze.begin")];
|
||||
if let Some(schema) = schema.map(str::trim).filter(|schema| !schema.is_empty()) {
|
||||
statements.push((
|
||||
postgres_set_search_path_sql(schema, PostgresSearchPathContext::LocalQueryTransaction),
|
||||
"explain_analyze.schema",
|
||||
));
|
||||
}
|
||||
statements
|
||||
}
|
||||
|
||||
fn postgres_read_only_transaction_cleanup_error(error: String) -> String {
|
||||
format!("PostgreSQL read-only transaction cleanup failed: {error}")
|
||||
}
|
||||
|
||||
fn merge_postgres_operation_and_rollback_result<T>(
|
||||
operation_result: Result<T, String>,
|
||||
rollback_result: Result<(), String>,
|
||||
) -> Result<T, String> {
|
||||
match (operation_result, rollback_result) {
|
||||
(Ok(result), Ok(())) => Ok(result),
|
||||
(Err(operation_error), Ok(())) => Err(operation_error),
|
||||
(Ok(_), Err(rollback_error)) => Err(postgres_read_only_transaction_cleanup_error(rollback_error)),
|
||||
(Err(operation_error), Err(rollback_error)) => {
|
||||
Err(format!("{operation_error}; {}", postgres_read_only_transaction_cleanup_error(rollback_error)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_postgres_operation_with_rollback<T, Operation, OperationFuture, Rollback, RollbackFuture>(
|
||||
operation: Operation,
|
||||
rollback: Rollback,
|
||||
) -> Result<T, String>
|
||||
where
|
||||
Operation: FnOnce() -> OperationFuture,
|
||||
OperationFuture: Future<Output = Result<T, String>>,
|
||||
Rollback: FnOnce() -> RollbackFuture,
|
||||
RollbackFuture: Future<Output = Result<(), String>>,
|
||||
{
|
||||
let operation_result = operation().await;
|
||||
let rollback_result = rollback().await;
|
||||
merge_postgres_operation_and_rollback_result(operation_result, rollback_result)
|
||||
}
|
||||
|
||||
pub async fn execute_query_in_read_only_transaction_with_rollback(
|
||||
pool: &Pool,
|
||||
schema: Option<&str>,
|
||||
sql: &str,
|
||||
max_rows: Option<usize>,
|
||||
cancel_token: Option<CancellationToken>,
|
||||
budget: DbOperationBudget,
|
||||
cancel_context: Option<PostgresCancelContext>,
|
||||
) -> Result<QueryResult, String> {
|
||||
let client = checkout_postgres_client(pool, cancel_token.as_ref(), budget.checkout_timeout).await?;
|
||||
let setup = postgres_read_only_transaction_setup(schema);
|
||||
|
||||
run_postgres_operation_with_rollback(
|
||||
|| async {
|
||||
for (statement, stage) in setup {
|
||||
execute_postgres_infra_statement(&client, &statement, budget.recycle_timeout, stage).await?;
|
||||
}
|
||||
|
||||
let pg_cancel_token = client.cancel_token();
|
||||
wait_postgres_query(
|
||||
pg_cancel_token,
|
||||
cancel_context,
|
||||
cancel_token,
|
||||
budget.query_timeout,
|
||||
budget.cancel_timeout,
|
||||
execute_query_with_max_rows_inner(&client, sql, max_rows, false),
|
||||
)
|
||||
.await
|
||||
},
|
||||
|| async {
|
||||
execute_postgres_infra_statement(&client, "ROLLBACK", budget.cleanup_timeout, "explain_analyze.rollback")
|
||||
.await
|
||||
.map(|_| ())
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn stream_select_query_with_cancel(
|
||||
pool: &Pool,
|
||||
schema: Option<&str>,
|
||||
@@ -4487,6 +4571,7 @@ pub async fn copy_in(pool: &Pool, sql: &str, data: &[u8]) -> Result<(), String>
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::process::Command;
|
||||
use std::time::Instant;
|
||||
use tokio_postgres::types::FromSql;
|
||||
@@ -4578,6 +4663,65 @@ mod tests {
|
||||
assert!(!Vec::<Option<serde_json::Value>>::accepts(&Type::INT4_ARRAY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_explain_analyze_uses_read_only_transaction_local_schema() {
|
||||
assert_eq!(
|
||||
postgres_read_only_transaction_setup(Some("sales")),
|
||||
vec![
|
||||
("BEGIN READ ONLY".to_string(), "explain_analyze.begin"),
|
||||
("SET LOCAL search_path TO \"sales\", pg_catalog, public".to_string(), "explain_analyze.schema"),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
postgres_read_only_transaction_setup(None),
|
||||
vec![("BEGIN READ ONLY".to_string(), "explain_analyze.begin")]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn postgres_explain_analyze_rolls_back_after_success_and_query_failures() {
|
||||
let rollback_calls = Cell::new(0);
|
||||
let result = run_postgres_operation_with_rollback(
|
||||
|| async { Ok::<_, String>(7) },
|
||||
|| async {
|
||||
rollback_calls.set(rollback_calls.get() + 1);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result, Ok(7));
|
||||
assert_eq!(rollback_calls.get(), 1);
|
||||
|
||||
for operation_error in ["query failed", crate::query::QUERY_CANCELED, "Query timed out after 30 seconds"] {
|
||||
let rollback_calls = Cell::new(0);
|
||||
let result = run_postgres_operation_with_rollback(
|
||||
|| async { Err::<(), _>(operation_error.to_string()) },
|
||||
|| async {
|
||||
rollback_calls.set(rollback_calls.get() + 1);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(result, Err(operation_error.to_string()));
|
||||
assert_eq!(rollback_calls.get(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn postgres_explain_analyze_marks_rollback_failure_as_pool_pollution() {
|
||||
let result = run_postgres_operation_with_rollback(
|
||||
|| async { Err::<(), _>("query failed".to_string()) },
|
||||
|| async { Err("PostgreSQL explain_analyze.rollback timed out after 3 seconds".to_string()) },
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("query failed; PostgreSQL read-only transaction cleanup failed: PostgreSQL explain_analyze.rollback timed out after 3 seconds".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
fn pg_interval_bytes(microseconds: i64, days: i32, months: i32) -> [u8; 16] {
|
||||
let mut raw = [0_u8; 16];
|
||||
raw[0..8].copy_from_slice(µseconds.to_be_bytes());
|
||||
@@ -4692,6 +4836,10 @@ mod tests {
|
||||
postgres_set_search_path_sql("application", PostgresSearchPathContext::LocalTransaction),
|
||||
"SET LOCAL search_path TO \"application\", pg_catalog"
|
||||
);
|
||||
assert_eq!(
|
||||
postgres_set_search_path_sql("application", PostgresSearchPathContext::LocalQueryTransaction),
|
||||
"SET LOCAL search_path TO \"application\", pg_catalog, public"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2605,8 +2605,8 @@ pub async fn execute_batch_with_max_rows(
|
||||
/// Execute a SQL Server batch directly through TDS simple-query mode.
|
||||
///
|
||||
/// This intentionally bypasses result-set type probing and SQL rewriting. It is
|
||||
/// required while `SHOWPLAN_XML` is enabled because any probe issued on the same
|
||||
/// session is itself affected by SHOWPLAN state.
|
||||
/// required while `SHOWPLAN_XML` or `STATISTICS XML` is enabled because any probe
|
||||
/// issued on the same session is itself affected by the plan-capture state.
|
||||
pub async fn execute_simple_batch_with_max_rows(
|
||||
client: &mut SqlServerClient,
|
||||
sql: &str,
|
||||
@@ -2748,6 +2748,13 @@ fn requires_simple_query_batch(sql: &str) -> bool {
|
||||
if tokens.len() >= 2 && tokens[0].eq_ignore_ascii_case("SET") && tokens[1].eq_ignore_ascii_case("SHOWPLAN_XML") {
|
||||
return true;
|
||||
}
|
||||
if tokens.len() >= 3
|
||||
&& tokens[0].eq_ignore_ascii_case("SET")
|
||||
&& tokens[1].eq_ignore_ascii_case("STATISTICS")
|
||||
&& tokens[2].eq_ignore_ascii_case("XML")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if tokens.len() >= 2 && tokens[0].eq_ignore_ascii_case("CREATE") && tokens[1].eq_ignore_ascii_case("SCHEMA") {
|
||||
return true;
|
||||
}
|
||||
@@ -3012,6 +3019,9 @@ mod tests {
|
||||
fn sqlserver_module_definitions_require_simple_query_batch() {
|
||||
assert!(requires_simple_query_batch("SET SHOWPLAN_XML ON;"));
|
||||
assert!(requires_simple_query_batch("SET SHOWPLAN_XML OFF;"));
|
||||
assert!(requires_simple_query_batch("SET STATISTICS XML ON;"));
|
||||
assert!(requires_simple_query_batch("SET STATISTICS XML OFF;"));
|
||||
assert!(!requires_simple_query_batch("SET STATISTICS IO ON;"));
|
||||
assert!(requires_simple_query_batch("CREATE SCHEMA [analytics];"));
|
||||
assert!(requires_simple_query_batch("CREATE FUNCTION dbo.fn_demo() RETURNS INT AS BEGIN RETURN 1; END;"));
|
||||
assert!(requires_simple_query_batch("ALTER PROCEDURE dbo.usp_demo AS SELECT 1;"));
|
||||
|
||||
@@ -540,6 +540,7 @@ pub enum QueryExecutionMode {
|
||||
#[default]
|
||||
Standard,
|
||||
Simple,
|
||||
PostgresReadOnlyTransaction,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -564,9 +565,31 @@ pub struct QueryExecutionOptions {
|
||||
pub continue_on_error: bool,
|
||||
/// Explicit low-level execution path. `Simple` is currently used by SQL Server
|
||||
/// SHOWPLAN so the source SQL bypasses result-set probing and query rewriting.
|
||||
/// `PostgresReadOnlyTransaction` executes on an isolated client session and
|
||||
/// always rolls the transaction back after the result is collected.
|
||||
pub execution_mode: QueryExecutionMode,
|
||||
}
|
||||
|
||||
fn validate_query_execution_mode(
|
||||
db_type: Option<DatabaseType>,
|
||||
sql: &str,
|
||||
options: &QueryExecutionOptions,
|
||||
) -> Result<(), String> {
|
||||
if options.execution_mode != QueryExecutionMode::PostgresReadOnlyTransaction {
|
||||
return Ok(());
|
||||
}
|
||||
if db_type != Some(DatabaseType::Postgres) {
|
||||
return Err("PostgreSQL read-only transaction mode requires a PostgreSQL connection".to_string());
|
||||
}
|
||||
if options.client_session_id.as_deref().is_none_or(|session_id| session_id.trim().is_empty()) {
|
||||
return Err("PostgreSQL read-only transaction mode requires an isolated client session".to_string());
|
||||
}
|
||||
if crate::sql::split_sql_statements_for_database(sql, DatabaseType::Postgres).len() != 1 {
|
||||
return Err("PostgreSQL read-only transaction mode requires exactly one statement".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn query_result_row_limit(max_rows: Option<usize>) -> usize {
|
||||
max_rows.unwrap_or(MAX_ROWS).max(1)
|
||||
}
|
||||
@@ -701,6 +724,10 @@ fn is_schema_reset_cleanup_error(lower: &str) -> bool {
|
||||
lower.contains("schema.reset cleanup failed")
|
||||
}
|
||||
|
||||
fn is_postgres_transaction_cleanup_error(lower: &str) -> bool {
|
||||
lower.contains("postgresql read-only transaction cleanup failed")
|
||||
}
|
||||
|
||||
fn should_discard_agent_pool_after_error(err: &str) -> bool {
|
||||
crate::db::agent_driver::agent_recovery_decision(err, RecoveryScope::UserOperation).discards_session()
|
||||
}
|
||||
@@ -719,6 +746,7 @@ pub fn pool_error_action(db_type: Option<DatabaseType>, err: &str) -> PoolErrorA
|
||||
if db::sqlserver::is_driver_panic_error(err)
|
||||
|| (is_dbx_query_timeout_error(&lower) && should_discard_pool_after_query_timeout(db_type))
|
||||
|| is_schema_reset_cleanup_error(&lower)
|
||||
|| is_postgres_transaction_cleanup_error(&lower)
|
||||
{
|
||||
return PoolErrorAction::Discard;
|
||||
}
|
||||
@@ -1284,9 +1312,21 @@ async fn do_execute_typed(
|
||||
let schema = schema.map(|s| s.to_string());
|
||||
let max_rows = options.max_rows;
|
||||
let prefer_text_protocol = postgres_prefers_text_protocol(pool_db_type);
|
||||
let execution_mode = options.execution_mode;
|
||||
let cancel_context = state.get_postgres_cancel_context(pool_key).await;
|
||||
drop(connections);
|
||||
if let Some(schema) = schema {
|
||||
if execution_mode == QueryExecutionMode::PostgresReadOnlyTransaction {
|
||||
db::postgres::execute_query_in_read_only_transaction_with_rollback(
|
||||
&p,
|
||||
schema.as_deref(),
|
||||
sql,
|
||||
max_rows,
|
||||
cancel_token,
|
||||
operation_budget.clone(),
|
||||
cancel_context,
|
||||
)
|
||||
.await
|
||||
} else if let Some(schema) = schema {
|
||||
db::postgres::execute_query_with_schema_and_max_rows_and_cancel(
|
||||
&p,
|
||||
&schema,
|
||||
@@ -1700,6 +1740,7 @@ pub async fn execute_sql_statement_with_options_typed(
|
||||
}
|
||||
|
||||
let db_type = connection_database_type(state, connection_id).await;
|
||||
validate_query_execution_mode(db_type, sql, &options)?;
|
||||
let has_executable_sql = db_type.map_or_else(
|
||||
|| crate::sql::has_executable_sql(sql),
|
||||
|db_type| crate::sql::has_executable_sql_for_database(sql, db_type),
|
||||
@@ -2007,6 +2048,15 @@ pub async fn execute_multi_core_with_options_for_client_and_progress_typed(
|
||||
return Err(MONGO_SHELL_COMMAND_HINT.into());
|
||||
}
|
||||
|
||||
let db_type = connection_database_type(state, connection_id).await;
|
||||
validate_query_execution_mode(db_type, sql, &options)?;
|
||||
if options.execution_mode == QueryExecutionMode::PostgresReadOnlyTransaction {
|
||||
let result =
|
||||
execute_sql_statement_with_options(state, connection_id, database, sql, schema, cancel_token, options)
|
||||
.await?;
|
||||
return Ok(vec![result.into()]);
|
||||
}
|
||||
|
||||
let pool_key = state
|
||||
.get_or_create_pool_for_session(connection_id, pool_database, options.client_session_id.as_deref())
|
||||
.await
|
||||
@@ -2050,7 +2100,6 @@ pub async fn execute_multi_core_with_options_for_client_and_progress_typed(
|
||||
);
|
||||
}
|
||||
|
||||
let db_type = connection_database_type(state, connection_id).await;
|
||||
let statements = db_type.map_or_else(
|
||||
|| split_sql_statements(sql),
|
||||
|db_type| crate::sql::split_sql_statements_for_database(sql, db_type),
|
||||
@@ -4251,6 +4300,28 @@ for line in sys.stdin:
|
||||
assert_eq!(QueryExecutionMode::default(), QueryExecutionMode::Standard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_execution_mode_deserializes_postgres_read_only_transaction() {
|
||||
let mode: QueryExecutionMode = serde_json::from_str("\"postgres_read_only_transaction\"").unwrap();
|
||||
|
||||
assert_eq!(mode, QueryExecutionMode::PostgresReadOnlyTransaction);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_read_only_transaction_requires_postgres_and_isolated_session() {
|
||||
let mut options = QueryExecutionOptions {
|
||||
execution_mode: QueryExecutionMode::PostgresReadOnlyTransaction,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(validate_query_execution_mode(Some(DatabaseType::Mysql), "SELECT 1", &options).is_err());
|
||||
assert!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1", &options).is_err());
|
||||
|
||||
options.client_session_id = Some("tab:explain:execution".to_string());
|
||||
assert_eq!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1", &options), Ok(()));
|
||||
assert!(validate_query_execution_mode(Some(DatabaseType::Postgres), "SELECT 1; SELECT 2", &options).is_err());
|
||||
}
|
||||
|
||||
fn test_connection_config(db_type: DatabaseType) -> ConnectionConfig {
|
||||
ConnectionConfig {
|
||||
id: "conn-1".to_string(),
|
||||
@@ -5492,6 +5563,14 @@ for line in sys.stdin:
|
||||
assert!(should_discard_pool_after_error(Some(DatabaseType::Postgres), err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pool_error_action_discards_postgres_read_only_transaction_cleanup_without_retry() {
|
||||
let err = "PostgreSQL read-only transaction cleanup failed: PostgreSQL explain_analyze.rollback timed out after 3 seconds";
|
||||
|
||||
assert_eq!(pool_error_action(Some(DatabaseType::Postgres), err), PoolErrorAction::Discard);
|
||||
assert!(should_discard_pool_after_error(Some(DatabaseType::Postgres), err));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pool_error_action_reconnects_non_agent_errors_but_never_replays_agent_operations() {
|
||||
let err = "connection reset by peer";
|
||||
|
||||
@@ -20,6 +20,10 @@ pub struct ExplainSqlOptions {
|
||||
/// Omitted formats retain the existing JSON behavior.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<ExplainFormat>,
|
||||
/// PostgreSQL and SQL Server only: run the statement and report measured
|
||||
/// rows/timings. Every other engine ignores the flag.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub analyze: Option<bool>,
|
||||
pub sql: String,
|
||||
}
|
||||
|
||||
@@ -53,11 +57,24 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {
|
||||
if !is_safe_explain_sql(&source) {
|
||||
return explain_err("unsafe");
|
||||
}
|
||||
if options.analyze == Some(true)
|
||||
&& options.database_type.is_some_and(|database_type| {
|
||||
matches!(database_type, DatabaseType::Postgres | DatabaseType::SqlServer)
|
||||
&& is_write_sql_for_database(&source, database_type)
|
||||
})
|
||||
{
|
||||
return explain_err("unsafe");
|
||||
}
|
||||
if options.database_type == Some(DatabaseType::SqlServer) && crate::sql::split_sql_batches(&source).len() != 1 {
|
||||
return explain_err("unsafe");
|
||||
}
|
||||
|
||||
let sql = match options.database_type {
|
||||
// ANALYZE executes the statement; is_safe_explain_sql has already limited
|
||||
// the source to SELECT/WITH/TABLE/VALUES. MongoDb shares the plain arm only.
|
||||
Some(DatabaseType::Postgres) if options.analyze == Some(true) => {
|
||||
format!("EXPLAIN (ANALYZE, FORMAT JSON) {source}")
|
||||
}
|
||||
Some(DatabaseType::Postgres | DatabaseType::MongoDb) => {
|
||||
format!("EXPLAIN (FORMAT JSON) {source}")
|
||||
}
|
||||
@@ -65,6 +82,11 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {
|
||||
format!("EXPLAIN {source}")
|
||||
}
|
||||
Some(DatabaseType::Oracle) => format!("EXPLAIN PLAN FOR {source}"),
|
||||
// STATISTICS XML returns the same ShowPlanXML document plus per-operator
|
||||
// runtime counters, at the price of actually running the statement.
|
||||
Some(DatabaseType::SqlServer) if options.analyze == Some(true) => {
|
||||
format!("SET STATISTICS XML ON;\nGO\n{source}\nGO\nSET STATISTICS XML OFF;")
|
||||
}
|
||||
Some(DatabaseType::SqlServer) => {
|
||||
format!("SET SHOWPLAN_XML ON;\nGO\n{source}\nGO\nSET SHOWPLAN_XML OFF;")
|
||||
}
|
||||
@@ -288,7 +310,7 @@ fn strip_leading_search_engine_comments(input: &str) -> &str {
|
||||
}
|
||||
|
||||
fn is_write_sql_with_database_type(sql: &str, database_type: Option<DatabaseType>) -> bool {
|
||||
if database_type == Some(DatabaseType::SqlServer) && is_sqlserver_showplan_xml_set(sql) {
|
||||
if database_type == Some(DatabaseType::SqlServer) && is_sqlserver_plan_capture_set(sql) {
|
||||
return false;
|
||||
}
|
||||
if database_type.is_some_and(|database_type| has_dialect_specific_write(sql, database_type)) {
|
||||
@@ -309,12 +331,15 @@ fn is_write_sql_with_database_type(sql: &str, database_type: Option<DatabaseType
|
||||
.any(|statement| is_write_sql_statement(statement, detect_mysql_executable_comments, detect_select_into))
|
||||
}
|
||||
|
||||
fn is_sqlserver_showplan_xml_set(sql: &str) -> bool {
|
||||
/// The explain flows toggle plan capture with a standalone SET statement:
|
||||
/// `SHOWPLAN_XML` for the estimated plan, `STATISTICS XML` for the actual one.
|
||||
fn is_sqlserver_plan_capture_set(sql: &str) -> bool {
|
||||
let normalized = strip_sql_comments(sql)
|
||||
.split_whitespace()
|
||||
.map(|part| part.trim_end_matches(';').to_ascii_uppercase())
|
||||
.collect::<Vec<_>>();
|
||||
matches!(normalized.as_slice(), [set, showplan, value] if set == "SET" && showplan == "SHOWPLAN_XML" && matches!(value.as_str(), "ON" | "OFF"))
|
||||
let tokens = normalized.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
matches!(tokens.as_slice(), ["SET", "SHOWPLAN_XML", "ON" | "OFF"] | ["SET", "STATISTICS", "XML", "ON" | "OFF"])
|
||||
}
|
||||
|
||||
fn is_mysql_compatible_database(database_type: DatabaseType) -> bool {
|
||||
@@ -765,6 +790,7 @@ mod tests {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Postgres),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: " select * from users where id = 1; ".to_string(),
|
||||
});
|
||||
|
||||
@@ -778,11 +804,148 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_postgres_analyze_explain_sql() {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Postgres),
|
||||
format: None,
|
||||
analyze: Some(true),
|
||||
sql: " select * from users where id = 1; ".to_string(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
ExplainSqlBuildResult {
|
||||
ok: true,
|
||||
sql: Some("EXPLAIN (ANALYZE, FORMAT JSON) select * from users where id = 1".to_string()),
|
||||
reason: None,
|
||||
}
|
||||
);
|
||||
|
||||
// analyze: Some(false) must behave exactly like the omitted flag.
|
||||
assert_eq!(
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Postgres),
|
||||
format: None,
|
||||
analyze: Some(false),
|
||||
sql: "SELECT 1".to_string(),
|
||||
})
|
||||
.sql,
|
||||
Some("EXPLAIN (FORMAT JSON) SELECT 1".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_sqlserver_actual_plan_explain_sql() {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: Some(true),
|
||||
sql: " select * from dbo.orders where id = 1; ".to_string(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
ExplainSqlBuildResult {
|
||||
ok: true,
|
||||
sql: Some(
|
||||
"SET STATISTICS XML ON;\nGO\nselect * from dbo.orders where id = 1\nGO\nSET STATISTICS XML OFF;"
|
||||
.to_string()
|
||||
),
|
||||
reason: None,
|
||||
}
|
||||
);
|
||||
|
||||
// analyze: Some(false) must keep the estimated SHOWPLAN plan.
|
||||
assert_eq!(
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: Some(false),
|
||||
sql: "SELECT 1".to_string(),
|
||||
})
|
||||
.sql,
|
||||
Some("SET SHOWPLAN_XML ON;\nGO\nSELECT 1\nGO\nSET SHOWPLAN_XML OFF;".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_sqlserver_analyze_on_non_select_sources() {
|
||||
// STATISTICS XML runs the statement, so the safety gate stays load-bearing.
|
||||
for sql in [
|
||||
"delete from dbo.orders",
|
||||
"update dbo.orders set name = 'x'",
|
||||
"SELECT * INTO dbo.orders_copy FROM dbo.orders",
|
||||
"SELECT 1\nGO\nDROP TABLE dbo.orders",
|
||||
] {
|
||||
assert_eq!(
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: Some(true),
|
||||
sql: sql.to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) },
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_analyze_for_every_engine_but_postgres_and_sqlserver() {
|
||||
for (db_type, expected) in [
|
||||
(DatabaseType::MongoDb, "EXPLAIN (FORMAT JSON) SELECT 1"),
|
||||
(DatabaseType::Mysql, "EXPLAIN FORMAT=JSON SELECT 1"),
|
||||
(DatabaseType::Dameng, "EXPLAIN SELECT 1"),
|
||||
(DatabaseType::Questdb, "EXPLAIN SELECT 1"),
|
||||
(DatabaseType::Oracle, "EXPLAIN PLAN FOR SELECT 1"),
|
||||
] {
|
||||
let analyzed = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(db_type),
|
||||
format: None,
|
||||
analyze: Some(true),
|
||||
sql: "SELECT 1".to_string(),
|
||||
});
|
||||
let plain = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(db_type),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT 1".to_string(),
|
||||
});
|
||||
|
||||
assert_eq!(analyzed, plain, "{db_type:?} must ignore the analyze flag");
|
||||
// MongoDb is rejected earlier by supports_explain_plan, so it never
|
||||
// reaches the match arm it nominally shares with Postgres.
|
||||
if db_type != DatabaseType::MongoDb {
|
||||
assert_eq!(analyzed.sql, Some(expected.to_string()), "{db_type:?}");
|
||||
} else {
|
||||
assert_eq!(analyzed.reason, Some("unsupported".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_analyze_on_non_select_sources() {
|
||||
for sql in ["delete from users", "update users set name = 'x'", "SELECT 1; DROP TABLE users"] {
|
||||
assert_eq!(
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Postgres),
|
||||
format: None,
|
||||
analyze: Some(true),
|
||||
sql: sql.to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) },
|
||||
"{sql}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_dameng_explain_sql() {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Dameng),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT * FROM t1 WHERE id = 1".to_string(),
|
||||
});
|
||||
|
||||
@@ -801,6 +964,7 @@ mod tests {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Oracle),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "WITH rows AS (SELECT 1 AS id FROM dual) SELECT * FROM rows;".to_string(),
|
||||
});
|
||||
|
||||
@@ -819,6 +983,7 @@ mod tests {
|
||||
let result = build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "WITH rows AS (SELECT 1 AS id) SELECT * FROM rows;".to_string(),
|
||||
});
|
||||
|
||||
@@ -838,6 +1003,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT 1\nGO\nSELECT 2".to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }
|
||||
@@ -846,6 +1012,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::SqlServer),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT 'first line\nGO\nlast line' AS text".to_string(),
|
||||
})
|
||||
.ok
|
||||
@@ -868,6 +1035,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT * FROM users;".to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult {
|
||||
@@ -881,6 +1049,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "delete from users".to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }
|
||||
@@ -890,6 +1059,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
format: None,
|
||||
analyze: None,
|
||||
sql: "SELECT * FROM users; DELETE FROM users".to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult { ok: false, sql: None, reason: Some("unsafe".to_string()) }
|
||||
@@ -899,6 +1069,7 @@ mod tests {
|
||||
build_explain_sql(ExplainSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
format: Some(ExplainFormat::Standard),
|
||||
analyze: None,
|
||||
sql: "SELECT * FROM users;".to_string(),
|
||||
}),
|
||||
ExplainSqlBuildResult {
|
||||
@@ -1281,13 +1452,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_read_only_allows_only_sqlserver_showplan_xml_session_switches() {
|
||||
for sql in ["SET SHOWPLAN_XML ON;", "-- explain\nSET SHOWPLAN_XML OFF"] {
|
||||
fn check_read_only_allows_only_sqlserver_plan_capture_session_switches() {
|
||||
for sql in [
|
||||
"SET SHOWPLAN_XML ON;",
|
||||
"-- explain\nSET SHOWPLAN_XML OFF",
|
||||
"SET STATISTICS XML ON;",
|
||||
"-- actual plan\nSET STATISTICS XML OFF",
|
||||
] {
|
||||
assert_eq!(check_read_only(sql, "readonly", DatabaseType::SqlServer), Ok(()));
|
||||
}
|
||||
assert!(check_read_only("SET SHOWPLAN_ALL ON", "readonly", DatabaseType::SqlServer).is_err());
|
||||
assert!(check_read_only("SET STATISTICS IO ON", "readonly", DatabaseType::SqlServer).is_err());
|
||||
assert!(check_read_only("SET SHOWPLAN_XML ON; SELECT 1", "readonly", DatabaseType::SqlServer).is_err());
|
||||
assert!(check_read_only("SET SHOWPLAN_XML OFF; DROP TABLE users", "readonly", DatabaseType::SqlServer).is_err());
|
||||
assert!(
|
||||
check_read_only("SET STATISTICS XML OFF; DROP TABLE users", "readonly", DatabaseType::SqlServer).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user