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 <[email protected]>
Цей коміт міститься в:
pHтаvvnadolskyy authored and GitHub committed 2026-12-03 03:35:38 +08:00
1 джерело 581672eebc
коміт 72f7b59e3b
6 files changed
+275 -37

No files matched your search

+8 -3
Переглянути файл
@@ -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()
+8 -3
Переглянути файл
@@ -259,12 +259,17 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
pub(crate) async fn session(pool: &SnowflakePool) -> IdeResult<crate::SessionContext> {
// 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<String> = 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 })
+86 -8
Переглянути файл
@@ -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 <name>`: the session moves.
Place,
}
fn use_kind(sql: &str) -> Option<Use> {
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<QueryResult> {
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
});
}
+152 -18
Переглянути файл
@@ -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<String> =
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<String> =
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<String> = 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<String> =
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]
+18 -3
Переглянути файл
@@ -562,7 +562,9 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
/>
{ddlTable && <IconButton icon="refresh" title="Reload the DDL" onClick={() => void reloadDdl(path)} />}
<span className={styles.spacer} />
{bound && driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
{bound && driver === "snowflake" && (
<SnowflakeSession target={bound} idle={!running} schema={schema} path={path} />
)}
<Select
variant="ghost"
aria-label="Data source"
@@ -701,8 +703,20 @@ const quoted = (name: string) => `"${name.replace(/"/g, '""')}"`;
/**
* Warehouse and role of a Snowflake data source's session (its consoles share them). Read
* once connected and after each run, since `USE WAREHOUSE` / `USE ROLE` in a console moves them too.
* Neither moves the session out of the console's database and schema, which the new role may not
* be allowed to enter.
*/
function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
function SnowflakeSession({
target,
idle,
schema,
path,
}: {
target: string;
idle: boolean;
schema: string;
path: string;
}) {
const connected = useDatabase((s) => s.connected.has(target));
const [state, setState] = useState<DbSessionContext>({
warehouse: "",
@@ -730,7 +744,8 @@ function SnowflakeSession({ target, idle }: { target: string; idle: boolean }) {
}, [target, connected, idle]);
if (!connected) return null;
const use = async (what: "WAREHOUSE" | "ROLE", name: string) => {
if (await runSql(target, [`USE ${what} ${quoted(name)}`]))
// In the console's schema: the session enters it before the role changes, and stays there.
if (await runSql(target, [`USE ${what} ${quoted(name)}`], schema, path))
setState((s) => (what === "WAREHOUSE" ? { ...s, warehouse: name } : { ...s, role: name }));
};
const options = (names: string[], current: string) =>
+3 -2
Переглянути файл
@@ -1933,14 +1933,15 @@ async function run(
/**
* Runs statements the tree's object actions generated (Drop, Rename, Modify
* Table…) on `id`, logging them to Output; false (and a notification) on error.
* With `schema` and `path`, they run as that console's statements do.
*/
export async function runSql(id: string, texts: string[]): Promise<boolean> {
export async function runSql(id: string, texts: string[], schema?: string, path?: string): Promise<boolean> {
const statements = texts.map((t) => {
const text = t.trim().replace(/;$/, "");
return { from: 0, to: text.length, text };
});
try {
const outcomes = await run(id, statements, nextRequestId());
const outcomes = await run(id, statements, nextRequestId(), undefined, 0, schema, path);
const failed = outcomes.find((o) => o.error);
if (failed) {
notifications().notify({