Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: optimize jit export button (#20513)
ecmadao77a58c6f2e31
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsxindex 994d0e6bb5..190c111680 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx@@ -12,6 +12,7 @@ import {import { DatabaseTableView } from "@/react/components/database";import { EngineIconPath } from "@/react/components/instance/constants";import { RequestExportButton } from "@/react/components/sql-editor/RequestExportButton";+import { useExportGrantBypass } from "@/react/components/sql-editor/useExportGrantBypass";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";@@ -139,11 +140,6 @@ export function BatchQuerySelect({}}, [filteredItems, selectedDatabase, onSelectedDatabaseChange]);- const databaseList = useMemo(- () => queriedDatabaseNames.map((name) => getDatabaseByName(name)),- [queriedDatabaseNames, getDatabaseByName]- );-const supportFormats = useMemo(() => [ExportFormat.CSV,@@ -165,13 +161,48 @@ export function BatchQuerySelect({return "";}, [contextsByDatabase]);- // Mirror SingleResultView / ResultView: when policy disables export,- // swap the Export button for a "Request export" affordance that opens- // the access-grant drawer pre-filled with the queried databases and- // the batch statement. The grant-allows-export path is naturally- // handled per-database inside each tab's SingleResultView since the- // applied grant is per-result.- const showExport = !queryDataPolicy?.disableExport;+ // Per-DB grant lookup. When the policy disables direct export, the+ // hook reports which of the queried DBs are covered by an active+ // export grant (matched) and which are not (unmatched). Both lists+ // feed the partial-coverage UX: Export operates on the matched set+ // only, Request Export pre-seeds the unmatched set.+ const policyAllowsExport = !queryDataPolicy?.disableExport;+ const {+ matchedDatabases,+ unmatchedDatabases,+ tooltip: exportTooltip,+ } = useExportGrantBypass({+ enabled: !policyAllowsExport,+ project,+ statement: batchStatement,+ targets: queriedDatabaseNames,+ });++ // When the policy allows export, every queried DB is authorized;+ // otherwise only the JIT-matched subset. The Export drawer's+ // `DatabaseTableView` is filtered to this list so users can't+ // physically pick an unauthorized DB — eliminating the partial-+ // failure toast storm.+ const exportableDatabaseNames = policyAllowsExport+ ? queriedDatabaseNames+ : matchedDatabases;+ const exportableDatabaseList = useMemo(+ () => exportableDatabaseNames.map((name) => getDatabaseByName(name)),+ [exportableDatabaseNames, getDatabaseByName]+ );++ const showExport = exportableDatabaseNames.length > 0;+ // Surface "Request Export" whenever the batch contains uncovered DBs.+ // Visible alongside Export in the partial-coverage case (e.g. 2 of 5+ // covered) so users can request grants for the missing ones without+ // losing the immediate export of the covered set.+ const showRequestExport =+ !policyAllowsExport && unmatchedDatabases.length > 0;+ // Partial-coverage flag: some matched, some not. Drives the Export+ // button label change from "Batch export" to "Partial batch export"+ // so the user knows up-front the action operates on a strict subset.+ const isPartialExport =+ showExport && !policyAllowsExport && unmatchedDatabases.length > 0;const handleCloseSingleResultView = (item: BatchQueryItem) => {const contexts = currentTab?.databaseQueryContexts?.get(item.database.name);@@ -229,7 +260,13 @@ export function BatchQuerySelect({const contents: DownloadContent[] = [];const tabsState = getSQLEditorTabsState();const tab = tabsState.tabsById.get(tabsState.currentTabId);+ // Defensive intersect — the drawer already filters to authorized+ // DBs, but if a stale name lingers in `selectedDatabaseNames` we+ // skip it here rather than firing a doomed backend call that+ // would produce a "failed for db" toast.+ const exportableSet = new Set(exportableDatabaseNames);for (const databaseName of Array.from(selectedDatabaseNames)) {+ if (!exportableSet.has(databaseName)) continue;const database = getDatabaseByName(databaseName);const context = head(tab?.databaseQueryContexts?.get(databaseName));if (!context) continue;@@ -299,15 +336,32 @@ export function BatchQuerySelect({</Tooltip>)}- <div className="mb-2">- {showExport ? (+ {/*+ Partial-coverage UX: when the policy disables export and only a+ subset of the queried DBs has an active grant, both buttons can+ appear — Export operates on the covered set, Request Export+ pre-seeds the uncovered set so the user can extend coverage+ without losing the immediate export.+ */}+ <div className="mb-2 flex flex-row gap-2">+ {showExport && (<DataExportButtonsize="sm"viewMode="DRAWER"supportFormats={supportFormats}supportPassword- text={t("sql-editor.batch-export.self")}- tooltip={t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}+ text={+ isPartialExport+ ? t("sql-editor.batch-export.partial")+ : t("sql-editor.batch-export.self")+ }+ // Surface the grant-bypass explanation when the export is+ // only available because of a JIT grant; otherwise keep the+ // long-standing "select at most N databases" hint.+ tooltip={+ exportTooltip ??+ t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })+ }validate={validateExport}maximumExportCount={queryDataPolicy.maximumResultRows}onExport={handleExport}@@ -322,8 +376,13 @@ export function BatchQuerySelect({{t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT })}</span></div>+ {/*+ Filtered to `exportableDatabaseList` so users can only+ check authorized DBs. Unauthorized ones are routed to+ the Request Export button next to this one.+ */}<DatabaseTableView- databases={databaseList}+ databases={exportableDatabaseList}mode="PROJECT"selectedNames={selectedDatabaseNames}onSelectedNamesChange={setSelectedDatabaseNames}@@ -331,10 +390,14 @@ export function BatchQuerySelect({</div>}/>- ) : (+ )}+ {showRequestExport && (<RequestExportButtonstatement={batchStatement}- targets={queriedDatabaseNames}+ // Pre-seed only the uncovered DBs so approvers see the+ // minimum new blast radius (matched DBs already have a+ // grant — no need to duplicate).+ targets={unmatchedDatabases}/>)}</div>diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex 7763e617b1..4ca09c5ef5 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -10,6 +10,7 @@ import {} from "@/react/components/DataExportButton";import { RequestExportButton } from "@/react/components/sql-editor/RequestExportButton";import { RequestQueryButton } from "@/react/components/sql-editor/RequestQueryButton";+import { useExportGrantBypass } from "@/react/components/sql-editor/useExportGrantBypass";import { Button } from "@/react/components/ui/button";import {Tabs,@@ -128,110 +129,26 @@ export function ResultView({return false;}, [queryDataPolicy, envQueryDataPolicy]);- // Show the real export button when the policy allows export, OR when the- // user holds any active export-capable grant for this statement — even if- // it's not the grant the Query path applied (Query prefers Unmask, so the- // applied grant may be unmask-only while a separate export grant exists).- // Without this independent search the UI would hide the Export button and- // direct the user to "Request export" despite already having a grant — see- // PR #20491 bot review (#3349086832).- const searchMyAccessGrants = useAppStore((s) => s.searchMyAccessGrants);- const databaseProjectName = database.project;- const [exportGrantName, setExportGrantName] = useState<string>("");-- useEffect(() => {- if (- !queryDataPolicy?.disableExport ||- !executeParams?.statement ||- !databaseProjectName- ) {- setExportGrantName("");- return;- }- let canceled = false;- void (async () => {- const result = await searchMyAccessGrants({- parent: databaseProjectName,- filter: {- target: database.name,- // Exact match — the backend's JIT authorization path uses- // `query == ...` (preCheckAccess in sql_service.go). A- // substring match (`statement: ...`) would expose Export for- // queries that don't actually match any grant. PR #20491 bot- // review #3349385091.- statementExact: executeParams.statement,- status: ["ACTIVE"],- export: true,- },- });- if (!canceled) {- setExportGrantName(result.accessGrants[0]?.name ?? "");- }- })();- return () => {- canceled = true;- };- }, [- queryDataPolicy?.disableExport,- executeParams?.statement,- databaseProjectName,- database.name,- searchMyAccessGrants,- ]);-- // Pull display fields from the cache populated by the search above.- const exportGrantIssue = useAppStore((s) =>- exportGrantName ? (s.accessGrantsByName[exportGrantName]?.issue ?? "") : ""- );- const exportGrantReason = useAppStore((s) =>- exportGrantName ? (s.accessGrantsByName[exportGrantName]?.reason ?? "") : ""- );+ // Look up an active JIT export grant for this (target, statement) pair.+ // When one exists, flip `showExport` so the real Export button surfaces+ // even when the policy would normally block direct export — and let the+ // hook render the attribution tooltip (PR #20491 bot reviews #3349086832,+ // #3349385091). The check is independent of the Query-applied grant: the+ // Query path prefers Unmask, so the applied grant may be unmask-only+ // while a separate export grant exists.+ // Hook dedupes `targets` by joined-string identity, so a fresh+ // `[database.name]` literal per render is safe (no re-fetch unless+ // the name actually changes).+ const { grantName: exportGrantName, tooltip: exportTooltip } =+ useExportGrantBypass({+ enabled: !!queryDataPolicy?.disableExport,+ project: database.project,+ statement: executeParams?.statement ?? "",+ targets: [database.name],+ });const showExport = !queryDataPolicy?.disableExport || !!exportGrantName;- // Surface a tooltip explaining the grant-based bypass only when the policy- // itself would normally block export — in the everyday "policy allows- // export" case, no tooltip is needed. Attributes to the export-capable- // grant (which may differ from the Query-applied grant when the user has- // separate unmask + export grants for the same statement).- const exportTooltip = useMemo<ReactNode>(() => {- if (!queryDataPolicy?.disableExport || !exportGrantName) {- return undefined;- }- const issueHref = exportGrantIssue- ? exportGrantIssue.startsWith("/")- ? exportGrantIssue- : `/${exportGrantIssue}`- : undefined;- return (- <div className="flex flex-col gap-y-1">- <span>{t("sql-editor.export-enabled-by-grant")}</span>- {issueHref ? (- <a- href={issueHref}- target="_blank"- rel="noreferrer"- className="break-all underline"- onClick={(e) => e.stopPropagation()}- >- {exportGrantName}- </a>- ) : (- <span className="break-all">{exportGrantName}</span>- )}- {exportGrantReason && (- <span className="text-xs opacity-80">{exportGrantReason}</span>- )}- </div>- );- }, [- t,- queryDataPolicy?.disableExport,- exportGrantName,- exportGrantIssue,- exportGrantReason,- ]);-// When direct export is unavailable, offer a "Request export" affordance that// opens the access-grant drawer (pre-filled with this database, statement,// and unmask + export checked). The button self-hides when the projectdiff --git a/frontend/src/react/components/sql-editor/useExportGrantBypass.tsx b/frontend/src/react/components/sql-editor/useExportGrantBypass.tsxnew file mode 100644index 0000000000..a8966fe395--- /dev/null+++ b/frontend/src/react/components/sql-editor/useExportGrantBypass.tsx@@ -0,0 +1,398 @@+import { type ReactNode, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { useAppStore } from "@/react/stores/app";+import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";++interface UseExportGrantBypassArgs {+ /**+ * Whether to actively look for a JIT export grant. Pass+ * `policy.disableExport` — when the policy already allows export+ * there's no bypass to surface.+ */+ enabled: boolean;+ /**+ * Project parent for the access-grant search (e.g. `"projects/foo"`).+ * The hook is a no-op when this is empty / undefined.+ */+ project: string | undefined;+ /** Exact statement to match against grant.payload.query. */+ statement: string;+ /**+ * Queried target database resource names. Single-element OK —+ * `ResultView` passes `[database.name]`, `BatchQuerySelect` passes+ * the full queried set. Empty array == no lookup.+ *+ * Internally the hook fires one `searchMyAccessGrants` call per+ * target in parallel (each with `target == "x"` and `pageSize: 1`).+ * The fan-out shape is correct by construction: a single multi-+ * target `target in [...]` query with a row-limit could cluster all+ * results on one target and silently hide coverage for the others.+ */+ targets: readonly string[];+}++interface UseExportGrantBypassResult {+ /**+ * Subset of `targets` for which an active export grant exists.+ * `BatchQuerySelect` uses this to filter the export drawer's+ * `DatabaseTableView` so users can only pick authorized databases.+ * Single-target callers can check `length > 0`.+ */+ matchedDatabases: string[];+ /**+ * Subset of `targets` NOT covered by any grant. Drives the+ * "Request Export" affordance — pre-seed it with these databases.+ */+ unmatchedDatabases: string[];+ /**+ * Fullname of the primary matching grant (first unique grant covering+ * any matched DB), or `""` when none. Callers typically use+ * `!!grantName` to flip `showExport`.+ */+ grantName: string;+ /**+ * Pre-rendered tooltip describing the matched grant(s):+ * - 1 unique grant: title + reason + "View issue" link.+ * - N>1 unique grants: count header + bulleted list of issue titles+ * (each links to its issue), capped at 5 rows + "… and N more".+ * `undefined` when no grant matched.+ */+ tooltip: ReactNode;+}++// Cap the multi-grant list to keep the tooltip compact. 20 distinct+// grants on a 224px-wide popup would overflow most viewports+// vertically; capping at 5 + "and N more" keeps the worst case+// readable.+const LIST_CAP = 5;++// Cap parallel `SearchMyAccessGrants` lookups so a batch query over+// hundreds of databases (database-group expansion, multi-tenant+// projects) doesn't fire hundreds of concurrent RPCs the moment+// results render — that would put real DB/CEL-parser pressure on the+// API for a UI affordance the user might never interact with. Bot+// review #3357335452.+//+// 10 is a pragmatic ceiling: the common 1–10 DB batch fits in one+// chunk (same single round-trip as before the cap), and a 200-DB+// batch becomes 20 sequential rounds of 10 — bounded server load,+// ≤2s tail latency on typical RTTs.+const LOOKUP_CONCURRENCY = 10;++export function useExportGrantBypass({+ enabled,+ project,+ statement,+ targets,+}: UseExportGrantBypassArgs): UseExportGrantBypassResult {+ const { t } = useTranslation();+ const searchMyAccessGrants = useAppStore((s) => s.searchMyAccessGrants);+ const fetchIssueByName = useAppStore((s) => s.fetchIssueByName);++ // Per-target grant: `grantsByTarget[target]` is the active export+ // grant for that target, or `undefined` when none.+ const [grantsByTarget, setGrantsByTarget] = useState<+ Record<string, AccessGrant | undefined>+ >({});+ // Issue title per unique grant name. Populated by parallel fetches+ // once `uniqueGrants` is known.+ const [issueTitlesByGrantName, setIssueTitlesByGrantName] = useState<+ Record<string, string>+ >({});++ // Stable join key so identity changes on the `targets` array don't+ // re-fire the search effect on every parent render.+ const targetsKey = useMemo(() => targets.join(","), [targets]);++ useEffect(() => {+ if (!enabled || !statement || !project || targetsKey === "") {+ // Idempotent reset — only swap state when it actually needs to+ // clear, so callers passing a fresh `[database.name]` literal+ // each render don't trip a "reset → re-render → reset" loop+ // (`Object.is({}, {})` is false).+ setGrantsByTarget((prev) => (Object.keys(prev).length === 0 ? prev : {}));+ return;+ }+ // Clear stale matches synchronously so the UI doesn't surface a+ // grant matched to the previous (statement, targets) tuple while+ // the new search is in flight. Without this, a user changing the+ // SQL statement would briefly see Export promise authorization+ // the new statement doesn't actually have. Bot review #3357266207.+ // Same idempotent-reset guard so the no-prior-data case (initial+ // mount, subsequent identity-only re-renders) doesn't churn.+ setGrantsByTarget((prev) => (Object.keys(prev).length === 0 ? prev : {}));+ let canceled = false;+ void (async () => {+ // Fan out: one search per target. Each call narrows to the+ // single target server-side so `pageSize: 1` suffices.+ //+ // Each request is independently try/catch'd: a failure on+ // target A (network, auth, rate-limit) MUST NOT discard the+ // successful results from targets B/C/D. `Promise.all` would+ // reject the whole batch on the first failure; we want partial+ // success. The failed target falls back to `undefined`, which+ // ResultView/BatchQuerySelect treat as "no grant" → Request+ // Export surfaces for that DB. Bot review #3357266207.+ //+ // Chunked at `LOOKUP_CONCURRENCY` so we cap the in-flight RPC+ // count even on batches of hundreds of DBs. Bot review+ // #3357335452.+ const byTarget: Record<string, AccessGrant | undefined> = {};+ for (let i = 0; i < targets.length; i += LOOKUP_CONCURRENCY) {+ if (canceled) return;+ const chunk = targets.slice(i, i + LOOKUP_CONCURRENCY);+ const chunkResults = await Promise.all(+ chunk.map(async (target) => {+ try {+ const res = await searchMyAccessGrants({+ parent: project,+ filter: {+ statementExact: statement,+ status: ["ACTIVE"],+ export: true,+ target,+ },+ pageSize: 1,+ });+ return { target, grant: res.accessGrants[0] };+ } catch {+ return {+ target,+ grant: undefined as AccessGrant | undefined,+ };+ }+ })+ );+ for (const { target, grant } of chunkResults) {+ byTarget[target] = grant;+ }+ }+ if (canceled) return;+ // Single commit at the end (not per-chunk) — the matched /+ // unmatched derivation downstream is whole-set, so partial+ // updates would flicker Export ↔ Request Export as chunks+ // resolve.+ setGrantsByTarget(byTarget);+ })();+ return () => {+ canceled = true;+ };+ // `targets` intentionally NOT in the dep array — the array literal+ // is a fresh identity on every parent render, which would defeat+ // the `targetsKey` stabilization and trigger an infinite "search+ // → setState → re-render → search" loop. The closure captures the+ // `targets` from the render that last bumped `targetsKey`; since+ // `targetsKey` is a value-stable join of the same content, that+ // captured array carries the right values to iterate.+ }, [enabled, project, statement, targetsKey, searchMyAccessGrants]);++ // Partition into matched/unmatched AND build the dedup'd grant list.+ // A single grant can cover multiple targets (its `targets` array+ // overlapping the queried set), so the per-target search returns the+ // same grant for several keys — collapse by `grant.name`.+ //+ // Keyed by `targetsKey` (not `targets`) so per-render fresh array+ // literals don't churn this memo's identity, which would in turn+ // churn every downstream `useMemo` / `useEffect` that depends on+ // `uniqueGrants` (and trip an infinite loop via the issue-fetch+ // effect).+ const { matchedDatabases, unmatchedDatabases, uniqueGrants } = useMemo(() => {+ const matched: string[] = [];+ const unmatched: string[] = [];+ const seen = new Map<string, AccessGrant>();+ for (const target of targets) {+ const grant = grantsByTarget[target];+ if (grant) {+ matched.push(target);+ if (!seen.has(grant.name)) seen.set(grant.name, grant);+ } else {+ unmatched.push(target);+ }+ }+ return {+ matchedDatabases: matched,+ unmatchedDatabases: unmatched,+ uniqueGrants: Array.from(seen.values()),+ };+ // See the search-effect dep-array comment: keyed by `targetsKey`+ // (a value-stable join), not by `targets` (a fresh identity each+ // render).+ }, [targetsKey, grantsByTarget]);++ const primaryGrant = uniqueGrants[0];+ const grantName = primaryGrant?.name ?? "";++ // Stable key over the unique-grant set's `issue` fields so we don't+ // refetch on every identity change to `uniqueGrants`.+ const issueFetchKey = useMemo(+ () => uniqueGrants.map((g) => `${g.name}:${g.issue}`).join("|"),+ [uniqueGrants]+ );++ // Fetch every unique grant's approval-issue title in parallel.+ // `fetchIssueByName` is stateless (no per-issue cache) so the titles+ // live in local state. Keyed by `issueFetchKey` (a value-stable+ // string over the unique-grant set's name+issue pairs); `uniqueGrants`+ // is read from closure to avoid the per-render identity churn that+ // caused the previous infinite loop.+ useEffect(() => {+ if (issueFetchKey === "") {+ // Idempotent reset (`Object.is({}, {})` is false → without this,+ // each render with no unique grants schedules a new render).+ setIssueTitlesByGrantName((prev) =>+ Object.keys(prev).length === 0 ? prev : {}+ );+ return;+ }+ let canceled = false;+ void (async () => {+ const withIssue = uniqueGrants.filter((g) => g.issue);+ if (withIssue.length === 0) {+ setIssueTitlesByGrantName((prev) =>+ Object.keys(prev).length === 0 ? prev : {}+ );+ return;+ }+ const fetched = await Promise.all(+ withIssue.map(async (g) => {+ try {+ const issue = await fetchIssueByName(g.issue, true /* silent */);+ return { name: g.name, title: issue?.title ?? "" };+ } catch {+ return { name: g.name, title: "" };+ }+ })+ );+ if (canceled) return;+ const map: Record<string, string> = {};+ for (const { name, title } of fetched) {+ if (title) map[name] = title;+ }+ setIssueTitlesByGrantName(map);+ })();+ return () => {+ canceled = true;+ };+ }, [issueFetchKey, fetchIssueByName]);++ const tooltip = useMemo<ReactNode>(() => {+ if (!enabled || uniqueGrants.length === 0) return undefined;++ // ============ Single-grant detail view ============+ if (uniqueGrants.length === 1) {+ const grant = uniqueGrants[0];+ const fetchedTitle = issueTitlesByGrantName[grant.name];+ // Title format: `Export available via issue "X"` when the grant+ // has an approval issue whose title we could fetch; otherwise+ // the generic phrase. The generic phrase also covers the brief+ // window before the issue fetch resolves.+ const headline = fetchedTitle+ ? t("sql-editor.export-available-via-issue", { title: fetchedTitle })+ : t("sql-editor.export-enabled-by-grant");+ const issueName = grant.issue ?? "";+ const issueHref = issueName+ ? issueName.startsWith("/")+ ? issueName+ : `/${issueName}`+ : undefined;+ // No min-width here — that would override the primitive+ // Tooltip's `max-w-56` cap (min-width wins over max-width),+ // pushing the popup past the viewport when the trigger is near+ // the right edge and Floating UI can't shift it back.+ return (+ <div className="flex flex-col gap-y-1">+ {/* `break-words` wraps long emails/IDs in the title onto a+ new line instead of clipping. */}+ <span className="font-medium break-words">{headline}</span>+ {grant.reason && (+ // Cap at 3 lines with auto-ellipsis. Full reason is one+ // click away via the View Issue link.+ <span className="text-xs opacity-80 break-words line-clamp-3">+ {grant.reason}+ </span>+ )}+ {issueHref && (+ <div className="flex justify-end pt-1">+ <a+ href={issueHref}+ target="_blank"+ rel="noreferrer"+ className="text-xs underline whitespace-nowrap"+ onClick={(e) => e.stopPropagation()}+ >+ {t("sql-editor.view-issue")}+ </a>+ </div>+ )}+ </div>+ );+ }++ // ============ Multi-grant list view (N>1) ============+ const visible = uniqueGrants.slice(0, LIST_CAP);+ const overflow = uniqueGrants.length - visible.length;+ return (+ <div className="flex flex-col gap-y-1">+ <span className="font-medium break-words">+ {t("sql-editor.export-available-via-n-grants", {+ count: uniqueGrants.length,+ })}+ </span>+ <div className="flex flex-col gap-y-0.5 text-xs">+ {visible.map((grant) => {+ const issueName = grant.issue ?? "";+ const href = issueName+ ? issueName.startsWith("/")+ ? issueName+ : `/${issueName}`+ : undefined;+ // Display priority: fetched issue title → grant.reason →+ // generic phrase. `reason` exists on every grant the user+ // submitted; the generic phrase only kicks in for auto-+ // active grants without an issue or reason, which are+ // rare. `line-clamp-1` truncates long titles/reasons so+ // each row is exactly one line.+ const display =+ issueTitlesByGrantName[grant.name] ||+ grant.reason ||+ t("sql-editor.export-enabled-by-grant");+ return (+ <div key={grant.name} className="flex items-start gap-x-1">+ <span className="select-none opacity-60">•</span>+ {href ? (+ <a+ href={href}+ target="_blank"+ rel="noreferrer"+ className="flex-1 min-w-0 underline break-words line-clamp-1"+ onClick={(e) => e.stopPropagation()}+ >+ {display}+ </a>+ ) : (+ <span className="flex-1 min-w-0 break-words line-clamp-1">+ {display}+ </span>+ )}+ </div>+ );+ })}+ {overflow > 0 && (+ <div className="opacity-70 italic">+ {overflow === 1+ ? t("sql-editor.and-more-grant", { count: overflow })+ : t("sql-editor.and-more-grants", { count: overflow })}+ </div>+ )}+ </div>+ </div>+ );+ }, [t, enabled, uniqueGrants, issueTitlesByGrantName]);++ return {+ matchedDatabases,+ unmatchedDatabases,+ grantName,+ tooltip,+ };+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 7dedb7b679..e1fec2ff61 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -2637,9 +2637,12 @@"self": "Admin mode"},"allow-admin-mode-only": "Instance <instance></instance> is accessible in admin mode only.",+ "and-more-grant": "… and {{count}} more grant",+ "and-more-grants": "… and {{count}} more grants","and-n-more-databases": "and {{n}} more databases","batch-export": {"failed-for-db": "Failed to export data for {{db}}",+ "partial": "Partial batch export","self": "Batch export","tooltip": "Select at most {{max}} databases to batch export latest query results"},@@ -2682,6 +2685,8 @@"expire-at": "Expire at {{time}}","expire-in": "Expire in {{time}}","expired": "Expired",+ "export-available-via-issue": "Export available via issue \"{{title}}\"",+ "export-available-via-n-grants": "Export available via {{count}} access grants:","export-enabled-by-grant": "Export enabled by access grant","format": "Format","format-default": "Default",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 09e23aec2d..a19915dc3b 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -2637,9 +2637,12 @@"self": "Modo administrador"},"allow-admin-mode-only": "La instancia <instance></instance> solo es accesible en modo administrador.",+ "and-more-grant": "… y {{count}} concesión más",+ "and-more-grants": "… y {{count}} concesiones más","and-n-more-databases": "y {{n}} bases de datos más","batch-export": {"failed-for-db": "No se pudieron exportar los datos de {{db}}",+ "partial": "Exportación parcial por lotes","self": "Exportación por lotes","tooltip": "Seleccione como máximo {{max}} bases de datos para exportar por lotes los resultados de las últimas consultas"},@@ -2682,6 +2685,8 @@"expire-at": "Expira el {{time}}","expire-in": "Expira en {{time}}","expired": "Expirado",+ "export-available-via-issue": "Exportación disponible vía issue \"{{title}}\"",+ "export-available-via-n-grants": "Exportación disponible vía {{count}} concesiones de acceso:","export-enabled-by-grant": "Exportación habilitada por la concesión de acceso","format": "Formato","format-default": "Predeterminado",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 8f9fd0b82f..ab5786ef0e 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -2637,9 +2637,12 @@"self": "管理者モード"},"allow-admin-mode-only": "インスタンス <instance></instance> には管理者モードでのみアクセスできます。",+ "and-more-grant": "他 {{count}} 件のアクセス権限",+ "and-more-grants": "他 {{count}} 件のアクセス権限","and-n-more-databases": "他 {{n}} 件のデータベース","batch-export": {"failed-for-db": "{{db}} のデータのエクスポートに失敗しました",+ "partial": "部分的な一括エクスポート","self": "一括エクスポート","tooltip": "最新のクエリ結果を一括エクスポートするには、最大 {{max}} 個のデータベースを選択してください"},@@ -2682,6 +2685,8 @@"expire-at": "{{time}} に期限切れ","expire-in": "{{time}} 後に期限切れ","expired": "期限切れ",+ "export-available-via-issue": "Issue「{{title}}」によりエクスポート可能",+ "export-available-via-n-grants": "{{count}} 件のアクセス権限によりエクスポート可能:","export-enabled-by-grant": "アクセス権限により有効になっています","format": "フォーマット","format-default": "デフォルト",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex ea60c2c8cc..89bc6a0c5e 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -2637,9 +2637,12 @@"self": "Chế độ quản trị"},"allow-admin-mode-only": "Phiên bản <instance></instance> chỉ có thể truy cập ở chế độ quản trị.",+ "and-more-grant": "… và {{count}} cấp quyền nữa",+ "and-more-grants": "… và {{count}} cấp quyền nữa","and-n-more-databases": "và {{n}} cơ sở dữ liệu khác","batch-export": {"failed-for-db": "Không xuất được dữ liệu cho {{db}}",+ "partial": "Xuất hàng loạt một phần","self": "Xuất hàng loạt","tooltip": "Chọn tối đa {{max}} cơ sở dữ liệu để xuất hàng loạt kết quả truy vấn mới nhất"},@@ -2682,6 +2685,8 @@"expire-at": "Hết hạn lúc {{time}}","expire-in": "Hết hạn sau {{time}}","expired": "Đã hết hạn",+ "export-available-via-issue": "Xuất khả dụng qua issue \"{{title}}\"",+ "export-available-via-n-grants": "Xuất khả dụng qua {{count}} cấp quyền truy cập:","export-enabled-by-grant": "Xuất được kích hoạt bởi cấp quyền truy cập","format": "Định dạng","format-default": "Mặc định",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 9fccaf0ff7..17f8c25e77 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -2637,9 +2637,12 @@"self": "管理员模式"},"allow-admin-mode-only": "实例<instance></instance>只能通过管理员模式访问。",+ "and-more-grant": "… 还有 {{count}} 个授权",+ "and-more-grants": "… 还有 {{count}} 个授权","and-n-more-databases": "及其他 {{n}} 个数据库","batch-export": {"failed-for-db": "无法导出 {{db}} 的数据",+ "partial": "部分批量导出","self": "批量导出","tooltip": "最多选择 {{max}} 个数据库,批量导出最后一次执行的查询结果"},@@ -2682,6 +2685,8 @@"expire-at": "{{time}} 过期","expire-in": "{{time}} 后过期","expired": "已过期",+ "export-available-via-issue": "通过工单 \"{{title}}\" 可导出",+ "export-available-via-n-grants": "通过 {{count}} 个访问授权可导出:","export-enabled-by-grant": "由访问授权启用导出","format": "格式化","format-default": "默认",