feat(oracle): hide commit/rollback for clean manual-transaction state

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-08-27 11:30:27 +08:00
1 parent d2326acb81
commit bd05c0350d
13 files changed
+729 -22

No files matched your search

+103 -5
View File
@@ -23,7 +23,7 @@ use crate::database_capabilities;
use crate::db;
use crate::db::agent_driver::{AgentCallError, AgentErrorStage, AgentOperationOutcome};
use crate::models::connection::{ConnectionConfig, DatabaseType};
use crate::query_execution_sql::{is_write_sql, strip_sql_comments_and_literals};
use crate::query_execution_sql::{is_oracle_proven_read_only_statement, is_write_sql, strip_sql_comments_and_literals};
use crate::sql::{split_sql_batches, split_sql_statements, starts_with_executable_sql_keyword_for_database};
use crate::sql_dialect::{resolve_for_db, CAP_TRANSACTIONAL_DDL};
use crate::sql_risk::{classify_sql_risk_for_database, SqlRisk};
@@ -197,6 +197,18 @@ pub struct ExecuteMultiResult {
pub error: Option<crate::backend_error::BackendError>,
#[serde(skip_serializing_if = "is_false")]
pub server_message: bool,
/// Oracle-only manual-transaction UX metadata: true only for a statement
/// proven to be an ordinary top-level read. Absent/false for every other
/// Oracle statement and every non-Oracle execution. Not part of the
/// reusable database-result model (`db::QueryResult`).
#[serde(skip_serializing_if = "is_false")]
pub manual_transaction_proven_read_only: bool,
/// Oracle-only manual-transaction UX metadata: true on the synthetic
/// successful result when the manual-execution splitter found zero
/// statements (empty/whitespace/comments-only script). Lets the frontend
/// treat it as a no-op rather than an unproven statement.
#[serde(skip_serializing_if = "is_false")]
pub manual_transaction_no_statement: bool,
}
#[derive(Debug, Clone, PartialEq)]
@@ -243,6 +255,8 @@ impl ExecuteMultiResult {
statement_index: None,
error,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
@@ -256,6 +270,8 @@ impl ExecuteMultiResult {
statement_index: Some(statement_index),
error,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
@@ -271,6 +287,8 @@ impl ExecuteMultiResult {
statement_index,
error: Some(error),
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
@@ -282,6 +300,8 @@ impl ExecuteMultiResult {
statement_index: Some(statement_index),
error: None,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
@@ -304,6 +324,8 @@ impl ExecuteMultiResult {
statement_index: Some(statement_index),
error: None,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
@@ -325,9 +347,21 @@ impl ExecuteMultiResult {
statement_index: None,
error: None,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
fn with_manual_transaction_proven_read_only(mut self) -> Self {
self.manual_transaction_proven_read_only = true;
self
}
fn with_manual_transaction_no_statement(mut self) -> Self {
self.manual_transaction_no_statement = true;
self
}
pub fn without_error_detail(mut self) -> Self {
self.error = self.error.map(crate::backend_error::BackendError::without_detail);
self
@@ -600,6 +634,8 @@ impl From<db::QueryResult> for ExecuteMultiResult {
statement_index: None,
error: None,
server_message: false,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
}
@@ -613,6 +649,8 @@ impl From<db::sqlserver::SqlServerBatchResult> for ExecuteMultiResult {
statement_index: None,
error: None,
server_message: result.server_message,
manual_transaction_proven_read_only: false,
manual_transaction_no_statement: false,
}
}
}
@@ -4597,6 +4635,12 @@ pub struct ManualTransactionExecutionOptions {
pub table_data_preview: bool,
pub page_size: Option<usize>,
pub result_session_id: Option<String>,
/// User-facing SQL to classify (Oracle-only). When present, the core
/// classifies each split statement of this SQL rather than the rewritten
/// execution SQL, pairing them by count and position so DBX-owned
/// read-preserving rewrites (hidden primary keys, sort wrappers,
/// pagination) do not change toolbar semantics. Fail-closed on mismatch.
pub classification_sql: Option<String>,
}
pub async fn execute_in_manual_transaction_with_options(
@@ -4624,10 +4668,18 @@ pub async fn execute_in_manual_transaction_with_options(
|db_type| crate::sql::split_sql_statements_for_database(sql, db_type),
);
if statements.is_empty() {
return Ok(vec![ExecuteMultiResult::success_with_optional_server_large_values(
// Oracle-only UX marker: the no-op is Core's decision that the script
// (empty/whitespace/comments-only) has no statements, so the frontend
// must not treat it as an unproven statement. Every other database
// receives the plain empty result.
let mut result = ExecuteMultiResult::success_with_optional_server_large_values(
empty_query_result(0),
options.table_data_preview,
)]);
);
if db_type == Some(DatabaseType::Oracle) {
result = result.with_manual_transaction_no_statement();
}
return Ok(vec![result]);
}
// A result-session cursor can only track one result set, so pagination is
// single-statement only. Multi-statement scripts predate pagination: keep
@@ -4680,6 +4732,30 @@ pub async fn execute_in_manual_transaction_with_options(
let row_limit = options.max_rows.unwrap_or(MAX_ROWS).max(1);
let mut results = Vec::with_capacity(statements.len());
// Oracle-only classification pairing. The core splits both the execution
// SQL and, when present, the user-facing classification SQL with the same
// Oracle-aware splitter. A marker is emitted only when both lists have the
// same non-zero count and every paired user statement is proven read-only;
// any mismatch is fail-closed (no marker). This is deliberately a
// trust-boundary count/position pairing, not a SQL-equivalence parser.
let classification: Vec<bool> = if db_type == Some(DatabaseType::Oracle) {
match options.classification_sql.as_deref() {
Some(classification_sql) => {
let user_statements =
crate::sql::split_sql_statements_for_database(classification_sql, DatabaseType::Oracle);
let paired = user_statements.len() == statements.len() && !user_statements.is_empty();
if paired {
user_statements.iter().map(|statement| is_oracle_proven_read_only_statement(statement)).collect()
} else {
Vec::new()
}
}
None => Vec::new(),
}
} else {
Vec::new()
};
let mut conn = connection.lock().await;
for (i, statement) in statements.iter().enumerate() {
let result = match &mut *conn {
@@ -4708,10 +4784,14 @@ pub async fn execute_in_manual_transaction_with_options(
};
match result {
Ok(query_result) => {
results.push(ExecuteMultiResult::success_with_optional_server_large_values(
let mut executed = ExecuteMultiResult::success_with_optional_server_large_values(
query_result,
options.table_data_preview,
));
);
if classification.get(i).copied().unwrap_or(false) {
executed = executed.with_manual_transaction_proven_read_only();
}
results.push(executed);
}
Err(e) => {
// Statement failure ends the transaction. If another cleanup path
@@ -5320,6 +5400,24 @@ mod tests {
assert!(!postgres_prefers_text_protocol(None));
}
#[test]
fn execute_multi_result_manual_transaction_markers_serialize_conditionally() {
let plain = ExecuteMultiResult::success_with_optional_server_large_values(empty_query_result(0), false);
let plain_value = serde_json::to_value(&plain).unwrap();
assert!(plain_value.get("manual_transaction_proven_read_only").is_none());
assert!(plain_value.get("manual_transaction_no_statement").is_none());
let proven = plain.clone().with_manual_transaction_proven_read_only();
let proven_value = serde_json::to_value(&proven).unwrap();
assert_eq!(proven_value.get("manual_transaction_proven_read_only"), Some(&serde_json::Value::Bool(true)));
assert!(proven_value.get("manual_transaction_no_statement").is_none());
let no_statement = plain.with_manual_transaction_no_statement();
let no_statement_value = serde_json::to_value(&no_statement).unwrap();
assert_eq!(no_statement_value.get("manual_transaction_no_statement"), Some(&serde_json::Value::Bool(true)));
assert!(no_statement_value.get("manual_transaction_proven_read_only").is_none());
}
#[test]
fn schema_diff_destructive_detection_covers_drop_and_alter_drop() {
assert!(is_destructive_schema_diff_statement("DROP INDEX idx_users_email ON users"));
+174
View File
@@ -590,6 +590,93 @@ pub fn check_read_only(sql: &str, connection_name: &str, database_type: Database
Ok(())
}
/// Oracle-only, fail-closed classifier for manual-transaction UX. Returns true
/// only for an ordinary top-level read that DBX can prove harmless: a single
/// top-level `SELECT` (not `WITH`) that after Oracle-aware comment/literal
/// stripping contains no row-locking, transaction-control, DDL/DCL, `CALL`/
/// `EXEC`, PL/SQL block, `EXECUTE IMMEDIATE`, database-link, sequence
/// pseudocolumn (`NEXTVAL`/`CURRVAL`), function-invocation, or subquery
/// syntax. Any lexical ambiguity is **not** proven read-only; the classifier
/// deliberately whitelists no functions because user/package function side
/// effects cannot be proven and would create an unbounded compatibility
/// surface.
pub fn is_oracle_proven_read_only_statement(sql: &str) -> bool {
let cleaned = strip_sql_comments_and_literals(sql);
let trimmed = cleaned.trim_start();
if trimmed.is_empty() {
return false;
}
let upper = trimmed.to_uppercase();
// Single top-level SELECT only (WITH is excluded because data-modifying
// CTEs can hide writes in a row-returning path).
if !starts_with_keyword(&upper, "SELECT") {
return false;
}
let lower = cleaned.to_lowercase();
// Function invocation or subquery syntax: any '(' after literal stripping.
// This deliberately excludes SELECT upper(name), COUNT(*), package
// functions, and subqueries DBX cannot prove harmless.
if lower.contains('(') {
return false;
}
// Database link: '@' cannot appear in an unquoted Oracle identifier, so any
// remaining '@' after literal stripping is a remote-object reference.
if lower.contains('@') {
return false;
}
// Word-boundary forbidden keywords. These are Oracle keywords/reserved
// words, so they cannot be legitimate unquoted identifiers inside a simple
// read; a quoted occurrence is already stripped to spaces above.
const FORBIDDEN_WORDS: &[&str] = &[
// row locking
"for",
"update",
"lock",
// transaction control
"begin",
"commit",
"rollback",
"savepoint",
// DDL/DCL
"create",
"alter",
"drop",
"truncate",
"rename",
"grant",
"revoke",
"comment",
"purge",
"audit",
"noaudit",
"analyze",
"flashback",
"merge",
"insert",
"delete",
// set operators (a UNION is not a single top-level SELECT)
"union",
"minus",
"intersect",
// stored procedures / dynamic SQL / PL/SQL blocks
"call",
"exec",
"execute",
"declare",
// sequence pseudocolumns
"nextval",
"currval",
// SELECT ... INTO is PL/SQL-only in Oracle
"into",
];
!FORBIDDEN_WORDS.iter().any(|word| contains_word(&lower, word))
}
fn contains_word(source: &str, word: &str) -> bool {
let bytes = source.as_bytes();
let word_bytes = word.as_bytes();
@@ -825,6 +912,93 @@ where
mod tests {
use super::*;
#[test]
fn oracle_proven_read_only_accepts_simple_top_level_selects() {
assert!(is_oracle_proven_read_only_statement("SELECT * FROM table"));
assert!(is_oracle_proven_read_only_statement("select id, name from users"));
assert!(is_oracle_proven_read_only_statement("SELECT * FROM users WHERE id = 1"));
assert!(is_oracle_proven_read_only_statement("SELECT * FROM users ORDER BY id"));
assert!(is_oracle_proven_read_only_statement("SELECT * FROM users FETCH FIRST 10 ROWS ONLY"));
assert!(is_oracle_proven_read_only_statement("SELECT 1"));
assert!(is_oracle_proven_read_only_statement("SELECT ROWNUM FROM dual"));
assert!(is_oracle_proven_read_only_statement("SELECT * FROM users"));
// Comment/literal stripping hides keywords that are not part of the SQL.
assert!(is_oracle_proven_read_only_statement("-- comment\nSELECT * FROM users"));
assert!(is_oracle_proven_read_only_statement("SELECT 'update' FROM dual"));
assert!(is_oracle_proven_read_only_statement("SELECT \"select\" FROM t"));
assert!(is_oracle_proven_read_only_statement("SELECT * FROM user_update"));
}
#[test]
fn oracle_proven_read_only_rejects_writes_and_ddl() {
for sql in [
"UPDATE users SET name = 'x'",
"INSERT INTO users VALUES (1)",
"DELETE FROM users",
"MERGE INTO target USING source ON (a = b) WHEN MATCHED THEN UPDATE",
"CREATE TABLE t (id INT)",
"ALTER TABLE t ADD COLUMN c INT",
"DROP TABLE t",
"TRUNCATE TABLE t",
"GRANT SELECT ON t TO x",
"REVOKE SELECT ON t FROM x",
] {
assert!(!is_oracle_proven_read_only_statement(sql), "expected rejected: {sql}");
}
}
#[test]
fn oracle_proven_read_only_rejects_cte_procedure_and_plsql() {
for sql in [
"WITH cte AS (SELECT 1 FROM dual) SELECT * FROM cte",
"CALL my_proc()",
"EXEC my_proc",
"EXECUTE IMMEDIATE 'DROP TABLE t'",
"BEGIN UPDATE t SET x = 1; END;",
"DECLARE x INT; BEGIN NULL; END;",
] {
assert!(!is_oracle_proven_read_only_statement(sql), "expected rejected: {sql}");
}
}
#[test]
fn oracle_proven_read_only_rejects_locking_and_sequence_pseudocolumns() {
for sql in [
"SELECT * FROM t FOR UPDATE",
"LOCK TABLE t IN EXCLUSIVE MODE",
"SELECT seq.NEXTVAL FROM dual",
"SELECT seq.CURRVAL FROM dual",
"SELECT * FROM t@dblink",
"SELECT * FROM t WHERE id = 1 FOR UPDATE",
] {
assert!(!is_oracle_proven_read_only_statement(sql), "expected rejected: {sql}");
}
}
#[test]
fn oracle_proven_read_only_rejects_functions_and_subqueries() {
for sql in [
"SELECT upper(name) FROM users",
"SELECT count(*) FROM users",
"SELECT pkg.fn() FROM dual",
"SELECT * FROM users WHERE id IN (SELECT id FROM orders)",
"SELECT * FROM (SELECT * FROM users)",
"SELECT NVL(name, 'x') FROM users",
] {
assert!(!is_oracle_proven_read_only_statement(sql), "expected rejected: {sql}");
}
}
#[test]
fn oracle_proven_read_only_rejects_empty_and_ambiguous_input() {
assert!(!is_oracle_proven_read_only_statement(""));
assert!(!is_oracle_proven_read_only_statement(" "));
assert!(!is_oracle_proven_read_only_statement("-- only a comment"));
assert!(!is_oracle_proven_read_only_statement("SELECT * FROM t WHERE a IN (1, 2)"));
assert!(!is_oracle_proven_read_only_statement("SELECT * FROM t WHERE b = 'x' AND c IN (3)"));
assert!(!is_oracle_proven_read_only_statement("SELECT 1 UNION SELECT 2"));
}
#[test]
fn builds_postgres_json_explain_sql() {
let result = build_explain_sql(ExplainSqlOptions {