дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 05:52:23 +02:00
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
Цей коміт міститься в:
1 джерело
de36b46660
коміт
a483ea77f4
18 files changed
+574
-107
No files matched your search
@@ -178,6 +178,18 @@ pub struct TableDetails {
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
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<Vec<TableGrant>> {
|
||||
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<SchemaObjects> {
|
||||
let pool = self.pool(id).await?;
|
||||
|
||||
@@ -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<String> {
|
||||
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();
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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<Vec<TableGrant>> {
|
||||
// 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<String> {
|
||||
// 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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -391,6 +391,7 @@ export const commands = {
|
||||
dbSources: () => typedError<DataSource_Serialize[], IdeError>(__TAURI_INVOKE("db_sources")),
|
||||
dbStatements: (id: string, text: string, from: number, to: number) => typedError<SqlStatement[], IdeError>(__TAURI_INVOKE("db_statements", { id, text, from, to })),
|
||||
dbTableDetails: (id: string, schema: string, table: string) => typedError<DbTableDetails, IdeError>(__TAURI_INVOKE("db_table_details", { id, schema, table })),
|
||||
dbTableGrants: (id: string, schema: string, table: string) => typedError<DbTableGrant[], IdeError>(__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<DbTablePage, IdeError>(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })),
|
||||
dbTables: (id: string, schema: string) => typedError<DbTableInfo[], IdeError>(__TAURI_INVOKE("db_tables", { id, schema })),
|
||||
dbTest: (source: DataSource_Deserialize, password: string | null, sshSecret: string | null) => typedError<string, IdeError>(__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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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({
|
||||
/>
|
||||
<span className={styles.formHint}>{schema}</span>
|
||||
</div>
|
||||
<div className={styles.modifyMain}>
|
||||
<div className={styles.modifyColumns}>
|
||||
<div className={styles.modifyToolbar}>
|
||||
<IconButton icon="plus" title="Add Column" size="small" onClick={add} />
|
||||
<IconButton
|
||||
icon="minus"
|
||||
title={current?.dropped ? "Keep Column" : "Drop Column"}
|
||||
size="small"
|
||||
disabled={!current}
|
||||
onClick={remove}
|
||||
/>
|
||||
{showGrants && (
|
||||
<Tabs
|
||||
variant="compact"
|
||||
aria-label={tx("Table properties")}
|
||||
activeId={tab}
|
||||
onSelect={(t) => setTab(t as "columns" | "grants")}
|
||||
items={[
|
||||
{ id: "columns", label: tx("Columns") },
|
||||
{ id: "grants", label: tx("Grants") },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
{showGrants && tab === "grants" ? (
|
||||
<GrantsPanel id={id} schema={schema} table={table} />
|
||||
) : (
|
||||
<div className={styles.modifyMain}>
|
||||
<div className={styles.modifyColumns}>
|
||||
<div className={styles.modifyToolbar}>
|
||||
<IconButton icon="plus" title="Add Column" size="small" onClick={add} />
|
||||
<IconButton
|
||||
icon="minus"
|
||||
title={current?.dropped ? "Keep Column" : "Drop Column"}
|
||||
size="small"
|
||||
disabled={!current}
|
||||
onClick={remove}
|
||||
/>
|
||||
</div>
|
||||
<div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}>
|
||||
{columns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}>
|
||||
{columns.map((c) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={c.key === selected}
|
||||
tabIndex={-1}
|
||||
className={styles.modifyItem}
|
||||
data-dropped={c.dropped || undefined}
|
||||
onMouseDown={() => setSelected(c.key)}
|
||||
>
|
||||
<Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} />
|
||||
<span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span>
|
||||
<span className={styles.treeType}>{c.dataType}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className={styles.modifyProps}>
|
||||
{current ? (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-col-name">
|
||||
<T>Name</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-name"
|
||||
value={current.name}
|
||||
disabled={current.dropped}
|
||||
onChange={(e) => patch({ name: e.target.value })}
|
||||
/>
|
||||
<label className={styles.formLabel} htmlFor="db-col-type">
|
||||
<T>Data type</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-type"
|
||||
mono
|
||||
list={typeList}
|
||||
value={current.dataType}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ dataType: e.target.value })}
|
||||
/>
|
||||
{driver !== "clickhouse" && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.notNull}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(notNull) => patch({ notNull })}
|
||||
label="Not null"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{!table && driver !== "clickhouse" && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.primaryKey}
|
||||
onChange={(primaryKey) => patch({ primaryKey })}
|
||||
label="Primary key"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<label className={styles.formLabel} htmlFor="db-col-default">
|
||||
<T>Default</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-default"
|
||||
mono
|
||||
placeholder="expression"
|
||||
value={current.default}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ default: e.target.value })}
|
||||
/>
|
||||
{locked && (
|
||||
<>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>SQLite can rename or drop an existing column, not change its type, NOT NULL or default.</T>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className={styles.formHint}>
|
||||
<T>Select a column</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.modifyProps}>
|
||||
{current ? (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-col-name">
|
||||
<T>Name</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-name"
|
||||
value={current.name}
|
||||
disabled={current.dropped}
|
||||
onChange={(e) => patch({ name: e.target.value })}
|
||||
/>
|
||||
<label className={styles.formLabel} htmlFor="db-col-type">
|
||||
<T>Data type</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-type"
|
||||
mono
|
||||
list={typeList}
|
||||
value={current.dataType}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ dataType: e.target.value })}
|
||||
/>
|
||||
{driver !== "clickhouse" && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.notNull}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(notNull) => patch({ notNull })}
|
||||
label="Not null"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{!table && driver !== "clickhouse" && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox
|
||||
checked={current.primaryKey}
|
||||
onChange={(primaryKey) => patch({ primaryKey })}
|
||||
label="Primary key"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<label className={styles.formLabel} htmlFor="db-col-default">
|
||||
<T>Default</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-default"
|
||||
mono
|
||||
placeholder="expression"
|
||||
value={current.default}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ default: e.target.value })}
|
||||
/>
|
||||
{locked && (
|
||||
<>
|
||||
<span />
|
||||
<span className={styles.formHint}>
|
||||
<T>SQLite can rename or drop an existing column, not change its type, NOT NULL or default.</T>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className={styles.formHint}>
|
||||
<T>Select a column</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<datalist id={typeList}>
|
||||
{TYPES[driver].map((t) => (
|
||||
<option key={t} value={t} />
|
||||
@@ -740,6 +774,92 @@ function ModifyTableForm({
|
||||
);
|
||||
}
|
||||
|
||||
type GrantsState =
|
||||
| { status: "loading" }
|
||||
| { status: "ok"; grants: DbTableGrant[] }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
/** The Modify Table dialog's Grants tab: who holds which privilege on `table`, read-only. */
|
||||
function GrantsPanel({ id, schema, table }: { id: string; schema: string; table: string }) {
|
||||
const [state, setState] = useState<GrantsState>({ status: "loading" });
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
loadGrants(id, schema, table).then(
|
||||
(grants) => live && setState({ status: "ok", grants }),
|
||||
(e: unknown) => live && setState({ status: "error", message: e instanceof Error ? e.message : String(e) }),
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [id, schema, table]);
|
||||
if (state.status !== "ok")
|
||||
return (
|
||||
<div className={styles.grantsPanel}>
|
||||
<span className={styles.formHint}>{state.status === "error" ? state.message : tx("Loading…")}</span>
|
||||
</div>
|
||||
);
|
||||
const { privileges, rows } = grantMatrix(state.grants);
|
||||
if (!rows.length)
|
||||
return (
|
||||
<div className={styles.grantsPanel}>
|
||||
<span className={styles.formHint}>
|
||||
<T>No privileges are granted on this table.</T>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={styles.grantsPanel}>
|
||||
<div className={styles.grantsScroll}>
|
||||
<table className={styles.grantsTable} aria-label={tx("Grants")}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<T>Grantee</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Grantor</T>
|
||||
</th>
|
||||
{privileges.map((p) => (
|
||||
<th key={p} className={styles.grantsFlag}>
|
||||
{p}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r) => (
|
||||
<tr key={`${r.grantee}\u0000${r.grantor ?? ""}`}>
|
||||
<td>{r.grantee}</td>
|
||||
<td className={r.grantor ? undefined : styles.grantsNone}>{r.grantor ?? "—"}</td>
|
||||
{privileges.map((p) => {
|
||||
const grantable = r.privileges.get(p);
|
||||
return (
|
||||
<td key={p} className={styles.grantsFlag}>
|
||||
{grantable !== undefined && (
|
||||
<span
|
||||
className={styles.grantsMark}
|
||||
aria-label={grantable ? tx("Granted with grant option") : tx("Granted")}
|
||||
{...tooltipAttrs(grantable ? tx("Granted with grant option") : undefined)}
|
||||
>
|
||||
<Icon name="check" size={16} />
|
||||
{grantable && <span className={styles.grantsOption}>*</span>}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<span className={styles.formHint}>
|
||||
<T>* With grant option: the grantee may grant the privilege to others.</T>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Data sources -------------------------------------------------------------
|
||||
|
||||
function SourceUrlDialog() {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DbColumnInfo } from "@/platform/ipc";
|
||||
import {
|
||||
grantMatrix,
|
||||
grantsSupported,
|
||||
alterTableSql,
|
||||
canDrop,
|
||||
canModifyTable,
|
||||
@@ -404,3 +406,35 @@ describe("database and schema SQL", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("table grants", () => {
|
||||
it("groups privileges per grantee and grantor in the standard order", () => {
|
||||
const grant = (grantee: string, privilege: string, grantable = false, grantor: string | null = "admin") => ({
|
||||
grantee,
|
||||
grantor,
|
||||
privilege,
|
||||
grantable,
|
||||
});
|
||||
const { privileges, rows } = grantMatrix([
|
||||
grant("writer", "UPDATE", true),
|
||||
grant("reader", "SELECT"),
|
||||
grant("writer", "INSERT"),
|
||||
grant("writer", "SHOW VIEW"),
|
||||
grant("writer", "MAINTAIN"),
|
||||
grant("reader", "SELECT", false, "other"),
|
||||
]);
|
||||
expect(privileges).toEqual(["SELECT", "INSERT", "UPDATE", "MAINTAIN", "SHOW VIEW"]);
|
||||
expect(rows.map((r) => [r.grantee, r.grantor, Object.fromEntries(r.privileges)])).toEqual([
|
||||
["writer", "admin", { UPDATE: true, INSERT: false, "SHOW VIEW": false, MAINTAIN: false }],
|
||||
["reader", "admin", { SELECT: false }],
|
||||
["reader", "other", { SELECT: false }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("queries only the engines with per-table privileges", () => {
|
||||
expect(grantsSupported("postgres")).toBe(true);
|
||||
expect(grantsSupported("mysql")).toBe(true);
|
||||
expect(grantsSupported("sqlite")).toBe(false);
|
||||
expect(grantsSupported("clickhouse")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@
|
||||
* Drop, Truncate, SQL Scripts › …, Modify Table, Copy Reference), per dialect.
|
||||
* Pure functions.
|
||||
*/
|
||||
import type { DbColumnInfo, DbDriver } from "@/platform/ipc";
|
||||
import type { DbColumnInfo, DbDriver, DbTableGrant } from "@/platform/ipc";
|
||||
import { isReserved } from "./sql/dialect";
|
||||
|
||||
export function quoteIdent(driver: DbDriver, name: string): string {
|
||||
@@ -444,3 +444,55 @@ export function alterTableSql(
|
||||
out.push(renameSql(driver, { kind: "table", schema, name: table }, name.trim()));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Grants -------------------------------------------------------------------
|
||||
|
||||
/** Engines whose table privileges the Modify Table dialog shows (others run no query). */
|
||||
export function grantsSupported(driver: DbDriver): boolean {
|
||||
return driver === "postgres" || driver === "mysql";
|
||||
}
|
||||
|
||||
/** Column order of the Grants table: the SQL standard's table privileges, then the engine's own. */
|
||||
const PRIVILEGE_ORDER = [
|
||||
"SELECT",
|
||||
"INSERT",
|
||||
"UPDATE",
|
||||
"DELETE",
|
||||
"TRUNCATE",
|
||||
"REFERENCES",
|
||||
"TRIGGER",
|
||||
"MAINTAIN",
|
||||
"INDEX",
|
||||
"ALTER",
|
||||
"CREATE",
|
||||
"DROP",
|
||||
"CREATE VIEW",
|
||||
"SHOW VIEW",
|
||||
"DELETE HISTORY",
|
||||
];
|
||||
|
||||
export interface GrantRow {
|
||||
grantee: string;
|
||||
grantor: string | null;
|
||||
/** Privilege → granted with GRANT OPTION. */
|
||||
privileges: Map<string, boolean>;
|
||||
}
|
||||
|
||||
/** One row per grantee and grantor, with the privileges they hold as columns. */
|
||||
export function grantMatrix(grants: DbTableGrant[]): { privileges: string[]; rows: GrantRow[] } {
|
||||
const rows = new Map<string, GrantRow>();
|
||||
const seen = new Set<string>();
|
||||
for (const g of grants) {
|
||||
const key = JSON.stringify([g.grantee, g.grantor]);
|
||||
let row = rows.get(key);
|
||||
if (!row) rows.set(key, (row = { grantee: g.grantee, grantor: g.grantor, privileges: new Map() }));
|
||||
row.privileges.set(g.privilege, (row.privileges.get(g.privilege) ?? false) || g.grantable);
|
||||
seen.add(g.privilege);
|
||||
}
|
||||
const rank = (p: string) => {
|
||||
const i = PRIVILEGE_ORDER.indexOf(p);
|
||||
return i < 0 ? PRIVILEGE_ORDER.length : i;
|
||||
};
|
||||
const privileges = [...seen].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
|
||||
return { privileges, rows: [...rows.values()] };
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type DbTableInfo,
|
||||
type DbTableKind,
|
||||
type DbVisibilityChange,
|
||||
type DbTableGrant,
|
||||
type RequestId,
|
||||
type SqlStatement,
|
||||
} from "@/platform/ipc";
|
||||
@@ -930,6 +931,11 @@ export async function loadDetails(id: string, schema: string, table: string): Pr
|
||||
}
|
||||
}
|
||||
|
||||
/** The privileges granted on a table (PostgreSQL and MySQL; see `grantsSupported`). */
|
||||
export function loadGrants(id: string, schema: string, table: string): Promise<DbTableGrant[]> {
|
||||
return withConnection(id, () => call(commands.dbTableGrants(id, schema, table)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects a table (or one of its columns) in the Database tool window,
|
||||
* loading and expanding the nodes that lead to it. Without `kind` the loaded
|
||||
|
||||
@@ -4070,5 +4070,13 @@
|
||||
"Transitive": "Transitive",
|
||||
"Version": "Version",
|
||||
"Search": "Search",
|
||||
".NET project": ".NET project"
|
||||
".NET project": ".NET project",
|
||||
"Table properties": "Table properties",
|
||||
"Grants": "Grants",
|
||||
"Grantee": "Grantee",
|
||||
"Grantor": "Grantor",
|
||||
"Granted": "Granted",
|
||||
"Granted with grant option": "Granted with grant option",
|
||||
"No privileges are granted on this table.": "No privileges are granted on this table.",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* With grant option: the grantee may grant the privilege to others."
|
||||
}
|
||||
@@ -10124,5 +10124,13 @@
|
||||
"Search NuGet packages": "Поиск пакетов NuGet",
|
||||
"Install / Update": "Установить / Обновить",
|
||||
"Versions": "Версии",
|
||||
"Transitive": "Транзитивные"
|
||||
"Transitive": "Транзитивные",
|
||||
"Table properties": "Свойства таблицы",
|
||||
"Grants": "Привилегии",
|
||||
"Grantee": "Получатель",
|
||||
"Grantor": "Кем выдано",
|
||||
"Granted": "Выдано",
|
||||
"Granted with grant option": "Выдано с правом передачи",
|
||||
"No privileges are granted on this table.": "На эту таблицу не выдано привилегий.",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION: получатель может передавать привилегию другим."
|
||||
}
|
||||
@@ -8781,5 +8781,13 @@
|
||||
"Search NuGet packages": "NuGet paketlerinde ara",
|
||||
"Install / Update": "Yükle / Güncelle",
|
||||
"Versions": "Sürümler",
|
||||
"Transitive": "Geçişli"
|
||||
"Transitive": "Geçişli",
|
||||
"Table properties": "Tablo özellikleri",
|
||||
"Grants": "Yetkiler",
|
||||
"Grantee": "Yetki verilen",
|
||||
"Grantor": "Yetki veren",
|
||||
"Granted": "Verildi",
|
||||
"Granted with grant option": "Yetki verme hakkıyla verildi",
|
||||
"No privileges are granted on this table.": "Bu tabloda verilmiş yetki yok.",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION: yetki verilen bu yetkiyi başkalarına verebilir."
|
||||
}
|
||||
@@ -9314,5 +9314,13 @@
|
||||
"Search NuGet packages": "搜尋 NuGet 包",
|
||||
"Install / Update": "安裝 / 更新",
|
||||
"Versions": "版本",
|
||||
"Transitive": "間接依賴"
|
||||
"Transitive": "間接依賴",
|
||||
"Table properties": "資料表屬性",
|
||||
"Grants": "授權",
|
||||
"Grantee": "被授權者",
|
||||
"Grantor": "授權者",
|
||||
"Granted": "已授予",
|
||||
"Granted with grant option": "已授予(可轉授)",
|
||||
"No privileges are granted on this table.": "此資料表未授予任何權限。",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授權者可以將該權限再授予他人。"
|
||||
}
|
||||
@@ -10381,5 +10381,13 @@
|
||||
"Search NuGet packages": "搜索 NuGet 包",
|
||||
"Install / Update": "安装 / 更新",
|
||||
"Versions": "版本",
|
||||
"Transitive": "间接依赖"
|
||||
"Transitive": "间接依赖",
|
||||
"Table properties": "表属性",
|
||||
"Grants": "授权",
|
||||
"Grantee": "被授权者",
|
||||
"Grantor": "授权者",
|
||||
"Granted": "已授予",
|
||||
"Granted with grant option": "已授予(可转授)",
|
||||
"No privileges are granted on this table.": "此表未授予任何权限。",
|
||||
"* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача