25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(oracle): add identity-bound session diagnostics
efeire69a0bc5ff49a
diff --git a/apps/desktop/src/components/admin/ProcessListPanel.vue b/apps/desktop/src/components/admin/ProcessListPanel.vueindex 37081c58f2..fddbd9cfa1 100644--- a/apps/desktop/src/components/admin/ProcessListPanel.vue+++ b/apps/desktop/src/components/admin/ProcessListPanel.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";+import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref, watch } from "vue";import { useI18n } from "vue-i18n";import { Activity, AlertTriangle, ArrowDown, ArrowUp, Ban, Copy, Loader2, PlugZap, RefreshCcw, Search } from "@lucide/vue";import { Button } from "@/components/ui/button";@@ -20,6 +20,8 @@ import { processListSelectionAfterClick } from "@/lib/database/processListSelectimport { oracleMajorVersion } from "@/lib/database/oracleSessionManagement";import { useTabUiState } from "@/lib/tabs/tabUiState";+const SessionDiagnostics = defineAsyncComponent(() => import("./SessionDiagnostics.vue"));+const props = defineProps<{connection: ConnectionConfig;}>();@@ -90,6 +92,7 @@ let managedClientSession: ManagedClientSession | null = null;// Full-text preview for long cells (SQL statement / info), opened by clicking them.const previewText = ref<string | null>(null);+const diagnosticRow = ref<ProcessRow | null>(null);const lockTarget = ref<ProcessRow | null>(null);const lockColumns = ref<string[]>([]);const lockRows = ref<unknown[][]>([]);@@ -105,6 +108,11 @@ function openPreview(value: string | number | null) {previewText.value = String(value);}+function showDiagnostics(row: ProcessRow) {+ if (!driver.value?.diagnosticEngine || actionsLocked.value || refreshing.value) return;+ diagnosticRow.value = { ...row };+}+function closeManagedSession(session: ManagedClientSession) {if (!session.closeRequested || session.active > 0) return;session.closeRequested = false;@@ -672,6 +680,7 @@ watch(lockTruncated.value = false;loadingLocks.value = false;lockRequestGeneration++;+ diagnosticRow.value = null;search.value = "";sortKey.value = driver.value?.defaultSortKey ?? "time";sortDir.value = "desc";@@ -819,6 +828,10 @@ onBeforeUnmount(() => {</td><td class="px-3 py-1.5 text-right"><span class="inline-flex items-center justify-end gap-1">+ <Button v-if="driver?.diagnosticEngine" variant="ghost" size="sm" class="h-6 gap-1 px-1.5 text-[11px]" :disabled="actionsLocked || refreshing" @click="showDiagnostics(row)">+ <Activity class="h-3.5 w-3.5" />+ {{ t("sessionDiagnostics.open") }}+ </Button><Button v-if="driver?.buildLockDetailsSql" variant="ghost" size="sm" class="h-6 gap-1 px-1.5 text-[11px]" :disabled="actionsLocked || refreshing || loadingLocks" :title="t('processList.oracleLockDetails')" @click="showLocks(row)"><Search class="h-3.5 w-3.5" />{{ t("processList.oracleLockDetails") }}@@ -859,6 +872,8 @@ onBeforeUnmount(() => {</table></div>+ <SessionDiagnostics v-if="diagnosticRow && driver?.diagnosticEngine" :connection="connection" :row="diagnosticRow" :engine="driver.diagnosticEngine" :version-major="versionMajor ?? undefined" :database="driver.database ?? ''" @close="diagnosticRow = null" />+<Dialog:open="cancelTarget !== null"@update:open="diff --git a/apps/desktop/src/components/admin/SessionDiagnostics.vue b/apps/desktop/src/components/admin/SessionDiagnostics.vuenew file mode 100644index 0000000000..bcc3f19b2c--- /dev/null+++ b/apps/desktop/src/components/admin/SessionDiagnostics.vue@@ -0,0 +1,250 @@+<script setup lang="ts">+import { computed, defineAsyncComponent, ref } from "vue";+import { useI18n } from "vue-i18n";+import { Copy, Loader2, RefreshCcw } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { useSessionDiagnostics } from "@/composables/useSessionDiagnostics";+import { useToast } from "@/composables/useToast";+import { copyToClipboard } from "@/lib/common/clipboard";+import type { ConnectionConfig, QueryResult } from "@/types/database";+import type { ProcessRow } from "@/lib/database/processListDrivers";+import type { DiagnosticEngine, DiagnosticSection } from "@/lib/database/sessionDiagnostics";++const ExplainPlanViewer = defineAsyncComponent(() => import("@/components/explain/ExplainPlanViewer.vue"));+const props = defineProps<{ connection: ConnectionConfig; row: ProcessRow; engine: DiagnosticEngine; database: string; versionMajor?: number }>();+const emit = defineEmits<{ close: [] }>();+const { t } = useI18n();+const { toast } = useToast();+const context = computed(() => ({ connection: props.connection, row: props.row, engine: props.engine, database: props.database, versionMajor: props.versionMajor }));+const { snapshot, busy, error, cleanupFailed, selection, refresh, stop } = useSessionDiagnostics(context);+const activeTab = ref("sql");+const section = computed<DiagnosticSection<unknown>>(() => (activeTab.value === "statistics" ? snapshot.value.metrics : activeTab.value === "longOperations" ? snapshot.value.longOperations : activeTab.value === "plan" ? snapshot.value.plan : snapshot.value.sql));+const tabs = ["sql", "plan", "statistics", "longOperations"];+const tables = computed(() => (activeTab.value === "longOperations" ? [{ key: "longOperations", section: snapshot.value.longOperations }] : [{ key: "waits", section: snapshot.value.waits }]));+const columnLabels: Record<string, string> = {+ SCOPE: "scope",+ WAIT_KIND: "waitKind",+ STATE: "state",+ EVENT: "event",+ WAIT_CLASS: "waitClass",+ SECONDS_IN_WAIT: "secondsInWait",+ BLOCKING_INSTANCE: "blockingInstance",+ BLOCKING_SESSION: "blockingSession",+ SID: "sid",+ SERIAL_NUMBER: "serial",+ INSTANCE_ID: "instance",+ OPNAME: "operation",+ TARGET: "target",+ SOFAR: "sofar",+ TOTALWORK: "totalWork",+ UNITS: "units",+ START_TIME: "startTime",+ LAST_UPDATE_TIME: "lastUpdateTime",+ ELAPSED_SECONDS: "elapsedSeconds",+ TIME_REMAINING: "remainingSeconds",+ MESSAGE: "message",+ SQL_ID: "sqlId",+ SQL_EXEC_ID: "sqlExecId",+ SQL_EXEC_START: "sqlExecStart",+ SVR_IP: "serverIp",+ SVR_PORT: "serverPort",+ TRACE_ID: "traceId",+ PROGRESS_PERCENT: "progress",+};++function formattedTime(value?: string) {+ if (!value) return "—";+ const date = new Date(value);+ return Number.isNaN(date.getTime()) ? value : date.toLocaleString();+}+function formattedMicros(value: string) {+ if (!/^\d+$/.test(value)) return value;+ const millis = Number(BigInt(value) / 1000n);+ return Number.isSafeInteger(millis) ? formattedTime(new Date(millis).toString()) : value;+}+function formatValue(value: unknown, column = "") {+ if (value === null || value === undefined) return "—";+ if ((column === "SCOPE" || column === "WAIT_KIND") && ["cursor_cumulative", "plan_cumulative", "request", "session_sample", "execution", "current_wait", "last_wait", "session_trace", "request_trace"].includes(String(value))) return t(`sessionDiagnostics.scopes.${value}`);+ return String(value);+}+function sectionStatus(value: DiagnosticSection<unknown>, longOperations = false) {+ if (value.state === "loading") return t("common.loading");+ if (value.state === "cancelled" || value.state === "timeout") return "";+ if (value.state === "empty" && longOperations) return t("sessionDiagnostics.longOperationsEmpty");+ if (value.reason) return t(`sessionDiagnostics.reasons.${value.reason}`);+ if (value.state === "failed") return t("sessionDiagnostics.reasons.failed");+ return "";+}+function columnLabel(column: string) {+ return columnLabels[column] ? t(`sessionDiagnostics.columns.${columnLabels[column]}`) : column;+}+async function copySql() {+ const text = snapshot.value.sql.data?.text;+ if (!text) return;+ try {+ await copyToClipboard(text);+ toast(t("processList.copied"), 1500);+ } catch (cause) {+ toast(cause instanceof Error ? cause.message : String(cause), 3000);+ }+}+function chooseRequest(event: Event) {+ void refresh({ requestKey: (event.target as HTMLSelectElement).value || undefined });+}+function choosePlan(event: Event) {+ void refresh({ ...selection.value, planKey: (event.target as HTMLSelectElement).value || undefined });+}+function tableRows(result?: QueryResult) {+ return result?.rows ?? [];+}+</script>++<template>+ <Dialog :open="true" @update:open="(open) => !open && emit('close')">+ <DialogContent class="flex h-[min(82vh,780px)] max-w-6xl flex-col gap-0 p-0" :aria-busy="busy">+ <DialogHeader class="shrink-0 space-y-2 border-b px-5 pb-4 pt-5 pr-12">+ <DialogTitle>{{ t("sessionDiagnostics.title", { id: row.id }) }}</DialogTitle>+ <div class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">+ <Badge variant="outline">{{ connection.name }}</Badge>+ <span>{{ engine === "oracle" ? "Oracle" : "OceanBase Oracle" }}</span>+ <span v-if="snapshot.identity.sqlId" class="font-mono">SQL_ID {{ snapshot.identity.sqlId }}</span>+ </div>+ <details class="text-xs text-muted-foreground">+ <summary class="w-fit cursor-pointer rounded focus-visible:outline focus-visible:outline-ring">{{ t("sessionDiagnostics.sampleContext") }}</summary>+ <dl class="mt-2 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1">+ <template v-for="(value, key) in snapshot.identity" :key="key">+ <template v-if="value"+ ><dt>{{ t(`sessionDiagnostics.identity.${key}`) }}</dt>+ <dd class="break-all font-mono">{{ value }}</dd></template+ >+ </template>+ <dt>{{ t("sessionDiagnostics.sampleWindow") }}</dt>+ <dd>{{ formattedTime(snapshot.startedAt) }} — {{ formattedTime(snapshot.finishedAt) }}</dd>+ </dl>+ </details>+ </DialogHeader>+ <div v-if="snapshot.stale" class="shrink-0 border-b bg-muted/30 px-5 py-2 text-xs text-muted-foreground" role="status">{{ t("sessionDiagnostics.stale") }}</div>+ <p v-if="snapshot.interrupted" class="shrink-0 border-b px-5 py-2 text-xs text-muted-foreground" role="status">{{ t(`sessionDiagnostics.states.${snapshot.interrupted}`) }}</p>+ <p v-if="error" class="shrink-0 border-b bg-destructive/10 px-5 py-2 text-xs text-destructive" role="alert">{{ error }}</p>+ <p v-if="cleanupFailed" class="shrink-0 border-b px-5 py-2 text-xs text-muted-foreground" role="status">{{ t("sessionDiagnostics.cleanupFailed") }}</p>+ <label v-if="snapshot.requestChoices.length > 1" class="flex shrink-0 flex-wrap items-center gap-2 border-b px-5 py-3 text-sm">+ {{ t("sessionDiagnostics.chooseRequest") }}+ <select :value="selection.requestKey ?? ''" class="h-8 max-w-full rounded-md border bg-background px-2 text-xs focus-visible:outline focus-visible:outline-ring" :disabled="busy" @change="chooseRequest">+ <option value="" disabled>{{ t("sessionDiagnostics.selectRequest") }}</option>+ <option v-for="choice in snapshot.requestChoices" :key="choice.key" :value="choice.key">{{ t("sessionDiagnostics.requestOption", { ...choice.identity, requestTime: formattedMicros(choice.identity.requestTime) }) }}</option>+ </select>+ </label>+ <Tabs v-model="activeTab" class="flex min-h-0 flex-1 flex-col">+ <TabsList variant="line" class="mx-4 mt-2 shrink-0">+ <TabsTrigger v-for="tab in tabs" :key="tab" :value="tab">{{ t(`sessionDiagnostics.tabs.${tab}`) }}</TabsTrigger>+ </TabsList>+ <div class="shrink-0 space-y-1 border-b px-5 py-2 text-xs text-muted-foreground" aria-live="polite">+ <div class="flex flex-wrap items-center gap-x-4 gap-y-1">+ <span v-if="section.source" class="break-all font-mono">{{ section.source }}</span+ ><span v-if="section.sampledAt">{{ formattedTime(section.sampledAt) }}</span>+ </div>+ <p v-if="sectionStatus(section, activeTab === 'longOperations')" class="flex items-center gap-2"><Loader2 v-if="section.state === 'loading'" class="h-3.5 w-3.5 animate-spin" />{{ sectionStatus(section, activeTab === "longOperations") }}</p>+ <p v-if="section.incomplete">{{ t("sessionDiagnostics.incomplete") }}</p>+ <p v-if="section.error" class="break-words text-destructive" role="alert">{{ section.error }}</p>+ <p v-if="section.data && section.dataSampledAt && section.dataSampledAt !== section.sampledAt">{{ t("sessionDiagnostics.previousSample", { time: formattedTime(section.dataSampledAt) }) }}</p>+ </div>+ <TabsContent value="sql" class="min-h-0 overflow-auto p-5">+ <template v-if="snapshot.sql.data">+ <div class="mb-3 flex items-center justify-between gap-3">+ <Badge variant="outline">{{ t(`sessionDiagnostics.completeness.${snapshot.sql.data.completeness}`) }}</Badge+ ><Button variant="outline" size="sm" class="gap-1.5" :disabled="!snapshot.sql.data.text" @click="copySql"><Copy class="h-3.5 w-3.5" />{{ t(snapshot.sql.data.completeness === "fragment" ? "sessionDiagnostics.copyFragment" : "sessionDiagnostics.copyText") }}</Button>+ </div>+ <pre class="select-text whitespace-pre-wrap break-words rounded-md border bg-muted/20 p-4 font-mono text-xs leading-5" tabindex="0">{{ snapshot.sql.data.text }}</pre>+ </template>+ </TabsContent>+ <TabsContent value="plan" class="flex min-h-0 flex-col overflow-hidden">+ <label v-if="snapshot.planChoices.length > 1 || (snapshot.planChoices.length > 0 && snapshot.plan.reason === 'target_changed')" class="flex shrink-0 flex-wrap items-center gap-2 px-5 py-3 text-sm"+ >{{ t("sessionDiagnostics.choosePlan")+ }}<select :value="selection.planKey ?? ''" class="h-8 max-w-full rounded-md border bg-background px-2 text-xs focus-visible:outline focus-visible:outline-ring" :disabled="busy" @change="choosePlan">+ <option value="" disabled>{{ t("sessionDiagnostics.selectPlan") }}</option>+ <option v-for="choice in snapshot.planChoices" :key="choice.key" :value="choice.key">{{ t("sessionDiagnostics.planOption", choice.identity) }}</option>+ </select></label+ >+ <template v-if="snapshot.plan.data"+ ><p class="shrink-0 px-5 py-2 text-xs text-muted-foreground">{{ t(`sessionDiagnostics.planBindings.${snapshot.plan.data.binding}`) }}</p>+ <div class="min-h-0 flex-1"><ExplainPlanViewer :plan="snapshot.plan.data.plan" :table-result="snapshot.plan.data.table" default-view="table" /></div+ ></template>+ </TabsContent>+ <TabsContent value="statistics" class="min-h-0 overflow-auto p-5">+ <div v-if="snapshot.metrics.data?.length" class="overflow-auto rounded-md border">+ <table class="w-full text-left text-xs">+ <thead class="bg-muted/30">+ <tr>+ <th v-for="key in ['metric', 'value', 'unit', 'scope', 'source']" :key="key" class="whitespace-nowrap px-3 py-2 font-medium">{{ t(`sessionDiagnostics.columns.${key}`) }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="metric in snapshot.metrics.data" :key="metric.source" class="border-t">+ <td class="px-3 py-2">{{ t(`sessionDiagnostics.metrics.${metric.name}`) }}</td>+ <td class="whitespace-nowrap px-3 py-2 font-mono">{{ formatValue(metric.value) }}</td>+ <td class="px-3 py-2">{{ t(`sessionDiagnostics.units.${metric.unit}`) }}</td>+ <td class="whitespace-nowrap px-3 py-2">{{ t(`sessionDiagnostics.scopes.${metric.scope}`) }}</td>+ <td class="break-all px-3 py-2 font-mono text-muted-foreground">{{ metric.source }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ <h3 class="mb-2 mt-5 text-sm font-medium">{{ t("sessionDiagnostics.waits") }}</h3>+ <div v-for="table in tables" :key="table.key" class="space-y-2">+ <p class="text-xs text-muted-foreground">{{ table.section.source }} · {{ formattedTime(table.section.sampledAt) }}</p>+ <p v-if="sectionStatus(table.section)" class="text-xs text-muted-foreground">{{ sectionStatus(table.section) }}</p>+ <p v-if="table.section.data && table.section.dataSampledAt && table.section.dataSampledAt !== table.section.sampledAt" class="text-xs text-muted-foreground">{{ t("sessionDiagnostics.previousSample", { time: formattedTime(table.section.dataSampledAt) }) }}</p>+ <p v-if="table.section.incomplete" class="text-xs text-muted-foreground">{{ t("sessionDiagnostics.incomplete") }}</p>+ <p v-if="table.section.error" class="break-words text-xs text-destructive">{{ table.section.error }}</p>+ <div v-if="table.section.data" class="overflow-auto rounded-md border">+ <table class="w-full text-left text-xs">+ <thead class="bg-muted/30">+ <tr>+ <th v-for="column in table.section.data.columns" :key="column" class="whitespace-nowrap px-3 py-2 font-medium" :title="column">{{ columnLabel(column) }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(values, index) in tableRows(table.section.data)" :key="index" class="border-t">+ <td v-for="(value, column) in values" :key="column" class="whitespace-nowrap px-3 py-2 font-mono">{{ formatValue(value, table.section.data.columns[column]) }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </TabsContent>+ <TabsContent value="longOperations" class="min-h-0 overflow-auto p-5">+ <p v-if="engine === 'oceanbase-oracle'" class="mb-3 text-xs text-muted-foreground">{{ t("sessionDiagnostics.obLongOperations") }}</p>+ <div v-if="snapshot.longOperations.data?.rows.length" class="overflow-auto rounded-md border">+ <table class="w-max min-w-full text-left text-xs">+ <thead class="bg-muted/30">+ <tr>+ <th v-for="column in snapshot.longOperations.data.columns" :key="column" class="whitespace-nowrap px-3 py-2 font-medium" :title="column">{{ columnLabel(column) }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(values, index) in snapshot.longOperations.data.rows" :key="index" class="border-t">+ <td+ v-for="(value, column) in values"+ :key="column"+ class="px-3 py-2"+ :class="snapshot.longOperations.data.columns[column] === 'MESSAGE' ? 'w-80 max-w-80 whitespace-normal break-words font-mono' : snapshot.longOperations.data.columns[column] === 'SCOPE' ? 'whitespace-nowrap' : 'whitespace-nowrap font-mono'"+ >+ {{ formatValue(value, snapshot.longOperations.data.columns[column]) }}+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </TabsContent>+ </Tabs>+ <DialogFooter class="shrink-0 items-center border-t px-5 py-3">+ <Button v-if="busy" variant="outline" @click="stop">{{ t("sessionDiagnostics.stop") }}</Button>+ <Button variant="outline" class="gap-1.5" :disabled="busy" @click="refresh()"><RefreshCcw class="h-3.5 w-3.5" />{{ t("grid.refresh") }}</Button>+ <Button variant="secondary" @click="emit('close')">{{ t("common.close") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts b/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.tsindex c2923558d7..788b9945cf 100644--- a/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts+++ b/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts@@ -13,6 +13,9 @@ const mocks = vi.hoisted(() => ({executeQuery: vi.fn(),executeMulti: vi.fn(),closeClientConnectionSession: vi.fn(),+ cancelQuery: vi.fn(),+ readLargeValueChunk: vi.fn(),+ diagnosticGate: null as null | (() => Promise<void>),contextGuard: vi.fn(),contextGuardGate: null as null | (() => Promise<void>),toast: vi.fn(),@@ -82,7 +85,8 @@ function dialogSurface(): Component {});}-vi.mock("vue-i18n", () => ({+vi.mock("vue-i18n", async (importOriginal) => ({+ ...(await importOriginal<typeof import("vue-i18n")>()),useI18n: () => ({t: (key: string, values?: Record<string, unknown>) => {const message = mocks.localeMessages?.[key.split(".")[0]!] as Record<string, unknown> | undefined;@@ -97,7 +101,7 @@ vi.mock("vue-i18n", () => ({}));vi.mock("@lucide/vue", () => {const Icon = passthrough("span");- return { Activity: Icon, AlertTriangle: Icon, ArrowDown: Icon, ArrowUp: Icon, Ban: Icon, Copy: Icon, Loader2: Icon, PlugZap: Icon, RefreshCcw: Icon, Search: Icon };+ return { Activity: Icon, AlertTriangle: Icon, ArrowDown: Icon, ArrowUp: Icon, Ban: Icon, Copy: Icon, Loader2: Icon, PlugZap: Icon, RefreshCcw: Icon, Search: Icon, AlertCircle: Icon, Braces: Icon, Check: Icon, Download: Icon, GitBranch: Icon, Table2: Icon, FileText: Icon, Workflow: Icon };});vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));vi.mock("@/components/ui/badge", () => ({ Badge: passthrough("span") }));@@ -113,7 +117,7 @@ vi.mock("@/stores/connectionStore", () => ({useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected }),}));vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));-vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery, executeMulti: mocks.executeMulti, closeClientConnectionSession: mocks.closeClientConnectionSession }));+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery, executeMulti: mocks.executeMulti, closeClientConnectionSession: mocks.closeClientConnectionSession, cancelQuery: mocks.cancelQuery, readLargeValueChunk: mocks.readLargeValueChunk }));vi.mock("@/lib/database/productionExecutionGuard", () => ({executeWithProductionSqlGuard: (options: { execute: () => Promise<unknown> }) => options.execute(),executeWithProductionContextGuard: async (options: { execute: () => Promise<unknown> }) => {@@ -193,7 +197,7 @@ let oracleTerminated = false;let oracleTerminateError = "";function oracleListResult() {const rows: unknown[][] = [["5", "30", "1", "3", "APP", "ACTIVE", "localhost", "DBX", "selfsql", null, null, null, "500", "2026-10-20 09:00:00"]];- if (!oracleTerminated) rows.push(["21", "42", "2", "3", "OTHER", "INACTIVE", "apphost", "worker", null, "SQL*Net message from client", null, null, "700", "2026-10-20 08:00:00"]);+ if (!oracleTerminated) rows.push(["21", "42", "2", "3", "OTHER", "INACTIVE", "apphost", "worker", "0123456789abc", "SQL*Net message from client", null, null, "700", "2026-10-20 08:00:00"]);return { columns: [], rows };}@@ -229,6 +233,51 @@ function postgresListResult() {};}+function diagnosticResult(row: Record<string, unknown>) {+ return { columns: Object.keys(row), rows: [Object.values(row)], affected_rows: 0, execution_time_ms: 1 };+}++async function diagnosticReply(sql: string) {+ if (sql.includes("FROM GV$SESSION_LONGOPS") || sql.includes("FROM SYS.GV$SESSION_LONGOPS")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 };+ if (sql.includes("FROM GV$SESSION s WHERE") || sql.includes("FROM SYS.GV$OB_PROCESSLIST WHERE")) {+ const gate = mocks.diagnosticGate;+ mocks.diagnosticGate = null;+ if (gate) await gate();+ return diagnosticResult(+ sql.includes("OB_PROCESSLIST")+ ? { SID: "21", SESSION_USER: "OTHER", TENANT: "tenant_a", SVR_IP: "127.0.0.1", SVR_PORT: "2882", PROXY_SESSID: null, DB_NAME: "db", SQL_ID: "A".repeat(32), TRACE_ID: "trace-1", STATE: "ACTIVE", SQL_TEXT: "SELECT 2" }+ : { SQL_ID: "0123456789abc", CHILD_NUMBER: "1", SQL_EXEC_ID: "2", SQL_EXEC_START: "2026-10-21T20:00:00", STATE: "WAITING", EVENT: "fixture wait", WAIT_CLASS: "Other", SECONDS_IN_WAIT: "0" },+ );+ }+ if (sql.includes(" AS NOW_US")) return diagnosticResult({ NOW_US: "1792593313000000" });+ if (sql.includes("FROM GV$SQL_PLAN_STATISTICS_ALL")) return diagnosticResult({ STARTS: "1", OUTPUT_ROWS: "2" });+ if (sql.includes("FROM GV$SQL_PLAN p")) return diagnosticResult({ ID: "0", PARENT_ID: null, OPERATION: "SELECT STATEMENT", COST: "1", ESTIMATED_ROWS: "2" });+ if (sql.includes("FROM GV$SQL s")) return diagnosticResult({ SQL_ID: "0123456789abc", CHILD_NUMBER: "1", CHILD_ADDRESS: "000000001234ABCD", FIRST_LOAD_TIME: "2026-10-21/19:00:00", PLAN_HASH: "9", SQL_TEXT: "SELECT 2", SOURCE_LENGTH: "8", EXECUTIONS: "2", ELAPSED_TIME: "0" });+ if (sql.includes("FROM SYS.GV$OB_SQL_AUDIT"))+ return diagnosticResult({+ TENANT_ID: "7",+ TENANT_NAME: "tenant_a",+ SVR_IP: "127.0.0.1",+ SVR_PORT: "2882",+ SID: "21",+ TRACE_ID: "trace-1",+ SQL_ID: "A".repeat(32),+ REQUEST_ID: "99",+ REQUEST_TIME: "1792593313123456",+ SQL_EXEC_ID: "2",+ PLAN_ID: "9",+ RET_CODE: "0",+ QUERY_SQL: "SELECT 2",+ ELAPSED_TIME: "0",+ RETURN_ROWS: "2",+ STATE: "WAITED SHORT TIME",+ EVENT: "fixture request wait",+ WAIT_CLASS: "Other",+ });+ if (sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_STAT")) return diagnosticResult({ TENANT_ID: "7", SVR_IP: "127.0.0.1", SVR_PORT: "2882", PLAN_ID: "9", SQL_ID: "A".repeat(32), FIRST_LOAD_TIME: "2026-10-21 20:00:00 +08:00", PLAN_HASH: "10", EXECUTIONS: "2" });+ if (sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_EXPLAIN")) return diagnosticResult({ PLAN_DEPTH: "0", PLAN_LINE_ID: "0", OPERATOR: "PHY_EXPR_VALUES", NAME: "NULL", COST: "0", ESTIMATED_ROWS: "2" });+}+let app: App<Element> | null = null;let root: HTMLDivElement | null = null;@@ -289,10 +338,13 @@ beforeEach(() => {mocks.oceanbaseTerminated = true;return { columns: [], rows: [] };}- return { columns: [], rows: [] };+ return (await diagnosticReply(sql)) ?? { columns: [], rows: [] };});mocks.executeMulti.mockReset().mockResolvedValue([{ columns: [], rows: [] }]);mocks.closeClientConnectionSession.mockReset().mockResolvedValue(undefined);+ mocks.cancelQuery.mockReset().mockResolvedValue(true);+ mocks.readLargeValueChunk.mockReset();+ mocks.diagnosticGate = null;mocks.contextGuard.mockReset();mocks.contextGuardGate = null;mocks.toast.mockReset();@@ -300,7 +352,7 @@ beforeEach(() => {oracleTerminateError = "";mocks.oceanbaseRows = [["5", "APP", "tenant_a", "localhost", "db", "Query", "0", "active", "SELECT 1", null, "127.0.0.1", "2882"],- ["21", "OTHER", "tenant_a", "apphost", "db", "Sleep", "4", "idle", "SELECT 2", null, "127.0.0.1", "2882"],+ ["21", "OTHER", "tenant_a", "apphost", "db", "Sleep", "4", "idle", "SELECT 2", null, "127.0.0.1", "2882", "A".repeat(32), "trace-1"],["22", "PROXY", "tenant_a", "proxyhost", "db", "Query", "5", "active", "SELECT 3", "99", "127.0.0.2", "2882"],];mocks.oceanbaseTerminated = false;@@ -987,3 +1039,206 @@ describe("ProcessListPanel batch terminate", () => {expect(root?.textContent).not.toContain("processList.transactionCount:0");});});++describe("ProcessListPanel linked diagnostics", () => {+ it("labels retained waits with their original sample time while refreshed metrics succeed", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ const oldTime = "2026-10-21T10:00:00.000Z",+ newTime = "2026-10-21T11:00:00.000Z";+ const clock = vi.spyOn(Date.prototype, "toISOString").mockReturnValue(oldTime);+ try {+ await mountOraclePanel();+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false), { timeout: 5000 });+ const tab = [...(root?.querySelectorAll<HTMLButtonElement>('[role="tab"]') ?? [])].find((value) => value.textContent?.trim() === "统计与等待");+ tab?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(root?.textContent).toContain("fixture wait"));+ clock.mockReturnValue(newTime);+ const execute = mocks.executeQuery.getMockImplementation()!;+ mocks.executeQuery.mockImplementation(async (...args: unknown[]) => {+ if (String(args[2]).includes("FROM GV$SESSION s WHERE")) throw new Error("ORA-01031: waits denied");+ return execute(...args);+ });+ findDialogButton("刷新")?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: waits denied"));+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false));+ const panel = root?.querySelector('[role="tabpanel"][data-state="active"]');+ expect(panel?.textContent).toContain("fixture wait");+ expect(panel?.textContent).toContain("游标累计");+ expect(panel?.textContent).toContain(zhCN.sessionDiagnostics.previousSample.replace("{time}", new Date(oldTime).toLocaleString()));+ expect(panel?.textContent).not.toContain(zhCN.sessionDiagnostics.previousSample.replace("{time}", new Date(newTime).toLocaleString()));+ } finally {+ clock.mockRestore();+ }+ });++ it.each([+ ["Oracle", oracleConnection, "游标累计"],+ ["OceanBase Oracle", oceanbaseConnection, "计划缓存累计"],+ ])("opens the complete %s diagnostic workflow from the existing session row", async (_label, connection, cumulativeLabel) => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ if (connection.db_type === "oracle") await mountOraclePanel();+ else await mountOceanbasePanel();+ const open = [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断");+ expect(open?.disabled).toBe(false);+ open?.click();+ await vi.waitFor(() => expect(root?.querySelector("[data-dialog] pre")?.textContent, root?.textContent ?? "").toBe("SELECT 2"), { timeout: 5000 });+ expect(root?.textContent).toContain("会话 21 诊断");+ const selectTab = async (label: string) => {+ const button = [...(root?.querySelectorAll<HTMLButtonElement>('[role="tab"]') ?? [])].find((tab) => tab.textContent?.trim() === label);+ expect(button).toBeDefined();+ button?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await nextTick();+ };+ await selectTab("已有计划");+ await vi.waitFor(() => expect(root?.textContent).toContain(connection.db_type === "oracle" ? "已有游标计划" : "已关联原请求的缓存计划"));+ await vi.waitFor(() => expect(root?.textContent).toContain(connection.db_type === "oracle" ? "ORACLE" : "OCEANBASE-ORACLE"), { timeout: 5000 });+ expect(root?.textContent).not.toContain("MYSQL");+ await selectTab("统计与等待");+ await vi.waitFor(() => expect(root?.textContent).toContain(cumulativeLabel));+ expect(root?.textContent).toContain("等待与会话状态");+ await selectTab("长操作");+ await vi.waitFor(() => expect(root?.textContent).toContain("本次未观察到长操作"));+ expect(root?.textContent).not.toContain("SQL 已完成");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ const calls = mocks.executeQuery.mock.calls.filter((call) => String((call[5] as { clientSessionId?: string })?.clientSessionId).startsWith("session-diagnostics:"));+ expect(calls.length).toBeGreaterThan(4);+ expect(calls.every((call) => String(call[2]).startsWith("SELECT "))).toBe(true);+ expect(calls.some((call) => call[2] === "SELECT 2")).toBe(false);+ findDialogButton("关闭")?.click();+ await vi.waitFor(() => expect(root?.textContent).not.toContain("会话 21 诊断"));+ expect(processRow("21").textContent).toContain("OTHER");+ });++ it("offers no diagnostic action for an unrelated engine", async () => {+ await mountPanel(mysqlConnection);+ expect(gridButtons().some((button) => button.textContent?.trim() === "sessionDiagnostics.open")).toBe(false);+ expect(findGridButton("processList.batchTerminate")).toBeDefined();+ });++ it("treats the exact-request placeholder as a prompt rather than an action that clears a bound request", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ const execute = mocks.executeQuery.getMockImplementation()!;+ mocks.executeQuery.mockImplementation(async (...args: unknown[]) => {+ const value = await execute(...args);+ if (!String(args[2]).includes("FROM SYS.GV$OB_SQL_AUDIT")) return value;+ const other = [...value.rows[0]];+ other[value.columns.indexOf("REQUEST_ID")] = "100";+ return { ...value, rows: [...value.rows, other] };+ });+ await mountOceanbasePanel();+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(root?.querySelector("select")?.options.length).toBe(3), { timeout: 5000 });+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false));+ const select = root?.querySelector("select")!;+ expect(select.options[0]?.disabled).toBe(true);+ select.value = select.options[1]!.value;+ select.dispatchEvent(new Event("change", { bubbles: true }));+ await vi.waitFor(() => expect(root?.textContent).toContain("SYS.GV$OB_SQL_AUDIT.QUERY_SQL"));+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false));+ expect(root?.querySelector("select")?.options[0]?.disabled).toBe(true);+ expect(root?.querySelector("select")?.value).toBe(select.options[1]!.value);+ });++ it("keeps explicit plan selection available when the captured audit narrows earlier cache candidates", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ let auditAvailable = false;+ const execute = mocks.executeQuery.getMockImplementation()!;+ mocks.executeQuery.mockImplementation(async (...args: unknown[]) => {+ const sql = String(args[2]);+ if (sql.includes("FROM SYS.GV$OB_SQL_AUDIT") && !auditAvailable) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 };+ if (sql.includes("FROM SYS.GV$OB_SESS_TIME_MODEL")) return diagnosticResult({ TENANT_ID: "7" });+ const value = await execute(...args);+ if (!sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_STAT")) return value;+ const original = Object.fromEntries(value.columns.map((column: string, index: number) => [column, value.rows[0][index]]));+ const alternative = { ...original, PLAN_ID: "10", PLAN_HASH: "11" };+ if (sql.includes("AND PLAN_ID=10")) return diagnosticResult(alternative);+ if (sql.includes("AND PLAN_ID=9") || auditAvailable) return diagnosticResult(original);+ const other = diagnosticResult(alternative);+ return { ...value, rows: [...other.rows, ...value.rows] };+ });+ await mountOceanbasePanel();+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(root?.querySelector('[role="tab"]')).not.toBeNull(), { timeout: 5000 });+ const tab = [...(root?.querySelectorAll<HTMLButtonElement>('[role="tab"]') ?? [])].find((value) => value.textContent?.trim() === "已有计划");+ tab?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(root?.querySelector("select")?.options.length).toBe(3));+ expect(root?.querySelector("select")?.options[0]?.disabled).toBe(true);+ const choose = (id: string) => {+ const select = root?.querySelector("select")!;+ select.value = [...select.options].find((option) => option.textContent?.startsWith(`计划 ${id} ·`))!.value;+ select.dispatchEvent(new Event("change", { bubbles: true }));+ };+ choose("10");+ await vi.waitFor(() => expect(root?.textContent).toContain("同 SQL 的缓存计划,未证实用于本次执行"));+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false));+ auditAvailable = true;+ findDialogButton("刷新")?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("目标身份或缓存代际已变化"));+ await vi.waitFor(() => expect(findDialogButton("刷新")?.disabled).toBe(false));+ expect(root?.querySelector("select")?.options.length).toBe(2);+ expect(root?.textContent).not.toContain("已关联原请求的缓存计划");+ choose("9");+ await vi.waitFor(() => expect(root?.textContent).toContain("已关联原请求的缓存计划"));+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it("shows the original missing SID and trace-level association for an OB long operation", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ const execute = mocks.executeQuery.getMockImplementation()!;+ mocks.executeQuery.mockImplementation(async (...args: unknown[]) =>+ String(args[2]).includes("FROM SYS.GV$SESSION_LONGOPS") ? diagnosticResult({ SID: "-1", TRACE_ID: "trace-1", SVR_IP: "127.0.0.1", SVR_PORT: "2882", OPNAME: "create index", TARGET: "table_id=42", ELAPSED_SECONDS: "2", TIME_REMAINING: "3" }) : execute(...args),+ );+ await mountOceanbasePanel();+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("会话 21 诊断"), { timeout: 5000 });+ const tab = [...(root?.querySelectorAll<HTMLButtonElement>('[role="tab"]') ?? [])].find((value) => value.textContent?.trim() === "长操作");+ tab?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, button: 0 }));+ await vi.waitFor(() => expect(root?.textContent).toContain("请求 trace 关联(未提供会话 ID)"));+ const panel = root?.querySelector('[role="tabpanel"][data-state="active"]');+ expect(panel?.textContent).toContain("-1");+ expect(panel?.textContent).toContain("create index");+ expect(panel?.textContent).not.toContain("%");+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it("stops local reading from the actual dialog while cancellation remains pending", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ let release!: () => void;+ mocks.diagnosticGate = () =>+ new Promise<void>((resolve) => {+ release = resolve;+ });+ mocks.cancelQuery.mockReturnValue(new Promise(() => {}));+ await mountOraclePanel();+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(findDialogButton("停止读取")).toBeDefined());+ findDialogButton("停止读取")?.click();+ await vi.waitFor(() => expect(findDialogButton("停止读取")).toBeUndefined());+ expect(root?.textContent).toContain("已停止本地读取");+ expect(findDialogButton("刷新")?.disabled).toBe(false);+ expect(mocks.cancelQuery).toHaveBeenCalledOnce();+ release();+ await nextTick();+ const calls = mocks.executeQuery.mock.calls.filter((call) => String((call[5] as { clientSessionId?: string })?.clientSessionId).startsWith("session-diagnostics:"));+ expect(calls).toHaveLength(1);+ });++ it("closes diagnostics on connection changes without sampling the old row on the new connection", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ let release!: () => void;+ mocks.diagnosticGate = () =>+ new Promise<void>((resolve) => {+ release = resolve;+ });+ const connection = await mountReactivePanel(oracleConnection);+ [...processRow("21").querySelectorAll("button")].find((button) => button.textContent?.trim() === "诊断")?.click();+ await vi.waitFor(() => expect(findDialogButton("停止读取")).toBeDefined());+ connection.id = "oracle-next";+ await vi.waitFor(() => expect(root?.textContent).not.toContain("会话 21 诊断"));+ release();+ await nextTick();+ expect(mocks.executeQuery.mock.calls.filter((call) => String((call[5] as { clientSessionId?: string })?.clientSessionId).startsWith("session-diagnostics:")).every((call) => call[0] === "oracle-1")).toBe(true);+ expect(mocks.cancelQuery).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/composables/__tests__/useSessionDiagnostics.spec.ts b/apps/desktop/src/composables/__tests__/useSessionDiagnostics.spec.tsnew file mode 100644index 0000000000..8ddf416d25--- /dev/null+++ b/apps/desktop/src/composables/__tests__/useSessionDiagnostics.spec.ts@@ -0,0 +1,131 @@+import { effectScope, ref } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { QueryResult } from "@/types/database";+import { useSessionDiagnostics, type SessionDiagnosticsContext } from "../useSessionDiagnostics";++const api = vi.hoisted(() => ({ executeQuery: vi.fn(), cancelQuery: vi.fn(), closeClientConnectionSession: vi.fn(), readLargeValueChunk: vi.fn() }));+vi.mock("@/lib/backend/api", () => api);++const scopes: ReturnType<typeof effectScope>[] = [];+const sqlId = "0123456789abc";+function result(row: Record<string, unknown>): QueryResult {+ return { columns: Object.keys(row), rows: [Object.values(row) as string[]], affected_rows: 0, execution_time_ms: 1 };+}+function context(connectionId = "oracle"): SessionDiagnosticsContext {+ return {+ connection: { id: connectionId, name: connectionId, db_type: "oracle", host: "localhost", port: 1521, username: "APP" },+ database: "",+ engine: "oracle",+ versionMajor: 19,+ row: { id: "17", serial: "8", instance: "1", container: "3", user: "APP", auditSession: "99", logonTime: "2026-10-21 10:00:00" },+ };+}+function start(value = context()) {+ const current = ref(value),+ scope = effectScope();+ scopes.push(scope);+ const diagnostics = scope.run(() => useSessionDiagnostics(current))!;+ return { current, diagnostics, scope };+}+beforeEach(() => {+ vi.useRealTimers();+ api.cancelQuery.mockReset().mockResolvedValue(true);+ api.closeClientConnectionSession.mockReset().mockResolvedValue(true);+ api.readLargeValueChunk.mockReset();+ api.executeQuery.mockReset().mockImplementation(async (connectionId: string, _db: string, sql: string) => {+ if (sql.includes("FROM GV$SESSION_LONGOPS")) return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 };+ if (sql.includes("FROM GV$SQL_PLAN_STATISTICS_ALL")) return result({ STARTS: "1", OUTPUT_ROWS: "1" });+ if (sql.includes("FROM GV$SQL_PLAN p")) return result({ ID: "0", PARENT_ID: null, OPERATION: "SELECT STATEMENT", COST: "0", ESTIMATED_ROWS: "1" });+ if (sql.includes("FROM GV$SESSION s")) return result({ SQL_ID: sqlId, CHILD_NUMBER: "1", SQL_EXEC_ID: "2", SQL_EXEC_START: "2026-10-21T20:00:00", STATE: "WAITING", EVENT: "fixture", WAIT_CLASS: "Other", SECONDS_IN_WAIT: "0" });+ if (sql.includes("FROM GV$SQL s")) return result({ SQL_ID: sqlId, CHILD_NUMBER: "1", CHILD_ADDRESS: "000000001234ABCD", FIRST_LOAD_TIME: "2026-10-21/19:00:00", PLAN_HASH: "9", SQL_TEXT: connectionId, SOURCE_LENGTH: String(connectionId.length), EXECUTIONS: "2" });+ throw new Error("Unexpected query");+ });+});+afterEach(() => {+ for (const scope of scopes.splice(0)) scope.stop();+ vi.useRealTimers();+});++describe("session diagnostic sampling lifecycle", () => {+ it("samples the full workflow and closes its own session, keeping engine and captured identity", async () => {+ const { diagnostics } = start();+ await vi.waitFor(() => expect(diagnostics.busy.value).toBe(false));+ expect(diagnostics.snapshot.value.sql.data?.text).toBe("oracle");+ expect(diagnostics.snapshot.value.plan.data?.binding).toBe("cursor");+ expect(diagnostics.snapshot.value.metrics.data?.some((value) => value.scope === "cursor_cumulative")).toBe(true);+ expect(diagnostics.snapshot.value.longOperations.state).toBe("empty");+ expect(diagnostics.snapshot.value.startedAt).toBeTruthy();+ expect(diagnostics.snapshot.value.finishedAt).toBeTruthy();+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledOnce());+ });++ it("stops busy locally and ignores a capture result that arrives after a connection switch", async () => {+ let finish!: (value: QueryResult) => void;+ api.executeQuery.mockImplementationOnce(+ () =>+ new Promise<QueryResult>((resolve) => {+ finish = resolve;+ }),+ );+ api.cancelQuery.mockReturnValue(new Promise(() => {}));+ const { current, diagnostics } = start(context("first"));+ expect(diagnostics.busy.value).toBe(true);+ current.value = context("second");+ expect(diagnostics.busy.value).toBe(false);+ expect(diagnostics.snapshot.value.sql.data).toBeUndefined();+ expect(api.executeQuery.mock.calls.some(([id]) => id === "second")).toBe(false);+ await diagnostics.refresh();+ await vi.waitFor(() => expect(diagnostics.snapshot.value.sql.data?.text).toBe("second"));+ finish(result({ SQL_ID: "fedcba9876543", CHILD_NUMBER: "9" }));+ await Promise.resolve();+ expect(diagnostics.snapshot.value.sql.data?.text).toBe("second");+ expect(api.executeQuery.mock.calls.filter(([id]) => id === "first")).toHaveLength(1);+ expect(api.cancelQuery).toHaveBeenCalledWith(api.executeQuery.mock.calls[0]?.[4]);+ });++ it("preserves verified data with its original data timestamp when a refresh loses permission", async () => {+ const { diagnostics } = start();+ await vi.waitFor(() => expect(diagnostics.busy.value).toBe(false));+ const original = diagnostics.snapshot.value.sql.dataSampledAt;+ const originalQuery = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => {+ if (String(args[2]).includes("FROM GV$SQL s")) throw new Error("ORA-01031: insufficient privileges");+ return originalQuery(...args);+ });+ await diagnostics.refresh();+ expect(diagnostics.snapshot.value.sql).toMatchObject({ state: "unavailable", reason: "permission_denied", dataSampledAt: original, data: { text: "oracle" } });+ expect(diagnostics.snapshot.value.waits.state).toBe("ready");+ });++ it("stops reading without discarding already verified sections", async () => {+ const { diagnostics } = start();+ await vi.waitFor(() => expect(diagnostics.busy.value).toBe(false));+ const originalQuery = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation((...args) => (String(args[2]).includes("FROM GV$SQL_PLAN p") ? new Promise(() => {}) : originalQuery(...args)));+ void diagnostics.refresh();+ await vi.waitFor(() => expect(diagnostics.snapshot.value.sql.state).toBe("ready"));+ diagnostics.stop();+ expect(diagnostics.busy.value).toBe(false);+ expect(diagnostics.snapshot.value.sql.data?.text).toBe("oracle");+ expect(diagnostics.snapshot.value.plan.state).toBe("cancelled");+ expect(diagnostics.snapshot.value.interrupted).toBe("cancelled");+ expect(diagnostics.snapshot.value.plan.data?.binding).toBe("cursor");+ });++ it("reports an asynchronous session-cleanup failure without replacing collected evidence", async () => {+ api.closeClientConnectionSession.mockRejectedValue(new Error("fixture cleanup failure"));+ const { diagnostics } = start();+ await vi.waitFor(() => expect(diagnostics.cleanupFailed.value).toBe(true));+ expect(diagnostics.snapshot.value.sql.data?.text).toBe("oracle");+ });++ it("invalidates an in-flight sample when disposed and sends no later queries", async () => {+ api.executeQuery.mockReturnValue(new Promise(() => {}));+ const { diagnostics, scope } = start();+ scope.stop();+ expect(diagnostics.busy.value).toBe(false);+ await Promise.resolve();+ expect(api.executeQuery).toHaveBeenCalledOnce();+ expect(api.cancelQuery).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/composables/useSessionDiagnostics.ts b/apps/desktop/src/composables/useSessionDiagnostics.tsnew file mode 100644index 0000000000..9bffc401c9--- /dev/null+++ b/apps/desktop/src/composables/useSessionDiagnostics.ts@@ -0,0 +1,112 @@+import { onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";+import type { ConnectionConfig } from "@/types/database";+import type { ProcessRow } from "@/lib/database/processListDrivers";+import { captureOceanbaseDiagnosticTarget, collectOceanbaseSessionDiagnostics, type OceanbaseDiagnosticTarget } from "@/lib/database/oceanbaseSessionDiagnostics";+import { captureOracleDiagnosticTarget, collectOracleSessionDiagnostics, type OracleDiagnosticTarget } from "@/lib/database/oracleSessionDiagnostics";+import { createSessionDiagnosticReader, DiagnosticReadStopped, type SessionDiagnosticReader } from "@/lib/database/sessionDiagnosticReader";+import { DIAGNOSTIC_SECTIONS, diagnosticFailure, emptySessionDiagnostics, mergeSessionDiagnostics, type DiagnosticEngine, type DiagnosticSelection, type SessionDiagnosticsSnapshot } from "@/lib/database/sessionDiagnostics";++export interface SessionDiagnosticsContext {+ connection: ConnectionConfig;+ engine: DiagnosticEngine;+ row: ProcessRow;+ database: string;+ versionMajor?: number;+}++export function useSessionDiagnostics(context: Readonly<Ref<SessionDiagnosticsContext>>) {+ const snapshot = shallowRef(emptySessionDiagnostics(context.value.engine));+ const busy = ref(false);+ const error = ref("");+ const cleanupFailed = ref(false);+ const selection = shallowRef<DiagnosticSelection>({});+ let target: OracleDiagnosticTarget | OceanbaseDiagnosticTarget | undefined;+ let activeReader: SessionDiagnosticReader | undefined;+ let generation = 0;+ let disposed = false;++ function stop() {+ generation++;+ activeReader?.stop();+ activeReader = undefined;+ busy.value = false;+ const patch: Partial<SessionDiagnosticsSnapshot> = { finishedAt: new Date().toISOString(), interrupted: "cancelled" };+ for (const section of DIAGNOSTIC_SECTIONS) {+ if (snapshot.value[section].state === "loading") Object.assign(patch, { [section]: { ...snapshot.value[section], state: "cancelled" } });+ }+ snapshot.value = mergeSessionDiagnostics(snapshot.value, patch);+ }++ async function refresh(nextSelection?: DiagnosticSelection) {+ if (disposed || busy.value) return;+ const frozen = context.value;+ const contextKey = JSON.stringify(frozen);+ const attempt = ++generation;+ const current = () => !disposed && generation === attempt && JSON.stringify(context.value) === contextKey;+ if (nextSelection && JSON.stringify(nextSelection) !== JSON.stringify(selection.value)) {+ selection.value = { ...nextSelection };+ snapshot.value = emptySessionDiagnostics(frozen.engine);+ }+ busy.value = true;+ error.value = "";+ const loading: Partial<SessionDiagnosticsSnapshot> = { startedAt: new Date().toISOString(), finishedAt: undefined, interrupted: undefined };+ for (const section of DIAGNOSTIC_SECTIONS) Object.assign(loading, { [section]: { ...snapshot.value[section], state: "loading" } });+ snapshot.value = mergeSessionDiagnostics(snapshot.value, loading);+ const reader = createSessionDiagnosticReader({ connectionId: frozen.connection.id, database: frozen.database });+ activeReader = reader;+ const publish = (patch: Partial<SessionDiagnosticsSnapshot>) => {+ if (current()) snapshot.value = mergeSessionDiagnostics(snapshot.value, patch);+ };+ try {+ if (!target) {+ const captured = frozen.engine === "oracle" ? await captureOracleDiagnosticTarget({ ...frozen.row }, frozen.versionMajor, reader) : await captureOceanbaseDiagnosticTarget({ ...frozen.row }, reader);+ if (!current()) return;+ target = captured;+ }+ if (!current()) return;+ if (target.engine === "oracle") await collectOracleSessionDiagnostics(target, reader, publish);+ else await collectOceanbaseSessionDiagnostics(target, reader, publish, selection.value);+ } catch (cause) {+ if (!current()) return;+ const patch: Partial<SessionDiagnosticsSnapshot> = {};+ if (cause instanceof DiagnosticReadStopped) {+ patch.interrupted = cause.reason;+ for (const section of DIAGNOSTIC_SECTIONS) if (snapshot.value[section].state === "loading") Object.assign(patch, { [section]: { ...snapshot.value[section], state: cause.reason } });+ } else {+ error.value = cause instanceof Error ? cause.message : String(cause);+ for (const section of DIAGNOSTIC_SECTIONS) if (snapshot.value[section].state === "loading") Object.assign(patch, { [section]: diagnosticFailure(snapshot.value[section].source, cause) });+ }+ publish(patch);+ } finally {+ reader.close();+ void reader.closed.catch(() => {+ if (!disposed && JSON.stringify(context.value) === contextKey) cleanupFailed.value = true;+ });+ if (current()) {+ busy.value = false;+ activeReader = undefined;+ publish({ finishedAt: new Date().toISOString() });+ }+ }+ }++ watch(+ () => JSON.stringify(context.value),+ (_key, previousKey) => {+ stop();+ target = undefined;+ selection.value = {};+ snapshot.value = emptySessionDiagnostics(context.value.engine);+ cleanupFailed.value = false;+ error.value = "";+ if (previousKey === undefined) void refresh();+ },+ { immediate: true, flush: "sync" },+ );++ onScopeDispose(() => {+ disposed = true;+ stop();+ });+ return { snapshot, busy, error, cleanupFailed, selection, refresh, stop };+}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 410128cc4c..bb6fd9d8a7 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -5216,6 +5216,147 @@ export default {noAvailable: "All available extensions are already installed.",noInstalled: "No extensions installed.",},+ sessionDiagnostics: {+ open: "Diagnose",+ title: "Session {id} diagnostics",+ sampleContext: "Sampling context",+ sampleWindow: "Sampling window (local clock)",+ stale: "The current execution changed or cannot be confirmed. These results still belong to the original SQL/request.",+ cleanupFailed: "Diagnostic connection cleanup is incomplete. Collected evidence is retained.",+ chooseRequest: "Associated request",+ selectRequest: "Select an exact request",+ requestOption: "Request {requestId} · execution {sqlExecId} · {requestTime} · return code {returnCode}",+ choosePlan: "Cached plan",+ selectPlan: "Select a cached plan",+ planOption: "Plan {planId} · {firstLoadTime}",+ previousSample: "Retained successful sample: {time}",+ incomplete: "Incomplete results. Check the source and limitations.",+ copyFragment: "Copy fragment",+ copyText: "Copy text",+ waits: "Waits and session state",+ longOperationsEmpty: "No long operations observed in this sample.",+ obLongOperations: "Shows elapsed and estimated remaining time. This view does not provide work-completion percentages.",+ stop: "Stop reading",+ tabs: {+ sql: "SQL",+ plan: "Existing plan",+ statistics: "Statistics and waits",+ longOperations: "Long operations",+ },+ states: {+ cancelled: "Local reading stopped. Server cancellation is not confirmed.",+ timeout: "Reading timed out. Completed samples are retained.",+ },+ reasons: {+ permission_denied: "Insufficient privileges for this section.",+ view_unavailable: "The view is inaccessible or absent; the cause is undetermined.",+ field_unavailable: "This field is unavailable.",+ target_missing: "The target record is not visible or has been evicted.",+ target_changed: "The target identity or cache generation changed.",+ not_collected: "Some evidence has not been collected or associated.",+ incomplete: "Incomplete results.",+ failed: "Reading failed. Check the error before retrying.",+ },+ completeness: {+ complete: "Complete text",+ fragment: "Fragment",+ unknown: "Source completeness unknown",+ template: "Cached template",+ },+ planBindings: {+ cursor: "Existing cursor plan. Rows and costs are estimates.",+ request: "Cached plan associated with the original request. Rows and costs are estimates.",+ same_sql: "A cached plan for the same SQL, not confirmed for this execution. Rows and costs are estimates.",+ },+ scopes: {+ cursor_cumulative: "Cursor cumulative",+ plan_cumulative: "Plan-cache cumulative",+ request: "Request",+ session_sample: "Session sample",+ execution: "Exact execution",+ current_wait: "Current wait",+ last_wait: "Most recent wait",+ session_trace: "Session and request trace",+ request_trace: "Request trace (session ID not provided)",+ },+ units: {+ count: "count",+ rows: "rows",+ blocks: "blocks",+ microseconds: "µs",+ seconds: "seconds",+ },+ metrics: {+ executions: "Executions",+ rows_processed: "Rows processed/returned",+ buffer_gets: "Buffer gets",+ disk_reads: "Disk reads",+ elapsed: "Elapsed time",+ cpu: "CPU time",+ application_wait: "Application wait",+ concurrency_wait: "Concurrency wait",+ cluster_wait: "Cluster wait",+ user_io_wait: "User I/O wait",+ root_output_rows: "Cumulative root output rows",+ execute: "Execution time",+ queue: "Queue time",+ total_wait: "Total wait time",+ },+ columns: {+ metric: "Metric",+ value: "Value",+ unit: "Unit",+ scope: "Scope",+ source: "Source",+ waitKind: "Wait scope",+ state: "State",+ event: "Event",+ waitClass: "Wait class",+ secondsInWait: "SECONDS_IN_WAIT (seconds)",+ blockingInstance: "Blocking instance",+ blockingSession: "Blocking session",+ sid: "Session ID",+ serial: "Serial",+ instance: "Instance",+ operation: "Operation",+ target: "Target",+ sofar: "Work completed",+ totalWork: "Total work",+ units: "Work units",+ startTime: "Start time",+ lastUpdateTime: "Last update",+ elapsedSeconds: "Elapsed (seconds)",+ remainingSeconds: "Estimated remaining (seconds)",+ message: "Message",+ sqlId: "SQL ID",+ sqlExecId: "SQL execution ID",+ sqlExecStart: "SQL execution start",+ serverIp: "Node address",+ serverPort: "Node port",+ traceId: "Trace ID",+ progress: "Work progress (%)",+ },+ identity: {+ sid: "Session ID",+ serial: "Serial",+ instance: "Instance",+ container: "Container",+ user: "User",+ sqlId: "SQL ID",+ childNumber: "Child cursor",+ sqlExecId: "SQL execution ID",+ sqlExecStart: "SQL execution start",+ tenant: "Tenant",+ tenantId: "Tenant ID",+ server: "Node",+ traceId: "Trace ID",+ requestId: "Request ID",+ requestTime: "Request time (database microseconds)",+ auditFromMicros: "Association window start (database microseconds)",+ auditToMicros: "Association window end (database microseconds)",+ returnCode: "Return code",+ },+ },processList: {oracleSerial: "Serial number",oracleAuditSession: "Audit session ID",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 3309f99732..bfbce62d91 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -11387,6 +11387,147 @@ export default withEnglishFallback({sourceStatus: "Control de solo lectura",sourceDataEditor: "Editor de datos",},+ sessionDiagnostics: {+ open: "Diagnosticar",+ title: "Diagnóstico de la sesión {id}",+ sampleContext: "Contexto de muestreo",+ sampleWindow: "Ventana de muestreo (hora local)",+ stale: "La ejecución actual cambió o no se puede confirmar. Estos resultados siguen correspondiendo al SQL o la solicitud originales.",+ cleanupFailed: "No se completó la limpieza de la conexión de diagnóstico. Se conservaron las evidencias recopiladas.",+ chooseRequest: "Solicitud asociada",+ selectRequest: "Seleccionar una solicitud exacta",+ requestOption: "Solicitud {requestId} · ejecución {sqlExecId} · {requestTime} · código de retorno {returnCode}",+ choosePlan: "Plan en caché",+ selectPlan: "Seleccionar un plan en caché",+ planOption: "Plan {planId} · {firstLoadTime}",+ previousSample: "Se conservó la última muestra correcta: {time}",+ incomplete: "Resultados incompletos. Compruebe el origen y las limitaciones.",+ copyFragment: "Copiar fragmento",+ copyText: "Copiar texto",+ waits: "Esperas y estado de la sesión",+ longOperationsEmpty: "No se observaron operaciones largas en esta muestra.",+ obLongOperations: "Muestra el tiempo transcurrido y el tiempo restante estimado. Esta vista no ofrece porcentajes de trabajo completado.",+ stop: "Detener lectura",+ tabs: {+ sql: "SQL",+ plan: "Plan existente",+ statistics: "Estadísticas y esperas",+ longOperations: "Operaciones largas",+ },+ states: {+ cancelled: "Se detuvo la lectura local. No se ha confirmado la cancelación en el servidor.",+ timeout: "Se agotó el tiempo de lectura. Se conservaron las muestras completadas.",+ },+ reasons: {+ permission_denied: "Privilegios insuficientes para esta sección.",+ view_unavailable: "La vista no es accesible o no existe; no se determinó la causa.",+ field_unavailable: "Este campo no está disponible.",+ target_missing: "El registro de destino no está visible o se ha descartado.",+ target_changed: "Cambió la identidad del destino o la generación de la caché.",+ not_collected: "No se recopilaron o asociaron algunas evidencias.",+ incomplete: "Resultados incompletos.",+ failed: "Falló la lectura. Revise el error antes de volver a intentarlo.",+ },+ completeness: {+ complete: "Texto completo",+ fragment: "Fragmento",+ unknown: "Se desconoce la integridad del origen",+ template: "Plantilla en caché",+ },+ planBindings: {+ cursor: "Plan del cursor existente. Las filas y los costos son estimaciones.",+ request: "Plan en caché asociado a la solicitud original. Las filas y los costos son estimaciones.",+ same_sql: "Plan en caché del mismo SQL, no confirmado para esta ejecución. Las filas y los costos son estimaciones.",+ },+ scopes: {+ cursor_cumulative: "Acumulado del cursor",+ plan_cumulative: "Acumulado de la caché de planes",+ request: "Solicitud",+ session_sample: "Muestra de sesión",+ execution: "Ejecución exacta",+ current_wait: "Espera actual",+ last_wait: "Espera más reciente",+ session_trace: "Sesión y traza de solicitud",+ request_trace: "Traza de solicitud (sin ID de sesión)",+ },+ units: {+ count: "recuentos",+ rows: "filas",+ blocks: "bloques",+ microseconds: "µs",+ seconds: "segundos",+ },+ metrics: {+ executions: "Ejecuciones",+ rows_processed: "Filas procesadas/devueltas",+ buffer_gets: "Lecturas de búfer",+ disk_reads: "Lecturas de disco",+ elapsed: "Tiempo transcurrido",+ cpu: "Tiempo de CPU",+ application_wait: "Espera de aplicación",+ concurrency_wait: "Espera de concurrencia",+ cluster_wait: "Espera de clúster",+ user_io_wait: "Espera de E/S de usuario",+ root_output_rows: "Filas de salida acumuladas del nodo raíz",+ execute: "Tiempo de ejecución",+ queue: "Tiempo en cola",+ total_wait: "Tiempo total de espera",+ },+ columns: {+ metric: "Métrica",+ value: "Valor",+ unit: "Unidad",+ scope: "Alcance",+ source: "Origen",+ waitKind: "Alcance de espera",+ state: "Estado",+ event: "Evento",+ waitClass: "Clase de espera",+ secondsInWait: "SECONDS_IN_WAIT (segundos)",+ blockingInstance: "Instancia bloqueadora",+ blockingSession: "Sesión bloqueadora",+ sid: "ID de sesión",+ serial: "Número de serie",+ instance: "Instancia",+ operation: "Operación",+ target: "Destino",+ sofar: "Trabajo completado",+ totalWork: "Trabajo total",+ units: "Unidades de trabajo",+ startTime: "Hora de inicio",+ lastUpdateTime: "Última actualización",+ elapsedSeconds: "Transcurrido (segundos)",+ remainingSeconds: "Restante estimado (segundos)",+ message: "Mensaje",+ sqlId: "SQL ID",+ sqlExecId: "ID de ejecución SQL",+ sqlExecStart: "Inicio de ejecución SQL",+ serverIp: "Dirección del nodo",+ serverPort: "Puerto del nodo",+ traceId: "Trace ID",+ progress: "Progreso del trabajo (%)",+ },+ identity: {+ sid: "ID de sesión",+ serial: "Número de serie",+ instance: "Instancia",+ container: "Contenedor",+ user: "Usuario",+ sqlId: "SQL ID",+ childNumber: "Cursor hijo",+ sqlExecId: "ID de ejecución SQL",+ sqlExecStart: "Inicio de ejecución SQL",+ tenant: "Inquilino",+ tenantId: "ID del inquilino",+ server: "Nodo",+ traceId: "Trace ID",+ requestId: "ID de solicitud",+ requestTime: "Hora de solicitud (microsegundos de la base de datos)",+ auditFromMicros: "Inicio de la ventana de asociación (microsegundos de la base de datos)",+ auditToMicros: "Fin de la ventana de asociación (microsegundos de la base de datos)",+ returnCode: "Código de retorno",+ },+ },processList: {oracleSerial: "Número de serie",oracleAuditSession: "ID de sesión de auditoría",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 00982fcbf8..2a94f2def3 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -11131,6 +11131,124 @@ export default withEnglishFallback({sourceStatus: "Controllo sola lettura",sourceDataEditor: "Editor dati",},+ sessionDiagnostics: {+ open: "Diagnostica",+ title: "Diagnostica sessione {id}",+ sampleContext: "Contesto del campionamento",+ sampleWindow: "Finestra di campionamento (ora locale)",+ stale: "L'esecuzione corrente è cambiata o non è verificabile. Questi risultati si riferiscono ancora all'SQL/richiesta originale.",+ cleanupFailed: "La pulizia della connessione di diagnostica non è riuscita. Le evidenze raccolte sono conservate.",+ chooseRequest: "Richiesta associata",+ selectRequest: "Seleziona una richiesta esatta",+ requestOption: "Richiesta {requestId} · esecuzione {sqlExecId} · {requestTime} · codice di ritorno {returnCode}",+ choosePlan: "Piano in cache",+ selectPlan: "Seleziona un piano in cache",+ planOption: "Piano {planId} · {firstLoadTime}",+ previousSample: "Ultimo campionamento riuscito conservato: {time}",+ incomplete: "Risultati incompleti. Verifica la fonte e i limiti.",+ copyFragment: "Copia frammento",+ copyText: "Copia testo",+ waits: "Attese e stato della sessione",+ longOperationsEmpty: "Nessuna operazione lunga osservata in questo campionamento.",+ obLongOperations: "Mostra il tempo trascorso e il tempo rimanente stimato. Questa vista non fornisce percentuali di completamento del lavoro.",+ stop: "Interrompi lettura",+ tabs: { sql: "SQL", plan: "Piano esistente", statistics: "Statistiche e attese", longOperations: "Operazioni lunghe" },+ states: { cancelled: "Lettura locale interrotta. La cancellazione sul server non è confermata.", timeout: "Tempo di lettura scaduto. I campionamenti completati sono conservati." },+ reasons: {+ permission_denied: "Privilegi insufficienti per questa sezione.",+ view_unavailable: "La vista non è accessibile o non esiste; la causa non è determinata.",+ field_unavailable: "Questo campo non è disponibile.",+ target_missing: "Il record di destinazione non è visibile o è stato rimosso dalla cache.",+ target_changed: "L'identità della destinazione o la generazione della cache è cambiata.",+ not_collected: "Alcune evidenze non sono state raccolte o associate.",+ incomplete: "Risultati incompleti.",+ failed: "Lettura non riuscita. Verifica l'errore prima di riprovare.",+ },+ completeness: { complete: "Testo completo", fragment: "Frammento", unknown: "Completezza della fonte sconosciuta", template: "Modello in cache" },+ planBindings: { cursor: "Piano del cursore esistente. Righe e costi sono stime.", request: "Piano in cache associato alla richiesta originale. Righe e costi sono stime.", same_sql: "Piano in cache per lo stesso SQL, non confermato per questa esecuzione. Righe e costi sono stime." },+ scopes: {+ cursor_cumulative: "Cumulativo del cursore",+ plan_cumulative: "Cumulativo della cache dei piani",+ request: "Richiesta",+ session_sample: "Campionamento della sessione",+ execution: "Esecuzione esatta",+ current_wait: "Attesa corrente",+ last_wait: "Attesa più recente",+ session_trace: "Sessione e traccia della richiesta",+ request_trace: "Traccia della richiesta (ID sessione non fornito)",+ },+ units: { count: "conteggi", rows: "righe", blocks: "blocchi", microseconds: "µs", seconds: "secondi" },+ metrics: {+ executions: "Esecuzioni",+ rows_processed: "Righe elaborate/restituite",+ buffer_gets: "Letture buffer",+ disk_reads: "Letture disco",+ elapsed: "Tempo trascorso",+ cpu: "Tempo CPU",+ application_wait: "Attesa applicativa",+ concurrency_wait: "Attesa di concorrenza",+ cluster_wait: "Attesa del cluster",+ user_io_wait: "Attesa I/O utente",+ root_output_rows: "Righe di output cumulative del nodo radice",+ execute: "Tempo di esecuzione",+ queue: "Tempo in coda",+ total_wait: "Tempo totale di attesa",+ },+ columns: {+ metric: "Metrica",+ value: "Valore",+ unit: "Unità",+ scope: "Ambito",+ source: "Fonte",+ waitKind: "Ambito di attesa",+ state: "Stato",+ event: "Evento",+ waitClass: "Classe di attesa",+ secondsInWait: "SECONDS_IN_WAIT (secondi)",+ blockingInstance: "Istanza bloccante",+ blockingSession: "Sessione bloccante",+ sid: "ID sessione",+ serial: "Numero di serie",+ instance: "Istanza",+ operation: "Operazione",+ target: "Destinazione",+ sofar: "Lavoro completato",+ totalWork: "Lavoro totale",+ units: "Unità di lavoro",+ startTime: "Ora di inizio",+ lastUpdateTime: "Ultimo aggiornamento",+ elapsedSeconds: "Trascorso (secondi)",+ remainingSeconds: "Rimanente stimato (secondi)",+ message: "Messaggio",+ sqlId: "SQL ID",+ sqlExecId: "ID esecuzione SQL",+ sqlExecStart: "Inizio esecuzione SQL",+ serverIp: "Indirizzo nodo",+ serverPort: "Porta nodo",+ traceId: "Trace ID",+ progress: "Avanzamento del lavoro (%)",+ },+ identity: {+ sid: "ID sessione",+ serial: "Numero di serie",+ instance: "Istanza",+ container: "Contenitore",+ user: "Utente",+ sqlId: "SQL ID",+ childNumber: "Cursore figlio",+ sqlExecId: "ID esecuzione SQL",+ sqlExecStart: "Inizio esecuzione SQL",+ tenant: "Tenant",+ tenantId: "ID tenant",+ server: "Nodo",+ traceId: "Trace ID",+ requestId: "ID richiesta",+ requestTime: "Ora della richiesta (microsecondi del database)",+ auditFromMicros: "Inizio finestra di associazione (microsecondi del database)",+ auditToMicros: "Fine finestra di associazione (microsecondi del database)",+ returnCode: "Codice di ritorno",+ },+ },processList: {oracleSerial: "Numero di serie",oracleAuditSession: "ID sessione di audit",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 8c63498499..253f237dcd 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -11167,6 +11167,147 @@ export default withEnglishFallback({sourceStatus: "読み取り専用コントロール",sourceDataEditor: "データエディター",},+ sessionDiagnostics: {+ open: "診断",+ title: "セッション {id} の診断",+ sampleContext: "サンプリング コンテキスト",+ sampleWindow: "サンプリング期間(ローカル時刻)",+ stale: "現在の実行は変化したか確認できません。これらの結果は引き続き元の SQL/リクエストに属します。",+ cleanupFailed: "診断接続のクリーンアップが完了していません。収集済みの証拠は保持されています。",+ chooseRequest: "関連リクエスト",+ selectRequest: "正確なリクエストを選択",+ requestOption: "リクエスト {requestId} · 実行 {sqlExecId} · {requestTime} · 戻りコード {returnCode}",+ choosePlan: "キャッシュ済みプラン",+ selectPlan: "キャッシュ済みプランを選択",+ planOption: "プラン {planId} · {firstLoadTime}",+ previousSample: "前回成功したサンプルを保持: {time}",+ incomplete: "結果は不完全です。ソースと制限を確認してください。",+ copyFragment: "断片をコピー",+ copyText: "テキストをコピー",+ waits: "待機とセッション状態",+ longOperationsEmpty: "このサンプルでは長時間操作は観測されませんでした。",+ obLongOperations: "経過時間と推定残り時間を表示します。このビューでは作業完了率は表示されません。",+ stop: "読み取りを停止",+ tabs: {+ sql: "SQL",+ plan: "既存プラン",+ statistics: "統計と待機",+ longOperations: "長時間操作",+ },+ states: {+ cancelled: "ローカルの読み取りを停止しました。サーバーでキャンセルされたことは確認できていません。",+ timeout: "読み取りがタイムアウトしました。完了済みのサンプルは保持されています。",+ },+ reasons: {+ permission_denied: "このセクションの権限が不足しています。",+ view_unavailable: "ビューにアクセスできないか存在しません。原因は特定されていません。",+ field_unavailable: "このフィールドは利用できません。",+ target_missing: "対象レコードが表示されないか、消去されています。",+ target_changed: "対象の識別情報またはキャッシュ世代が変わりました。",+ not_collected: "一部の証拠が未収集、または関連付けられていません。",+ incomplete: "結果は不完全です。",+ failed: "読み取りに失敗しました。再試行する前にエラーを確認してください。",+ },+ completeness: {+ complete: "完全なテキスト",+ fragment: "断片",+ unknown: "ソースの完全性は不明",+ template: "キャッシュ テンプレート",+ },+ planBindings: {+ cursor: "既存カーソルのプラン。行数とコストは推定値です。",+ request: "元のリクエストに関連付けられたキャッシュ済みプラン。行数とコストは推定値です。",+ same_sql: "同じ SQL のキャッシュ済みプランですが、この実行で使われたことは確認されていません。行数とコストは推定値です。",+ },+ scopes: {+ cursor_cumulative: "カーソル累積",+ plan_cumulative: "プラン キャッシュ累積",+ request: "リクエスト",+ session_sample: "セッション サンプル",+ execution: "特定の実行",+ current_wait: "現在の待機",+ last_wait: "直近の待機",+ session_trace: "セッションとリクエスト trace の関連付け",+ request_trace: "リクエスト trace の関連付け(セッション ID なし)",+ },+ units: {+ count: "件",+ rows: "行",+ blocks: "ブロック",+ microseconds: "µs",+ seconds: "秒",+ },+ metrics: {+ executions: "実行回数",+ rows_processed: "処理/返却行数",+ buffer_gets: "バッファ取得",+ disk_reads: "ディスク読み取り",+ elapsed: "経過時間",+ cpu: "CPU 時間",+ application_wait: "アプリケーション待機",+ concurrency_wait: "同時実行待機",+ cluster_wait: "クラスタ待機",+ user_io_wait: "ユーザー I/O 待機",+ root_output_rows: "ルート ノードの累積出力行数",+ execute: "実行時間",+ queue: "キュー時間",+ total_wait: "合計待機時間",+ },+ columns: {+ metric: "メトリック",+ value: "値",+ unit: "単位",+ scope: "範囲",+ source: "ソース",+ waitKind: "待機範囲",+ state: "状態",+ event: "イベント",+ waitClass: "待機クラス",+ secondsInWait: "SECONDS_IN_WAIT(秒)",+ blockingInstance: "ブロック元インスタンス",+ blockingSession: "ブロック元セッション",+ sid: "セッション ID",+ serial: "シリアル番号",+ instance: "インスタンス",+ operation: "操作",+ target: "対象",+ sofar: "完了した作業",+ totalWork: "総作業量",+ units: "作業単位",+ startTime: "開始時刻",+ lastUpdateTime: "最終更新",+ elapsedSeconds: "経過(秒)",+ remainingSeconds: "推定残り(秒)",+ message: "メッセージ",+ sqlId: "SQL ID",+ sqlExecId: "SQL 実行 ID",+ sqlExecStart: "SQL 実行開始",+ serverIp: "ノード アドレス",+ serverPort: "ノード ポート",+ traceId: "Trace ID",+ progress: "作業の進捗(%)",+ },+ identity: {+ sid: "セッション ID",+ serial: "シリアル番号",+ instance: "インスタンス",+ container: "コンテナ",+ user: "ユーザー",+ sqlId: "SQL ID",+ childNumber: "子カーソル",+ sqlExecId: "SQL 実行 ID",+ sqlExecStart: "SQL 実行開始",+ tenant: "テナント",+ tenantId: "テナント ID",+ server: "ノード",+ traceId: "Trace ID",+ requestId: "リクエスト ID",+ requestTime: "リクエスト時刻(データベースのマイクロ秒)",+ auditFromMicros: "関連付け期間の開始(データベースのマイクロ秒)",+ auditToMicros: "関連付け期間の終了(データベースのマイクロ秒)",+ returnCode: "戻りコード",+ },+ },processList: {oracleSerial: "シリアル番号",oracleAuditSession: "監査セッション ID",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 5d9fbba351..5b159cf2ba 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -4736,6 +4736,147 @@ export default withEnglishFallback({confirmDrop: '예약된 작업 "{name}"을(를) 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',actionSuccess: '"{name}"에 대한 {action}이(가) 완료되었습니다.',},+ sessionDiagnostics: {+ open: "진단",+ title: "세션 {id} 진단",+ sampleContext: "샘플링 컨텍스트",+ sampleWindow: "샘플링 기간(현지 시각)",+ stale: "현재 실행이 변경되었거나 확인할 수 없습니다. 이 결과는 계속 원래 SQL/요청에 해당합니다.",+ cleanupFailed: "진단 연결 정리가 완료되지 않았습니다. 수집된 증거는 유지됩니다.",+ chooseRequest: "연결된 요청",+ selectRequest: "정확한 요청 선택",+ requestOption: "요청 {requestId} · 실행 {sqlExecId} · {requestTime} · 반환 코드 {returnCode}",+ choosePlan: "캐시된 계획",+ selectPlan: "캐시된 계획 선택",+ planOption: "계획 {planId} · {firstLoadTime}",+ previousSample: "마지막 성공 샘플 유지: {time}",+ incomplete: "결과가 불완전합니다. 출처와 제한 사항을 확인하세요.",+ copyFragment: "조각 복사",+ copyText: "텍스트 복사",+ waits: "대기 및 세션 상태",+ longOperationsEmpty: "이 샘플에서 장시간 작업이 관찰되지 않았습니다.",+ obLongOperations: "경과 시간과 예상 남은 시간을 표시합니다. 이 보기에서는 작업 완료율을 제공하지 않습니다.",+ stop: "읽기 중지",+ tabs: {+ sql: "SQL",+ plan: "기존 계획",+ statistics: "통계 및 대기",+ longOperations: "장시간 작업",+ },+ states: {+ cancelled: "로컬 읽기가 중지되었습니다. 서버 취소 여부는 확인되지 않았습니다.",+ timeout: "읽기 시간이 초과되었습니다. 완료된 샘플은 유지됩니다.",+ },+ reasons: {+ permission_denied: "이 섹션의 권한이 부족합니다.",+ view_unavailable: "뷰에 접근할 수 없거나 존재하지 않으며 원인은 확인되지 않았습니다.",+ field_unavailable: "이 필드를 사용할 수 없습니다.",+ target_missing: "대상 레코드가 보이지 않거나 제거되었습니다.",+ target_changed: "대상 식별 정보 또는 캐시 세대가 변경되었습니다.",+ not_collected: "일부 증거가 수집되지 않았거나 연결되지 않았습니다.",+ incomplete: "결과가 불완전합니다.",+ failed: "읽기에 실패했습니다. 재시도하기 전에 오류를 확인하세요.",+ },+ completeness: {+ complete: "전체 텍스트",+ fragment: "조각",+ unknown: "출처 완전성 알 수 없음",+ template: "캐시 템플릿",+ },+ planBindings: {+ cursor: "기존 커서 계획입니다. 행 수와 비용은 추정값입니다.",+ request: "원래 요청에 연결된 캐시 계획입니다. 행 수와 비용은 추정값입니다.",+ same_sql: "같은 SQL의 캐시 계획이며 이 실행에 사용되었는지는 확인되지 않았습니다. 행 수와 비용은 추정값입니다.",+ },+ scopes: {+ cursor_cumulative: "커서 누적",+ plan_cumulative: "계획 캐시 누적",+ request: "요청",+ session_sample: "세션 샘플",+ execution: "정확한 실행",+ current_wait: "현재 대기",+ last_wait: "최근 대기",+ session_trace: "세션 및 요청 trace 연결",+ request_trace: "요청 trace 연결 (세션 ID 미제공)",+ },+ units: {+ count: "횟수",+ rows: "행",+ blocks: "블록",+ microseconds: "µs",+ seconds: "초",+ },+ metrics: {+ executions: "실행 횟수",+ rows_processed: "처리/반환 행",+ buffer_gets: "버퍼 획득",+ disk_reads: "디스크 읽기",+ elapsed: "경과 시간",+ cpu: "CPU 시간",+ application_wait: "애플리케이션 대기",+ concurrency_wait: "동시성 대기",+ cluster_wait: "클러스터 대기",+ user_io_wait: "사용자 I/O 대기",+ root_output_rows: "루트 노드 누적 출력 행",+ execute: "실행 시간",+ queue: "대기열 시간",+ total_wait: "총 대기 시간",+ },+ columns: {+ metric: "지표",+ value: "값",+ unit: "단위",+ scope: "범위",+ source: "출처",+ waitKind: "대기 범위",+ state: "상태",+ event: "이벤트",+ waitClass: "대기 클래스",+ secondsInWait: "SECONDS_IN_WAIT(초)",+ blockingInstance: "차단 인스턴스",+ blockingSession: "차단 세션",+ sid: "세션 ID",+ serial: "일련번호",+ instance: "인스턴스",+ operation: "작업",+ target: "대상",+ sofar: "완료된 작업",+ totalWork: "전체 작업",+ units: "작업 단위",+ startTime: "시작 시간",+ lastUpdateTime: "마지막 업데이트",+ elapsedSeconds: "경과(초)",+ remainingSeconds: "예상 남은 시간(초)",+ message: "메시지",+ sqlId: "SQL ID",+ sqlExecId: "SQL 실행 ID",+ sqlExecStart: "SQL 실행 시작",+ serverIp: "노드 주소",+ serverPort: "노드 포트",+ traceId: "Trace ID",+ progress: "작업 진행률(%)",+ },+ identity: {+ sid: "세션 ID",+ serial: "일련번호",+ instance: "인스턴스",+ container: "컨테이너",+ user: "사용자",+ sqlId: "SQL ID",+ childNumber: "하위 커서",+ sqlExecId: "SQL 실행 ID",+ sqlExecStart: "SQL 실행 시작",+ tenant: "테넌트",+ tenantId: "테넌트 ID",+ server: "노드",+ traceId: "Trace ID",+ requestId: "요청 ID",+ requestTime: "요청 시간(데이터베이스 마이크로초)",+ auditFromMicros: "연결 창 시작(데이터베이스 마이크로초)",+ auditToMicros: "연결 창 종료(데이터베이스 마이크로초)",+ returnCode: "반환 코드",+ },+ },processList: {oracleSerial: "일련번호",oracleAuditSession: "감사 세션 ID",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 89ac88ef42..de67c4108a 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -11127,6 +11127,147 @@ export default withEnglishFallback({sourceStatus: "Controle de somente leitura",sourceDataEditor: "Editor de dados",},+ sessionDiagnostics: {+ open: "Diagnosticar",+ title: "Diagnóstico da sessão {id}",+ sampleContext: "Contexto da amostragem",+ sampleWindow: "Janela de amostragem (horário local)",+ stale: "A execução atual mudou ou não pode ser confirmada. Estes resultados ainda pertencem ao SQL/solicitação original.",+ cleanupFailed: "A limpeza da conexão de diagnóstico não foi concluída. As evidências coletadas foram preservadas.",+ chooseRequest: "Solicitação associada",+ selectRequest: "Selecione uma solicitação exata",+ requestOption: "Solicitação {requestId} · execução {sqlExecId} · {requestTime} · código de retorno {returnCode}",+ choosePlan: "Plano em cache",+ selectPlan: "Selecione um plano em cache",+ planOption: "Plano {planId} · {firstLoadTime}",+ previousSample: "Última amostra bem-sucedida preservada: {time}",+ incomplete: "Resultados incompletos. Confira a origem e as limitações.",+ copyFragment: "Copiar trecho",+ copyText: "Copiar texto",+ waits: "Esperas e estado da sessão",+ longOperationsEmpty: "Nenhuma operação longa foi observada nesta amostra.",+ obLongOperations: "Mostra o tempo decorrido e o tempo restante estimado. Esta visualização não fornece percentuais de conclusão do trabalho.",+ stop: "Parar leitura",+ tabs: {+ sql: "SQL",+ plan: "Plano existente",+ statistics: "Estatísticas e esperas",+ longOperations: "Operações longas",+ },+ states: {+ cancelled: "A leitura local foi interrompida. O cancelamento no servidor não foi confirmado.",+ timeout: "A leitura atingiu o tempo limite. As amostras concluídas foram preservadas.",+ },+ reasons: {+ permission_denied: "Privilégios insuficientes para esta seção.",+ view_unavailable: "A visualização está inacessível ou não existe; a causa é desconhecida.",+ field_unavailable: "Este campo não está disponível.",+ target_missing: "O registro de destino não está visível ou foi removido.",+ target_changed: "A identidade do destino ou a geração do cache mudou.",+ not_collected: "Algumas evidências não foram coletadas ou associadas.",+ incomplete: "Resultados incompletos.",+ failed: "A leitura falhou. Confira o erro antes de tentar novamente.",+ },+ completeness: {+ complete: "Texto completo",+ fragment: "Trecho",+ unknown: "Integridade da origem desconhecida",+ template: "Modelo em cache",+ },+ planBindings: {+ cursor: "Plano do cursor existente. Linhas e custos são estimativas.",+ request: "Plano em cache associado à solicitação original. Linhas e custos são estimativas.",+ same_sql: "Plano em cache para o mesmo SQL, não confirmado para esta execução. Linhas e custos são estimativas.",+ },+ scopes: {+ cursor_cumulative: "Acumulado do cursor",+ plan_cumulative: "Acumulado do cache de planos",+ request: "Solicitação",+ session_sample: "Amostra da sessão",+ execution: "Execução exata",+ current_wait: "Espera atual",+ last_wait: "Espera mais recente",+ session_trace: "Sessão e rastreamento da solicitação",+ request_trace: "Rastreamento da solicitação (ID de sessão não fornecido)",+ },+ units: {+ count: "contagens",+ rows: "linhas",+ blocks: "blocos",+ microseconds: "µs",+ seconds: "segundos",+ },+ metrics: {+ executions: "Execuções",+ rows_processed: "Linhas processadas/devolvidas",+ buffer_gets: "Leituras de buffer",+ disk_reads: "Leituras de disco",+ elapsed: "Tempo decorrido",+ cpu: "Tempo de CPU",+ application_wait: "Espera da aplicação",+ concurrency_wait: "Espera de concorrência",+ cluster_wait: "Espera do cluster",+ user_io_wait: "Espera de E/S do usuário",+ root_output_rows: "Linhas de saída acumuladas do nó raiz",+ execute: "Tempo de execução",+ queue: "Tempo na fila",+ total_wait: "Tempo total de espera",+ },+ columns: {+ metric: "Métrica",+ value: "Valor",+ unit: "Unidade",+ scope: "Escopo",+ source: "Origem",+ waitKind: "Escopo da espera",+ state: "Estado",+ event: "Evento",+ waitClass: "Classe de espera",+ secondsInWait: "SECONDS_IN_WAIT (segundos)",+ blockingInstance: "Instância bloqueadora",+ blockingSession: "Sessão bloqueadora",+ sid: "ID da sessão",+ serial: "Número de série",+ instance: "Instância",+ operation: "Operação",+ target: "Destino",+ sofar: "Trabalho concluído",+ totalWork: "Trabalho total",+ units: "Unidades de trabalho",+ startTime: "Hora de início",+ lastUpdateTime: "Última atualização",+ elapsedSeconds: "Decorrido (segundos)",+ remainingSeconds: "Restante estimado (segundos)",+ message: "Mensagem",+ sqlId: "SQL ID",+ sqlExecId: "ID de execução SQL",+ sqlExecStart: "Início da execução SQL",+ serverIp: "Endereço do nó",+ serverPort: "Porta do nó",+ traceId: "Trace ID",+ progress: "Progresso do trabalho (%)",+ },+ identity: {+ sid: "ID da sessão",+ serial: "Número de série",+ instance: "Instância",+ container: "Contêiner",+ user: "Usuário",+ sqlId: "SQL ID",+ childNumber: "Cursor filho",+ sqlExecId: "ID de execução SQL",+ sqlExecStart: "Início da execução SQL",+ tenant: "Tenant",+ tenantId: "ID do tenant",+ server: "Nó",+ traceId: "Trace ID",+ requestId: "ID da solicitação",+ requestTime: "Horário da solicitação (microssegundos do banco de dados)",+ auditFromMicros: "Início da janela de associação (microssegundos do banco de dados)",+ auditToMicros: "Fim da janela de associação (microssegundos do banco de dados)",+ returnCode: "Código de retorno",+ },+ },processList: {oracleSerial: "Número de série",oracleAuditSession: "ID da sessão de auditoria",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex f12e0782cc..75a84e1138 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -4914,6 +4914,147 @@ export default withEnglishFallback({noAvailable: "Все доступные расширения уже установлены.",noInstalled: "Расширения не установлены.",},+ sessionDiagnostics: {+ open: "Диагностика",+ title: "Диагностика сеанса {id}",+ sampleContext: "Контекст выборки",+ sampleWindow: "Окно выборки (местное время)",+ stale: "Текущее выполнение изменилось или его не удаётся подтвердить. Эти результаты по-прежнему относятся к исходному SQL/запросу.",+ cleanupFailed: "Очистка диагностического подключения не завершена. Собранные данные сохранены.",+ chooseRequest: "Связанный запрос",+ selectRequest: "Выберите точный запрос",+ requestOption: "Запрос {requestId} · выполнение {sqlExecId} · {requestTime} · код возврата {returnCode}",+ choosePlan: "План в кэше",+ selectPlan: "Выберите план в кэше",+ planOption: "План {planId} · {firstLoadTime}",+ previousSample: "Сохранена последняя успешная выборка: {time}",+ incomplete: "Результаты неполные. Проверьте источник и ограничения.",+ copyFragment: "Копировать фрагмент",+ copyText: "Копировать текст",+ waits: "Ожидания и состояние сеанса",+ longOperationsEmpty: "В этой выборке длительные операции не обнаружены.",+ obLongOperations: "Показывает прошедшее и предполагаемое оставшееся время. В этом представлении нет процентов выполнения работы.",+ stop: "Остановить чтение",+ tabs: {+ sql: "SQL",+ plan: "Существующий план",+ statistics: "Статистика и ожидания",+ longOperations: "Длительные операции",+ },+ states: {+ cancelled: "Локальное чтение остановлено. Отмена на сервере не подтверждена.",+ timeout: "Время чтения истекло. Завершённые выборки сохранены.",+ },+ reasons: {+ permission_denied: "Недостаточно прав для этого раздела.",+ view_unavailable: "Представление недоступно или отсутствует; причина не определена.",+ field_unavailable: "Это поле недоступно.",+ target_missing: "Целевая запись не видна или удалена из кэша.",+ target_changed: "Идентификатор цели или поколение кэша изменились.",+ not_collected: "Некоторые данные не собраны или не связаны.",+ incomplete: "Результаты неполные.",+ failed: "Ошибка чтения. Проверьте её перед повторной попыткой.",+ },+ completeness: {+ complete: "Полный текст",+ fragment: "Фрагмент",+ unknown: "Полнота источника неизвестна",+ template: "Шаблон из кэша",+ },+ planBindings: {+ cursor: "План существующего курсора. Число строк и стоимость — оценки.",+ request: "План из кэша, связанный с исходным запросом. Число строк и стоимость — оценки.",+ same_sql: "План из кэша для того же SQL; его применение в этом выполнении не подтверждено. Число строк и стоимость — оценки.",+ },+ scopes: {+ cursor_cumulative: "Накопительно по курсору",+ plan_cumulative: "Накопительно по кэшу планов",+ request: "Запрос",+ session_sample: "Выборка сеанса",+ execution: "Точное выполнение",+ current_wait: "Текущее ожидание",+ last_wait: "Последнее ожидание",+ session_trace: "Сеанс и трассировка запроса",+ request_trace: "Трассировка запроса (ID сеанса не указан)",+ },+ units: {+ count: "количество",+ rows: "строки",+ blocks: "блоки",+ microseconds: "мкс",+ seconds: "секунды",+ },+ metrics: {+ executions: "Выполнения",+ rows_processed: "Обработано/возвращено строк",+ buffer_gets: "Получения из буфера",+ disk_reads: "Чтения с диска",+ elapsed: "Прошедшее время",+ cpu: "Время CPU",+ application_wait: "Ожидание приложения",+ concurrency_wait: "Ожидание конкуренции",+ cluster_wait: "Ожидание кластера",+ user_io_wait: "Ожидание пользовательского ввода-вывода",+ root_output_rows: "Накопительный вывод корневого узла (строки)",+ execute: "Время выполнения",+ queue: "Время в очереди",+ total_wait: "Общее время ожидания",+ },+ columns: {+ metric: "Метрика",+ value: "Значение",+ unit: "Единица",+ scope: "Область",+ source: "Источник",+ waitKind: "Тип ожидания",+ state: "Состояние",+ event: "Событие",+ waitClass: "Класс ожидания",+ secondsInWait: "SECONDS_IN_WAIT (секунды)",+ blockingInstance: "Блокирующий экземпляр",+ blockingSession: "Блокирующий сеанс",+ sid: "ID сеанса",+ serial: "Серийный номер",+ instance: "Экземпляр",+ operation: "Операция",+ target: "Цель",+ sofar: "Выполнено работы",+ totalWork: "Всего работы",+ units: "Единицы работы",+ startTime: "Время начала",+ lastUpdateTime: "Последнее обновление",+ elapsedSeconds: "Прошло (секунды)",+ remainingSeconds: "Осталось, оценка (секунды)",+ message: "Сообщение",+ sqlId: "SQL ID",+ sqlExecId: "ID выполнения SQL",+ sqlExecStart: "Начало выполнения SQL",+ serverIp: "Адрес узла",+ serverPort: "Порт узла",+ traceId: "Trace ID",+ progress: "Прогресс работы (%)",+ },+ identity: {+ sid: "ID сеанса",+ serial: "Серийный номер",+ instance: "Экземпляр",+ container: "Контейнер",+ user: "Пользователь",+ sqlId: "SQL ID",+ childNumber: "Дочерний курсор",+ sqlExecId: "ID выполнения SQL",+ sqlExecStart: "Начало выполнения SQL",+ tenant: "Тенант",+ tenantId: "ID тенанта",+ server: "Узел",+ traceId: "Trace ID",+ requestId: "ID запроса",+ requestTime: "Время запроса (микросекунды базы данных)",+ auditFromMicros: "Начало окна связи (микросекунды базы данных)",+ auditToMicros: "Конец окна связи (микросекунды базы данных)",+ returnCode: "Код возврата",+ },+ },processList: {oracleSerial: "Серийный номер",oracleAuditSession: "ID сеанса аудита",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 5e00133029..57d33838fd 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -5136,6 +5136,147 @@ export default withEnglishFallback({noAvailable: "ติดตั้ง Extensions ที่มีทั้งหมดแล้ว",noInstalled: "ยังไม่มี Extension ติดตั้ง",},+ sessionDiagnostics: {+ open: "วินิจฉัย",+ title: "วินิจฉัย Session {id}",+ sampleContext: "บริบทการ Sampling",+ sampleWindow: "ช่วงเวลา Sampling (เวลาท้องถิ่น)",+ stale: "การทำงานปัจจุบันเปลี่ยนไปหรือยืนยันไม่ได้ ผลลัพธ์นี้ยังคงเป็นของ SQL/Request เดิม",+ cleanupFailed: "ล้างการเชื่อมต่อสำหรับวินิจฉัยไม่เสร็จสมบูรณ์ โดยเก็บหลักฐานที่รวบรวมไว้แล้ว",+ chooseRequest: "Request ที่เชื่อมโยง",+ selectRequest: "เลือก Request ที่แน่นอน",+ requestOption: "Request {requestId} · การทำงาน {sqlExecId} · {requestTime} · Return Code {returnCode}",+ choosePlan: "แผนใน Cache",+ selectPlan: "เลือกแผนใน Cache",+ planOption: "แผน {planId} · {firstLoadTime}",+ previousSample: "เก็บตัวอย่างที่สำเร็จล่าสุดไว้: {time}",+ incomplete: "ผลลัพธ์ไม่สมบูรณ์ โปรดตรวจสอบแหล่งที่มาและข้อจำกัด",+ copyFragment: "คัดลอกส่วนย่อย",+ copyText: "คัดลอกข้อความ",+ waits: "Wait และสถานะ Session",+ longOperationsEmpty: "ไม่พบการทำงานระยะยาวในตัวอย่างนี้",+ obLongOperations: "แสดงเวลาที่ผ่านไปและเวลาที่เหลือโดยประมาณ มุมมองนี้ไม่มีเปอร์เซ็นต์ความคืบหน้าของงาน",+ stop: "หยุดอ่าน",+ tabs: {+ sql: "SQL",+ plan: "แผนที่มีอยู่",+ statistics: "สถิติและ Wait",+ longOperations: "การทำงานระยะยาว",+ },+ states: {+ cancelled: "หยุดอ่านในเครื่องแล้ว ยังไม่ยืนยันการยกเลิกบนเซิร์ฟเวอร์",+ timeout: "อ่านหมดเวลา โดยเก็บตัวอย่างที่เสร็จสมบูรณ์ไว้",+ },+ reasons: {+ permission_denied: "สิทธิ์ไม่เพียงพอสำหรับส่วนนี้",+ view_unavailable: "ไม่สามารถเข้าถึง View หรือไม่มีอยู่ ยังไม่ทราบสาเหตุ",+ field_unavailable: "ไม่มีฟิลด์นี้",+ target_missing: "ไม่พบระเบียนเป้าหมายหรือถูกนำออกแล้ว",+ target_changed: "ข้อมูลประจำตัวเป้าหมายหรือรุ่น Cache เปลี่ยนไป",+ not_collected: "หลักฐานบางส่วนยังไม่ได้รวบรวมหรือเชื่อมโยง",+ incomplete: "ผลลัพธ์ไม่สมบูรณ์",+ failed: "อ่านไม่สำเร็จ โปรดตรวจสอบข้อผิดพลาดก่อนลองอีกครั้ง",+ },+ completeness: {+ complete: "ข้อความทั้งหมด",+ fragment: "ส่วนย่อย",+ unknown: "ไม่ทราบความครบถ้วนของแหล่งที่มา",+ template: "Template ใน Cache",+ },+ planBindings: {+ cursor: "แผน Cursor ที่มีอยู่ จำนวนแถวและค่าใช้จ่ายเป็นค่าประมาณ",+ request: "แผนใน Cache ที่เชื่อมโยงกับ Request เดิม จำนวนแถวและค่าใช้จ่ายเป็นค่าประมาณ",+ same_sql: "แผนใน Cache สำหรับ SQL เดียวกัน แต่ยังยืนยันไม่ได้ว่าใช้กับการทำงานนี้ จำนวนแถวและค่าใช้จ่ายเป็นค่าประมาณ",+ },+ scopes: {+ cursor_cumulative: "ยอดสะสมของ Cursor",+ plan_cumulative: "ยอดสะสมของ Cache แผน",+ request: "Request",+ session_sample: "ตัวอย่าง Session",+ execution: "การทำงานที่แน่นอน",+ current_wait: "Wait ปัจจุบัน",+ last_wait: "Wait ล่าสุด",+ session_trace: "เชื่อมโยงเซสชันและ trace ของคำขอ",+ request_trace: "เชื่อมโยง trace ของคำขอ (ไม่ได้ระบุ ID เซสชัน)",+ },+ units: {+ count: "ครั้ง",+ rows: "แถว",+ blocks: "บล็อก",+ microseconds: "µs",+ seconds: "วินาที",+ },+ metrics: {+ executions: "จำนวนการทำงาน",+ rows_processed: "แถวที่ประมวลผล/ส่งกลับ",+ buffer_gets: "การอ่าน Buffer",+ disk_reads: "การอ่านดิสก์",+ elapsed: "เวลาที่ผ่านไป",+ cpu: "เวลา CPU",+ application_wait: "Application Wait",+ concurrency_wait: "Concurrency Wait",+ cluster_wait: "Cluster Wait",+ user_io_wait: "User I/O Wait",+ root_output_rows: "แถวผลลัพธ์สะสมของ Root Node",+ execute: "เวลาทำงาน",+ queue: "เวลารอคิว",+ total_wait: "เวลารอทั้งหมด",+ },+ columns: {+ metric: "Metric",+ value: "ค่า",+ unit: "หน่วย",+ scope: "Scope",+ source: "แหล่งที่มา",+ waitKind: "ขอบเขต Wait",+ state: "สถานะ",+ event: "Event",+ waitClass: "คลาส Wait",+ secondsInWait: "SECONDS_IN_WAIT (วินาที)",+ blockingInstance: "Instance ที่บล็อก",+ blockingSession: "Session ที่บล็อก",+ sid: "Session ID",+ serial: "Serial Number",+ instance: "Instance",+ operation: "การทำงาน",+ target: "เป้าหมาย",+ sofar: "งานที่เสร็จแล้ว",+ totalWork: "งานทั้งหมด",+ units: "หน่วยงาน",+ startTime: "เวลาเริ่มต้น",+ lastUpdateTime: "อัปเดตล่าสุด",+ elapsedSeconds: "เวลาที่ผ่านไป (วินาที)",+ remainingSeconds: "เวลาเหลือโดยประมาณ (วินาที)",+ message: "ข้อความ",+ sqlId: "SQL ID",+ sqlExecId: "SQL Execution ID",+ sqlExecStart: "เวลาเริ่ม SQL Execution",+ serverIp: "ที่อยู่โหนด",+ serverPort: "พอร์ตโหนด",+ traceId: "Trace ID",+ progress: "ความคืบหน้าของงาน (%)",+ },+ identity: {+ sid: "Session ID",+ serial: "Serial Number",+ instance: "Instance",+ container: "Container",+ user: "ผู้ใช้",+ sqlId: "SQL ID",+ childNumber: "Child Cursor",+ sqlExecId: "SQL Execution ID",+ sqlExecStart: "เวลาเริ่ม SQL Execution",+ tenant: "Tenant",+ tenantId: "Tenant ID",+ server: "โหนด",+ traceId: "Trace ID",+ requestId: "Request ID",+ requestTime: "เวลา Request (ไมโครวินาทีของฐานข้อมูล)",+ auditFromMicros: "จุดเริ่มต้นช่วงเชื่อมโยง (ไมโครวินาทีของฐานข้อมูล)",+ auditToMicros: "จุดสิ้นสุดช่วงเชื่อมโยง (ไมโครวินาทีของฐานข้อมูล)",+ returnCode: "Return Code",+ },+ },processList: {oracleSerial: "หมายเลขซีเรียล",oracleAuditSession: "ID เซสชันตรวจสอบ",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 104d003242..e9c89c7cb2 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -5144,6 +5144,147 @@ export default withEnglishFallback({noAvailable: "所有可用扩展均已安装。",noInstalled: "暂无已安装的扩展。",},+ sessionDiagnostics: {+ open: "诊断",+ title: "会话 {id} 诊断",+ sampleContext: "采样上下文",+ sampleWindow: "采样窗口(本机时间)",+ stale: "当前执行已变化或暂时无法确认,以下仍为原 SQL/请求的采样。",+ cleanupFailed: "诊断连接清理未完成,采样结果已保留。",+ chooseRequest: "关联请求",+ selectRequest: "选择明确请求",+ requestOption: "请求 {requestId} · 执行 {sqlExecId} · {requestTime} · 返回码 {returnCode}",+ choosePlan: "缓存计划",+ selectPlan: "选择缓存计划",+ planOption: "计划 {planId} · {firstLoadTime}",+ previousSample: "保留上次成功采样:{time}",+ incomplete: "结果不完整,请结合来源和限制判断。",+ copyFragment: "复制片段",+ copyText: "复制文本",+ waits: "等待与会话状态",+ longOperationsEmpty: "本次未观察到长操作。",+ obLongOperations: "显示已用时间与预计剩余时间;此视图不提供工作量百分比。",+ stop: "停止读取",+ tabs: {+ sql: "SQL",+ plan: "已有计划",+ statistics: "统计与等待",+ longOperations: "长操作",+ },+ states: {+ cancelled: "已停止本地读取,服务端取消尚未确认。",+ timeout: "读取超时,已保留完成的采样。",+ },+ reasons: {+ permission_denied: "当前区域权限不足。",+ view_unavailable: "视图不可访问或不存在,原因尚未确定。",+ field_unavailable: "当前字段不可用。",+ target_missing: "目标记录当前不可见或已淘汰。",+ target_changed: "目标身份或缓存代际已变化。",+ not_collected: "部分证据尚未采集或未能关联。",+ incomplete: "结果不完整。",+ failed: "读取失败,请查看错误后重试。",+ },+ completeness: {+ complete: "全文",+ fragment: "片段",+ unknown: "来源完整性未知",+ template: "缓存模板",+ },+ planBindings: {+ cursor: "已有游标计划;行数和成本为估算值。",+ request: "已关联原请求的缓存计划;行数和成本为估算值。",+ same_sql: "同 SQL 的缓存计划,未证实用于本次执行;行数和成本为估算值。",+ },+ scopes: {+ cursor_cumulative: "游标累计",+ plan_cumulative: "计划缓存累计",+ request: "请求",+ session_sample: "会话采样",+ execution: "明确执行",+ current_wait: "当前等待",+ last_wait: "最近等待",+ session_trace: "会话及请求 trace 关联",+ request_trace: "请求 trace 关联(未提供会话 ID)",+ },+ units: {+ count: "次",+ rows: "行",+ blocks: "块",+ microseconds: "微秒",+ seconds: "秒",+ },+ metrics: {+ executions: "执行次数",+ rows_processed: "处理/返回行数",+ buffer_gets: "缓冲区获取",+ disk_reads: "磁盘读取",+ elapsed: "总耗时",+ cpu: "CPU 时间",+ application_wait: "应用等待",+ concurrency_wait: "并发等待",+ cluster_wait: "集群等待",+ user_io_wait: "用户 I/O 等待",+ root_output_rows: "根节点累计输出行数",+ execute: "执行耗时",+ queue: "排队耗时",+ total_wait: "总等待时间",+ },+ columns: {+ metric: "指标",+ value: "值",+ unit: "单位",+ scope: "范围",+ source: "来源",+ waitKind: "等待口径",+ state: "状态",+ event: "事件",+ waitClass: "等待类别",+ secondsInWait: "SECONDS_IN_WAIT(秒)",+ blockingInstance: "阻塞实例",+ blockingSession: "阻塞会话",+ sid: "会话 ID",+ serial: "序列号",+ instance: "实例",+ operation: "操作",+ target: "对象",+ sofar: "已完成工作量",+ totalWork: "总工作量",+ units: "工作量单位",+ startTime: "开始时间",+ lastUpdateTime: "最后更新时间",+ elapsedSeconds: "已用时间(秒)",+ remainingSeconds: "预计剩余(秒)",+ message: "消息",+ sqlId: "SQL ID",+ sqlExecId: "SQL 执行 ID",+ sqlExecStart: "SQL 执行开始时间",+ serverIp: "节点地址",+ serverPort: "节点端口",+ traceId: "Trace ID",+ progress: "工作量进度(%)",+ },+ identity: {+ sid: "会话 ID",+ serial: "序列号",+ instance: "实例",+ container: "容器",+ user: "用户",+ sqlId: "SQL ID",+ childNumber: "子游标",+ sqlExecId: "SQL 执行 ID",+ sqlExecStart: "SQL 执行开始时间",+ tenant: "租户",+ tenantId: "租户 ID",+ server: "节点",+ traceId: "Trace ID",+ requestId: "请求 ID",+ requestTime: "请求时间(数据库微秒)",+ auditFromMicros: "关联窗口起点(数据库微秒)",+ auditToMicros: "关联窗口终点(数据库微秒)",+ returnCode: "返回码",+ },+ },processList: {oracleSerial: "序列号",oracleAuditSession: "审计会话 ID",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex a07577c41d..3a67cc7971 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -11137,6 +11137,147 @@ export default withEnglishFallback({sourceStatus: "唯讀控制",sourceDataEditor: "資料編輯器",},+ sessionDiagnostics: {+ open: "診斷",+ title: "工作階段 {id} 診斷",+ sampleContext: "取樣內容",+ sampleWindow: "取樣時段(本機時間)",+ stale: "目前執行已變更或無法確認。這些結果仍屬於原始 SQL/請求。",+ cleanupFailed: "診斷連線清理未完成。已保留收集到的證據。",+ chooseRequest: "關聯請求",+ selectRequest: "選取明確請求",+ requestOption: "請求 {requestId} · 執行 {sqlExecId} · {requestTime} · 回傳碼 {returnCode}",+ choosePlan: "快取計畫",+ selectPlan: "選取快取計畫",+ planOption: "計畫 {planId} · {firstLoadTime}",+ previousSample: "保留上次成功取樣:{time}",+ incomplete: "結果不完整,請依來源和限制判斷。",+ copyFragment: "複製片段",+ copyText: "複製文字",+ waits: "等待與工作階段狀態",+ longOperationsEmpty: "此取樣未觀察到長時間作業。",+ obLongOperations: "顯示已用時間和預估剩餘時間;此檢視不提供工作完成百分比。",+ stop: "停止讀取",+ tabs: {+ sql: "SQL",+ plan: "既有計畫",+ statistics: "統計與等待",+ longOperations: "長時間作業",+ },+ states: {+ cancelled: "已停止本機讀取,尚未確認伺服器取消。",+ timeout: "讀取逾時,已保留完成的取樣。",+ },+ reasons: {+ permission_denied: "此區域的權限不足。",+ view_unavailable: "檢視無法存取或不存在,原因尚未確定。",+ field_unavailable: "此欄位無法使用。",+ target_missing: "目標記錄目前不可見或已淘汰。",+ target_changed: "目標身分或快取世代已變更。",+ not_collected: "部分證據尚未收集或關聯。",+ incomplete: "結果不完整。",+ failed: "讀取失敗,請先查看錯誤再重試。",+ },+ completeness: {+ complete: "完整文字",+ fragment: "片段",+ unknown: "來源完整性未知",+ template: "快取範本",+ },+ planBindings: {+ cursor: "既有游標計畫;資料列數與成本為估算值。",+ request: "關聯至原始請求的快取計畫;資料列數與成本為估算值。",+ same_sql: "相同 SQL 的快取計畫,尚未證實用於此次執行;資料列數與成本為估算值。",+ },+ scopes: {+ cursor_cumulative: "游標累計",+ plan_cumulative: "計畫快取累計",+ request: "請求",+ session_sample: "工作階段取樣",+ execution: "明確執行",+ current_wait: "目前等待",+ last_wait: "最近等待",+ session_trace: "工作階段及請求 trace 關聯",+ request_trace: "請求 trace 關聯(未提供工作階段 ID)",+ },+ units: {+ count: "次",+ rows: "列",+ blocks: "區塊",+ microseconds: "微秒",+ seconds: "秒",+ },+ metrics: {+ executions: "執行次數",+ rows_processed: "已處理/回傳列數",+ buffer_gets: "緩衝區讀取",+ disk_reads: "磁碟讀取",+ elapsed: "經過時間",+ cpu: "CPU 時間",+ application_wait: "應用程式等待",+ concurrency_wait: "並行等待",+ cluster_wait: "叢集等待",+ user_io_wait: "使用者 I/O 等待",+ root_output_rows: "根節點累計輸出列數",+ execute: "執行時間",+ queue: "排隊時間",+ total_wait: "總等待時間",+ },+ columns: {+ metric: "指標",+ value: "值",+ unit: "單位",+ scope: "範圍",+ source: "來源",+ waitKind: "等待範圍",+ state: "狀態",+ event: "事件",+ waitClass: "等待類別",+ secondsInWait: "SECONDS_IN_WAIT(秒)",+ blockingInstance: "阻塞執行個體",+ blockingSession: "阻塞工作階段",+ sid: "工作階段 ID",+ serial: "序號",+ instance: "執行個體",+ operation: "作業",+ target: "目標",+ sofar: "已完成工作量",+ totalWork: "總工作量",+ units: "工作量單位",+ startTime: "開始時間",+ lastUpdateTime: "最後更新",+ elapsedSeconds: "已用時間(秒)",+ remainingSeconds: "預估剩餘時間(秒)",+ message: "訊息",+ sqlId: "SQL_ID",+ sqlExecId: "SQL 執行 ID",+ sqlExecStart: "SQL 執行開始時間",+ serverIp: "節點位址",+ serverPort: "節點連接埠",+ traceId: "Trace ID",+ progress: "工作進度(%)",+ },+ identity: {+ sid: "工作階段 ID",+ serial: "序號",+ instance: "執行個體",+ container: "容器",+ user: "使用者",+ sqlId: "SQL_ID",+ childNumber: "子游標",+ sqlExecId: "SQL 執行 ID",+ sqlExecStart: "SQL 執行開始時間",+ tenant: "租戶",+ tenantId: "租戶 ID",+ server: "節點",+ traceId: "Trace ID",+ requestId: "請求 ID",+ requestTime: "請求時間(資料庫微秒)",+ auditFromMicros: "關聯時段起點(資料庫微秒)",+ auditToMicros: "關聯時段終點(資料庫微秒)",+ returnCode: "回傳碼",+ },+ },processList: {oracleSerial: "序號",oracleAuditSession: "稽核工作階段 ID",diff --git a/apps/desktop/src/lib/dataGrid/largeValueSnapshot.ts b/apps/desktop/src/lib/dataGrid/largeValueSnapshot.tsindex 41f00a4b6e..7795936e9c 100644--- a/apps/desktop/src/lib/dataGrid/largeValueSnapshot.ts+++ b/apps/desktop/src/lib/dataGrid/largeValueSnapshot.ts@@ -23,12 +23,12 @@ export async function waitForLargeValueSnapshot<T>(promise: Promise<T>, signal?:}/** No cache: every request validates the original server locator's lifecycle. */-export async function readLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, consume: (chunk: LargeValueChunk) => Promise<void> | void, signal?: AbortSignal): Promise<void> {+export async function readLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, consume: (chunk: LargeValueChunk) => Promise<void> | void, signal?: AbortSignal, readChunk = api.readLargeValueChunk): Promise<void> {let offset = 0;while (true) {signal?.throwIfAborted();if (!isCurrent()) throw new Error("LOB result context changed");- const chunk = await waitForLargeValueSnapshot(api.readLargeValueChunk({ ...request, offset, limit: 4096 }), signal);+ const chunk = await waitForLargeValueSnapshot(readChunk({ ...request, offset, limit: 4096 }), signal);signal?.throwIfAborted();if (!isCurrent()) throw new Error("LOB result context changed");if (chunk.status !== "ok") throw new Error(`LOB snapshot ${chunk.status}; execute the query again`);@@ -51,7 +51,7 @@ export async function readLargeValueSnapshot(request: LargeValueRequest, isCurre}}-export async function materializeLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, signal?: AbortSignal): Promise<string> {+export async function materializeLargeValueSnapshot(request: LargeValueRequest, isCurrent: () => boolean, signal?: AbortSignal, readChunk = api.readLargeValueChunk): Promise<string> {const chunks: string[] = [];let bytes = 0;let kind: LargeValueChunk["value_kind"] | undefined;@@ -66,6 +66,7 @@ export async function materializeLargeValueSnapshot(request: LargeValueRequest,chunks.push(chunk.data);},signal,+ readChunk,);return (kind === "binary" ? "0x" : "") + chunks.join("");}diff --git a/apps/desktop/src/lib/database/__tests__/oceanbaseSessionDiagnostics.spec.ts b/apps/desktop/src/lib/database/__tests__/oceanbaseSessionDiagnostics.spec.tsnew file mode 100644index 0000000000..8a8f92e0db--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/oceanbaseSessionDiagnostics.spec.ts@@ -0,0 +1,288 @@+import { describe, expect, it, vi } from "vitest";+import type { QueryResult } from "@/types/database";+import { captureOceanbaseDiagnosticTarget, collectOceanbaseSessionDiagnostics, parseOceanbaseCachedPlan } from "../oceanbaseSessionDiagnostics";+import type { SessionDiagnosticsSnapshot } from "../sessionDiagnostics";+import { DiagnosticReadStopped } from "../sessionDiagnosticReader";+import { mapOceanbaseSessions } from "../oracleSessionManagement";++const sqlId = "A".repeat(32),+ traceId = "trace-1";+const session = { id: "9007199254740993", user: "APP'X", tenant: "tenant_a", serverIp: "127.0.0.1", serverPort: "2882", proxySessionId: null };+const live = { SID: session.id, SESSION_USER: session.user, TENANT: session.tenant, SVR_IP: session.serverIp, SVR_PORT: "2882", PROXY_SESSID: null, DB_NAME: "APP", SQL_ID: sqlId, TRACE_ID: traceId, STATE: "ACTIVE", SQL_TEXT: "SELECT 42 FROM DUAL" };+const audit = {+ TENANT_ID: "9007199254740995",+ TENANT_NAME: session.tenant,+ SVR_IP: session.serverIp,+ SVR_PORT: "2882",+ SID: session.id,+ TRACE_ID: traceId,+ SQL_ID: sqlId,+ REQUEST_ID: "9007199254740997",+ REQUEST_TIME: "1792593313123456",+ SQL_EXEC_ID: "9007199254740999",+ PLAN_ID: "9007199254741001",+ RET_CODE: "0",+ EVENT: "db file read",+ WAIT_CLASS: "USER_IO",+ STATE: "WAITED SHORT TIME",+ QUERY_SQL: "SELECT 42 FROM DUAL",+ ELAPSED_TIME: "0",+ RETURN_ROWS: "9007199254741003",+};+const planStat = { TENANT_ID: audit.TENANT_ID, SVR_IP: session.serverIp, SVR_PORT: "2882", PLAN_ID: audit.PLAN_ID, SQL_ID: sqlId, FIRST_LOAD_TIME: "2026-10-21 20:00:00 +08:00", PLAN_HASH: "9007199254741005", EXECUTIONS: "9007199254741007", ELAPSED_TIME: "2000000", APPLICATION_WATI_TIME: "17" };+const planRows = [+ { PLAN_DEPTH: "0", PLAN_LINE_ID: "0", OPERATOR: "PHY_SCALAR_AGGREGATE", NAME: "NULL", ESTIMATED_ROWS: "1", COST: "0", PROPERTY: null },+ { PLAN_DEPTH: "1", PLAN_LINE_ID: "1", OPERATOR: " PHY_TABLE_SCAN", NAME: "T", ESTIMATED_ROWS: "0", COST: "0", PROPERTY: "filter(T.X > 1)" },+];+function result(rows: Record<string, unknown>[], extra: Partial<QueryResult> = {}): QueryResult {+ const columns = rows.length ? Object.keys(rows[0]) : [];+ return { columns, rows: rows.map((row) => columns.map((column) => row[column] as string | number | null)), affected_rows: 0, execution_time_ms: 1, ...extra };+}+function fixture(+ options: {+ audits?: Record<string, unknown>[];+ planAfter?: Record<string, unknown>;+ auditError?: string;+ explainError?: string;+ liveErrorOnCollect?: string;+ changeAfterLongops?: boolean;+ changeBeforeLongops?: boolean;+ longops?: Record<string, unknown>[];+ longopsTruncated?: boolean;+ requireLongopsPredicate?: boolean;+ } = {},+) {+ let liveReads = 0,+ planReads = 0;+ const query = vi.fn(async (sql: string) => {+ if (sql.includes(" AS NOW_US")) return result([{ NOW_US: "1792593313000000" }]);+ if (sql.includes("FROM SYS.GV$OB_PROCESSLIST")) {+ liveReads++;+ if (liveReads > 1 && options.liveErrorOnCollect) throw new Error(options.liveErrorOnCollect);+ return result([{ ...live, ...((options.changeBeforeLongops && liveReads >= 3) || (options.changeAfterLongops && liveReads >= 4) ? { TRACE_ID: "trace-next" } : {}) }]);+ }+ if (sql.includes("FROM SYS.GV$OB_SQL_AUDIT")) {+ if (options.auditError) throw new Error(options.auditError);+ return result(options.audits ?? [audit]);+ }+ if (sql.includes("FROM SYS.GV$OB_SESS_TIME_MODEL")) return result([{ TENANT_ID: audit.TENANT_ID }]);+ if (sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_STAT")) return result([++planReads > 1 && options.planAfter ? options.planAfter : planStat]);+ if (sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_EXPLAIN")) {+ if (options.explainError) throw new Error(options.explainError);+ return result(planRows);+ }+ if (sql.includes("FROM SYS.GV$SESSION_LONGOPS")) {+ if (options.requireLongopsPredicate && !sql.includes(`WHERE (SID=${session.id} OR SID=-1) AND TRACE_ID='${traceId}' AND SVR_IP='${session.serverIp}' AND SVR_PORT=2882`)) return result([]);+ return result(options.longops ?? [], { truncated: options.longopsTruncated });+ }+ throw new Error(`Unexpected diagnostic query: ${sql}`);+ });+ const reader = { query, readCell: vi.fn(async (value: QueryResult, row: number, column: number) => String(value.rows[row]?.[column] ?? "")), stop: vi.fn(), close: vi.fn(), closed: Promise.resolve(), cleanupError: undefined };+ const snapshot: Partial<SessionDiagnosticsSnapshot> = {};+ const publish = (patch: Partial<SessionDiagnosticsSnapshot>) => Object.assign(snapshot, patch);+ return { reader, query, snapshot, publish };+}++describe("OceanBase session-linked diagnostics", () => {+ it("rejects a reused list session before sampling its replacement SQL or trace", async () => {+ const [selected] = mapOceanbaseSessions({ rows: [[session.id, session.user, session.tenant, "host", "APP", "Query", "0", "ACTIVE", "original SQL", null, session.serverIp, session.serverPort, sqlId, "original-trace"]] });+ const f = fixture();+ await expect(captureOceanbaseDiagnosticTarget(selected!, f.reader)).rejects.toThrow("Selected session SQL changed");+ expect(f.reader.readCell).not.toHaveBeenCalled();+ expect(f.query).toHaveBeenCalledOnce();+ });++ it("binds the captured trace to its exact request and cached plan without executing the target", async () => {+ const f = fixture();+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.identity).toMatchObject({ sid: session.id, requestId: audit.REQUEST_ID, tenantId: audit.TENANT_ID, returnCode: "0" });+ expect(f.snapshot.sql).toMatchObject({ state: "ready", data: { completeness: "unknown", text: "SELECT 42 FROM DUAL" } });+ expect(f.snapshot.plan).toMatchObject({ state: "ready", data: { binding: "request", plan: { databaseType: "oceanbase-oracle" } } });+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "elapsed", value: "0", unit: "microseconds", scope: "request" }));+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "executions", value: planStat.EXECUTIONS, scope: "plan_cumulative" }));+ expect(f.snapshot.longOperations).toMatchObject({ state: "empty", reason: "not_collected" });+ const auditSql = f.query.mock.calls.find(([sql]) => sql.includes("FROM SYS.GV$OB_SQL_AUDIT"))?.[0] ?? "";+ expect(auditSql).toContain(`SID=${session.id}`);+ expect(auditSql).toContain("TENANT_NAME='tenant_a'");+ expect(auditSql).toContain(`TRACE_ID='${traceId}'`);+ expect(auditSql).toContain("REQUEST_TIME BETWEEN 1792506913000000 AND 1792593314000000");+ expect(f.query.mock.calls.every(([sql]) => sql.startsWith("SELECT "))).toBe(true);+ expect(f.query.mock.calls.some(([sql]) => sql === live.SQL_TEXT)).toBe(false);+ });++ it("does not automatically choose one of multiple requests, and marks a same-SQL plan as unbound", async () => {+ const f = fixture({ audits: [audit, { ...audit, REQUEST_ID: "9007199254741011" }] });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(target.request).toBeUndefined();+ expect(f.snapshot.requestChoices).toHaveLength(2);+ expect(f.snapshot.plan?.data?.binding).toBe("same_sql");+ expect(f.snapshot.metrics?.data?.every((metric) => metric.scope === "plan_cumulative")).toBe(true);+ });++ it("preserves an audit permission failure beside available cache statistics", async () => {+ const f = fixture({ auditError: "ORA-01031: insufficient privileges" });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan?.state).toBe("ready");+ expect(f.snapshot.metrics).toMatchObject({ state: "ready", reason: "permission_denied", error: expect.stringContaining("ORA-01031") });+ });++ it.each(["ORA-01031: insufficient privileges", "ORA-00942: inaccessible"])("preserves verified cache measurements when plan details fail with %s", async (explainError) => {+ for (const auditError of [undefined, "ORA-01031: audit denied"]) {+ const f = fixture({ explainError, auditError });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan).toMatchObject({ state: "unavailable", source: "SYS.GV$OB_PLAN_CACHE_PLAN_EXPLAIN", error: explainError });+ expect(f.snapshot.metrics).toMatchObject({ state: "ready" });+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "executions", value: planStat.EXECUTIONS, scope: "plan_cumulative" }));+ expect(f.snapshot.metrics?.data?.some((metric) => metric.scope === "request")).toBe(!auditError);+ if (auditError) expect(f.snapshot.metrics?.reason).toBe("permission_denied");+ }+ });++ it("does not publish cache measurements from a changed generation even when plan details failed", async () => {+ const f = fixture({ explainError: "ORA-01031: denied", planAfter: { ...planStat, FIRST_LOAD_TIME: "changed" } });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.snapshot.metrics?.data?.every((metric) => metric.scope === "request")).toBe(true);+ });++ it("keeps a bound original request readable when a later live-session read is unavailable", async () => {+ const f = fixture();+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ const currentQuery = f.reader.query.getMockImplementation()!;+ f.reader.query.mockImplementation(async (sql: string) => {+ if (sql.includes("FROM SYS.GV$OB_PROCESSLIST")) throw new Error("ORA-00942: inaccessible");+ return currentQuery(sql);+ });+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.identity?.requestId).toBe(audit.REQUEST_ID);+ expect(f.snapshot.waits?.state).toBe("ready");+ expect(f.snapshot.stale).toBe(true);+ });++ it("rejects a plan-generation change without replacing request measurements", async () => {+ const f = fixture({ planAfter: { ...planStat, FIRST_LOAD_TIME: "new-generation" } });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.snapshot.metrics?.data?.every((metric) => metric.scope === "request")).toBe(true);+ });++ it("does not attach long-operation results after the session switches trace", async () => {+ const f = fixture({ changeAfterLongops: true });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.stale).toBe(true);+ expect(f.snapshot.longOperations).toMatchObject({ state: "unavailable", reason: "target_changed" });+ });++ it("keeps positive and missing SID tasks separately trace-bound under the same tenant and node", async () => {+ const row = { SID: session.id, TRACE_ID: traceId, SVR_IP: session.serverIp, SVR_PORT: session.serverPort, OPNAME: "create index", TARGET: "table_id=42", ELAPSED_SECONDS: "2", TIME_REMAINING: "3" };+ const f = fixture({ longops: [row, { ...row, SID: "-1" }, { ...row, SID: "-1", TARGET: "table_id=43" }], requireLongopsPredicate: true, longopsTruncated: true });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.longOperations).toMatchObject({ state: "ready", incomplete: true });+ expect(f.snapshot.longOperations?.data?.columns[0]).toBe("SCOPE");+ expect(f.snapshot.longOperations?.data?.rows.map((values) => values.slice(0, 2))).toEqual([+ ["session_trace", session.id],+ ["request_trace", "-1"],+ ["request_trace", "-1"],+ ]);+ const calls = f.query.mock.calls.map(([sql]) => sql);+ const index = calls.findIndex((sql) => sql.includes("FROM SYS.GV$SESSION_LONGOPS"));+ expect(calls[index - 1]).toContain("FROM SYS.GV$OB_PROCESSLIST");+ expect(calls[index + 1]).toContain("FROM SYS.GV$OB_PROCESSLIST");+ });++ it("rejects missing, unrelated or malformed long-operation identities", async () => {+ const row = { SID: "-1", TRACE_ID: traceId, SVR_IP: session.serverIp, SVR_PORT: session.serverPort };+ for (const invalid of [{ SID: "0" }, { SID: null }, { SID: "-2" }, { SID: "21" }, { TRACE_ID: "other" }, { TRACE_ID: null }, { SVR_IP: "other-node" }, { SVR_PORT: "2883" }]) {+ const f = fixture({ longops: [{ ...row, ...invalid }], requireLongopsPredicate: true });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.longOperations).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.snapshot.longOperations?.data).toBeUndefined();+ }+ });++ it("checks the original execution again immediately before reading long operations", async () => {+ const f = fixture({ changeBeforeLongops: true });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.longOperations).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.query.mock.calls.some(([sql]) => sql.includes("FROM SYS.GV$SESSION_LONGOPS"))).toBe(false);+ });++ it("keeps the chosen cache generation fixed across refreshes", async () => {+ const f = fixture();+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ const currentQuery = f.reader.query.getMockImplementation()!;+ f.reader.query.mockImplementation(async (sql: string) => (sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_STAT") ? result([{ ...planStat, FIRST_LOAD_TIME: "new-generation" }]) : currentQuery(sql)));+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(target.plan?.firstLoadTime).toBe(planStat.FIRST_LOAD_TIME);+ expect(f.query.mock.calls.filter(([sql]) => sql.includes("FROM SYS.GV$OB_PLAN_CACHE_PLAN_EXPLAIN"))).toHaveLength(1);+ });++ it("rejects cross-tenant or duplicate request identities rather than choosing a first row", async () => {+ for (const audits of [[{ ...audit, TENANT_NAME: "other_tenant" }], [audit, audit]]) {+ const f = fixture({ audits });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish, { requestKey: JSON.stringify([audit.TENANT_ID, audit.SVR_IP, audit.SVR_PORT, audit.SID, audit.TRACE_ID, audit.SQL_ID, audit.REQUEST_ID, audit.REQUEST_TIME, audit.SQL_EXEC_ID]) });+ expect(target.request).toBeUndefined();+ expect(f.snapshot.metrics?.data?.every((metric) => metric.scope !== "request")).toBe(true);+ }+ });++ it("does not continue with plan or long-operation queries after local cancellation", async () => {+ const f = fixture();+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ const currentQuery = f.reader.query.getMockImplementation()!;+ f.reader.query.mockImplementation(async (sql: string) => {+ if (sql.includes("FROM SYS.GV$OB_SQL_AUDIT")) throw new DiagnosticReadStopped("cancelled");+ return currentQuery(sql);+ });+ await expect(collectOceanbaseSessionDiagnostics(target, f.reader, f.publish)).rejects.toMatchObject({ reason: "cancelled" });+ expect(f.query.mock.calls.some(([sql]) => /FROM SYS.GV\$OB_PLAN_CACHE|FROM SYS.GV\$SESSION_LONGOPS/.test(sql))).toBe(false);+ });++ it("does not query a cache without a unique tenant binding", async () => {+ const f = fixture({ audits: [] });+ const target = await captureOceanbaseDiagnosticTarget(session, f.reader);+ const currentQuery = f.reader.query.getMockImplementation()!;+ f.reader.query.mockImplementation(async (sql: string) => (sql.includes("FROM SYS.GV$OB_SESS_TIME_MODEL") ? result([{ TENANT_ID: "1002" }, { TENANT_ID: "1003" }]) : currentQuery(sql)));+ await collectOceanbaseSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.plan).toMatchObject({ state: "unavailable", reason: "target_missing" });+ expect(f.query.mock.calls.some(([sql]) => sql.includes("FROM SYS.GV$OB_PLAN_CACHE"))).toBe(false);+ });++ it("keeps invalid or truncated tree rows as raw evidence without inventing hierarchy or actual rows", () => {+ const parsed = parseOceanbaseCachedPlan(result(planRows));+ expect(parsed.incomplete).toBe(false);+ expect(parsed.plan.nodes[0]?.children[0]).toMatchObject({ rows: "0", cost: "0", details: ["filter(T.X > 1)"] });+ expect(parseOceanbaseCachedPlan(result([{ ...planRows[0], PLAN_DEPTH: "2" }])).plan.nodes).toEqual([]);+ expect(parseOceanbaseCachedPlan(result(planRows, { truncated: true })).incomplete).toBe(true);+ for (const row of [+ { ...planRows[0], PLAN_LINE_ID: null },+ { ...planRows[1], PLAN_DEPTH: "invalid" },+ ]) {+ const raw = result([row]);+ expect(parseOceanbaseCachedPlan(raw)).toMatchObject({ incomplete: true, plan: { databaseType: "oceanbase-oracle", raw, nodes: [] } });+ }+ });++ it("uses numeric plan-line order after transport stringification", () => {+ const rows = Array.from({ length: 12 }, (_, index) => ({ ...planRows[0], PLAN_LINE_ID: String(index), PLAN_DEPTH: index === 0 ? "0" : index === 1 ? "1" : index === 11 ? "3" : "2" }));+ rows.sort((left, right) => left.PLAN_LINE_ID.localeCompare(right.PLAN_LINE_ID));+ const parsed = parseOceanbaseCachedPlan(result(rows));+ expect(parsed.incomplete).toBe(false);+ expect(parsed.plan.nodes[0]?.children[0]?.children.map((node) => node.id)).toEqual(["2", "3", "4", "5", "6", "7", "8", "9", "10"]);+ expect(parsed.plan.nodes[0]?.children[0]?.children.at(-1)?.children[0]?.id).toBe("11");+ });+});diff --git a/apps/desktop/src/lib/database/__tests__/oracleSessionDiagnostics.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleSessionDiagnostics.spec.tsnew file mode 100644index 0000000000..200b8c9b60--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/oracleSessionDiagnostics.spec.ts@@ -0,0 +1,207 @@+import { describe, expect, it, vi } from "vitest";+import type { QueryResult } from "@/types/database";+import { captureOracleDiagnosticTarget, collectOracleSessionDiagnostics, oracleLongOperationProgress, parseOracleCachedPlan } from "../oracleSessionDiagnostics";+import type { SessionDiagnosticsSnapshot } from "../sessionDiagnostics";++const sqlId = "0123456789abc";+const session = { id: "17", serial: "8", instance: "2", container: "3", user: "APP'X", auditSession: "9007199254740993", logonTime: "2026-10-21 10:00:00" };+const live = { SQL_ID: sqlId, CHILD_NUMBER: "1", SQL_EXEC_ID: "9007199254740995", SQL_EXEC_START: "2026-10-21T20:00:00", EVENT: "db file sequential read", WAIT_CLASS: "User I/O", STATE: "WAITING", SECONDS_IN_WAIT: "0", BLOCKING_INSTANCE: null, BLOCKING_SESSION: null };+const sqlText = "SELECT '中文😀' FROM DUAL";+const cursor = {+ SQL_ID: sqlId,+ CHILD_NUMBER: "1",+ CHILD_ADDRESS: "000000001234ABCD",+ FIRST_LOAD_TIME: "2026-10-21/19:50:00",+ PLAN_HASH: "9007199254740997",+ EXECUTIONS: "9007199254740999",+ ROWS_PROCESSED: "3",+ BUFFER_GETS: "0",+ DISK_READS: "0",+ ELAPSED_TIME: "1000",+ CPU_TIME: "400",+ USERS_EXECUTING: "2",+ SQL_TEXT: sqlText,+ SOURCE_LENGTH: String(sqlText.length),+};+const planRows = [+ { ID: "0", PARENT_ID: null, OPERATION: "SELECT STATEMENT", OPTIONS: null, OBJECT_OWNER: null, OBJECT_NAME: null, OBJECT_TYPE: null, COST: "2", ESTIMATED_ROWS: "100", ACCESS_PREDICATES: null, FILTER_PREDICATES: null },+ { ID: "1", PARENT_ID: "0", OPERATION: "TABLE ACCESS", OPTIONS: "FULL", OBJECT_OWNER: "APP", OBJECT_NAME: "T", OBJECT_TYPE: "TABLE", COST: "2", ESTIMATED_ROWS: "100", ACCESS_PREDICATES: null, FILTER_PREDICATES: '"T"."X">1' },+];+const longop = {+ SID: "17",+ SERIAL_NUMBER: "8",+ INSTANCE_ID: "2",+ OPNAME: "Table Scan",+ TARGET: "APP.T",+ SOFAR: "9007199254740999",+ TOTALWORK: "18014398509481998",+ UNITS: "Blocks",+ START_TIME: "2026-10-21T20:00:00",+ LAST_UPDATE_TIME: "2026-10-21T20:01:00",+ ELAPSED_SECONDS: "60",+ TIME_REMAINING: "60",+ MESSAGE: "fixture",+ SQL_ID: sqlId,+ SQL_EXEC_ID: live.SQL_EXEC_ID,+ SQL_EXEC_START: live.SQL_EXEC_START,+};+function result(rows: Record<string, unknown>[], extra: Partial<QueryResult> = {}): QueryResult {+ const columns = rows.length ? Object.keys(rows[0]) : [];+ return { columns, rows: rows.map((row) => columns.map((column) => row[column] as string | null)), affected_rows: 0, execution_time_ms: 1, ...extra };+}+function fixture(options: { rowError?: string; cursorError?: string; planError?: string; changedCursor?: boolean; sqlLength?: string; notCollected?: boolean; idle?: boolean; sqlSwitched?: boolean } = {}) {+ let sessionReads = 0,+ cursorReads = 0;+ const query = vi.fn(async (sql: string) => {+ if (sql.includes("PRODUCT_COMPONENT_VERSION")) return result([{ VERSION: "11.2.0.4.0" }]);+ if (sql.includes("FROM GV$SESSION_LONGOPS")) return result([longop]);+ if (sql.includes("FROM GV$SQL_PLAN_STATISTICS_ALL")) {+ if (options.rowError) throw new Error(options.rowError);+ return result([{ STARTS: options.notCollected ? "0" : "2", OUTPUT_ROWS: "9" }]);+ }+ if (sql.includes("FROM GV$SQL_PLAN p")) {+ if (options.planError) throw new Error(options.planError);+ return result(planRows);+ }+ if (sql.includes("FROM GV$SESSION s")) {+ sessionReads++;+ return result([{ ...live, ...(options.idle ? { SQL_ID: null, CHILD_NUMBER: null, SQL_EXEC_ID: null, SQL_EXEC_START: null } : {}), ...(options.sqlSwitched && sessionReads > 1 ? { SQL_ID: "fedcba9876543" } : {}) }]);+ }+ if (sql.includes("FROM GV$SQL s")) {+ cursorReads++;+ if (options.cursorError) throw new Error(options.cursorError);+ return result([{ ...cursor, ...(options.changedCursor && cursorReads > 2 ? { FIRST_LOAD_TIME: "new-generation" } : {}), ...(options.sqlLength ? { SOURCE_LENGTH: options.sqlLength } : {}) }]);+ }+ throw new Error(`Unexpected diagnostic query: ${sql}`);+ });+ const reader = { query, readCell: vi.fn(async (value: QueryResult, row: number, column: number) => String(value.rows[row]?.[column] ?? "")), stop: vi.fn(), close: vi.fn(), closed: Promise.resolve(), cleanupError: undefined };+ const snapshot: Partial<SessionDiagnosticsSnapshot> = {};+ return { reader, query, snapshot, publish: (patch: Partial<SessionDiagnosticsSnapshot>) => Object.assign(snapshot, patch) };+}++describe("Oracle session-linked diagnostics", () => {+ it("does not attach a new SQL to an idle row selected before that SQL began", async () => {+ const f = fixture();+ await expect(captureOracleDiagnosticTarget({ ...session, sqlId: "" }, 19, f.reader)).rejects.toThrow("Selected session SQL changed");+ expect(f.query).toHaveBeenCalledOnce();+ });++ it("keeps RAC/container/child identity and separates estimated rows from real cumulative counters", async () => {+ const f = fixture();+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.sql).toMatchObject({ state: "ready", data: { text: sqlText, completeness: "complete" } });+ expect(f.snapshot.identity).toMatchObject({ instance: "2", container: "3", childNumber: "1", sqlExecId: live.SQL_EXEC_ID });+ expect(f.snapshot.plan?.data?.plan.nodes[0]?.rows).toBe("100");+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "executions", value: cursor.EXECUTIONS, scope: "cursor_cumulative" }));+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "root_output_rows", value: "9", scope: "cursor_cumulative" }));+ const query = f.query.mock.calls.find(([sql]) => sql.includes("FROM GV$SQL_PLAN p"))?.[0] ?? "";+ expect(query).toContain("p.INST_ID=2 AND p.CON_ID=3");+ expect(query).toContain("p.CHILD_NUMBER=1");+ expect(query).toContain("RAWTOHEX(p.CHILD_ADDRESS)='000000001234ABCD'");+ expect(f.query.mock.calls.some(([sql]) => /USERS_EXECUTING\s*=\s*0|DISPLAY_CURSOR|EXPLAIN PLAN FOR/.test(sql))).toBe(false);+ });++ it("keeps Oracle 11g queries free of container columns and safely scopes full session identity", async () => {+ const f = fixture();+ const target = await captureOracleDiagnosticTarget({ ...session, container: "0" }, undefined, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(target.legacy).toBe(true);+ expect(f.query.mock.calls.every(([sql]) => !sql.includes("CON_ID"))).toBe(true);+ const query = f.query.mock.calls.find(([sql]) => sql.includes("FROM GV$SESSION s"))?.[0] ?? "";+ expect(query).toContain(`s.AUDSID=${session.auditSession}`);+ expect(query).toContain("s.USERNAME='APP''X'");+ expect(query).toContain("s.SERIAL#=8 AND s.INST_ID=2");+ });++ it("does not relabel a length-mismatched SQL prefix as complete", async () => {+ const f = fixture({ sqlLength: "999999" });+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.sql).toMatchObject({ state: "ready", incomplete: true, data: { completeness: "fragment" } });+ expect(f.snapshot.metrics?.state).toBe("ready");+ });++ it("keeps counters available when SQL snapshot materialization fails", async () => {+ const f = fixture();+ f.reader.readCell.mockRejectedValue(new Error("LOB snapshot expired"));+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.sql).toMatchObject({ incomplete: true, error: expect.stringContaining("expired"), data: { completeness: "fragment" } });+ expect(f.snapshot.metrics?.state).toBe("ready");+ });++ it("retains ordinary cursor counters beside a row-source permission failure", async () => {+ const f = fixture({ rowError: "ORA-01031: insufficient privileges" });+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.metrics).toMatchObject({ state: "ready", reason: "permission_denied", error: expect.stringContaining("ORA-01031") });+ expect(f.snapshot.metrics?.data?.length).toBe(10);+ });++ it("does not replace uncollected root output rows with optimizer cardinality", async () => {+ const f = fixture({ notCollected: true });+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.metrics?.data).toContainEqual(expect.objectContaining({ name: "root_output_rows", value: null }));+ expect(f.snapshot.metrics?.reason).toBe("not_collected");+ });++ it("rejects a replacement cursor generation while keeping independent session waits", async () => {+ const f = fixture({ changedCursor: true });+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.sql).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.snapshot.metrics).toMatchObject({ state: "unavailable", reason: "target_changed" });+ expect(f.snapshot.waits?.state).toBe("ready");+ });++ it("keeps the original cursor readable after the session moves to another SQL", async () => {+ const f = fixture({ sqlSwitched: true });+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.stale).toBe(true);+ expect(f.snapshot.sql?.data?.text).toBe(sqlText);+ expect(f.snapshot.plan?.data?.binding).toBe("cursor");+ expect(f.snapshot.waits?.reason).toBe("target_changed");+ expect(f.query.mock.calls.some(([sql]) => sql.includes("FROM GV$SESSION_LONGOPS"))).toBe(false);+ });++ it("labels long operations as execution-bound only with the complete execution identity", async () => {+ const f = fixture();+ const target = await captureOracleDiagnosticTarget(session, 19, f.reader);+ await collectOracleSessionDiagnostics(target, f.reader, f.publish);+ expect(f.snapshot.longOperations?.data?.rows[0]?.[0]).toBe("execution");+ expect(f.snapshot.longOperations?.data?.rows[0]?.at(-1)).toBe("50");+ const g = fixture({ idle: true });+ const idle = await captureOracleDiagnosticTarget(session, 19, g.reader);+ await collectOracleSessionDiagnostics(idle, g.reader, g.publish);+ expect(g.snapshot.sql?.reason).toBe("not_collected");+ expect(g.snapshot.longOperations?.data?.rows[0]?.[0]).toBe("session_sample");+ expect(g.query.mock.calls.some(([sql]) => sql.includes("PREV_SQL_ID"))).toBe(false);+ });++ it("uses progress units conservatively and keeps big counters out of floating-point arithmetic", () => {+ expect(oracleLongOperationProgress("1", "3", "Rows")).toBe("33.3");+ expect(oracleLongOperationProgress("9007199254740999", "18014398509481998", "Blocks")).toBe("50");+ expect(oracleLongOperationProgress("100", "0", "Blocks")).toBeNull();+ expect(oracleLongOperationProgress("10", "20", "")).toBeNull();+ expect(oracleLongOperationProgress("1.5", "20", "Blocks")).toBeNull();+ });++ it("keeps malformed or disconnected plans as raw Oracle evidence", () => {+ expect(parseOracleCachedPlan(result(planRows)).plan.nodes[0]?.children[0]?.relation).toBe("APP.T");+ expect(parseOracleCachedPlan(result([{ ...planRows[1], PARENT_ID: "99" }])).incomplete).toBe(true);+ expect(parseOracleCachedPlan(result([planRows[0], { ...planRows[1], PARENT_ID: "1" }])).plan.nodes).toEqual([]);+ expect(parseOracleCachedPlan(result(planRows, { has_more: true })).plan.databaseType).toBe("oracle");+ expect(parseOracleCachedPlan(result(planRows, { has_more: true })).plan.nodes).toEqual([]);+ expect(parseOracleCachedPlan(result([]))).toMatchObject({ incomplete: false, plan: { databaseType: "oracle", nodes: [] } });+ for (const row of [+ { ...planRows[0], ID: null },+ { ...planRows[1], PARENT_ID: "invalid" },+ ]) {+ const raw = result([row]);+ expect(parseOracleCachedPlan(raw)).toMatchObject({ incomplete: true, plan: { databaseType: "oracle", raw, nodes: [] } });+ }+ });+});diff --git a/apps/desktop/src/lib/database/__tests__/sessionDiagnosticReader.spec.ts b/apps/desktop/src/lib/database/__tests__/sessionDiagnosticReader.spec.tsnew file mode 100644index 0000000000..b1e61e68a1--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/sessionDiagnosticReader.spec.ts@@ -0,0 +1,117 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { QueryResult } from "@/types/database";+import { createSessionDiagnosticReader } from "../sessionDiagnosticReader";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+const result = (rows: QueryResult["rows"] = [["value"]]): QueryResult => ({ columns: ["VALUE"], rows, affected_rows: 0, execution_time_ms: 1 });+function backend() {+ return {+ executeQuery: vi.fn().mockResolvedValue(result()),+ cancelQuery: vi.fn().mockResolvedValue(true),+ closeClientConnectionSession: vi.fn().mockResolvedValue(true),+ readLargeValueChunk: vi.fn(),+ };+}+afterEach(() => vi.useRealTimers());++describe("isolated session diagnostic reads", () => {+ it("uses a dedicated session and a unique execution id for every dictionary read", async () => {+ const api = backend();+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ await reader.query("SELECT 1 FROM DUAL", 2);+ await reader.query("SELECT 2 FROM DUAL", 4);+ const [first, second] = api.executeQuery.mock.calls;+ expect(first?.slice(0, 4)).toEqual(["ob", "APP", "SELECT 1 FROM DUAL", undefined]);+ expect(first?.[4]).not.toBe(second?.[4]);+ expect(first?.[5]).toMatchObject({ clientSessionId: expect.stringMatching(/^session-diagnostics:/), maxRows: 2, timeoutSecs: 10 });+ expect(second?.[5].clientSessionId).toBe(first?.[5].clientSessionId);+ reader.close();+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledOnce());+ });++ it("stops local waiting even if query and cancellation never return, then cleans up only after transport ends", async () => {+ const api = backend();+ const pending = deferred<QueryResult>();+ api.executeQuery.mockReturnValue(pending.promise);+ api.cancelQuery.mockReturnValue(new Promise(() => {}));+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ const reading = reader.query("SELECT 1 FROM DUAL");+ const stopped = expect(reading).rejects.toMatchObject({ reason: "cancelled" });+ reader.stop();+ await stopped;+ expect(api.cancelQuery).toHaveBeenCalledWith(api.executeQuery.mock.calls[0]?.[4]);+ expect(api.closeClientConnectionSession).not.toHaveBeenCalled();+ await expect(reader.query("SELECT 2 FROM DUAL")).rejects.toMatchObject({ reason: "cancelled" });+ expect(api.executeQuery).toHaveBeenCalledOnce();+ pending.resolve(result());+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledOnce());+ });++ it("ends a stalled read on its bounded timeout without waiting for server cancellation", async () => {+ vi.useFakeTimers();+ const api = backend();+ api.executeQuery.mockReturnValue(new Promise(() => {}));+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ const reading = expect(reader.query("SELECT 1 FROM DUAL")).rejects.toMatchObject({ reason: "timeout" });+ await vi.advanceTimersByTimeAsync(10_000);+ await reading;+ expect(api.cancelQuery).toHaveBeenCalledOnce();+ expect(api.closeClientConnectionSession).not.toHaveBeenCalled();+ });++ it("rejects backend execution errors and preserves collection completeness flags", async () => {+ const api = backend();+ api.executeQuery.mockResolvedValueOnce({ ...result(), execution_error: true, error: { message: "ORA-01031: insufficient privileges" } });+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ await expect(reader.query("SELECT 1 FROM DUAL")).rejects.toThrow("ORA-01031");+ api.executeQuery.mockResolvedValueOnce({ ...result(), truncated: true, has_more: true });+ expect(await reader.query("SELECT 2 FROM DUAL")).toMatchObject({ truncated: true, has_more: true });+ reader.close();+ });++ it("passes the chunk cancellation id and retains the dedicated session until the actual chunk transport finishes", async () => {+ const api = backend();+ const chunk = deferred<any>();+ api.readLargeValueChunk.mockReturnValue(chunk.promise);+ api.executeQuery.mockResolvedValueOnce({ ...result([["preview"]]), large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 100, value_ref: "sql-ref" }] });+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ const value = await reader.query("SELECT SQL_FULLTEXT FROM GV$SQL");+ const clientSessionId = api.executeQuery.mock.calls[0]?.[5].clientSessionId;+ const reading = reader.readCell(value, 0, 0);+ const stopped = expect(reading).rejects.toMatchObject({ reason: "cancelled" });+ reader.stop();+ await stopped;+ const request = api.readLargeValueChunk.mock.calls[0]?.[0];+ expect(request).toMatchObject({ clientSessionId, valueRef: "sql-ref", offset: 0, executionId: expect.any(String) });+ expect(api.cancelQuery).toHaveBeenCalledWith(request.executionId);+ expect(api.closeClientConnectionSession).not.toHaveBeenCalled();+ chunk.resolve({ status: "ok", data: "完整😀", next_offset: 3, eof: true, value_kind: "text" });+ await vi.waitFor(() => expect(api.closeClientConnectionSession).toHaveBeenCalledOnce());+ expect(value.rows).toEqual([["preview"]]);+ });++ it("materializes the original text and refuses missing or foreign snapshot references", async () => {+ const api = backend();+ api.readLargeValueChunk.mockResolvedValue({ status: "ok", data: "完整😀", next_offset: 3, eof: true, value_kind: "text" });+ api.executeQuery.mockResolvedValueOnce({ ...result([["preview"]]), large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 100, value_ref: "sql-ref" }] });+ const reader = createSessionDiagnosticReader({ connectionId: "ob", database: "APP" }, api);+ const value = await reader.query("SELECT SQL_FULLTEXT FROM GV$SQL");+ const clientSessionId = api.executeQuery.mock.calls[0]?.[5].clientSessionId;+ expect(value.large_value_context).toEqual({ connectionId: "ob", database: "APP", clientSessionId });+ expect(await reader.readCell(value, 0, 0)).toBe("完整😀");+ api.readLargeValueChunk.mockResolvedValueOnce({ status: "expired" });+ await expect(reader.readCell(value, 0, 0)).rejects.toThrow("refresh diagnostics");+ expect(api.executeQuery).toHaveBeenCalledOnce();+ await expect(reader.readCell({ ...value, large_value_context: { connectionId: "ob", database: "APP", clientSessionId: "editor" } }, 0, 0)).rejects.toThrow("context");+ await expect(reader.readCell({ ...value, large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 100 }] }, 0, 0)).rejects.toThrow("reference");+ reader.close();+ });+});diff --git a/apps/desktop/src/lib/database/oceanbaseSessionDiagnostics.ts b/apps/desktop/src/lib/database/oceanbaseSessionDiagnostics.tsnew file mode 100644index 0000000000..ad51135786--- /dev/null+++ b/apps/desktop/src/lib/database/oceanbaseSessionDiagnostics.ts@@ -0,0 +1,465 @@+import type { ExplainPlanNode, ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import type { QueryResult } from "@/types/database";+import type { ProcessRow } from "./processListDrivers";+import { DiagnosticReadStopped, type SessionDiagnosticReader } from "./sessionDiagnosticReader";+import {+ diagnosticFailure,+ diagnosticInteger,+ diagnosticLiteral,+ diagnosticResultComplete,+ diagnosticRows,+ diagnosticSection,+ diagnosticString,+ diagnosticUnavailable,+ type DiagnosticChoice,+ type DiagnosticMetric,+ type DiagnosticPlan,+ type DiagnosticPublish,+ type DiagnosticSection,+ type DiagnosticSelection,+ type DiagnosticSql,+} from "./sessionDiagnostics";++const PROCESS_SOURCE = "SYS.GV$OB_PROCESSLIST";+const AUDIT_SOURCE = "SYS.GV$OB_SQL_AUDIT";+const PLAN_SOURCE = "SYS.GV$OB_PLAN_CACHE_PLAN_STAT";+const EXPLAIN_SOURCE = "SYS.GV$OB_PLAN_CACHE_PLAN_EXPLAIN";+const LONGOPS_SOURCE = "SYS.GV$SESSION_LONGOPS";+const CLOCK_SQL = "SELECT TO_CHAR(ROUND((CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE)-DATE '1970-01-01')*86400)*1000000) AS NOW_US FROM SYS.DUAL";+const DAY_US = 86_400_000_000n;+type Row = ReturnType<typeof diagnosticRows>[number];++interface AuditIdentity {+ tenantId: string;+ serverIp: string;+ serverPort: string;+ sid: string;+ traceId: string;+ sqlId: string;+ requestId: string;+ requestTime: string;+ sqlExecId: string;+ planId: string;+}+interface PlanIdentity {+ tenantId: string;+ serverIp: string;+ serverPort: string;+ planId: string;+ sqlId: string;+ firstLoadTime: string;+ planHash: string;+}+export interface OceanbaseDiagnosticTarget {+ engine: "oceanbase-oracle";+ session: ProcessRow;+ sqlId: string;+ traceId: string;+ database: string;+ info: string;+ infoError?: string;+ tenantId?: string;+ fromMicros: string;+ toMicros?: string;+ request?: AuditIdentity;+ plan?: PlanIdentity;+ sql?: DiagnosticSection<DiagnosticSql>;+}++function sessionWhere(row: ProcessRow): string {+ const sid = diagnosticInteger(row.id);+ const port = diagnosticInteger(row.serverPort);+ const user = diagnosticString(row.user),+ tenant = diagnosticString(row.tenant),+ server = diagnosticString(row.serverIp);+ if (!user || !tenant || !server) throw new Error("Incomplete OceanBase session identity");+ const proxy = row.proxySessionId === null || row.proxySessionId === undefined || row.proxySessionId === "" ? "IS NULL" : `= ${diagnosticInteger(row.proxySessionId)}`;+ return `ID=${sid} AND "USER"=${diagnosticLiteral(user)} AND TENANT=${diagnosticLiteral(tenant)} AND SVR_IP=${diagnosticLiteral(server)} AND SVR_PORT=${port} AND PROXY_SESSID ${proxy}`;+}++async function liveSession(target: ProcessRow, reader: SessionDiagnosticReader) {+ const result = await reader.query(+ `SELECT TO_CHAR(ID) AS SID,"USER" AS SESSION_USER,TENANT,SVR_IP,TO_CHAR(SVR_PORT) AS SVR_PORT,TO_CHAR(PROXY_SESSID) AS PROXY_SESSID,DB AS DB_NAME,SQL_ID,TRACE_ID,STATE,INFO AS SQL_TEXT FROM ${PROCESS_SOURCE} WHERE ${sessionWhere(target)} AND TENANT=(SELECT TENANT FROM SYS.GV$OB_SESSION WHERE ID=SYS_CONTEXT('USERENV','SID') AND "USER"=SYS_CONTEXT('USERENV','SESSION_USER') AND ROWNUM=1)`,+ 2,+ );+ const rows = diagnosticRows(result);+ return { result, row: rows.length === 1 && diagnosticResultComplete(result) ? rows[0] : null };+}++function sameSql(target: OceanbaseDiagnosticTarget, row: Row | null): boolean {+ return !!row && diagnosticString(row.SQL_ID) === target.sqlId && diagnosticString(row.TRACE_ID) === target.traceId;+}++async function databaseMicros(reader: SessionDiagnosticReader): Promise<bigint> {+ const result = await reader.query(CLOCK_SQL, 2);+ const rows = diagnosticRows(result);+ if (rows.length !== 1 || !diagnosticResultComplete(result)) throw new Error("Database clock unavailable");+ return BigInt(diagnosticInteger(rows[0].NOW_US));+}++export async function captureOceanbaseDiagnosticTarget(row: ProcessRow, reader: SessionDiagnosticReader): Promise<OceanbaseDiagnosticTarget> {+ const session = { ...row };+ const observed = await liveSession(session, reader);+ if (!observed.row) throw new Error("Selected session identity changed; refresh the session list");+ const current = observed.row;+ const sqlId = diagnosticString(current.SQL_ID),+ traceId = diagnosticString(current.TRACE_ID);+ if (sqlId && !/^[a-fA-F0-9]{32}$/.test(sqlId)) throw new Error("Invalid OceanBase SQL identity");+ if (traceId && !/^[A-Za-z0-9_:-]{1,128}$/.test(traceId)) throw new Error("Invalid OceanBase trace identity");+ if ((row.sqlId !== undefined && diagnosticString(row.sqlId) !== sqlId) || (row.traceId !== undefined && diagnosticString(row.traceId) !== traceId)) throw new Error("Selected session SQL changed; refresh the session list");+ const index = observed.result.columns.findIndex((column) => column.toUpperCase() === "SQL_TEXT");+ let info = diagnosticString(current.SQL_TEXT),+ infoError: string | undefined;+ if (index >= 0) {+ try {+ info = await reader.readCell(observed.result, 0, index);+ } catch (error) {+ if (error instanceof DiagnosticReadStopped) throw error;+ infoError = error instanceof Error ? error.message : String(error);+ }+ }+ const now = sqlId && traceId ? await databaseMicros(reader) : 0n;+ return { engine: "oceanbase-oracle", session, sqlId, traceId, database: diagnosticString(current.DB_NAME), info, infoError, fromMicros: (now > DAY_US ? now - DAY_US : 0n).toString() };+}++function auditIdentity(row: Row): AuditIdentity {+ return {+ tenantId: diagnosticInteger(row.TENANT_ID),+ serverIp: diagnosticString(row.SVR_IP),+ serverPort: diagnosticInteger(row.SVR_PORT),+ sid: diagnosticInteger(row.SID),+ traceId: diagnosticString(row.TRACE_ID),+ sqlId: diagnosticString(row.SQL_ID),+ requestId: diagnosticInteger(row.REQUEST_ID),+ requestTime: diagnosticInteger(row.REQUEST_TIME),+ sqlExecId: diagnosticInteger(row.SQL_EXEC_ID),+ planId: diagnosticInteger(row.PLAN_ID),+ };+}+function auditKey(row: AuditIdentity): string {+ return JSON.stringify([row.tenantId, row.serverIp, row.serverPort, row.sid, row.traceId, row.sqlId, row.requestId, row.requestTime, row.sqlExecId]);+}+function nodeWhere(target: OceanbaseDiagnosticTarget): string {+ return `SVR_IP=${diagnosticLiteral(diagnosticString(target.session.serverIp))} AND SVR_PORT=${diagnosticInteger(target.session.serverPort)}`;+}+function auditWhere(target: OceanbaseDiagnosticTarget, bound?: AuditIdentity): string {+ const base = `TENANT_NAME=${diagnosticLiteral(diagnosticString(target.session.tenant))} AND ${nodeWhere(target)} AND SID=${diagnosticInteger(target.session.id)} AND TRACE_ID=${diagnosticLiteral(target.traceId)} AND SQL_ID=${diagnosticLiteral(target.sqlId)} AND IS_INNER_SQL=0 AND IS_EXECUTOR_RPC=0`;+ if (bound) return `${base} AND TENANT_ID=${bound.tenantId} AND REQUEST_ID=${bound.requestId} AND REQUEST_TIME=${bound.requestTime} AND SQL_EXEC_ID=${bound.sqlExecId}`;+ return base + (target.tenantId ? ` AND TENANT_ID=${target.tenantId}` : "");+}+const AUDIT_COLUMNS =+ "TO_CHAR(TENANT_ID) AS TENANT_ID,TENANT_NAME,SVR_IP,TO_CHAR(SVR_PORT) AS SVR_PORT,TO_CHAR(SID) AS SID,TRACE_ID,SQL_ID,TO_CHAR(REQUEST_ID) AS REQUEST_ID,TO_CHAR(REQUEST_TIME) AS REQUEST_TIME,TO_CHAR(SQL_EXEC_ID) AS SQL_EXEC_ID,TO_CHAR(PLAN_ID) AS PLAN_ID,TO_CHAR(RET_CODE) AS RET_CODE,EVENT,WAIT_CLASS,STATE,QUERY_SQL";+const REQUEST_METRICS = [+ ["elapsed", "ELAPSED_TIME", "microseconds"],+ ["execute", "EXECUTE_TIME", "microseconds"],+ ["queue", "QUEUE_TIME", "microseconds"],+ ["total_wait", "TOTAL_WAIT_TIME_MICRO", "microseconds"],+ ["application_wait", "APPLICATION_WAIT_TIME", "microseconds"],+ ["concurrency_wait", "CONCURRENCY_WAIT_TIME", "microseconds"],+ ["user_io_wait", "USER_IO_WAIT_TIME", "microseconds"],+ ["rows_processed", "RETURN_ROWS", "rows"],+ ["disk_reads", "DISK_READS", "count"],+] as const;+const PLAN_METRICS = [+ ["executions", "EXECUTIONS", "count"],+ ["rows_processed", "ROWS_PROCESSED", "rows"],+ ["buffer_gets", "BUFFERS_GETS", "count"],+ ["disk_reads", "DISK_READS", "count"],+ ["elapsed", "ELAPSED_TIME", "microseconds"],+ ["cpu", "CPU_TIME", "microseconds"],+ ["application_wait", "APPLICATION_WATI_TIME", "microseconds"],+ ["concurrency_wait", "CONCURRENCY_WAIT_TIME", "microseconds"],+ ["user_io_wait", "USER_IO_WAIT_TIME", "microseconds"],+] as const;+function metricColumns(definitions: readonly (readonly [string, string, string])[]): string {+ return definitions.map(([, column]) => `TO_CHAR(${column}) AS ${column}`).join(",");+}+function metrics(row: Row, definitions: readonly (readonly [string, string, DiagnosticMetric["unit"]])[], source: string, scope: DiagnosticMetric["scope"]): DiagnosticMetric[] {+ return definitions.map(([name, column, unit]) => ({ name, value: typeof row[column] === "string" && /^\d+(?:\.\d+)?$/.test(row[column]) ? row[column] : null, unit, scope, source: `${source}.${column}` }));+}++async function readAudit(target: OceanbaseDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish, selection: DiagnosticSelection): Promise<{ row: Row | null; issue?: DiagnosticSection<DiagnosticMetric[]> }> {+ const bound = selection.requestKey && target.request && selection.requestKey !== auditKey(target.request) ? undefined : target.request;+ let window = "";+ if (!bound) {+ target.toMicros = ((await databaseMicros(reader)) + 1_000_000n).toString();+ window = ` AND REQUEST_TIME BETWEEN ${target.fromMicros} AND ${target.toMicros}`;+ }+ publish({ identity: { auditFromMicros: target.fromMicros, ...(target.toMicros ? { auditToMicros: target.toMicros } : {}) } });+ const result = await reader.query(`SELECT ${AUDIT_COLUMNS},${metricColumns(REQUEST_METRICS)} FROM ${AUDIT_SOURCE} WHERE ${auditWhere(target, bound)}${window} ORDER BY REQUEST_TIME,REQUEST_ID`, 101);+ const rows = diagnosticRows(result);+ const identities = rows.map(auditIdentity);+ if (+ identities.some(+ (identity, index) =>+ identity.sid !== diagnosticInteger(target.session.id) ||+ identity.sqlId !== target.sqlId ||+ identity.traceId !== target.traceId ||+ identity.serverIp !== target.session.serverIp ||+ identity.serverPort !== diagnosticInteger(target.session.serverPort) ||+ diagnosticString(rows[index].TENANT_NAME) !== target.session.tenant ||+ (target.tenantId && identity.tenantId !== target.tenantId) ||+ (bound && identity.planId !== bound.planId),+ )+ )+ throw new Error("Audit request identity changed");+ const incomplete = !diagnosticResultComplete(result) || rows.length > 100;+ const choices: DiagnosticChoice[] = identities.slice(0, 100).map((identity, index) => ({ key: auditKey(identity), identity: { requestId: identity.requestId, requestTime: identity.requestTime, sqlExecId: identity.sqlExecId, returnCode: diagnosticString(rows[index].RET_CODE) } }));+ if (!bound) publish({ requestChoices: choices });+ let selected = bound ? identities.findIndex((identity) => auditKey(identity) === auditKey(bound)) : selection.requestKey ? identities.findIndex((identity) => auditKey(identity) === selection.requestKey) : rows.length === 1 && !incomplete ? 0 : -1;+ if (bound && (rows.length !== 1 || incomplete)) selected = -1;+ if (selected >= 0 && identities.filter((identity) => auditKey(identity) === auditKey(identities[selected])).length !== 1) selected = -1;+ if (selected < 0) {+ const issue = { ...diagnosticUnavailable<DiagnosticMetric[]>(AUDIT_SOURCE, bound ? "target_missing" : "not_collected"), incomplete };+ publish({ metrics: issue });+ return { row: null, issue };+ }+ const identity = identities[selected];+ if (target.request && auditKey(target.request) !== auditKey(identity)) target.plan = undefined;+ target.request = identity;+ target.tenantId = identity.tenantId;+ const row = rows[selected];+ const column = result.columns.findIndex((name) => name.toUpperCase() === "QUERY_SQL");+ if (column >= 0) {+ try {+ const text = await reader.readCell(result, selected, column);+ if (text) {+ target.sql = diagnosticSection(`${AUDIT_SOURCE}.QUERY_SQL`, { text, completeness: "unknown" });+ publish({ sql: target.sql });+ }+ } catch (error) {+ const failure = diagnosticFailure(AUDIT_SOURCE, error);+ publish({ sql: { ...(target.sql ?? diagnosticSection(`${PROCESS_SOURCE}.INFO`, { text: target.info, completeness: "fragment" as const }, true)), error: failure.error } });+ }+ }+ publish({+ identity: {+ sqlId: target.sqlId,+ traceId: target.traceId,+ tenant: diagnosticString(target.session.tenant),+ tenantId: identity.tenantId,+ server: `${identity.serverIp}:${identity.serverPort}`,+ sid: identity.sid,+ requestId: identity.requestId,+ requestTime: identity.requestTime,+ sqlExecId: identity.sqlExecId,+ returnCode: diagnosticString(row.RET_CODE),+ },+ });+ return { row };+}++function planIdentity(row: Row): PlanIdentity {+ return {+ tenantId: diagnosticInteger(row.TENANT_ID),+ serverIp: diagnosticString(row.SVR_IP),+ serverPort: diagnosticInteger(row.SVR_PORT),+ planId: diagnosticInteger(row.PLAN_ID),+ sqlId: diagnosticString(row.SQL_ID),+ firstLoadTime: diagnosticString(row.FIRST_LOAD_TIME),+ planHash: diagnosticInteger(row.PLAN_HASH),+ };+}+function planKey(identity: PlanIdentity): string {+ return JSON.stringify([identity.tenantId, identity.serverIp, identity.serverPort, identity.planId, identity.sqlId, identity.firstLoadTime, identity.planHash]);+}+const PLAN_COLUMNS = `TO_CHAR(TENANT_ID) AS TENANT_ID,SVR_IP,TO_CHAR(SVR_PORT) AS SVR_PORT,TO_CHAR(PLAN_ID) AS PLAN_ID,SQL_ID,TO_CHAR(FIRST_LOAD_TIME) AS FIRST_LOAD_TIME,TO_CHAR(PLAN_HASH) AS PLAN_HASH,${metricColumns(PLAN_METRICS)}`;++export function parseOceanbaseCachedPlan(result: QueryResult): { plan: ParsedExplainPlan; incomplete: boolean } {+ const roots: ExplainPlanNode[] = [],+ stack: ExplainPlanNode[] = [];+ const ids = new Set<string>();+ let incomplete = !diagnosticResultComplete(result);+ const records = diagnosticRows(result);+ if (records.some((row) => [row.PLAN_LINE_ID, row.PLAN_DEPTH].some((value) => typeof value !== "string" || !/^\d+$/.test(value)))) return { plan: { databaseType: "oceanbase-oracle", raw: result, nodes: [] }, incomplete: true };+ const ordered = records.sort((left, right) => {+ const a = BigInt(diagnosticInteger(left.PLAN_LINE_ID)),+ b = BigInt(diagnosticInteger(right.PLAN_LINE_ID));+ return a < b ? -1 : a > b ? 1 : 0;+ });+ for (const row of ordered) {+ const id = diagnosticInteger(row.PLAN_LINE_ID),+ rawDepth = diagnosticInteger(row.PLAN_DEPTH);+ if (BigInt(rawDepth) > BigInt(result.rows.length) || ids.has(id)) {+ incomplete = true;+ break;+ }+ const depth = Number(rawDepth);+ if (depth > stack.length || (roots.length > 0 && depth === 0) || (roots.length === 0 && (depth !== 0 || id !== "0"))) {+ incomplete = true;+ break;+ }+ const operation = diagnosticString(row.OPERATOR).trim();+ if (!operation) {+ incomplete = true;+ break;+ }+ const rawName = diagnosticString(row.NAME),+ name = rawName === "NULL" ? "" : rawName;+ const node: ExplainPlanNode = {+ id,+ nodeType: operation,+ title: name ? `${operation} on ${name}` : operation,+ dialect: "oceanbase-oracle",+ relation: name || undefined,+ cost: row.COST === null ? undefined : diagnosticString(row.COST),+ rows: row.ESTIMATED_ROWS === null ? undefined : diagnosticString(row.ESTIMATED_ROWS),+ costModel: "unknown",+ details: row.PROPERTY ? [diagnosticString(row.PROPERTY)] : [],+ children: [],+ };+ ids.add(id);+ stack.length = depth;+ if (depth === 0) roots.push(node);+ else stack[depth - 1].children.push(node);+ stack.push(node);+ }+ return { plan: { databaseType: "oceanbase-oracle", raw: result, nodes: incomplete ? [] : roots }, incomplete };+}++async function readPlan(target: OceanbaseDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish, selection: DiagnosticSelection, requestMetrics: DiagnosticMetric[], requestIssue?: DiagnosticSection<DiagnosticMetric[]>): Promise<void> {+ if (!target.tenantId) {+ const mapping = await reader.query(`SELECT DISTINCT TO_CHAR(TENANT_ID) AS TENANT_ID FROM SYS.GV$OB_SESS_TIME_MODEL WHERE SID=${diagnosticInteger(target.session.id)} AND ${nodeWhere(target)}`, 2);+ const rows = diagnosticRows(mapping);+ if (rows.length !== 1 || !diagnosticResultComplete(mapping)) {+ publish({ plan: diagnosticUnavailable(PLAN_SOURCE, "target_missing") });+ return;+ }+ target.tenantId = diagnosticInteger(rows[0].TENANT_ID);+ }+ const where = `TENANT_ID=${target.tenantId} AND ${nodeWhere(target)} AND SQL_ID=${diagnosticLiteral(target.sqlId)}`;+ const result = await reader.query(`SELECT ${PLAN_COLUMNS} FROM ${PLAN_SOURCE} WHERE ${where}${target.request ? ` AND PLAN_ID=${target.request.planId}` : ""} ORDER BY PLAN_ID`, 101);+ const rows = diagnosticRows(result),+ identities = rows.map(planIdentity);+ if (identities.some((identity) => identity.tenantId !== target.tenantId || identity.serverIp !== target.session.serverIp || identity.serverPort !== diagnosticInteger(target.session.serverPort) || identity.sqlId !== target.sqlId || !identity.firstLoadTime))+ throw new Error("Cached plan identity changed");+ const incomplete = !diagnosticResultComplete(result) || rows.length > 100;+ publish({ planChoices: identities.slice(0, 100).map((identity) => ({ key: planKey(identity), identity: { planId: identity.planId, planHash: identity.planHash, firstLoadTime: identity.firstLoadTime } })) });+ const selectedKey = selection.planKey ?? (target.plan ? planKey(target.plan) : undefined);+ const index = selectedKey ? identities.findIndex((identity) => planKey(identity) === selectedKey) : rows.length === 1 && !incomplete ? 0 : -1;+ if (index < 0 || (target.request && (rows.length !== 1 || incomplete))) {+ publish({ plan: { ...diagnosticUnavailable(PLAN_SOURCE, target.plan && rows.length ? "target_changed" : rows.length ? "not_collected" : "target_missing"), incomplete } });+ return;+ }+ const chosen = identities[index];+ const exact = `${where} AND PLAN_ID=${chosen.planId}`;+ let raw: QueryResult | undefined;+ let planFailure: DiagnosticSection<DiagnosticPlan> | undefined;+ try {+ raw = await reader.query(+ `SELECT TO_CHAR(PLAN_DEPTH) AS PLAN_DEPTH,TO_CHAR(PLAN_LINE_ID) AS PLAN_LINE_ID,OPERATOR,NAME,TO_CHAR("ROWS") AS ESTIMATED_ROWS,TO_CHAR(COST) AS COST,PROPERTY FROM ${EXPLAIN_SOURCE} p WHERE TENANT_ID=${chosen.tenantId} AND ${nodeWhere(target)} AND PLAN_ID=${chosen.planId} ORDER BY p.PLAN_LINE_ID`,+ 501,+ );+ } catch (error) {+ planFailure = diagnosticFailure(EXPLAIN_SOURCE, error);+ }+ const after = await reader.query(`SELECT ${PLAN_COLUMNS} FROM ${PLAN_SOURCE} WHERE ${exact}`, 2);+ const afterRows = diagnosticRows(after);+ if (afterRows.length !== 1 || !diagnosticResultComplete(after) || planKey(planIdentity(afterRows[0])) !== planKey(chosen)) {+ publish({ plan: diagnosticUnavailable(PLAN_SOURCE, "target_changed") });+ return;+ }+ target.plan = chosen;+ publish({+ metrics: {+ ...diagnosticSection(`${requestMetrics.length || requestIssue ? `${AUDIT_SOURCE}; ` : ""}${PLAN_SOURCE}`, [...requestMetrics, ...metrics(rows[index], PLAN_METRICS, PLAN_SOURCE, "plan_cumulative")]),+ ...(requestIssue ? { reason: requestIssue.reason, error: requestIssue.error, incomplete: requestIssue.incomplete } : {}),+ },+ });+ if (planFailure) publish({ plan: planFailure });+ else if (raw) {+ const parsed = parseOceanbaseCachedPlan(raw);+ publish({ plan: { ...diagnosticSection(EXPLAIN_SOURCE, { plan: parsed.plan, table: raw, binding: target.request ? ("request" as const) : ("same_sql" as const) }, parsed.incomplete), ...(raw.rows.length === 0 ? { state: "empty" as const, reason: "not_collected" as const } : {}) } });+ }+}++export async function collectOceanbaseSessionDiagnostics(target: OceanbaseDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish, selection: DiagnosticSelection = {}): Promise<void> {+ if (selection.requestKey && target.request && selection.requestKey !== auditKey(target.request)) {+ target.request = undefined;+ target.plan = undefined;+ target.sql = undefined;+ }+ publish({+ engine: target.engine,+ identity: { sid: diagnosticString(target.session.id), user: diagnosticString(target.session.user), tenant: diagnosticString(target.session.tenant), server: `${target.session.serverIp}:${target.session.serverPort}`, sqlId: target.sqlId, traceId: target.traceId },+ sql: target.sql ?? (target.info ? { ...diagnosticSection(`${PROCESS_SOURCE}.INFO`, { text: target.info, completeness: "fragment" as const }), error: target.infoError } : diagnosticUnavailable(`${PROCESS_SOURCE}.INFO`, "not_collected")),+ });+ let before: { row: Row | null } = { row: null };+ let liveFailure: DiagnosticSection<QueryResult> | undefined;+ try {+ before = await liveSession(target.session, reader);+ } catch (error) {+ liveFailure = diagnosticFailure(PROCESS_SOURCE, error);+ }+ const current = sameSql(target, before.row);+ publish({ stale: !current });+ if (before.row && current) {+ publish({ waits: diagnosticSection(PROCESS_SOURCE, { columns: ["STATE"], rows: [[before.row.STATE]], affected_rows: 0, execution_time_ms: 0 }) });+ } else publish({ waits: liveFailure ?? diagnosticUnavailable(PROCESS_SOURCE, "target_changed") });+ let requestMetrics: DiagnosticMetric[] = [];+ let requestIssue: DiagnosticSection<DiagnosticMetric[]> | undefined;+ if (target.sqlId && target.traceId) {+ try {+ const observed = await readAudit(target, reader, publish, selection);+ const audit = observed.row;+ requestIssue = observed.issue;+ if (audit) {+ requestMetrics = metrics(audit, REQUEST_METRICS, AUDIT_SOURCE, "request");+ publish({ metrics: diagnosticSection(AUDIT_SOURCE, requestMetrics) });+ publish({+ waits: {+ ...diagnosticSection(`${current || liveFailure ? `${PROCESS_SOURCE}; ` : ""}${AUDIT_SOURCE}`, {+ columns: ["SCOPE", "STATE", "EVENT", "WAIT_CLASS"],+ rows: [...(current && before.row ? [["session_sample", before.row.STATE, null, null]] : []), ["request", audit.STATE, audit.EVENT, audit.WAIT_CLASS]],+ affected_rows: 0,+ execution_time_ms: 0,+ }),+ ...(liveFailure ? { reason: liveFailure.reason, error: liveFailure.error } : {}),+ },+ });+ }+ } catch (error) {+ requestIssue = diagnosticFailure(AUDIT_SOURCE, error);+ publish({ metrics: requestIssue });+ }+ } else {+ requestIssue = diagnosticUnavailable(AUDIT_SOURCE, "not_collected");+ publish({ metrics: requestIssue });+ }+ if (target.sqlId) {+ try {+ await readPlan(target, reader, publish, selection, requestMetrics, requestIssue);+ } catch (error) {+ publish({ plan: diagnosticFailure(PLAN_SOURCE, error) });+ }+ } else publish({ plan: diagnosticUnavailable(PLAN_SOURCE, "not_collected") });+ if (!current || !target.traceId || !target.tenantId) {+ publish({ longOperations: diagnosticUnavailable(LONGOPS_SOURCE, current ? "not_collected" : "target_changed") });+ return;+ }+ try {+ const longopsBefore = await liveSession(target.session, reader);+ if (!sameSql(target, longopsBefore.row)) {+ publish({ stale: true, longOperations: diagnosticUnavailable(LONGOPS_SOURCE, "target_changed") });+ return;+ }+ const result = await reader.query(+ `SELECT TO_CHAR(SID) AS SID,TRACE_ID,OPNAME,TARGET,SVR_IP,TO_CHAR(SVR_PORT) AS SVR_PORT,TO_CHAR(START_TIME) AS START_TIME,TO_CHAR(ELAPSED_SECONDS) AS ELAPSED_SECONDS,TO_CHAR(TIME_REMAINING) AS TIME_REMAINING,TO_CHAR(LAST_UPDATE_TIME) AS LAST_UPDATE_TIME,MESSAGE FROM ${LONGOPS_SOURCE} WHERE (SID=${diagnosticInteger(target.session.id)} OR SID=-1) AND TRACE_ID=${diagnosticLiteral(target.traceId)} AND ${nodeWhere(target)} ORDER BY START_TIME`,+ 101,+ );+ const after = await liveSession(target.session, reader);+ if (!sameSql(target, after.row)) {+ publish({ stale: true, longOperations: diagnosticUnavailable(LONGOPS_SOURCE, "target_changed") });+ return;+ }+ const rows = diagnosticRows(result);+ if (rows.some((row) => (row.SID !== "-1" && row.SID !== diagnosticInteger(target.session.id)) || row.TRACE_ID !== target.traceId || row.SVR_IP !== target.session.serverIp || row.SVR_PORT !== diagnosticInteger(target.session.serverPort))) {+ publish({ longOperations: diagnosticUnavailable(LONGOPS_SOURCE, "target_changed") });+ return;+ }+ const table = { ...result, columns: ["SCOPE", ...result.columns], rows: result.rows.map((row, index) => [rows[index].SID === "-1" ? "request_trace" : "session_trace", ...row]) };+ publish({ longOperations: { ...diagnosticSection(LONGOPS_SOURCE, table, !diagnosticResultComplete(result)), ...(result.rows.length === 0 ? { state: "empty" as const, reason: "not_collected" as const } : {}) } });+ } catch (error) {+ publish({ longOperations: diagnosticFailure(LONGOPS_SOURCE, error) });+ }+}diff --git a/apps/desktop/src/lib/database/oracleSessionDiagnostics.ts b/apps/desktop/src/lib/database/oracleSessionDiagnostics.tsnew file mode 100644index 0000000000..08c7833c6c--- /dev/null+++ b/apps/desktop/src/lib/database/oracleSessionDiagnostics.ts@@ -0,0 +1,342 @@+import type { ExplainPlanNode, ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import type { QueryResult } from "@/types/database";+import type { ProcessRow } from "./processListDrivers";+import { oracleMajorVersion, ORACLE_SESSION_VERSION_SQL } from "./oracleSessionManagement";+import { DiagnosticReadStopped, type SessionDiagnosticReader } from "./sessionDiagnosticReader";+import { diagnosticFailure, diagnosticInteger, diagnosticLiteral, diagnosticResultComplete, diagnosticRows, diagnosticSection, diagnosticString, diagnosticUnavailable, type DiagnosticMetric, type DiagnosticPublish, type DiagnosticSection, type DiagnosticSql } from "./sessionDiagnostics";++const SESSION_SOURCE = "GV$SESSION",+ CURSOR_SOURCE = "GV$SQL",+ PLAN_SOURCE = "GV$SQL_PLAN",+ ROW_SOURCE = "GV$SQL_PLAN_STATISTICS_ALL",+ LONGOPS_SOURCE = "GV$SESSION_LONGOPS";+type Row = ReturnType<typeof diagnosticRows>[number];+interface OracleCursor {+ sqlId: string;+ childNumber: string;+ childAddress: string;+ firstLoadTime: string;+ planHash: string;+}+export interface OracleDiagnosticTarget {+ engine: "oracle";+ session: ProcessRow;+ legacy: boolean;+ sqlId: string;+ childNumber: string;+ sqlExecId: string;+ sqlExecStart: string;+ cursor?: OracleCursor;+ cursorError?: string;+ sql?: DiagnosticSection<DiagnosticSql>;+}+const COUNTERS = [+ ["executions", "EXECUTIONS", "count"],+ ["rows_processed", "ROWS_PROCESSED", "rows"],+ ["buffer_gets", "BUFFER_GETS", "count"],+ ["disk_reads", "DISK_READS", "count"],+ ["elapsed", "ELAPSED_TIME", "microseconds"],+ ["cpu", "CPU_TIME", "microseconds"],+ ["application_wait", "APPLICATION_WAIT_TIME", "microseconds"],+ ["concurrency_wait", "CONCURRENCY_WAIT_TIME", "microseconds"],+ ["cluster_wait", "CLUSTER_WAIT_TIME", "microseconds"],+ ["user_io_wait", "USER_IO_WAIT_TIME", "microseconds"],+] as const;++function containerPredicate(target: OracleDiagnosticTarget, alias: string): string {+ return target.legacy ? "" : ` AND ${alias}.CON_ID=${diagnosticInteger(target.session.container)}`;+}+function sessionWhere(target: OracleDiagnosticTarget, alias = "s"): string {+ const row = target.session;+ const user = diagnosticString(row.user),+ logon = diagnosticString(row.logonTime);+ if (!user || !logon) throw new Error("Incomplete Oracle session identity");+ return `${alias}.SID=${diagnosticInteger(row.id)} AND ${alias}.SERIAL#=${diagnosticInteger(row.serial)} AND ${alias}.INST_ID=${diagnosticInteger(row.instance)}${containerPredicate(target, alias)} AND ${alias}.USERNAME=${diagnosticLiteral(user)} AND ${alias}.AUDSID=${diagnosticInteger(row.auditSession)} AND TO_CHAR(${alias}.LOGON_TIME,'YYYY-MM-DD HH24:MI:SS')=${diagnosticLiteral(logon)}${target.legacy ? "" : ` AND ${alias}.CON_ID=TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID'))`}`;+}+async function liveSession(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader): Promise<Row | null> {+ const result = await reader.query(+ `SELECT s.SQL_ID,TO_CHAR(s.SQL_CHILD_NUMBER) AS CHILD_NUMBER,TO_CHAR(s.SQL_EXEC_ID) AS SQL_EXEC_ID,TO_CHAR(s.SQL_EXEC_START,'YYYY-MM-DD"T"HH24:MI:SS') AS SQL_EXEC_START,s.EVENT,s.WAIT_CLASS,s.STATE,TO_CHAR(s.SECONDS_IN_WAIT) AS SECONDS_IN_WAIT,TO_CHAR(s.BLOCKING_INSTANCE) AS BLOCKING_INSTANCE,TO_CHAR(s.BLOCKING_SESSION) AS BLOCKING_SESSION FROM ${SESSION_SOURCE} s WHERE ${sessionWhere(target)}`,+ 2,+ );+ const rows = diagnosticRows(result);+ return rows.length === 1 && diagnosticResultComplete(result) ? rows[0] : null;+}+function executionMatches(target: OracleDiagnosticTarget, row: Row | null): boolean {+ return !!row && diagnosticString(row.SQL_ID) === target.sqlId && diagnosticString(row.CHILD_NUMBER) === target.childNumber && diagnosticString(row.SQL_EXEC_ID) === target.sqlExecId && diagnosticString(row.SQL_EXEC_START) === target.sqlExecStart;+}+function cursorWhere(target: OracleDiagnosticTarget, alias: string, includeGeneration: boolean): string {+ const where = `${alias}.INST_ID=${diagnosticInteger(target.session.instance)}${containerPredicate(target, alias)} AND ${alias}.SQL_ID=${diagnosticLiteral(target.sqlId)} AND ${alias}.CHILD_NUMBER=${diagnosticInteger(target.childNumber)}`;+ if (!includeGeneration || !target.cursor) return where;+ return `${where} AND RAWTOHEX(${alias}.CHILD_ADDRESS)=${diagnosticLiteral(target.cursor.childAddress)} AND ${alias}.PLAN_HASH_VALUE=${target.cursor.planHash}`;+}+function cursorIdentity(row: Row): OracleCursor {+ const sqlId = diagnosticString(row.SQL_ID),+ childAddress = diagnosticString(row.CHILD_ADDRESS),+ firstLoadTime = diagnosticString(row.FIRST_LOAD_TIME);+ if (!/^[a-z0-9]{13}$/.test(sqlId) || !/^[0-9A-Fa-f]{8,32}$/.test(childAddress) || !firstLoadTime) throw new Error("Invalid Oracle cursor identity");+ return { sqlId, childNumber: diagnosticInteger(row.CHILD_NUMBER), childAddress, firstLoadTime, planHash: diagnosticInteger(row.PLAN_HASH) };+}+function cursorKey(cursor: OracleCursor): string {+ return JSON.stringify([cursor.sqlId, cursor.childNumber, cursor.childAddress, cursor.firstLoadTime, cursor.planHash]);+}+const CURSOR_COLUMNS = "s.SQL_ID,TO_CHAR(s.CHILD_NUMBER) AS CHILD_NUMBER,RAWTOHEX(s.CHILD_ADDRESS) AS CHILD_ADDRESS,s.FIRST_LOAD_TIME,TO_CHAR(s.PLAN_HASH_VALUE) AS PLAN_HASH";+async function findCursor(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader): Promise<OracleCursor | undefined> {+ if (!target.sqlId || !target.childNumber) return;+ const result = await reader.query(`SELECT ${CURSOR_COLUMNS} FROM ${CURSOR_SOURCE} s WHERE ${cursorWhere(target, "s", false)}`, 2);+ const rows = diagnosticRows(result);+ if (rows.length !== 1 || !diagnosticResultComplete(result)) return;+ const cursor = cursorIdentity(rows[0]);+ if (cursor.sqlId !== target.sqlId || cursor.childNumber !== target.childNumber) throw new Error("Oracle cursor identity changed");+ return cursor;+}++export async function captureOracleDiagnosticTarget(row: ProcessRow, versionMajor: number | undefined, reader: SessionDiagnosticReader): Promise<OracleDiagnosticTarget> {+ let major = versionMajor;+ if (!major) {+ const result = await reader.query(ORACLE_SESSION_VERSION_SQL, 2);+ if (result.rows.length !== 1 || !diagnosticResultComplete(result)) throw new Error("Oracle version unavailable");+ major = oracleMajorVersion(diagnosticString(result.rows[0][0])) ?? undefined;+ }+ if (!major || major < 11) throw new Error("Oracle session diagnostics require a verified Oracle 11g or newer version");+ const target: OracleDiagnosticTarget = { engine: "oracle", session: { ...row }, legacy: major < 12, sqlId: "", childNumber: "", sqlExecId: "", sqlExecStart: "" };+ const current = await liveSession(target, reader);+ if (!current) throw new Error("Selected session identity changed; refresh the session list");+ target.sqlId = diagnosticString(current.SQL_ID);+ target.childNumber = diagnosticString(current.CHILD_NUMBER);+ target.sqlExecId = diagnosticString(current.SQL_EXEC_ID);+ target.sqlExecStart = diagnosticString(current.SQL_EXEC_START);+ if (target.sqlId && !/^[a-z0-9]{13}$/.test(target.sqlId)) throw new Error("Invalid Oracle SQL identity");+ if (target.childNumber) diagnosticInteger(target.childNumber);+ if (target.sqlExecId) diagnosticInteger(target.sqlExecId);+ if (row.sqlId !== undefined && diagnosticString(row.sqlId) !== target.sqlId) throw new Error("Selected session SQL changed; refresh the session list");+ try {+ target.cursor = await findCursor(target, reader);+ } catch (error) {+ if (error instanceof DiagnosticReadStopped) throw error;+ target.cursorError = error instanceof Error ? error.message : String(error);+ }+ return target;+}++function cursorMetrics(row: Row): DiagnosticMetric[] {+ return COUNTERS.map(([name, column, unit]) => ({ name, value: typeof row[column] === "string" && /^\d+(?:\.\d+)?$/.test(row[column]) ? row[column] : null, unit, scope: "cursor_cumulative", source: `${CURSOR_SOURCE}.${column}` }));+}+async function verifyCursor(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader): Promise<boolean> {+ if (!target.cursor) return false;+ const current = await findCursor(target, reader);+ return !!current && cursorKey(current) === cursorKey(target.cursor);+}++async function readCursor(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish): Promise<DiagnosticMetric[] | null> {+ const source = `${CURSOR_SOURCE}.SQL_FULLTEXT`;+ const result = await reader.query(+ `SELECT ${CURSOR_COLUMNS},${COUNTERS.map(([, column]) => `TO_CHAR(s.${column}) AS ${column}`).join(",")},s.SQL_FULLTEXT AS SQL_TEXT,TO_CHAR(LENGTH(s.SQL_FULLTEXT)) AS SOURCE_LENGTH FROM ${CURSOR_SOURCE} s WHERE ${cursorWhere(target, "s", true)} AND s.FIRST_LOAD_TIME=${diagnosticLiteral(target.cursor!.firstLoadTime)}`,+ 2,+ );+ const rows = diagnosticRows(result);+ if (rows.length !== 1 || !diagnosticResultComplete(result) || cursorKey(cursorIdentity(rows[0])) !== cursorKey(target.cursor!)) {+ publish({ sql: diagnosticUnavailable(source, "target_missing"), metrics: diagnosticUnavailable(CURSOR_SOURCE, "target_missing") });+ return null;+ }+ const row = rows[0];+ let sql: DiagnosticSection<DiagnosticSql>;+ try {+ const column = result.columns.findIndex((name) => name.toUpperCase() === "SQL_TEXT");+ if (column < 0) throw new Error("Oracle SQL text column unavailable");+ const text = await reader.readCell(result, 0, column);+ const expected = diagnosticInteger(row.SOURCE_LENGTH);+ sql = diagnosticSection(source, { text, completeness: BigInt(text.length) === BigInt(expected) ? "complete" : "fragment" }, BigInt(text.length) !== BigInt(expected));+ } catch (error) {+ const failed = diagnosticFailure<DiagnosticSql>(source, error);+ sql = { ...diagnosticSection(source, { text: diagnosticString(row.SQL_TEXT), completeness: "fragment" as const }, true), reason: failed.reason, error: failed.error };+ }+ if (!(await verifyCursor(target, reader))) {+ publish({ sql: diagnosticUnavailable(source, "target_changed"), metrics: diagnosticUnavailable(CURSOR_SOURCE, "target_changed") });+ return null;+ }+ target.sql = sql;+ const measured = cursorMetrics(row);+ publish({ sql, metrics: diagnosticSection(CURSOR_SOURCE, measured) });+ return measured;+}++export function parseOracleCachedPlan(result: QueryResult): { plan: ParsedExplainPlan; incomplete: boolean } {+ const records = diagnosticRows(result),+ nodes = new Map<string, ExplainPlanNode>(),+ parents = new Map<string, string>();+ if (!records.length || records.some((row) => typeof row.ID !== "string" || !/^\d+$/.test(row.ID) || (row.PARENT_ID !== null && (typeof row.PARENT_ID !== "string" || !/^\d+$/.test(row.PARENT_ID)))))+ return { plan: { databaseType: "oracle", raw: result, nodes: [] }, incomplete: records.length > 0 || !diagnosticResultComplete(result) };+ let incomplete = !diagnosticResultComplete(result);+ for (const row of records) {+ const id = diagnosticInteger(row.ID),+ parent = row.PARENT_ID === null ? "" : diagnosticInteger(row.PARENT_ID);+ if (nodes.has(id) || (!parent && id !== "0") || parent === id) {+ incomplete = true;+ break;+ }+ const operation = [diagnosticString(row.OPERATION), diagnosticString(row.OPTIONS)].filter(Boolean).join(" ");+ if (!operation) {+ incomplete = true;+ break;+ }+ const name = [diagnosticString(row.OBJECT_OWNER), diagnosticString(row.OBJECT_NAME)].filter(Boolean).join(".");+ const index = /INDEX/.test(diagnosticString(row.OBJECT_TYPE)) || /INDEX/.test(operation);+ nodes.set(id, {+ id,+ nodeType: operation,+ title: name ? `${operation} on ${name}` : operation,+ dialect: "oracle",+ relation: !index && name ? name : undefined,+ index: index && name ? name : undefined,+ cost: row.COST === null ? undefined : diagnosticString(row.COST),+ rows: row.ESTIMATED_ROWS === null ? undefined : diagnosticString(row.ESTIMATED_ROWS),+ costModel: "unknown",+ details: [row.ACCESS_PREDICATES ? `Access: ${row.ACCESS_PREDICATES}` : "", row.FILTER_PREDICATES ? `Filter: ${row.FILTER_PREDICATES}` : ""].filter(Boolean),+ children: [],+ });+ parents.set(id, parent);+ }+ for (const [id, parent] of parents) {+ if (!parent) continue;+ const owner = nodes.get(parent);+ if (!owner) {+ incomplete = true;+ break;+ }+ owner.children.push(nodes.get(id)!);+ }+ for (const node of nodes.values()) node.children.sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));+ const root = nodes.get("0"),+ visited = new Set<string>(),+ queue = root ? [root] : [];+ while (queue.length && !incomplete) {+ const node = queue.shift()!;+ if (visited.has(node.id)) {+ incomplete = true;+ break;+ }+ visited.add(node.id);+ queue.push(...node.children);+ }+ if (visited.size !== nodes.size || !root) incomplete = true;+ return { plan: { databaseType: "oracle", raw: result, nodes: incomplete ? [] : [root!] }, incomplete };+}++async function readPlan(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish): Promise<void> {+ const result = await reader.query(+ `SELECT TO_CHAR(p.ID) AS ID,TO_CHAR(p.PARENT_ID) AS PARENT_ID,p.OPERATION,p.OPTIONS,p.OBJECT_OWNER,p.OBJECT_NAME,p.OBJECT_TYPE,TO_CHAR(p.COST) AS COST,TO_CHAR(p.CARDINALITY) AS ESTIMATED_ROWS,p.ACCESS_PREDICATES,p.FILTER_PREDICATES FROM ${PLAN_SOURCE} p WHERE ${cursorWhere(target, "p", true)} ORDER BY p.ID`,+ 501,+ );+ if (!(await verifyCursor(target, reader))) {+ publish({ plan: diagnosticUnavailable(PLAN_SOURCE, "target_changed") });+ return;+ }+ const parsed = parseOracleCachedPlan(result);+ publish({ plan: { ...diagnosticSection(PLAN_SOURCE, { plan: parsed.plan, table: result, binding: "cursor" as const }, parsed.incomplete), ...(result.rows.length ? {} : { state: "empty" as const, reason: "not_collected" as const }) } });+}++async function readRowCounters(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish, measured: DiagnosticMetric[]): Promise<void> {+ const result = await reader.query(`SELECT TO_CHAR(p.STARTS) AS STARTS,TO_CHAR(p.OUTPUT_ROWS) AS OUTPUT_ROWS FROM ${ROW_SOURCE} p WHERE ${cursorWhere(target, "p", true)} AND p.ID=0`, 2);+ const rows = diagnosticRows(result);+ if (rows.length > 1 || !diagnosticResultComplete(result) || !(await verifyCursor(target, reader))) throw new Error("Row-source identity changed");+ const starts = rows[0]?.STARTS,+ output = rows[0]?.OUTPUT_ROWS;+ const collected = typeof starts === "string" && /^\d+$/.test(starts) && BigInt(starts) > 0n;+ const metric: DiagnosticMetric = { name: "root_output_rows", value: collected && typeof output === "string" && /^\d+$/.test(output) ? output : null, unit: "rows", scope: "cursor_cumulative", source: `${ROW_SOURCE}.OUTPUT_ROWS (ID=0)` };+ publish({ metrics: { ...diagnosticSection(`${CURSOR_SOURCE}; ${ROW_SOURCE}`, [...measured, metric]), ...(!collected ? { reason: "not_collected" as const } : {}) } });+}++export function oracleLongOperationProgress(sofar: unknown, total: unknown, units: unknown): string | null {+ if (typeof sofar !== "string" || typeof total !== "string" || !/^\d+$/.test(sofar) || !/^\d+$/.test(total) || !units || BigInt(total) === 0n) return null;+ return (Number(BigInt(sofar) >= BigInt(total) ? 1000n : (BigInt(sofar) * 1000n) / BigInt(total)) / 10).toString();+}++async function readLongOperations(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish): Promise<void> {+ const executionBound = !!target.sqlId && !!target.sqlExecId && !!target.sqlExecStart;+ const executionWhere = executionBound ? ` AND l.SQL_ID=${diagnosticLiteral(target.sqlId)} AND l.SQL_EXEC_ID=${diagnosticInteger(target.sqlExecId)} AND TO_CHAR(l.SQL_EXEC_START,'YYYY-MM-DD"T"HH24:MI:SS')=${diagnosticLiteral(target.sqlExecStart)}` : "";+ const result = await reader.query(+ `SELECT TO_CHAR(l.SID) AS SID,TO_CHAR(l.SERIAL#) AS SERIAL_NUMBER,TO_CHAR(l.INST_ID) AS INSTANCE_ID,l.OPNAME,l.TARGET,TO_CHAR(l.SOFAR) AS SOFAR,TO_CHAR(l.TOTALWORK) AS TOTALWORK,l.UNITS,TO_CHAR(l.START_TIME,'YYYY-MM-DD"T"HH24:MI:SS') AS START_TIME,TO_CHAR(l.LAST_UPDATE_TIME,'YYYY-MM-DD"T"HH24:MI:SS') AS LAST_UPDATE_TIME,TO_CHAR(l.ELAPSED_SECONDS) AS ELAPSED_SECONDS,TO_CHAR(l.TIME_REMAINING) AS TIME_REMAINING,l.MESSAGE,l.SQL_ID,TO_CHAR(l.SQL_EXEC_ID) AS SQL_EXEC_ID,TO_CHAR(l.SQL_EXEC_START,'YYYY-MM-DD"T"HH24:MI:SS') AS SQL_EXEC_START FROM ${LONGOPS_SOURCE} l WHERE l.SID=${diagnosticInteger(target.session.id)} AND l.SERIAL#=${diagnosticInteger(target.session.serial)} AND l.INST_ID=${diagnosticInteger(target.session.instance)}${containerPredicate(target, "l")}${executionWhere} AND EXISTS (SELECT 1 FROM ${SESSION_SOURCE} s WHERE ${sessionWhere(target)}) ORDER BY l.START_TIME`,+ 101,+ );+ if (!executionMatches(target, await liveSession(target, reader))) {+ publish({ stale: true, longOperations: diagnosticUnavailable(LONGOPS_SOURCE, "target_changed") });+ return;+ }+ const source = diagnosticRows(result);+ const data: QueryResult = { ...result, columns: ["SCOPE", ...result.columns, "PROGRESS_PERCENT"], rows: result.rows.map((row, index) => [executionBound ? "execution" : "session_sample", ...row, oracleLongOperationProgress(source[index].SOFAR, source[index].TOTALWORK, source[index].UNITS)]) };+ publish({ longOperations: { ...diagnosticSection(LONGOPS_SOURCE, data, !diagnosticResultComplete(result)), ...(result.rows.length ? {} : { state: "empty" as const, reason: "not_collected" as const }) } });+}++export async function collectOracleSessionDiagnostics(target: OracleDiagnosticTarget, reader: SessionDiagnosticReader, publish: DiagnosticPublish): Promise<void> {+ publish({+ engine: "oracle",+ identity: {+ sid: diagnosticString(target.session.id),+ serial: diagnosticString(target.session.serial),+ instance: diagnosticString(target.session.instance),+ container: diagnosticString(target.session.container),+ user: diagnosticString(target.session.user),+ sqlId: target.sqlId,+ childNumber: target.childNumber,+ sqlExecId: target.sqlExecId,+ sqlExecStart: target.sqlExecStart,+ },+ ...(target.sql ? { sql: target.sql } : {}),+ });+ let current: Row | null = null;+ try {+ current = await liveSession(target, reader);+ publish({ stale: !executionMatches(target, current) });+ if (executionMatches(target, current)) {+ publish({+ waits: diagnosticSection(SESSION_SOURCE, {+ columns: ["WAIT_KIND", "STATE", "EVENT", "WAIT_CLASS", "SECONDS_IN_WAIT", "BLOCKING_INSTANCE", "BLOCKING_SESSION"],+ rows: [[current!.STATE === "WAITING" ? "current_wait" : "last_wait", current!.STATE, current!.EVENT, current!.WAIT_CLASS, current!.SECONDS_IN_WAIT, current!.BLOCKING_INSTANCE, current!.BLOCKING_SESSION]],+ affected_rows: 0,+ execution_time_ms: 0,+ }),+ });+ } else publish({ waits: diagnosticUnavailable(SESSION_SOURCE, "target_changed") });+ } catch (error) {+ publish({ stale: true, waits: diagnosticFailure(SESSION_SOURCE, error) });+ }+ if (!target.cursor && executionMatches(target, current)) {+ try {+ target.cursor = await findCursor(target, reader);+ } catch (error) {+ if (error instanceof DiagnosticReadStopped) throw error;+ target.cursorError = error instanceof Error ? error.message : String(error);+ }+ }+ if (target.cursor) {+ let measured: DiagnosticMetric[] | null = null;+ try {+ measured = await readCursor(target, reader, publish);+ } catch (error) {+ publish({ sql: diagnosticFailure(`${CURSOR_SOURCE}.SQL_FULLTEXT`, error), metrics: diagnosticFailure(CURSOR_SOURCE, error) });+ }+ try {+ await readPlan(target, reader, publish);+ } catch (error) {+ publish({ plan: diagnosticFailure(PLAN_SOURCE, error) });+ }+ if (measured) {+ try {+ await readRowCounters(target, reader, publish, measured);+ } catch (error) {+ const failure = diagnosticFailure(ROW_SOURCE, error);+ publish({ metrics: { ...diagnosticSection(`${CURSOR_SOURCE}; ${ROW_SOURCE}`, measured), reason: failure.reason, error: failure.error } });+ }+ }+ } else {+ const unavailable = target.cursorError ? diagnosticFailure<never>(CURSOR_SOURCE, new Error(target.cursorError)) : diagnosticUnavailable<never>(CURSOR_SOURCE, target.sqlId ? "target_missing" : "not_collected");+ publish({ sql: unavailable, plan: unavailable, metrics: unavailable });+ }+ if (executionMatches(target, current)) {+ try {+ await readLongOperations(target, reader, publish);+ } catch (error) {+ publish({ longOperations: diagnosticFailure(LONGOPS_SOURCE, error) });+ }+ } else publish({ longOperations: diagnosticUnavailable(LONGOPS_SOURCE, "target_changed") });+}diff --git a/apps/desktop/src/lib/database/oracleSessionManagement.ts b/apps/desktop/src/lib/database/oracleSessionManagement.tsindex b18722e030..6d8c051217 100644--- a/apps/desktop/src/lib/database/oracleSessionManagement.ts+++ b/apps/desktop/src/lib/database/oracleSessionManagement.ts@@ -153,14 +153,14 @@ export function buildOracleLockDetailsSql(target: OracleSessionTarget, legacy: bexport function buildOceanbaseSessionListSql(): string {// In Oracle mode bare USER is the login function, not the USER dictionary column.- return `SELECT TO_CHAR(ID) AS SESSION_ID, "USER" AS SESSION_USER, TENANT AS TENANT, HOST AS HOST, DB AS DB_NAME, COMMAND AS COMMAND, TIME AS ELAPSED_TIME, STATE AS STATE, INFO AS INFO, PROXY_SESSID AS PROXY_SESSION_ID, SVR_IP AS SERVER_IP, SVR_PORT AS SERVER_PORT FROM GV$OB_PROCESSLIST WHERE TENANT = (SELECT TENANT FROM GV$OB_SESSION WHERE ID = SYS_CONTEXT('USERENV','SID') AND "USER" = SYS_CONTEXT('USERENV','SESSION_USER') AND ROWNUM = 1) ORDER BY ID`;+ return `SELECT TO_CHAR(ID) AS SESSION_ID, "USER" AS SESSION_USER, TENANT AS TENANT, HOST AS HOST, DB AS DB_NAME, COMMAND AS COMMAND, TIME AS ELAPSED_TIME, STATE AS STATE, INFO AS INFO, PROXY_SESSID AS PROXY_SESSION_ID, SVR_IP AS SERVER_IP, SVR_PORT AS SERVER_PORT, SQL_ID AS SQL_ID, TRACE_ID AS TRACE_ID FROM GV$OB_PROCESSLIST WHERE TENANT = (SELECT TENANT FROM GV$OB_SESSION WHERE ID = SYS_CONTEXT('USERENV','SID') AND "USER" = SYS_CONTEXT('USERENV','SESSION_USER') AND ROWNUM = 1) ORDER BY ID`;}export const OCEANBASE_OWN_SESSION_SQL = `SELECT TO_CHAR(ID), "USER", TENANT FROM GV$OB_SESSION WHERE ID = SYS_CONTEXT('USERENV','SID') AND "USER" = SYS_CONTEXT('USERENV','SESSION_USER') AND ROWNUM = 1`;export function mapOceanbaseSessions(result: QueryResult | null | undefined): ProcessRow[] {return (result?.rows ?? []).flatMap((row) => {- const [id, user, tenant, host, db, command, time, state, info, proxySessionId, serverIp, serverPort] = row;+ const [id, user, tenant, host, db, command, time, state, info, proxySessionId, serverIp, serverPort, sqlId, traceId] = row;if (id === null || id === undefined || !/^\d+$/.test(String(id)) || user === null || tenant === null) return [];return [{@@ -177,6 +177,8 @@ export function mapOceanbaseSessions(result: QueryResult | null | undefined): PrserverIp: String(serverIp ?? ""),serverPort: String(serverPort ?? ""),server: `${String(serverIp ?? "")}:${String(serverPort ?? "")}`,+ sqlId: String(sqlId ?? ""),+ traceId: String(traceId ?? ""),},];});diff --git a/apps/desktop/src/lib/database/processListDrivers.ts b/apps/desktop/src/lib/database/processListDrivers.tsindex 6717e89e2c..d6ae8740f3 100644--- a/apps/desktop/src/lib/database/processListDrivers.ts+++ b/apps/desktop/src/lib/database/processListDrivers.ts@@ -1,5 +1,6 @@import type { ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import type { DiagnosticEngine } from "./sessionDiagnostics";import { buildXuguKillTransactionSql, mapXuguTransactionRows, XUGU_OWN_SESSION_SQL, XUGU_TRANSACTION_LIST_SQL, xuguTransactionKey } from "./xuguProcessList";import { buildCancelQuerySql as buildMysqlCancelQuerySql, buildTerminateSessionSql as buildMysqlTerminateSessionSql, mapProcessRows as mapMysqlProcessRows, PROCESS_LIST_SQL as MYSQL_PROCESS_LIST_SQL, supportsProcessList as supportsMysqlProcessList } from "./mysqlProcessList";import {@@ -76,6 +77,7 @@ export interface ProcessColumn {}export interface ProcessListDriver {+ diagnosticEngine?: DiagnosticEngine;/** Xugu displays active transactions rather than a full session list. */mode?: "transaction";/** Execution database for a system-wide administrative view. */@@ -261,6 +263,7 @@ const XUGU_DRIVER: ProcessListDriver = {};const ORACLE_DRIVER: ProcessListDriver = {+ diagnosticEngine: "oracle",versionSql: ORACLE_SESSION_VERSION_SQL,listSql: buildOracleSessionListSql(false),listSqlForVersion: (major) => buildOracleSessionListSql(major < 12),@@ -282,6 +285,7 @@ const ORACLE_DRIVER: ProcessListDriver = {};const OCEANBASE_ORACLE_DRIVER: ProcessListDriver = {+ diagnosticEngine: "oceanbase-oracle",listSql: buildOceanbaseSessionListSql(),ownSessionSql: OCEANBASE_OWN_SESSION_SQL,useClientSession: true,diff --git a/apps/desktop/src/lib/database/sessionDiagnosticReader.ts b/apps/desktop/src/lib/database/sessionDiagnosticReader.tsnew file mode 100644index 0000000000..082c4437b2--- /dev/null+++ b/apps/desktop/src/lib/database/sessionDiagnosticReader.ts@@ -0,0 +1,119 @@+import * as api from "@/lib/backend/api";+import { formatError } from "@/lib/backend/errorUtils";+import { uuid } from "@/lib/common/utils";+import { materializeLargeValueSnapshot, waitForLargeValueSnapshot } from "@/lib/dataGrid/largeValueSnapshot";+import type { QueryResult } from "@/types/database";++type DiagnosticBackend = Pick<typeof api, "executeQuery" | "cancelQuery" | "closeClientConnectionSession" | "readLargeValueChunk">;++export class DiagnosticReadStopped extends Error {+ constructor(public readonly reason: "cancelled" | "timeout") {+ super(`Diagnostic reading ${reason}`);+ }+}++export function createSessionDiagnosticReader(context: { connectionId: string; database: string }, backend: DiagnosticBackend = api) {+ const { connectionId, database } = context;+ const clientSessionId = `session-diagnostics:${uuid()}`;+ const controller = new AbortController();+ const pending = new Set<Promise<unknown>>();+ const executionIds = new Set<string>();+ let closeRequested = false;+ let closeStarted = false;+ let cleanupError: unknown;+ let resolveClosed!: () => void;+ let rejectClosed!: (error: unknown) => void;+ const closed = new Promise<void>((resolve, reject) => {+ resolveClosed = resolve;+ rejectClosed = reject;+ });+ void closed.catch(() => undefined);+ const deadline = setTimeout(() => stop("timeout"), 60_000);++ function closeWhenSettled() {+ if (!closeRequested || closeStarted || pending.size) return;+ closeStarted = true;+ void backend+ .closeClientConnectionSession(connectionId, database, clientSessionId)+ .then(resolveClosed)+ .catch((error) => {+ cleanupError = error;+ rejectClosed(error);+ });+ }++ function track<T>(transport: Promise<T>, executionId: string): Promise<T> {+ executionIds.add(executionId);+ const tracked = transport.finally(() => {+ pending.delete(tracked);+ executionIds.delete(executionId);+ closeWhenSettled();+ });+ pending.add(tracked);+ return tracked;+ }++ function stop(reason: "cancelled" | "timeout" = "cancelled") {+ closeRequested = true;+ clearTimeout(deadline);+ if (!controller.signal.aborted) {+ controller.abort(new DiagnosticReadStopped(reason));+ for (const executionId of executionIds) void backend.cancelQuery(executionId).catch(() => undefined);+ }+ closeWhenSettled();+ }++ async function query(sql: string, maxRows = 501): Promise<QueryResult> {+ controller.signal.throwIfAborted();+ const executionId = uuid();+ const timer = setTimeout(() => stop("timeout"), 10_000);+ try {+ const transport = track(backend.executeQuery(connectionId, database, sql, undefined, executionId, { clientSessionId, maxRows, timeoutSecs: 10 }), executionId);+ const result = await waitForLargeValueSnapshot(transport, controller.signal);+ controller.signal.throwIfAborted();+ if (result.execution_error) throw new Error(result.error ? formatError(result.error) : "Diagnostic query failed");+ if (result.large_value_cells?.some((cell) => cell.value_ref) && !result.large_value_context) return { ...result, large_value_context: { connectionId, database, clientSessionId } };+ return result;+ } finally {+ clearTimeout(timer);+ }+ }++ async function readCell(result: QueryResult, rowIndex: number, columnIndex: number): Promise<string> {+ controller.signal.throwIfAborted();+ const cell = result.large_value_cells?.find((value) => value.row_index === rowIndex && value.column_index === columnIndex);+ if (!cell) return String(result.rows[rowIndex]?.[columnIndex] ?? "");+ if (!cell.value_ref) throw new Error("SQL preview has no complete snapshot reference");+ const original = result.large_value_context;+ if (!original || original.connectionId !== connectionId || original.database !== database || original.clientSessionId !== clientSessionId || original.txnSessionId) throw new Error("SQL snapshot context changed");+ const executionId = uuid();+ const timer = setTimeout(() => stop("timeout"), 10_000);+ try {+ return await materializeLargeValueSnapshot(+ { ...original, valueRef: cell.value_ref, executionId },+ () => !controller.signal.aborted,+ controller.signal,+ async (request) => {+ const chunk = await track(backend.readLargeValueChunk(request), executionId);+ if (chunk.status !== "ok") throw new Error(`Diagnostic SQL snapshot ${chunk.status}; refresh diagnostics`);+ return chunk;+ },+ );+ } finally {+ clearTimeout(timer);+ }+ }++ return {+ query,+ readCell,+ stop,+ close: () => stop(),+ closed,+ get cleanupError() {+ return cleanupError;+ },+ };+}++export type SessionDiagnosticReader = ReturnType<typeof createSessionDiagnosticReader>;diff --git a/apps/desktop/src/lib/database/sessionDiagnostics.ts b/apps/desktop/src/lib/database/sessionDiagnostics.tsnew file mode 100644index 0000000000..aa0e0bf4de--- /dev/null+++ b/apps/desktop/src/lib/database/sessionDiagnostics.ts@@ -0,0 +1,114 @@+import type { ParsedExplainPlan } from "@/lib/diagram/explainPlan";+import type { QueryResult } from "@/types/database";+import { DiagnosticReadStopped } from "./sessionDiagnosticReader";++export type DiagnosticEngine = "oracle" | "oceanbase-oracle";+export type DiagnosticState = "loading" | "ready" | "empty" | "unavailable" | "failed" | "cancelled" | "timeout";+export type DiagnosticReason = "permission_denied" | "view_unavailable" | "field_unavailable" | "target_missing" | "target_changed" | "not_collected" | "incomplete" | "failed";+export interface DiagnosticSection<T> {+ state: DiagnosticState;+ source: string;+ sampledAt: string;+ dataSampledAt?: string;+ data?: T;+ reason?: DiagnosticReason;+ error?: string;+ incomplete?: boolean;+}+export interface DiagnosticSql {+ text: string;+ completeness: "complete" | "fragment" | "unknown" | "template";+}+export interface DiagnosticMetric {+ name: string;+ value: string | null;+ unit: "count" | "rows" | "blocks" | "microseconds" | "seconds";+ scope: "cursor_cumulative" | "plan_cumulative" | "request" | "session_sample";+ source: string;+}+export interface DiagnosticPlan {+ plan: ParsedExplainPlan;+ table: QueryResult;+ binding: "cursor" | "request" | "same_sql";+}+export interface DiagnosticChoice {+ key: string;+ identity: Record<string, string>;+}+export interface SessionDiagnosticsSnapshot {+ engine: DiagnosticEngine;+ identity: Record<string, string>;+ stale: boolean;+ startedAt?: string;+ finishedAt?: string;+ interrupted?: "cancelled" | "timeout";+ sql: DiagnosticSection<DiagnosticSql>;+ plan: DiagnosticSection<DiagnosticPlan>;+ metrics: DiagnosticSection<DiagnosticMetric[]>;+ waits: DiagnosticSection<QueryResult>;+ longOperations: DiagnosticSection<QueryResult>;+ requestChoices: DiagnosticChoice[];+ planChoices: DiagnosticChoice[];+}+export type DiagnosticPublish = (patch: Partial<SessionDiagnosticsSnapshot>) => void;+export interface DiagnosticSelection {+ requestKey?: string;+ planKey?: string;+}++export function diagnosticSection<T>(source: string, data: T, incomplete = false): DiagnosticSection<T> {+ return { state: "ready", source, sampledAt: new Date().toISOString(), data, ...(incomplete ? { incomplete: true } : {}) };+}++export function diagnosticUnavailable<T>(source: string, reason: DiagnosticReason): DiagnosticSection<T> {+ return { state: reason === "not_collected" ? "empty" : "unavailable", source, reason, sampledAt: new Date().toISOString() };+}++export function diagnosticFailure<T>(source: string, error: unknown): DiagnosticSection<T> {+ if (error instanceof DiagnosticReadStopped) throw error;+ const message = error instanceof Error ? error.message : String(error);+ const reason = /ORA-01031/.test(message) ? "permission_denied" : /ORA-00942/.test(message) ? "view_unavailable" : /ORA-00904/.test(message) ? "field_unavailable" : "failed";+ return { state: reason === "failed" ? "failed" : "unavailable", source, reason, error: message, sampledAt: new Date().toISOString() };+}++export function diagnosticRows(result: QueryResult): Record<string, QueryResult["rows"][number][number]>[] {+ if (result.execution_error) throw new Error("Diagnostic query failed");+ return result.rows.map((row) => Object.fromEntries(result.columns.map((column, index) => [column.toUpperCase(), row[index] ?? null])));+}++export function diagnosticString(value: unknown): string {+ return value === null || value === undefined ? "" : String(value);+}++export function diagnosticInteger(value: unknown): string {+ if (typeof value !== "string" || !/^\d+$/.test(value)) throw new Error("Invalid diagnostic integer identity");+ return value.replace(/^0+(?=\d)/, "");+}++export function diagnosticLiteral(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++export function diagnosticResultComplete(result: QueryResult): boolean {+ return !result.truncated && !result.has_more;+}++export const DIAGNOSTIC_SECTIONS = ["sql", "plan", "metrics", "waits", "longOperations"] as const;++export function emptySessionDiagnostics(engine: DiagnosticEngine): SessionDiagnosticsSnapshot {+ const loading = { state: "loading" as const, source: "", sampledAt: "" };+ return { engine, identity: {}, stale: false, sql: { ...loading }, plan: { ...loading }, metrics: { ...loading }, waits: { ...loading }, longOperations: { ...loading }, requestChoices: [], planChoices: [] };+}++export function mergeSessionDiagnostics(previous: SessionDiagnosticsSnapshot, patch: Partial<SessionDiagnosticsSnapshot>): SessionDiagnosticsSnapshot {+ const next = { ...previous, ...patch, identity: { ...previous.identity, ...patch.identity } };+ for (const section of DIAGNOSTIC_SECTIONS) {+ const update = patch[section];+ if (!update) continue;+ const old = previous[section];+ if (update.data === undefined && old.data !== undefined) {+ Object.assign(next, { [section]: { ...update, data: old.data, dataSampledAt: old.dataSampledAt ?? old.sampledAt } });+ } else if (update.data !== undefined) Object.assign(next, { [section]: { ...update, dataSampledAt: update.dataSampledAt ?? update.sampledAt } });+ }+ return next;+}diff --git a/docs/content/docs/query-editor.cn.mdx b/docs/content/docs/query-editor.cn.mdxindex 5046dc4086..def206c671 100644--- a/docs/content/docs/query-editor.cn.mdx+++ b/docs/content/docs/query-editor.cn.mdx@@ -211,6 +211,14 @@ vnoremap <Space>r :DbxExecuteSql<CR>不同数据库的 `EXPLAIN` 语义不同,部分引擎只提供表格或文本结果。执行计划反映优化器估算,不等于真实生产性能;需要结合数据量、统计信息、索引和实际耗时判断。+### 查看会话已有的诊断证据++Oracle 和 OceanBase Oracle 连接可从连接右键菜单打开**进程列表**,点击会话行的**诊断**,查看 SQL、已有计划、统计与等待、长操作。此入口只读取数据库已经保留的证据,不执行目标 SQL,也不生成新的执行计划。++诊断会固定打开时的会话与 SQL 身份;刷新继续读取同一目标。会话切换 SQL 后,页面会标明目标已变化,不会把新 SQL 的数据接到原结果。多个审计请求或缓存计划需要手动选择。SQL 文本会标明完整性;缓存计划中的行数是估算值,Oracle 游标累计统计、OB 请求统计和缓存累计统计分别标明口径。++**停止读取**结束本地等待,并尝试取消诊断查询,不会终止目标会话。权限不足、视图不可用、缓存淘汰或数据未采集会分别显示;刷新失败时保留此前读到的数据及其采样时间。长操作没有记录不代表 SQL 已完成;OB 长操作只显示已有时间信息,不推算工作量百分比。+## 查询历史在 **设置 → 数据 → 查询历史保留条数** 中,可选择 **200**、**1000**(默认)、**5000**、**10000** 或 **不限**。上限由所有连接及执行来源(包括 MCP)共用。调小后,下次记录历史时才会删除超出上限的旧记录;提高上限不会恢复已删除的记录。历史分页大小保持不变。diff --git a/docs/content/docs/query-editor.mdx b/docs/content/docs/query-editor.mdxindex 7efef839d6..16795ce26f 100644--- a/docs/content/docs/query-editor.mdx+++ b/docs/content/docs/query-editor.mdx@@ -211,6 +211,14 @@ Explain Plan accepts query-like SQL that is safe to analyze, such as `SELECT`, ``EXPLAIN` semantics vary by database, and some engines provide only table or text output. A plan reflects optimizer estimates rather than real production performance; evaluate it together with data volume, statistics, indexes, and measured runtime.+### Inspect Existing Session Evidence++For Oracle and OceanBase Oracle connections, open **Process List** from the connection context menu, then choose **Diagnostics** on a session row to inspect SQL, an existing plan, statistics and waits, and long operations. This reads evidence already retained by the database; it does not execute the target SQL or generate a new plan.++Diagnostics freezes the session and SQL identity captured when opened. Refresh reads the same target. If the session moves to another SQL statement, the page marks the change instead of attaching the new statement's data to the original result. Select explicitly when several audit requests or cached plans match. SQL text shows its completeness. Plan rows are estimates; Oracle cursor counters, OB request statistics, and cached-plan cumulative statistics have separate scope labels.++**Stop reading** ends the local wait and attempts to cancel diagnostic queries without terminating the target session. Permission errors, unavailable views, evicted cache entries, and uncollected data have distinct states. Failed refreshes retain earlier data with its sampling time. An empty long-operation result does not mean the SQL has finished. OB long operations show available timing information without inventing a work percentage.+## Query HistoryIn **Settings → Data → Query history retention**, choose **200**, **1000** (default), **5000**, **10000**, or **Unlimited**. The limit is shared by all connections and execution sources, including MCP. A lower limit takes effect the next time a history entry is recorded: older entries beyond the limit are deleted. Raising the limit does not recover deleted entries. History page sizes remain unchanged.