From 72f7b59e3b8eadd5e0745811ec933a680f109bfa Mon Sep 17 00:00:00 2001 From: pH Date: Wed, 2 Dec 2026 21:35:38 +0200 Subject: [PATCH] fix(database): run Snowflake statements after switching to a role that can't use the current warehouse (#7596) After switching to a role without usage on the current warehouse, Snowflake statements failed. The session now picks a warehouse the active role can use, the warehouse picker reads grants under the active role, and a schema refusal after reconnecting no longer restores stale session context. Co-authored-by: vvnadolskyy <12991410+vvnadolskyy@users.noreply.github.com> --- crates/ide-db/src/snowflake/commands.rs | 11 +- crates/ide-db/src/snowflake/meta.rs | 11 +- crates/ide-db/src/snowflake/mod.rs | 94 +++++++++++-- crates/ide-db/src/snowflake/tests.rs | 170 +++++++++++++++++++++--- src/features/database/console.tsx | 21 ++- src/features/database/store.ts | 5 +- 6 files changed, 275 insertions(+), 37 deletions(-) diff --git a/crates/ide-db/src/snowflake/commands.rs b/crates/ide-db/src/snowflake/commands.rs index 86401ff957..ac0ebca28c 100644 --- a/crates/ide-db/src/snowflake/commands.rs +++ b/crates/ide-db/src/snowflake/commands.rs @@ -8,7 +8,7 @@ //! statement valid, which the ignored live test does for the commands that only read. use super::tests::{CLOSED_OK, LOGIN_OK, bind, ok, result, serve, source}; -use super::{first_word, is_write}; +use super::{Use, first_word, is_write, use_kind}; use crate::conn::Pool; use crate::source::DbDriver; use crate::split::split; @@ -106,11 +106,16 @@ async fn every_command_reaches_the_server_as_written_and_its_answer_is_read() { let mut replies = vec![ok(LOGIN_OK)]; let mut entered = true; for c in commands.iter().filter(|c| !transfers(c)) { - if !entered && first_word(&c.sql) != "USE" { + // A role switch enters the schema first, like a statement that runs in it. + let switch = use_kind(&c.sql); + if !entered && matches!(switch, None | Some(Use::Role)) { replies.push(ok(status.clone())); } // These leave the session wherever they went: its schema is entered again afterwards. - entered = !matches!(first_word(&c.sql).as_str(), "USE" | "CALL" | "EXECUTE"); + // A warehouse leaves it as it was. + if switch != Some(Use::Warehouse) { + entered = switch != Some(Use::Place) && !matches!(first_word(&c.sql).as_str(), "CALL" | "EXECUTE"); + } let dml = matches!(first_word(&c.sql).as_str(), "INSERT" | "UPDATE" | "DELETE" | "MERGE"); replies.push(ok(if c.reads && first_word(&c.sql) != "USE" { rows.clone() diff --git a/crates/ide-db/src/snowflake/meta.rs b/crates/ide-db/src/snowflake/meta.rs index d60e0dbdec..e9a2eebba8 100644 --- a/crates/ide-db/src/snowflake/meta.rs +++ b/crates/ide-db/src/snowflake/meta.rs @@ -259,12 +259,17 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult IdeResult { // The consoles' session: `USE WAREHOUSE` / `USE ROLE` there is what the pickers show. let sql = "SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()"; - let current = pool.execute(sql, 1, &CancellationToken::new()).await?.rows; + // It names no table: the role just switched to may not use this target's schema. + let cancel = CancellationToken::new(); + let current = pool.execute_here(sql, 1, &cancel).await?.rows; let cell = |i: usize| current.first().and_then(|r| r.get(i).cloned().flatten()).unwrap_or_default(); let mut roles: Vec = serde_json::from_str(&cell(2)).unwrap_or_default(); roles.sort(); - let warehouses = match show(pool, "SHOW WAREHOUSES").await { - Ok(shown) => shown.values("name").flatten().map(str::to_owned).collect(), + let warehouses = match pool.execute_here("SHOW WAREHOUSES", MAX_ROWS, &cancel).await { + Ok(result) => { + let shown = Shown { columns: result.columns.into_iter().map(|c| c.name).collect(), rows: result.rows }; + shown.values("name").flatten().map(str::to_owned).collect() + } Err(_) => Vec::new(), }; Ok(crate::SessionContext { warehouse: cell(0), role: cell(1), warehouses, roles }) diff --git a/crates/ide-db/src/snowflake/mod.rs b/crates/ide-db/src/snowflake/mod.rs index 67a9b6498c..b8255a1cd3 100644 --- a/crates/ide-db/src/snowflake/mod.rs +++ b/crates/ide-db/src/snowflake/mod.rs @@ -209,7 +209,8 @@ fn typed(name: &str) -> String { crate::sql::quote_ident(crate::DbDriver::Snowflake, &name) } -fn first_word(sql: &str) -> String { +/// `sql` without the comments and blanks it starts with. +fn skip_comments(sql: &str) -> &str { let mut sql = sql.trim_start(); loop { if let Some(rest) = sql.strip_prefix("--").or_else(|| sql.strip_prefix("//")) { @@ -220,7 +221,41 @@ fn first_word(sql: &str) -> String { break; } } - sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default().to_ascii_uppercase() + sql +} + +fn word(sql: &str) -> &str { + sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default() +} + +fn first_word(sql: &str) -> String { + word(skip_comments(sql)).to_ascii_uppercase() +} + +/// What a `USE` statement switches. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Use { + /// `USE ROLE`, `USE SECONDARY ROLES`: what the session may reach changes, not where it is. + Role, + /// `USE WAREHOUSE`: neither. + Warehouse, + /// `USE DATABASE`, `USE SCHEMA`, `USE `: the session moves. + Place, +} + +fn use_kind(sql: &str) -> Option { + let sql = skip_comments(sql); + let first = word(sql); + if !first.eq_ignore_ascii_case("USE") { + return None; + } + let rest = skip_comments(&sql[first.len()..]); + // `USE "ROLE"` is a database of that name. + Some(match word(rest).to_ascii_uppercase().as_str() { + "ROLE" | "SECONDARY" => Use::Role, + "WAREHOUSE" => Use::Warehouse, + _ => Use::Place, + }) } /// Whether `sql` may change data or objects (a read-only data source refuses it). @@ -657,17 +692,33 @@ impl SnowflakePool { () = self.closed.cancelled() => return Err(closed()), turn = self.lane().turn.lock() => turn, }; + let switch = use_kind(sql); // A `USE` needs no schema to run in, and may be what makes the schema reachable. Ending a // transaction needs none either, and must not fail because the schema is gone meanwhile. - let context = match first_word(sql).as_str() { - "USE" | "COMMIT" | "ROLLBACK" => None, + let first = first_word(sql); + let context = match first.as_str() { + "USE" => { + // The role being left may use this schema and the next one may not: the session + // goes there first, and stays there, as a session of its own would. Refused: the + // new role may be the one that can. + if switch == Some(Use::Role) + && let Err(error) = self.enter(schema, cancel).await + && error.kind != ErrorKind::InvalidInput + { + return Err(error); + } + None + } + "COMMIT" | "ROLLBACK" => None, _ => { self.enter(schema, cancel).await?; self.context(schema) } }; - // These can move the session to another database or schema. - let moves = matches!(first_word(sql).as_str(), "USE" | "CALL" | "EXECUTE"); + // These can move the session to another database or schema. A role or a warehouse does + // not: the schema is not asked for again, which the new role may not be allowed to use + // while its statements name what they read in full. + let moves = switch == Some(Use::Place) || matches!(first.as_str(), "CALL" | "EXECUTE"); let result = self.statement(sql, skip, max_rows, Lost::Enter(context.as_deref()), cancel).await; if moves { *self.lane().context.lock() = None; @@ -675,18 +726,45 @@ impl SnowflakePool { result.map_err(|error| explain_use(sql, error)) } + /// A statement about the session itself (its role, its warehouse): it runs wherever the + /// session is and leaves it there, so the session's role need not be allowed to use this + /// target's schema. + pub(crate) async fn execute_here( + &self, + sql: &str, + max_rows: usize, + cancel: &CancellationToken, + ) -> IdeResult { + let _turn = tokio::select! { + biased; + () = cancel.cancelled() => return Err(IdeError::cancelled()), + () = self.closed.cancelled() => return Err(closed()), + turn = self.lane().turn.lock() => turn, + }; + self.statement(sql, 0, max_rows, Lost::Enter(None), cancel).await + } + /// Puts the session under this target's database and `schema` when it is not there already. async fn enter(&self, schema: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> { if let Some(wanted) = self.context(schema) && self.lane().context.lock().as_deref() != Some(wanted.as_str()) { - *self.lane().context.lock() = None; // Refused (the session's role may not use this database or schema): the statement // does not run, since the session is still wherever it was, which may be another // target's database. Tried again with the next statement. if let Err(error) = self.statement(&wanted, 0, 0, Lost::Enter(None), cancel).await { + // Snowflake's own refusal leaves the session where it was known to be; after + // anything else (cancelled, the session lost) it may be anywhere. + if error.kind != ErrorKind::InvalidInput { + *self.lane().context.lock() = None; + } + let hint = if error.kind == ErrorKind::InvalidInput { + "\nChoose a schema the current role can use, or switch roles." + } else { + "" + }; return Err(IdeError { - message: format!("{wanted} failed, so the statement was not run: {}", error.message), + message: format!("{wanted} failed, so the statement was not run: {}{hint}", error.message), ..error }); } diff --git a/crates/ide-db/src/snowflake/tests.rs b/crates/ide-db/src/snowflake/tests.rs index 0128cba1d1..5e9634f0cc 100644 --- a/crates/ide-db/src/snowflake/tests.rs +++ b/crates/ide-db/src/snowflake/tests.rs @@ -764,22 +764,122 @@ async fn a_console_schema_is_switched_with_its_statement_and_only_when_needed() ); } +fn status() -> String { + json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }], + "rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } }) + .to_string() +} + +const REFUSED: &str = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#; + +#[test] +fn a_use_statement_says_whether_it_moves_the_session() { + assert_eq!(use_kind("use role auditor"), Some(Use::Role)); + assert_eq!(use_kind("-- admin\n/* now */ USE /* the */ ROLE \"Auditor\""), Some(Use::Role)); + assert_eq!(use_kind("Use Secondary Roles ALL"), Some(Use::Role)); + assert_eq!(use_kind("use warehouse wh"), Some(Use::Warehouse)); + assert_eq!(use_kind("use database d"), Some(Use::Place)); + assert_eq!(use_kind("use schema d.s"), Some(Use::Place)); + assert_eq!(use_kind("use d.s"), Some(Use::Place)); + // A database called ROLE. + assert_eq!(use_kind("use \"ROLE\""), Some(Use::Place)); + assert_eq!(use_kind("use"), Some(Use::Place)); + assert_eq!(use_kind("select 'use role x'"), None); + assert_eq!(use_kind("user_defined()"), None); +} + #[tokio::test] -async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() { - let status = || { - json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }], - "rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } }) - .to_string() - }; - let refused = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#; +async fn a_role_switch_keeps_the_session_where_it_is() { let (listener, port) = bind().await; - // use role | the schema is refused, the statement is not sent | asked again, refused again | - // use role back, the schema is entered, the statement runs + // The schema is not asked for again after a role or a warehouse: the new role may not use it, + // and statements that name what they read in full still run. + let replies = + vec![ok(LOGIN_OK), ok(status()), ok(one()), ok(status()), ok(one()), ok(status()), ok(one()), ok(CLOSED_OK)]; + let server = serve(listener, replies); + let pool = Pool::connect(&source(port), None, None).await.unwrap(); + let cancel = CancellationToken::new(); + let statements = + ["use role auditor", "select 1", "USE WAREHOUSE \"Big\"", "select 2", "use secondary roles all", "select 3"]; + for sql in statements { + pool.execute(sql, 1, &cancel).await.unwrap(); + } + pool.close().await; + let sent: Vec = + server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect(); + assert_eq!(sent, statements); +} + +#[tokio::test] +async fn a_role_switch_first_enters_the_consoles_schema() { + let (listener, port) = bind().await; + // select 1 in PUBLIC | the console's schema, while the role being left may use it, use role | + // select 2 without asking for the schema again + let replies = vec![ok(LOGIN_OK), ok(one()), ok(status()), ok(status()), ok(one()), ok(CLOSED_OK)]; + let server = serve(listener, replies); + let pool = Pool::connect(&source(port), None, None).await.unwrap(); + let cancel = CancellationToken::new(); + pool.execute("select 1", 1, &cancel).await.unwrap(); + let mut console = crate::conn::Held::acquire(&pool).await.unwrap(); + console.apply_context(Some("SALES")).await.unwrap(); + console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap(); + console.execute(&pool, "select 2", 1, &cancel).await.unwrap(); + pool.close().await; + let sent: Vec = + server.await.unwrap()[1..5].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect(); + assert_eq!(sent, ["select 1", "USE SCHEMA \"ANALYTICS\".\"SALES\"", "use role auditor", "select 2"]); +} + +#[tokio::test] +async fn reading_the_role_and_warehouse_leaves_the_session_where_it_is() { + let (listener, port) = bind().await; + let current = json!({ "success": true, "data": { "rowtype": [{ "name": "W", "type": "text" }, + { "name": "R", "type": "text" }, { "name": "A", "type": "text" }], + "rowset": [["WH", "AUDITOR", "[\"AUDITOR\",\"ANALYST\"]"]], "queryResultFormat": "json" } }) + .to_string(); + let warehouses = json!({ "success": true, "data": { "rowtype": [{ "name": "name", "type": "text" }], + "rowset": [["AUDIT_WH"]], "queryResultFormat": "json" } }) + .to_string(); + // Both pickers read the console session, where the new role is active. + let replies = vec![ok(LOGIN_OK), ok(status()), ok(status()), ok(current), ok(warehouses), ok(one()), ok(CLOSED_OK)]; + let server = serve(listener, replies); + let pool = Pool::connect(&source(port), None, None).await.unwrap(); + let Pool::Snowflake(snowflake) = &pool else { unreachable!() }; + let cancel = CancellationToken::new(); + let mut console = crate::conn::Held::acquire(&pool).await.unwrap(); + console.apply_context(Some("SALES")).await.unwrap(); + console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap(); + let session = meta::session(snowflake).await.unwrap(); + assert_eq!((session.role.as_str(), session.roles.len()), ("AUDITOR", 2)); + assert_eq!(session.warehouses, ["AUDIT_WH"]); + console.execute(&pool, "select 1", 1, &cancel).await.unwrap(); + pool.close().await; + let seen = server.await.unwrap(); + let sent: Vec = seen.iter().filter_map(|r| r.json()["sqlText"].as_str().map(str::to_owned)).collect(); + assert_eq!( + sent, + [ + "USE SCHEMA \"ANALYTICS\".\"SALES\"", + "use role auditor", + "SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()", + "SHOW WAREHOUSES", + "select 1" + ] + ); +} + +#[tokio::test] +async fn a_schema_the_role_may_not_use_runs_nothing_elsewhere() { + let (listener, port) = bind().await; + // use role in PUBLIC | the console's schema is refused, its statement is not sent | select 2 + // in PUBLIC, where the session still is | refused again | refused before use role, which is + // sent all the same | the schema is entered, select 4 let replies = vec![ ok(LOGIN_OK), ok(status()), - ok(refused), - ok(refused), + ok(REFUSED), + ok(one()), + ok(REFUSED), + ok(REFUSED), ok(status()), ok(status()), ok(one()), @@ -788,8 +888,10 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() { let server = serve(listener, replies); let pool = Pool::connect(&source(port), None, None).await.unwrap(); let cancel = CancellationToken::new(); + let mut console = crate::conn::Held::acquire(&pool).await.unwrap(); + console.apply_context(Some("SALES")).await.unwrap(); pool.execute("use role auditor", 0, &cancel).await.unwrap(); - let error = pool.execute("delete from t", 1, &cancel).await.unwrap_err(); + let error = console.execute(&pool, "delete from t", 1, &cancel).await.unwrap_err(); assert!( error.message.contains("USE SCHEMA") && error.message.contains("was not run") @@ -797,14 +899,46 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() { "{}", error.message ); - assert!(pool.execute("select 2", 1, &cancel).await.is_err()); - pool.execute("use role analyst", 0, &cancel).await.unwrap(); - pool.execute("select 3", 1, &cancel).await.unwrap(); + pool.execute("select 2", 1, &cancel).await.unwrap(); + assert!(console.execute(&pool, "select 3", 1, &cancel).await.is_err()); + console.execute(&pool, "use role analyst", 0, &cancel).await.unwrap(); + console.execute(&pool, "select 4", 1, &cancel).await.unwrap(); pool.close().await; let sent: Vec = - server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect(); - let schema = "USE SCHEMA \"ANALYTICS\".\"PUBLIC\""; - assert_eq!(sent, ["use role auditor", schema, schema, "use role analyst", schema, "select 3"]); + server.await.unwrap()[1..9].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect(); + let sales = "USE SCHEMA \"ANALYTICS\".\"SALES\""; + assert_eq!(sent, ["use role auditor", sales, "select 2", sales, sales, "use role analyst", sales, "select 4"]); +} + +#[tokio::test] +async fn a_schema_refusal_after_login_does_not_restore_the_old_context() { + let (listener, port) = bind().await; + let gone = r#"{"success":false,"code":"390114","message":"Session closed."}"#; + let server = serve( + listener, + vec![ + ok(LOGIN_OK), + ok(status()), + ok(status()), + ok(gone), + ok(LOGIN_OK), + ok(REFUSED), + ok(status()), + ok(one()), + ok(CLOSED_OK), + ], + ); + let pool = Pool::connect(&source(port), None, None).await.unwrap(); + let cancel = CancellationToken::new(); + let mut sales = crate::conn::Held::acquire(&pool).await.unwrap(); + sales.apply_context(Some("SALES")).await.unwrap(); + sales.execute(&pool, "use role auditor", 0, &cancel).await.unwrap(); + assert!(pool.execute("select 1", 1, &cancel).await.is_err()); + sales.execute(&pool, "select 2", 1, &cancel).await.unwrap(); + pool.close().await; + let seen = server.await.unwrap(); + assert_eq!(seen[6].json()["sqlText"], "USE SCHEMA \"ANALYTICS\".\"SALES\""); + assert_eq!(seen[7].json()["sqlText"], "select 2"); } #[tokio::test] diff --git a/src/features/database/console.tsx b/src/features/database/console.tsx index cd28bd4235..832d22e841 100644 --- a/src/features/database/console.tsx +++ b/src/features/database/console.tsx @@ -562,7 +562,9 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) { /> {ddlTable && void reloadDdl(path)} />} - {bound && driver === "snowflake" && } + {bound && driver === "snowflake" && ( + + )}