feat(admin): add table grants for postgres and starrocks

Closes #10251
This commit is contained in:
t8y2 authored and t8y2 committed 2026-09-27 12:04:10 +08:00
1 parent 627a8498d0
commit deaa867498
7 files changed
+1106 -151

No files matched your search

@@ -6,7 +6,7 @@ import { Badge } from "@/components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import * as api from "@/lib/backend/api";
import { authorizationPrivileges, type AuthorizationPreset, type DatabaseAuthorizationSelection } from "@/lib/database/databaseAuthorizationPlan";
import { authorizationPresetPrivileges, authorizationPrivileges, type AuthorizationDatabaseOption, type AuthorizationPreset, type AuthorizationTableSelection, type DatabaseAuthorizationSelection } from "@/lib/database/databaseAuthorizationPlan";
import type { DatabaseUserAdminProvider } from "@/lib/database/databaseUserAdmin";
/**
@@ -21,7 +21,7 @@ const props = defineProps<{
/** 当前连接的权限提供者,用于判断是否支持表级授权以及表级可用权限 */
provider: DatabaseUserAdminProvider | null;
/** 当前连接下的数据库名列表 */
databases: string[];
databases: AuthorizationDatabaseOption[];
/** 数据库列表是否正在加载 */
databasesLoading?: boolean;
/** 连接 ID,用于按库懒加载表列表 */
@@ -37,9 +37,10 @@ const emit = defineEmits<{
const { t } = useI18n();
// 全局作用域标识:MySQL 的 GRANT/REVOKE 支持 ON *.*,权限编辑面板需要保留这一能力
const GLOBAL_SCOPE = "*";
const GLOBAL_OPTION: AuthorizationDatabaseOption = { database: GLOBAL_SCOPE };
const search = ref("");
// 表列表按库懒加载并缓存,避免下拉展开时重复请求
const tables = ref<Record<string, string[]>>({});
const tables = ref<Record<string, AuthorizationTableSelection[]>>({});
const tablesLoading = ref<Record<string, boolean>>({});
const tableErrors = ref<Record<string, string>>({});
const tableSearch = ref<Record<string, string>>({});
@@ -47,12 +48,12 @@ const tableSearch = ref<Record<string, string>>({});
const supportsTableGrants = computed(() => !!props.provider?.supportsTableGrantsOnCreate);
const filteredDatabases = computed(() => {
const query = search.value.trim().toLowerCase();
return query ? props.databases.filter((database) => database.toLowerCase().includes(query)) : props.databases;
return query ? props.databases.filter((database) => databaseLabel(database).toLowerCase().includes(query)) : props.databases;
});
// 紧凑模式(权限编辑面板)在列表顶部提供固定的「全局」入口,且不受库搜索影响;
// 新增用户弹窗保持只勾选真实数据库,不改变原有产品行为。
const visibleDatabases = computed(() => (props.compact ? [GLOBAL_SCOPE, ...filteredDatabases.value] : filteredDatabases.value));
const selectedDatabaseSet = computed(() => new Set(props.modelValue.map((selection) => selection.database)));
const visibleDatabases = computed(() => (props.compact && props.provider?.authorizationModel === "mysql" ? [GLOBAL_OPTION, ...filteredDatabases.value] : filteredDatabases.value));
const selectedDatabaseSet = computed(() => new Set(props.modelValue.map(authorizationSelectionKey)));
// 同一 tick 内连续触发多次选择变更时(例如连续点击多张表),父组件回流的 props 尚未更新,
// 这里用最近一次发出的值作为基准,避免后一次变更覆盖前一次导致选择丢失。
@@ -61,6 +62,19 @@ watch(
() => props.modelValue,
(value) => {
pendingSelections = value;
for (const selection of value) {
if (selection.tables !== undefined) void loadTables({ database: selection.database, ...(selection.catalog ? { catalog: selection.catalog } : {}) });
}
},
{ immediate: true },
);
watch(
() => props.databases,
() => {
for (const selection of props.modelValue) {
if (selection.tables !== undefined) void loadTables({ database: selection.database, ...(selection.catalog ? { catalog: selection.catalog } : {}) });
}
},
);
@@ -73,33 +87,34 @@ function commitSelections(next: DatabaseAuthorizationSelection[]) {
emit("update:modelValue", next);
}
function selectionFor(database: string): DatabaseAuthorizationSelection | undefined {
return props.modelValue.find((selection) => selection.database === database);
function selectionFor(database: AuthorizationDatabaseOption): DatabaseAuthorizationSelection | undefined {
const key = authorizationOptionKey(database);
return props.modelValue.find((selection) => authorizationSelectionKey(selection) === key);
}
/**
* 统一以“不可变更新”方式回写选中项:始终替换为新的数组与对象,
* 避免直接修改 props 中的对象引用(v-model 单向数据流的约束)。
*/
function patchSelection(database: string, patch: (selection: DatabaseAuthorizationSelection) => DatabaseAuthorizationSelection | undefined) {
function patchSelection(database: AuthorizationDatabaseOption, patch: (selection: DatabaseAuthorizationSelection) => DatabaseAuthorizationSelection | undefined) {
const next: DatabaseAuthorizationSelection[] = [];
for (const selection of currentSelections()) {
if (selection.database !== database) {
if (authorizationSelectionKey(selection) !== authorizationOptionKey(database)) {
next.push(selection);
continue;
}
const updated = patch({ ...selection });
if (updated) next.push({ ...updated, tables: updated.tables ? [...updated.tables] : undefined, privileges: updated.privileges ? [...updated.privileges] : undefined });
if (updated) next.push({ ...updated, tables: updated.tables?.map((table) => ({ ...table })), privileges: updated.privileges ? [...updated.privileges] : undefined });
}
commitSelections(next);
}
function toggleDatabase(database: string) {
function toggleDatabase(database: AuthorizationDatabaseOption) {
if (selectionFor(database)) {
commitSelections(currentSelections().filter((selection) => selection.database !== database));
commitSelections(currentSelections().filter((selection) => authorizationSelectionKey(selection) !== authorizationOptionKey(database)));
return;
}
commitSelections([...currentSelections(), { database, preset: "readOnly", privileges: ["SELECT"] }]);
commitSelections([...currentSelections(), { database: database.database, ...(database.catalog ? { catalog: database.catalog } : {}), preset: "readOnly", privileges: ["SELECT"] }]);
}
// 表范围下 MySQL 不支持 CREATE ROUTINE / EVENT 等库级权限,需要按目标作用域过滤可选权限
@@ -109,43 +124,63 @@ function privilegesForSelection(selection?: DatabaseAuthorizationSelection): str
return authorizationPrivileges(userProvider, selection?.tables === undefined ? "database" : "table");
}
function usesSelectedTables(database: string): boolean {
function usesSelectedTables(database: AuthorizationDatabaseOption): boolean {
return selectionFor(database)?.tables !== undefined;
}
function isTableSelected(database: string, table: string): boolean {
return selectionFor(database)?.tables?.includes(table) ?? false;
function isTableSelected(database: AuthorizationDatabaseOption, table: AuthorizationTableSelection): boolean {
return selectionFor(database)?.tables?.some((selected) => authorizationTableKey(selected) === authorizationTableKey(table)) ?? false;
}
function allTablesSelected(database: string): boolean {
const available = tables.value[database] ?? [];
return available.length > 0 && selectionFor(database)?.tables?.length === available.length;
function allTablesSelected(database: AuthorizationDatabaseOption): boolean {
const key = authorizationOptionKey(database);
const available = tables.value[key] ?? [];
const selected = new Set(selectionFor(database)?.tables?.map(authorizationTableKey) ?? []);
return available.length > 0 && available.every((table) => selected.has(authorizationTableKey(table)));
}
function filteredTables(database: string): string[] {
const query = (tableSearch.value[database] ?? "").trim().toLowerCase();
const available = tables.value[database] ?? [];
return query ? available.filter((table) => table.toLowerCase().includes(query)) : available;
function filteredTables(database: AuthorizationDatabaseOption): AuthorizationTableSelection[] {
const key = authorizationOptionKey(database);
const query = (tableSearch.value[key] ?? "").trim().toLowerCase();
const available = tables.value[key] ?? [];
return query ? available.filter((table) => tableLabel(table).toLowerCase().includes(query)) : available;
}
async function loadTables(database: string) {
if (tables.value[database] || tablesLoading.value[database]) return;
tablesLoading.value = { ...tablesLoading.value, [database]: true };
tableErrors.value = { ...tableErrors.value, [database]: "" };
async function loadTables(database: AuthorizationDatabaseOption) {
const key = authorizationOptionKey(database);
if (tables.value[key] || tablesLoading.value[key]) return;
tablesLoading.value = { ...tablesLoading.value, [key]: true };
tableErrors.value = { ...tableErrors.value, [key]: "" };
try {
const result = await api.listTables(props.connectionId, database, "");
let result: AuthorizationTableSelection[];
if (props.provider?.authorizationModel === "postgres") {
const schemas = (await api.listSchemas(props.connectionId, database.database)).filter(isPostgresGrantSchema);
const schemaTables = await Promise.all(
schemas.map(async (schema) => {
const items = await api.listTables(props.connectionId, database.database, schema, undefined, undefined, undefined, ["TABLE"]);
return items.map((table) => ({ name: table.name, schema }));
}),
);
result = schemaTables.flat();
} else if (props.provider?.authorizationModel === "starrocks") {
const items = await api.listTables(props.connectionId, database.database, "", undefined, undefined, undefined, ["TABLE"], database.catalog);
result = items.map((table) => ({ name: table.name }));
} else {
const items = await api.listTables(props.connectionId, database.database, "");
result = items.map((table) => ({ name: table.name }));
}
tables.value = {
...tables.value,
[database]: Array.from(new Set(result.map((table) => table.name.trim()).filter(Boolean))).sort((left, right) => left.localeCompare(right)),
[key]: uniqueTableOptions(result).sort((left, right) => tableLabel(left).localeCompare(tableLabel(right))),
};
} catch (error: any) {
tableErrors.value = { ...tableErrors.value, [database]: error?.message || String(error) };
tableErrors.value = { ...tableErrors.value, [key]: error?.message || String(error) };
} finally {
tablesLoading.value = { ...tablesLoading.value, [database]: false };
tablesLoading.value = { ...tablesLoading.value, [key]: false };
}
}
async function updateTableScope(database: string, selectTables: boolean) {
async function updateTableScope(database: AuthorizationDatabaseOption, selectTables: boolean) {
if (!selectTables) {
patchSelection(database, (selection) => {
delete selection.tables;
@@ -155,6 +190,7 @@ async function updateTableScope(database: string, selectTables: boolean) {
}
patchSelection(database, (selection) => {
selection.tables = selection.tables ?? [];
if (authorizationPresetPrivileges(props.provider!, selection.preset, selection.privileges, "table").length === 0) selection.preset = "readOnly";
if (selection.preset === "custom") {
const allowed = new Set(privilegesForSelection(selection));
selection.privileges = (selection.privileges ?? []).filter((privilege) => allowed.has(privilege));
@@ -164,27 +200,25 @@ async function updateTableScope(database: string, selectTables: boolean) {
await loadTables(database);
}
function toggleTable(database: string, table: string) {
function toggleTable(database: AuthorizationDatabaseOption, table: AuthorizationTableSelection) {
patchSelection(database, (selection) => {
if (!selection.tables) return selection;
const next = new Set(selection.tables);
if (next.has(table)) next.delete(table);
else next.add(table);
selection.tables = Array.from(next);
const key = authorizationTableKey(table);
selection.tables = selection.tables.some((selected) => authorizationTableKey(selected) === key) ? selection.tables.filter((selected) => authorizationTableKey(selected) !== key) : [...selection.tables, table];
return selection;
});
}
function toggleAllTables(database: string) {
function toggleAllTables(database: AuthorizationDatabaseOption) {
patchSelection(database, (selection) => {
if (!selection.tables) return selection;
const available = tables.value[database] ?? [];
selection.tables = selection.tables.length === available.length ? [] : [...available];
const available = tables.value[authorizationOptionKey(database)] ?? [];
selection.tables = allTablesSelected(database) ? [] : [...available];
return selection;
});
}
function updatePreset(database: string, preset: unknown) {
function updatePreset(database: AuthorizationDatabaseOption, preset: unknown) {
if (typeof preset !== "string") return;
patchSelection(database, (selection) => {
selection.preset = preset as AuthorizationPreset;
@@ -192,7 +226,7 @@ function updatePreset(database: string, preset: unknown) {
});
}
function togglePrivilege(database: string, privilege: string) {
function togglePrivilege(database: AuthorizationDatabaseOption, privilege: string) {
patchSelection(database, (selection) => {
const next = new Set(selection.privileges ?? []);
if (next.has(privilege)) next.delete(privilege);
@@ -202,9 +236,45 @@ function togglePrivilege(database: string, privilege: string) {
});
}
function isPrivilegeSelected(database: string, privilege: string): boolean {
function isPrivilegeSelected(database: AuthorizationDatabaseOption, privilege: string): boolean {
return selectionFor(database)?.privileges?.includes(privilege) ?? false;
}
function authorizationOptionKey(option: AuthorizationDatabaseOption): string {
return JSON.stringify([option.catalog ?? "", option.database]);
}
function authorizationSelectionKey(selection: Pick<DatabaseAuthorizationSelection, "catalog" | "database">): string {
return authorizationOptionKey(selection);
}
function databaseLabel(option: AuthorizationDatabaseOption): string {
return option.catalog ? `${option.catalog} / ${option.database}` : option.database;
}
function authorizationTableKey(table: AuthorizationTableSelection): string {
return JSON.stringify([table.schema ?? "", table.name]);
}
function tableLabel(table: AuthorizationTableSelection): string {
return table.schema ? `${table.schema}.${table.name}` : table.name;
}
function uniqueTableOptions(options: AuthorizationTableSelection[]): AuthorizationTableSelection[] {
const seen = new Set<string>();
return options.filter((option) => {
if (!option.name.trim()) return false;
const key = authorizationTableKey(option);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
function isPostgresGrantSchema(schema: string): boolean {
const normalized = schema.toLowerCase();
return !!schema.trim() && normalized !== "information_schema" && normalized !== "sys_catalog" && !normalized.startsWith("pg_");
}
</script>
<template>
@@ -227,13 +297,13 @@ function isPrivilegeSelected(database: string, privilege: string): boolean {
{{ t("userAdmin.loadingDatabases") }}
</div>
<div v-else-if="visibleDatabases.length === 0" class="p-3 text-center text-xs text-muted-foreground">{{ t("userAdmin.emptyDatabases") }}</div>
<div v-for="database in visibleDatabases" :key="database" class="border-b p-2" :class="compact ? '' : 'last:border-b-0'">
<div v-for="database in visibleDatabases" :key="authorizationOptionKey(database)" class="border-b p-2" :class="compact ? '' : 'last:border-b-0'">
<div class="flex items-center gap-2">
<input :checked="selectedDatabaseSet.has(database)" type="checkbox" class="h-3.5 w-3.5 accent-primary" @change="toggleDatabase(database)" />
<input :checked="selectedDatabaseSet.has(authorizationOptionKey(database))" type="checkbox" class="h-3.5 w-3.5 accent-primary" @change="toggleDatabase(database)" />
<button type="button" class="min-w-0 flex-1 truncate text-left text-xs font-medium" @click="toggleDatabase(database)">
{{ database === GLOBAL_SCOPE ? t("userAdmin.globalScope") : database }}
{{ database.database === GLOBAL_SCOPE ? t("userAdmin.globalScope") : databaseLabel(database) }}
</button>
<Select v-if="selectedDatabaseSet.has(database)" :model-value="selectionFor(database)?.preset" @update:model-value="updatePreset(database, $event)">
<Select v-if="selectedDatabaseSet.has(authorizationOptionKey(database))" :model-value="selectionFor(database)?.preset" @update:model-value="updatePreset(database, $event)">
<SelectTrigger class="h-7 text-xs" :class="compact ? 'w-28' : 'w-32'"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="readWrite">{{ t("userAdmin.presetReadWrite") }}</SelectItem>
@@ -244,7 +314,7 @@ function isPrivilegeSelected(database: string, privilege: string): boolean {
</SelectContent>
</Select>
</div>
<div v-if="supportsTableGrants && database !== GLOBAL_SCOPE && selectedDatabaseSet.has(database)" class="mt-2 flex gap-2" :class="compact ? 'flex-col gap-1.5' : 'items-center pl-5'">
<div v-if="supportsTableGrants && database.database !== GLOBAL_SCOPE && selectedDatabaseSet.has(authorizationOptionKey(database))" class="mt-2 flex gap-2" :class="compact ? 'flex-col gap-1.5' : 'items-center pl-5'">
<div class="flex items-center gap-2">
<span v-if="!compact" class="shrink-0 text-[11px] text-muted-foreground">{{ t("userAdmin.tableScope") }}</span>
<div class="flex h-7 shrink-0 items-center rounded-md border bg-muted/30 p-0.5">
@@ -263,7 +333,7 @@ function isPrivilegeSelected(database: string, privilege: string): boolean {
<span class="min-w-0 flex-1 truncate">
{{ selectionFor(database)?.tables?.length ? t("userAdmin.selectedTableCount", { count: selectionFor(database)?.tables?.length }) : t("userAdmin.chooseTables") }}
</span>
<Loader2 v-if="tablesLoading[database]" class="h-3.5 w-3.5 shrink-0 animate-spin" />
<Loader2 v-if="tablesLoading[authorizationOptionKey(database)]" class="h-3.5 w-3.5 shrink-0 animate-spin" />
<ChevronDown v-else class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</button>
</PopoverTrigger>
@@ -271,29 +341,29 @@ function isPrivilegeSelected(database: string, privilege: string): boolean {
<div class="flex items-center gap-2 border-b p-2">
<div class="flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded-md border px-2">
<Search class="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input v-model="tableSearch[database]" class="min-w-0 flex-1 bg-transparent text-[11px] outline-none" :placeholder="t('userAdmin.searchTable')" />
<input v-model="tableSearch[authorizationOptionKey(database)]" class="min-w-0 flex-1 bg-transparent text-[11px] outline-none" :placeholder="t('userAdmin.searchTable')" />
</div>
<button type="button" class="shrink-0 text-[11px] text-primary disabled:text-muted-foreground" :disabled="!(tables[database]?.length > 0)" @click="toggleAllTables(database)">
<button type="button" class="shrink-0 text-[11px] text-primary disabled:text-muted-foreground" :disabled="!(tables[authorizationOptionKey(database)]?.length > 0)" @click="toggleAllTables(database)">
{{ t(allTablesSelected(database) ? "userAdmin.clearAllTables" : "userAdmin.selectAllTables") }}
</button>
</div>
<div class="max-h-56 overflow-auto p-1">
<div v-if="tablesLoading[database]" class="flex items-center justify-center gap-2 px-3 py-6 text-xs text-muted-foreground">
<div v-if="tablesLoading[authorizationOptionKey(database)]" class="flex items-center justify-center gap-2 px-3 py-6 text-xs text-muted-foreground">
<Loader2 class="h-3.5 w-3.5 animate-spin" />
{{ t("userAdmin.loadingTables") }}
</div>
<div v-else-if="tableErrors[database]" class="px-3 py-4 text-center text-xs text-destructive">
<p class="break-words">{{ t("userAdmin.loadTablesFailed", { message: tableErrors[database] }) }}</p>
<div v-else-if="tableErrors[authorizationOptionKey(database)]" class="px-3 py-4 text-center text-xs text-destructive">
<p class="break-words">{{ t("userAdmin.loadTablesFailed", { message: tableErrors[authorizationOptionKey(database)] }) }}</p>
<button type="button" class="mt-2 text-primary" @click="loadTables(database)">{{ t("userAdmin.retry") }}</button>
</div>
<div v-else-if="filteredTables(database).length === 0" class="px-3 py-6 text-center text-xs text-muted-foreground">
{{ t("userAdmin.emptyTables") }}
</div>
<button v-for="table in filteredTables(database)" :key="table" type="button" class="flex h-8 w-full items-center gap-2 rounded px-2 text-left text-xs hover:bg-accent" @click="toggleTable(database, table)">
<button v-for="table in filteredTables(database)" :key="authorizationTableKey(table)" type="button" class="flex h-8 w-full items-center gap-2 rounded px-2 text-left text-xs hover:bg-accent" @click="toggleTable(database, table)">
<span class="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border" :class="isTableSelected(database, table) ? 'border-primary bg-primary text-primary-foreground' : 'border-border'">
<Check v-if="isTableSelected(database, table)" class="h-2.5 w-2.5" />
</span>
<span class="min-w-0 flex-1 truncate">{{ table }}</span>
<span class="min-w-0 flex-1 truncate">{{ tableLabel(table) }}</span>
</button>
</div>
</PopoverContent>
@@ -319,7 +389,7 @@ function isPrivilegeSelected(database: string, privilege: string): boolean {
{{ t("userAdmin.customPrivilegeRequired") }}
</p>
</div>
<p v-if="provider?.dialect === 'postgres' && selectedDatabaseSet.has(database) && selectionFor(database)?.preset === 'ddl'" class="mt-2 text-[10px] text-muted-foreground" :class="compact ? '' : 'pl-5'">
<p v-if="provider?.dialect === 'postgres' && selectedDatabaseSet.has(authorizationOptionKey(database)) && selectionFor(database)?.preset === 'ddl'" class="mt-2 text-[10px] text-muted-foreground" :class="compact ? '' : 'pl-5'">
{{ t("userAdmin.postgresDdlHint") }}
</p>
</div>
@@ -16,15 +16,18 @@ import { useSqlHighlighter } from "@/composables/useSqlHighlighter";
import type { ConnectionConfig } from "@/types/database";
import * as api from "@/lib/backend/api";
import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
import { grantsFromQueryResult, resolveDatabaseUserAdminProviderForConnection, type DatabaseUserIdentity, type PrivilegeScope } from "@/lib/database/databaseUserAdmin";
import { grantsFromQueryResult, normalizeStarrocksCatalog, resolveDatabaseUserAdminProviderForConnection, type DatabaseTablePrivilegeGrant, type DatabaseUserIdentity, type PrivilegeScope } from "@/lib/database/databaseUserAdmin";
import {
authorizationPlanSql,
authorizationPlanStatus,
authorizationPresetPrivileges,
authorizationPrivileges,
buildCreateUserAuthorizationPlan,
buildGrantAuthorizationPlan,
databaseAuthorizationsFromTableGrants,
executeAuthorizationPlan,
type AuthorizationAccountType,
type AuthorizationDatabaseOption,
type AuthorizationPlan,
type AuthorizationStepResult,
type DatabaseAuthorizationSelection,
@@ -88,12 +91,19 @@ const grantOption = ref(restoredUiState.grantOption ?? false);
const selectedPrivileges = ref<string[]>(restoredUiState.selectedPrivileges ?? ["SELECT"]);
const createCanLogin = ref(true);
const createAccountType = ref<AuthorizationAccountType>("standard");
const createDatabases = ref<string[]>([]);
const createDatabases = ref<AuthorizationDatabaseOption[]>([]);
const createDatabasesLoading = ref(false);
const createDatabasesLoadError = ref("");
const createDatabaseAuthorizations = ref<DatabaseAuthorizationSelection[]>([]);
// 权限编辑面板的授权范围选择(MySQL 表级授权场景),与新增用户弹窗复用同一个范围编辑器
// 权限编辑面板的授权范围选择,与新增用户弹窗复用同一个范围编辑器
const privilegeAuthorizations = ref<DatabaseAuthorizationSelection[]>([]);
const currentTableGrants = ref<DatabaseTablePrivilegeGrant[]>([]);
const currentTableGrantsLoaded = ref(false);
const currentTableGrantsLoading = ref(false);
const tableGrantLoadError = ref("");
let createPlanRequestId = 0;
let tableGrantRequestId = 0;
let databaseLoadPromise: Promise<void> | undefined;
let preserveRestoredPrivilegeSelection = restoredUiState.selectedPrivileges !== undefined || restoredUiState.grantOption !== undefined;
trackUiState(() => ({
@@ -139,9 +149,9 @@ const grantsSqlText = computed(() => grants.value.join("\n") || t("userAdmin.noG
const highlightedGrantsSql = computed(() => highlight(grantsSqlText.value));
const highlightedPendingSql = computed(() => highlight(pendingSql.value));
const createDatabaseAuthorizationsValid = computed(() => authorizationSelectionsValid(createDatabaseAuthorizations.value));
// MySQL 表级授权场景下,权限编辑面板复用与新增用户一致的授权范围编辑器
const usePrivilegeScopeEditor = computed(() => canEditPrivileges.value && supportsCreateTableGrants.value && privilegeScope.value !== "role");
const usePrivilegeScopeEditor = computed(() => canEditPrivileges.value && supportsCreateTableGrants.value && privilegeScope.value !== "role" && (provider.value?.authorizationModel !== "postgres" || privilegeScope.value === "table"));
const privilegeAuthorizationsValid = computed(() => authorizationSelectionsValid(privilegeAuthorizations.value));
const tableGrantDiffReady = computed(() => provider.value?.authorizationModel === "mysql" || currentTableGrantsLoaded.value);
const pendingStatus = computed(() => (pendingResults.value.length > 0 ? authorizationPlanStatus(pendingResults.value) : undefined));
const canPreviewHostChange = computed(() => {
const host = newHost.value.trim();
@@ -221,23 +231,94 @@ async function loadGrants() {
loadingGrants.value = true;
grantsLoaded.value = false;
grantError.value = "";
if (userProvider.authorizationModel !== "mysql") {
currentTableGrants.value = [];
currentTableGrantsLoaded.value = false;
currentTableGrantsLoading.value = false;
tableGrantLoadError.value = "";
}
try {
const result = await api.executeQuery(props.connection.id, "", userProvider.showGrantsSql(user), undefined, undefined, {
maxRows: 1000,
});
grants.value = (userProvider.parseGrants ?? grantsFromQueryResult)(result);
grantsLoaded.value = true;
if (userProvider.tableGrantsFromShowGrants && userProvider.parseTableGrants) {
currentTableGrants.value = userProvider.parseTableGrants(result);
currentTableGrantsLoaded.value = true;
tableGrantLoadError.value = "";
syncAuthorizationSelectionsFromTableGrants();
}
// Existing-user editing reflects the exact SHOW GRANTS scope; create-user defaults stay independent.
syncPrivilegeSelectionFromGrants();
if (userProvider.authorizationModel === "postgres" && usePrivilegeScopeEditor.value) await loadCurrentTableGrants();
} catch (error: any) {
grantError.value = error?.message || String(error);
grants.value = [];
grantsLoaded.value = false;
currentTableGrants.value = [];
currentTableGrantsLoaded.value = false;
} finally {
loadingGrants.value = false;
}
}
async function loadCurrentTableGrants() {
const user = selectedUser.value;
const userProvider = provider.value;
if (!user || !userProvider?.tableGrantsSql || !userProvider.parseTableGrants || currentTableGrantsLoading.value) return;
const requestId = ++tableGrantRequestId;
const selectedKey = userKey(user);
currentTableGrantsLoading.value = true;
currentTableGrantsLoaded.value = false;
tableGrantLoadError.value = "";
try {
if (createDatabases.value.length === 0) await loadDatabases();
if (createDatabasesLoadError.value) throw new Error(createDatabasesLoadError.value);
const grantsByDatabase = await Promise.all(
createDatabases.value.map(async ({ database }) => {
const result = await api.executeQuery(props.connection.id, database, userProvider.tableGrantsSql!(user), undefined, undefined, { maxRows: 10000 });
return userProvider.parseTableGrants!(result, { database });
}),
);
if (requestId !== tableGrantRequestId || selectedUserKey.value !== selectedKey) return;
currentTableGrants.value = grantsByDatabase.flat();
currentTableGrantsLoaded.value = true;
syncAuthorizationSelectionsFromTableGrants();
} catch (error: any) {
if (requestId !== tableGrantRequestId || selectedUserKey.value !== selectedKey) return;
currentTableGrants.value = [];
currentTableGrantsLoaded.value = false;
tableGrantLoadError.value = error?.message || String(error);
} finally {
if (requestId === tableGrantRequestId) currentTableGrantsLoading.value = false;
}
}
function syncAuthorizationSelectionsFromTableGrants() {
const userProvider = provider.value;
if (!userProvider || createDatabases.value.length === 0 || privilegeAuthorizations.value.length > 0) return;
const loaded = databaseAuthorizationsFromTableGrants(userProvider, currentTableGrants.value);
const available = new Map(createDatabases.value.map((option) => [authorizationDatabaseOptionKey(option), option]));
const selections = loaded.selections.flatMap((selection) => {
const option = available.get(authorizationDatabaseOptionKey(selection));
if (!option) return [];
return [{ ...selection, catalog: option.catalog }];
});
privilegeAuthorizations.value = selections;
if (selections.length > 0) grantOption.value = loaded.grantOption;
}
function authorizationDatabaseOptionKey(option: AuthorizationDatabaseOption): string {
const catalog = provider.value?.authorizationModel === "starrocks" ? (normalizeStarrocksCatalog(option.catalog ?? "") ?? "default_catalog") : (option.catalog ?? "");
return JSON.stringify([catalog, option.database]);
}
async function preparePrivilegeScopeEditor() {
if (createDatabases.value.length === 0) await loadDatabases();
if (provider.value?.authorizationModel === "postgres" && !currentTableGrantsLoaded.value) await loadCurrentTableGrants();
}
function selectUser(user: DatabaseUserIdentity) {
selectedUserKey.value = userKey(user);
}
@@ -257,19 +338,39 @@ function togglePrivilege(privilege: string) {
}
// 加载当前连接下的数据库列表:新增用户弹窗与权限编辑面板的授权范围编辑器共用
async function loadDatabases() {
if (createDatabasesLoading.value) return;
createDatabases.value = [];
createDatabasesLoading.value = true;
try {
await ensureConnection();
const config = props.connection;
createDatabases.value = config.db_type === "dameng" ? await fetchNamespaceOptionsForConnection(config.id, config) : (await api.listDatabases(config.id)).map((database) => database.name);
} catch (error: any) {
toast(t("userAdmin.loadDatabasesFailed", { message: error?.message || String(error) }), 5000);
} finally {
createDatabasesLoading.value = false;
}
function loadDatabases(): Promise<void> {
if (databaseLoadPromise) return databaseLoadPromise;
let request!: Promise<void>;
request = (async () => {
createDatabases.value = [];
createDatabasesLoading.value = true;
createDatabasesLoadError.value = "";
try {
await ensureConnection();
const config = props.connection;
if (provider.value?.authorizationModel === "starrocks") {
const catalogs = await api.listDorisCatalogs(config.id);
if (catalogs.length > 0) {
const catalogDatabases = await Promise.all(catalogs.map(async (catalog) => (await api.listDorisCatalogDatabases(config.id, catalog.name)).map((database) => ({ catalog: catalog.name, database: database.name }))));
createDatabases.value = catalogDatabases.flat();
} else {
createDatabases.value = (await api.listDatabases(config.id)).map((database) => ({ database: database.name }));
}
} else {
const databases = config.db_type === "dameng" ? await fetchNamespaceOptionsForConnection(config.id, config) : (await api.listDatabases(config.id)).map((database) => database.name);
createDatabases.value = databases.map((database) => ({ database }));
}
if (currentTableGrantsLoaded.value) syncAuthorizationSelectionsFromTableGrants();
} catch (error: any) {
createDatabasesLoadError.value = error?.message || String(error);
toast(t("userAdmin.loadDatabasesFailed", { message: createDatabasesLoadError.value }), 5000);
} finally {
createDatabasesLoading.value = false;
if (databaseLoadPromise === request) databaseLoadPromise = undefined;
}
})();
databaseLoadPromise = request;
return request;
}
async function openCreateUserDialog() {
@@ -290,11 +391,23 @@ function authorizationSelectionsValid(selections: DatabaseAuthorizationSelection
if (!userProvider) return false;
return selections.every((selection) => {
if (selection.tables !== undefined && selection.tables.length === 0) return false;
if (selection.preset !== "custom") return true;
return authorizationPrivileges(userProvider, selection.tables === undefined ? "database" : "table").some((privilege) => selection.privileges?.includes(privilege));
const targetScope = selection.tables === undefined && userProvider.authorizationModel !== "starrocks" ? "database" : "table";
const available = authorizationPrivileges(userProvider, targetScope);
if (selection.preset !== "custom") return authorizationPresetPrivileges(userProvider, selection.preset, selection.privileges, targetScope).length > 0;
return available.some((privilege) => selection.privileges?.includes(privilege));
});
}
async function prepareAuthorizationSelections(selections: DatabaseAuthorizationSelection[]): Promise<DatabaseAuthorizationSelection[]> {
if (provider.value?.authorizationModel !== "postgres") return selections;
return Promise.all(
selections.map(async (selection) => ({
...selection,
schemas: selection.tables === undefined ? await api.listSchemas(props.connection.id, selection.database) : Array.from(new Set(selection.tables.flatMap((table) => (table.schema ? [table.schema] : [])))),
})),
);
}
function previewSql(sql: string, options: { danger?: boolean; afterApply?: () => Promise<void> } = {}) {
pendingSql.value = sql;
pendingPlan.value = undefined;
@@ -315,7 +428,7 @@ async function applyPendingSql() {
source: t("production.sourceAdmin"),
execute: async () => {
if (pendingPlan.value) {
return executeAuthorizationPlan(pendingPlan.value, (step) => api.executeMulti(props.connection.id, step.database, step.sql, undefined, undefined, { maxRows: 1000, continueOnError: true }));
return executeAuthorizationPlan(pendingPlan.value, (step) => api.executeMulti(props.connection.id, step.database, step.sql, undefined, undefined, { maxRows: 1000, catalog: step.targetCatalog, continueOnError: step.targetCatalog ? false : true }));
}
const queryResults = await api.executeMulti(props.connection.id, "", pendingSql.value, undefined, undefined, { maxRows: 1000, continueOnError: true });
const failed = queryResults.find((item) => item.execution_error === true);
@@ -392,12 +505,15 @@ function authorizationStepLabel(result: AuthorizationStepResult): string {
if (step.operation === "createUser") return t("userAdmin.stepCreateUser");
if (step.operation === "grantAdmin") return t("userAdmin.stepGrantAdmin", { user: step.subject });
if (step.operation === "grantDatabase") {
return step.targetTable ? t("userAdmin.stepGrantTable", { user: step.subject, database: step.targetDatabase, table: step.targetTable }) : t("userAdmin.stepGrantDatabase", { user: step.subject, database: step.targetDatabase });
const database = authorizationStepDatabase(step);
return step.targetTable ? t("userAdmin.stepGrantTable", { user: step.subject, database, table: step.targetTable }) : t("userAdmin.stepGrantDatabase", { user: step.subject, database });
}
if (step.operation === "revokePrivileges") {
return step.targetTable ? t("userAdmin.stepRevokeTable", { user: step.subject, database: step.targetDatabase, table: step.targetTable }) : t("userAdmin.stepRevokeDatabase", { user: step.subject, database: step.targetDatabase });
const database = authorizationStepDatabase(step);
return step.targetTable ? t("userAdmin.stepRevokeTable", { user: step.subject, database, table: step.targetTable }) : t("userAdmin.stepRevokeDatabase", { user: step.subject, database });
}
if (step.operation === "grantCurrentObjects") {
if (step.targetTable) return t("userAdmin.stepGrantTable", { user: step.subject, database: authorizationStepDatabase(step), table: step.targetTable });
return t("userAdmin.stepGrantCurrentObjects", {
user: step.subject,
database: step.targetDatabase,
@@ -413,6 +529,10 @@ function authorizationStepLabel(result: AuthorizationStepResult): string {
return step.label;
}
function authorizationStepDatabase(step: AuthorizationStepResult["step"]): string {
return [step.targetCatalog, step.targetDatabase, step.targetSchema].filter(Boolean).join(".");
}
function authorizationObjectScopeLabel(scope: AuthorizationStepResult["step"]["objectScope"]): string {
if (scope === "schemas") return t("userAdmin.scopeSchemas");
if (scope === "tables") return t("userAdmin.scopeTables");
@@ -480,15 +600,23 @@ function previewPlan(plan: AuthorizationPlan, options: { danger?: boolean } = {}
sqlDialogOpen.value = true;
}
function previewGrant() {
async function previewGrant() {
const user = selectedUser.value;
const userProvider = provider.value;
const grantPrivilegesSql = userProvider?.grantPrivilegesSql;
if (!user || !userProvider || !grantPrivilegesSql || (privilegeScope.value === "role" && !privilegeRole.value.trim())) return;
if (usePrivilegeScopeEditor.value) {
// MySQL 表级授权:按所选库/表展开为多条 GRANT(仅追加,不回收该用户已有权限)
if (!privilegeAuthorizationsValid.value) return;
previewPlan(buildGrantAuthorizationPlan({ provider: userProvider, user, databases: privilegeAuthorizations.value, grantOption: grantOption.value }));
if (!privilegeAuthorizationsValid.value || !tableGrantDiffReady.value) return;
const databases = await prepareAuthorizationSelections(privilegeAuthorizations.value);
previewPlan(
buildGrantAuthorizationPlan({
provider: userProvider,
user,
databases,
grantOption: grantOption.value,
currentGrants: userProvider.authorizationModel === "mysql" ? undefined : currentTableGrants.value,
}),
);
return;
}
previewSql(
@@ -504,15 +632,15 @@ function previewGrant() {
);
}
function previewRevoke() {
async function previewRevoke() {
const user = selectedUser.value;
const userProvider = provider.value;
const revokePrivilegesSql = userProvider?.revokePrivilegesSql;
if (!user || !userProvider || !revokePrivilegesSql || (privilegeScope.value === "role" && !privilegeRole.value.trim())) return;
if (usePrivilegeScopeEditor.value) {
// 与授权保持同一套选择:按所选库/表展开为多条 REVOKE
if (!privilegeAuthorizationsValid.value) return;
previewPlan(buildGrantAuthorizationPlan({ provider: userProvider, user, databases: privilegeAuthorizations.value, revoke: true }), { danger: true });
if (!privilegeAuthorizationsValid.value || !tableGrantDiffReady.value) return;
const databases = await prepareAuthorizationSelections(privilegeAuthorizations.value);
previewPlan(buildGrantAuthorizationPlan({ provider: userProvider, user, databases, revoke: true, currentGrants: userProvider.authorizationModel === "mysql" ? undefined : currentTableGrants.value }), { danger: true });
return;
}
previewSql(
@@ -551,9 +679,14 @@ watch(
watch(
() => selectedUserKey.value,
() => {
tableGrantRequestId += 1;
grantsLoaded.value = false;
// 切换用户时清空上一位用户选择的授权范围,避免把权限误授给当前用户
privilegeAuthorizations.value = [];
currentTableGrants.value = [];
currentTableGrantsLoaded.value = false;
currentTableGrantsLoading.value = false;
tableGrantLoadError.value = "";
void loadGrants();
},
);
@@ -561,17 +694,23 @@ watch(
watch(
() => props.connection.id,
() => {
tableGrantRequestId += 1;
users.value = [];
createDatabases.value = [];
createDatabasesLoadError.value = "";
createDatabaseAuthorizations.value = [];
privilegeAuthorizations.value = [];
currentTableGrants.value = [];
currentTableGrantsLoaded.value = false;
currentTableGrantsLoading.value = false;
tableGrantLoadError.value = "";
selectedUserKey.value = "";
grants.value = [];
grantsLoaded.value = false;
privilegeScope.value = provider.value?.defaultScope ?? "mysql";
resetPrivilegeDefaults(privilegeScope.value);
void loadUsers();
if (usePrivilegeScopeEditor.value) void loadDatabases();
if (usePrivilegeScopeEditor.value) void preparePrivilegeScopeEditor();
},
);
@@ -599,10 +738,17 @@ watch(
watch([privilegeDatabase, privilegeTable], syncPrivilegeSelectionFromGrants);
watch(
() => usePrivilegeScopeEditor.value,
async (enabled) => {
if (!enabled) return;
await preparePrivilegeScopeEditor();
},
);
onMounted(() => {
void loadUsers();
// 权限编辑面板的授权范围选择需要数据库列表,进入页面即预加载(仅 MySQL 表级授权场景)
if (usePrivilegeScopeEditor.value) void loadDatabases();
if (usePrivilegeScopeEditor.value) void preparePrivilegeScopeEditor();
});
</script>
@@ -721,7 +867,7 @@ onMounted(() => {
<aside v-if="canEditPrivileges" class="flex min-h-0 flex-col bg-muted/10">
<div class="border-b p-3">
<div class="text-xs font-semibold">{{ t("userAdmin.privilegeEditor") }}</div>
<div class="mt-1 text-[11px] leading-4 text-muted-foreground">{{ t(usePrivilegeScopeEditor ? "userAdmin.privilegeAppendHint" : "userAdmin.privilegeHint") }}</div>
<div class="mt-1 text-[11px] leading-4 text-muted-foreground">{{ t(usePrivilegeScopeEditor && provider?.authorizationModel === "mysql" ? "userAdmin.privilegeAppendHint" : "userAdmin.privilegeHint") }}</div>
</div>
<div class="min-h-0 flex-1 overflow-auto p-3">
<template v-if="isPostgres">
@@ -743,7 +889,14 @@ onMounted(() => {
<label class="mb-2 block text-xs font-medium">{{ t("userAdmin.memberRole") }}</label>
<Input v-model="privilegeRole" class="mb-3 h-8 text-xs" :placeholder="t('userAdmin.memberRole')" />
</template>
<AuthorizationScopeEditor v-else-if="usePrivilegeScopeEditor" v-model="privilegeAuthorizations" compact :provider="provider" :databases="createDatabases" :databases-loading="createDatabasesLoading" :connection-id="connection.id" />
<div v-else-if="usePrivilegeScopeEditor" class="flex h-full min-h-0 flex-col gap-2">
<AuthorizationScopeEditor v-model="privilegeAuthorizations" compact :provider="provider" :databases="createDatabases" :databases-loading="createDatabasesLoading" :connection-id="connection.id" />
<div v-if="currentTableGrantsLoading" class="flex items-center gap-2 text-[11px] text-muted-foreground">
<Loader2 class="h-3.5 w-3.5 animate-spin" />
{{ t("userAdmin.loadingGrants") }}
</div>
<p v-else-if="tableGrantLoadError" class="text-[11px] text-destructive">{{ tableGrantLoadError }}</p>
</div>
<template v-else>
<label class="mb-2 block text-xs font-medium">
{{ isPostgres && privilegeScope !== "database" ? t("userAdmin.schema") : t("userAdmin.database") }}
@@ -781,10 +934,10 @@ onMounted(() => {
</span>
</label>
<div class="flex shrink-0 items-center justify-end gap-2 border-t p-3">
<Button v-if="canRevokePrivileges" variant="outline" size="sm" class="h-7 px-2 text-xs" :disabled="usePrivilegeScopeEditor && !privilegeAuthorizationsValid" @click="previewRevoke">
<Button v-if="canRevokePrivileges" variant="outline" size="sm" class="h-7 px-2 text-xs" :disabled="usePrivilegeScopeEditor && (!privilegeAuthorizationsValid || !tableGrantDiffReady)" @click="previewRevoke">
{{ t("userAdmin.revoke") }}
</Button>
<Button v-if="canGrantPrivileges" size="sm" class="h-7 px-2 text-xs" :disabled="usePrivilegeScopeEditor && !privilegeAuthorizationsValid" @click="previewGrant">
<Button v-if="canGrantPrivileges" size="sm" class="h-7 px-2 text-xs" :disabled="usePrivilegeScopeEditor && (!privilegeAuthorizationsValid || !tableGrantDiffReady)" @click="previewGrant">
{{ t("userAdmin.grant") }}
</Button>
</div>