From a483ea77f48478cda921856748355f4e10566732 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 26 Nov 2026 04:37:53 +0800 Subject: [PATCH] feat(database): show table grants in the Modify Table dialog (#5965) The Modify Table dialog gains a read-only Grants tab for PostgreSQL and MySQL tables: one row per grantee and grantor, a column per privilege, and a `*` mark for privileges held WITH GRANT OPTION. - PostgreSQL expands the table ACL with aclexplode, falling back to the owner's implicit privileges when relacl is null; PUBLIC is listed. - MySQL reads information_schema.table_privileges (no grantor there). - Other engines show no tab and run no query; grants load only when the tab is opened. Fixes #5832 --- crates/ide-db/src/lib.rs | 34 +++ crates/ide-db/src/sql.rs | 22 ++ crates/ide-db/tests/mysql.rs | 36 +++ crates/ide-db/tests/postgres.rs | 44 +++ crates/ide-host/src/ops/db.rs | 16 +- crates/ide-host/tests/rpc.rs | 1 + src-tauri/tests/commands.snap | 1 + src/bindings.ts | 12 + src/features/database/Database.module.css | 51 ++++ src/features/database/ObjectDialogs.tsx | 320 +++++++++++++++------- src/features/database/objects.test.ts | 34 +++ src/features/database/objects.ts | 54 +++- src/features/database/store.ts | 6 + src/platform/locales/text/en.json | 10 +- src/platform/locales/text/ru.json | 10 +- src/platform/locales/text/tr.json | 10 +- src/platform/locales/text/zh-TW.json | 10 +- src/platform/locales/text/zh.json | 10 +- 18 files changed, 574 insertions(+), 107 deletions(-) diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 87422396b..2ceb5ab1f 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -178,6 +178,18 @@ pub struct TableDetails { pub triggers: Vec, } +/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted +/// by `grantor` (unknown on MySQL), and may grant it on when `grantable`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +#[serde(rename = "DbTableGrant")] +pub struct TableGrant { + pub grantee: String, + pub grantor: Option, + pub privilege: String, + pub grantable: bool, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] #[serde(rename = "DbCompletionColumn")] @@ -1164,6 +1176,28 @@ impl DbManager { Ok(TableDetails { columns, indexes, foreign_keys, triggers }) } + /// The object privileges granted on `table`; empty, without a query, on the engines + /// [`sql::table_grants`] doesn't cover. + pub async fn table_grants(&self, id: &str, schema: &str, table: &str) -> IdeResult> { + let pool = self.pool(id).await?; + let Some(q) = sql::table_grants(pool.driver(), schema, table) else { + return Ok(Vec::new()); + }; + Ok(pool + .rows(&q, MAX_META_ROWS) + .await? + .into_iter() + .filter_map(|r| { + let mut it = r.into_iter(); + let grantee = it.next().flatten()?; + let grantor = it.next().flatten().filter(|g| !g.is_empty()); + let privilege = it.next().flatten()?.to_ascii_uppercase(); + let grantable = flag(&it.next().flatten()); + Some(TableGrant { grantee, grantor, privilege, grantable }) + }) + .collect()) + } + /// The routines and sequences of `schema`. pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult { let pool = self.pool(id).await?; diff --git a/crates/ide-db/src/sql.rs b/crates/ide-db/src/sql.rs index 779beca4d..d9f0a919e 100644 --- a/crates/ide-db/src/sql.rs +++ b/crates/ide-db/src/sql.rs @@ -673,6 +673,28 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String { } } +/// `grantee, grantor, privilege, grantable` rows of `table`'s object privileges, for the +/// engines whose catalog keeps them per table: PostgreSQL's ACL (its implicit owner +/// privileges when `relacl` is null) and MySQL's `TABLE_PRIVILEGES` (no grantor). `None` +/// for the other engines, which then run no query. +pub fn table_grants(driver: DbDriver, schema: &str, table: &str) -> Option { + let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); + match driver { + DbDriver::Postgres => Some(format!( + "SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \ + pg_get_userbyid(a.grantor), a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END \ + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \ + CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a \ + WHERE n.nspname = {s} AND c.relname = {t} ORDER BY 1, 2" + )), + DbDriver::Mysql => Some(format!( + "SELECT grantee, NULL, privilege_type, is_grantable FROM information_schema.table_privileges \ + WHERE table_schema = {s} AND table_name = {t} ORDER BY 1" + )), + _ => None, + } +} + /// `before`, `insert` of SQLite's `CREATE TRIGGER name BEFORE INSERT ON …` (its catalog keeps only the text). pub fn sqlite_trigger_event(sql: &str) -> (String, String) { let upper = sql.to_ascii_uppercase(); diff --git a/crates/ide-db/tests/mysql.rs b/crates/ide-db/tests/mysql.rs index be7fcfa8d..90126046e 100644 --- a/crates/ide-db/tests/mysql.rs +++ b/crates/ide-db/tests/mysql.rs @@ -322,3 +322,39 @@ async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> Id } Ok(()) } + +#[tokio::test] +async fn table_grants_list_table_privileges() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp, "").await else { return Ok(()) }; + let c = CancellationToken::new(); + for stmt in [ + "DROP DATABASE IF EXISTS oi_grants", + "DROP USER IF EXISTS 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'", + "CREATE USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'", + "CREATE DATABASE oi_grants", + "CREATE TABLE oi_grants.shared (id INT)", + "CREATE TABLE oi_grants.private (id INT)", + "GRANT SELECT ON oi_grants.shared TO 'oi_grant_reader'@'%'", + "GRANT INSERT, UPDATE ON oi_grants.shared TO 'oi_grant_writer'@'%' WITH GRANT OPTION", + ] { + db.execute("m", stmt, 10, &c).await?; + } + let grants = db.table_grants("m", "oi_grants", "shared").await?; + let mut rows: Vec<_> = + grants.iter().map(|g| (g.grantee.as_str(), g.privilege.as_str(), g.grantable, g.grantor.clone())).collect(); + rows.sort(); + assert_eq!( + rows, + [ + ("'oi_grant_reader'@'%'", "SELECT", false, None), + ("'oi_grant_writer'@'%'", "INSERT", true, None), + ("'oi_grant_writer'@'%'", "UPDATE", true, None), + ] + ); + assert!(db.table_grants("m", "oi_grants", "private").await?.is_empty()); + for stmt in ["DROP DATABASE oi_grants", "DROP USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'"] { + db.execute("m", stmt, 10, &c).await?; + } + Ok(()) +} diff --git a/crates/ide-db/tests/postgres.rs b/crates/ide-db/tests/postgres.rs index 865055ed9..86f0bec30 100644 --- a/crates/ide-db/tests/postgres.rs +++ b/crates/ide-db/tests/postgres.rs @@ -735,3 +735,47 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled)); Ok(()) } + +#[tokio::test] +async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> { + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp).await else { return Ok(()) }; + let c = CancellationToken::new(); + for stmt in [ + "DROP SCHEMA IF EXISTS oi_grants CASCADE", + "DROP ROLE IF EXISTS oi_grant_reader", + "DROP ROLE IF EXISTS oi_grant_writer", + "CREATE ROLE oi_grant_reader", + "CREATE ROLE oi_grant_writer", + "CREATE SCHEMA oi_grants", + "CREATE TABLE oi_grants.shared (id INT)", + "CREATE TABLE oi_grants.private (id INT)", + "GRANT SELECT ON oi_grants.shared TO oi_grant_reader, PUBLIC", + "GRANT INSERT, UPDATE ON oi_grants.shared TO oi_grant_writer WITH GRANT OPTION", + ] { + db.execute("p", stmt, 10, &c).await?; + } + let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap(); + let grants = db.table_grants("p", "oi_grants", "shared").await?; + let of = |grantee: &str| { + let mut v: Vec<_> = grants + .iter() + .filter(|g| g.grantee == grantee) + .map(|g| (g.privilege.as_str(), g.grantable, g.grantor.as_deref() == Some(owner.as_str()))) + .collect(); + v.sort(); + v + }; + assert_eq!(of("oi_grant_reader"), [("SELECT", false, true)], "{grants:?}"); + assert_eq!(of("PUBLIC"), [("SELECT", false, true)], "{grants:?}"); + assert_eq!(of("oi_grant_writer"), [("INSERT", true, true), ("UPDATE", true, true)], "{grants:?}"); + assert!(of(&owner).contains(&("TRUNCATE", false, true)), "{grants:?}"); + // No ACL yet: the owner's implicit privileges. + let private = db.table_grants("p", "oi_grants", "private").await?; + assert!(private.iter().all(|g| g.grantee == owner), "{private:?}"); + assert!(private.iter().any(|g| g.privilege == "SELECT"), "{private:?}"); + for stmt in ["DROP SCHEMA oi_grants CASCADE", "DROP ROLE oi_grant_reader", "DROP ROLE oi_grant_writer"] { + db.execute("p", stmt, 10, &c).await?; + } + Ok(()) +} diff --git a/crates/ide-host/src/ops/db.rs b/crates/ide-host/src/ops/db.rs index 9cb831d95..76fc491e5 100644 --- a/crates/ide-host/src/ops/db.rs +++ b/crates/ide-host/src/ops/db.rs @@ -9,7 +9,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, RequestId}; use ide_db::split::SqlStatement; use ide_db::{ CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode, - QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage, + QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage, }; use serde::{Deserialize, Serialize}; use specta::Type; @@ -293,6 +293,19 @@ pub async fn db_table_details( db.table_details(&id, &schema, &table).await } +#[command(trust = trusted)] +pub async fn db_table_grants( + host: &Host, + window: &str, + id: String, + schema: String, + table: String, +) -> IdeResult> { + // Who may read or change `table` (PostgreSQL and MySQL; empty elsewhere). + let db = host.project(window)?.db.clone(); + db.table_grants(&id, &schema, &table).await +} + #[command(trust = trusted)] pub async fn db_ddl(host: &Host, window: &str, id: String, schema: String, table: String) -> IdeResult { // The DDL of table or view `table` (Go to DDL, Generate DDL). @@ -691,6 +704,7 @@ ide_command::domain!( db_sources, db_statements, db_table_details, + db_table_grants, db_table_page, db_tables, db_test, diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs index 277a42d9d..8eda9f6ad 100644 --- a/crates/ide-host/tests/rpc.rs +++ b/crates/ide-host/tests/rpc.rs @@ -407,6 +407,7 @@ async fn local_deployment_runs_on_the_project_host() { "db_schemas", "db_tables", "db_table_details", + "db_table_grants", "db_ddl", "db_schema_objects", "db_object_ddl", diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index fae1cc9e1..bd3e2872b 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -144,6 +144,7 @@ db_set_ssh_secret trusted project_host bin db_sources trusted project_host bindings sync db_statements trusted project_host bindings sync db_table_details trusted project_host bindings async +db_table_grants trusted project_host bindings async db_table_page trusted project_host bindings async db_tables trusted project_host bindings async db_test trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 3f55289b8..4d64648b8 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -391,6 +391,7 @@ export const commands = { dbSources: () => typedError(__TAURI_INVOKE("db_sources")), dbStatements: (id: string, text: string, from: number, to: number) => typedError(__TAURI_INVOKE("db_statements", { id, text, from, to })), dbTableDetails: (id: string, schema: string, table: string) => typedError(__TAURI_INVOKE("db_table_details", { id, schema, table })), + dbTableGrants: (id: string, schema: string, table: string) => typedError(__TAURI_INVOKE("db_table_grants", { id, schema, table })), dbTablePage: (request: RequestId, id: string, schema: string, table: string, filter: string | null, sort: DbSortKey[], offset: number, limit: number) => typedError(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })), dbTables: (id: string, schema: string) => typedError(__TAURI_INVOKE("db_tables", { id, schema })), dbTest: (source: DataSource_Deserialize, password: string | null, sshSecret: string | null) => typedError(__TAURI_INVOKE("db_test", { source, password, sshSecret })), @@ -5613,6 +5614,17 @@ export type DbTableDetails = { triggers: DbTriggerInfo[], }; +/** + * One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted + * by `grantor` (unknown on MySQL), and may grant it on when `grantable`. + */ +export type DbTableGrant = { + grantee: string, + grantor: string | null, + privilege: string, + grantable: boolean, +}; + export type DbTableInfo = { name: string, kind: DbTableKind, diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 42b2de424..3700c74ff 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -995,6 +995,57 @@ text-align: left; overflow-wrap: anywhere; } +.grantsPanel { + flex: 1; + display: flex; + flex-direction: column; + gap: var(--space-2); + min-height: 0; +} +.grantsScroll { + flex: 1; + min-height: 0; + overflow: auto; + border: 1px solid var(--border); + border-radius: var(--radius-small); +} +.grantsTable { + border-collapse: collapse; + min-width: 100%; + white-space: nowrap; +} +.grantsTable th { + position: sticky; + top: 0; + padding: 4px 8px; + text-align: left; + font-weight: 500; + color: var(--fg-muted); + background: var(--bg-dialog); + border-bottom: 1px solid var(--border); +} +.grantsTable td { + height: 24px; + padding: 0 8px; +} +.grantsTable tbody tr:hover { + background: var(--bg-hover); +} +.grantsTable .grantsFlag { + text-align: center; +} +.grantsNone { + color: var(--fg-muted); +} +.grantsMark { + display: inline-flex; + align-items: center; + vertical-align: middle; +} +.grantsOption { + font-weight: 600; + color: var(--accent); +} .quickDoc { width: 460px; max-width: calc(100vw - 32px); diff --git a/src/features/database/ObjectDialogs.tsx b/src/features/database/ObjectDialogs.tsx index daa58bcb4..8aab3ffac 100644 --- a/src/features/database/ObjectDialogs.tsx +++ b/src/features/database/ObjectDialogs.tsx @@ -4,9 +4,22 @@ * Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup. */ import { useEffect, useMemo, useRef, useState } from "react"; -import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc"; +import { call, commands, type DbColumnInfo, type DbDriver, type DbTableGrant } from "@/platform/ipc"; import { highlightInto } from "@/editor/lsp/markdown"; -import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui"; +import { + Button, + Checkbox, + Dialog, + IconButton, + Input, + Popup, + Icon, + Select, + T, + Tabs, + tooltipAttrs, + type SelectOption, +} from "@/ui"; import { parseSourceUrl, sourceLabel, splitTarget } from "./model"; import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes"; import { @@ -17,6 +30,8 @@ import { createTableSql, draftOf, dropDatabaseSql, + grantMatrix, + grantsSupported, renameDatabaseSql, dropSql, ident, @@ -36,6 +51,7 @@ import { dropDatabase, renameDatabase, loadDetails, + loadGrants, openSourceDialog, readableDdl, refresh, @@ -595,6 +611,8 @@ function ModifyTableForm({ } }; const locked = !!current && !canAlterColumn(driver, current); + const showGrants = !!table && grantsSupported(driver); + const [tab, setTab] = useState<"columns" | "grants">("columns"); const title = table ? `Modify Table ${table}` : "Create Table"; const typeList = `db-types-${driver}`; @@ -628,107 +646,123 @@ function ModifyTableForm({ /> {schema} -
-
-
- - + {showGrants && ( + setTab(t as "columns" | "grants")} + items={[ + { id: "columns", label: tx("Columns") }, + { id: "grants", label: tx("Grants") }, + ]} + /> + )} + {showGrants && tab === "grants" ? ( + + ) : ( +
+
+
+ + +
+
+ {columns.map((c) => ( +
setSelected(c.key)} + > + + {c.name || ""} + {c.dataType} +
+ ))} +
-
- {columns.map((c) => ( -
setSelected(c.key)} - > - - {c.name || ""} - {c.dataType} -
- ))} +
+ {current ? ( + <> + + patch({ name: e.target.value })} + /> + + patch({ dataType: e.target.value })} + /> + {driver !== "clickhouse" && ( + <> + + patch({ notNull })} + label="Not null" + /> + + )} + {!table && driver !== "clickhouse" && ( + <> + + patch({ primaryKey })} + label="Primary key" + /> + + )} + + patch({ default: e.target.value })} + /> + {locked && ( + <> + + + SQLite can rename or drop an existing column, not change its type, NOT NULL or default. + + + )} + + ) : ( + + Select a column + + )}
-
- {current ? ( - <> - - patch({ name: e.target.value })} - /> - - patch({ dataType: e.target.value })} - /> - {driver !== "clickhouse" && ( - <> - - patch({ notNull })} - label="Not null" - /> - - )} - {!table && driver !== "clickhouse" && ( - <> - - patch({ primaryKey })} - label="Primary key" - /> - - )} - - patch({ default: e.target.value })} - /> - {locked && ( - <> - - - SQLite can rename or drop an existing column, not change its type, NOT NULL or default. - - - )} - - ) : ( - - Select a column - - )} -
-
+ )} {TYPES[driver].map((t) => (