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 invalid object compilation and session lock management (#12773)
efeireb5e4aab0167f
diff --git a/apps/desktop/src/components/admin/ProcessListPanel.vue b/apps/desktop/src/components/admin/ProcessListPanel.vueindex 00f33e79cc..37081c58f2 100644--- a/apps/desktop/src/components/admin/ProcessListPanel.vue+++ b/apps/desktop/src/components/admin/ProcessListPanel.vue@@ -10,11 +10,14 @@ import { useConnectionStore } from "@/stores/connectionStore";import { useToast } from "@/composables/useToast";import type { ConnectionConfig } from "@/types/database";import * as api from "@/lib/backend/api";-import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { formatError } from "@/lib/backend/errorUtils";+import { executeWithProductionContextGuard, executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { uuid } from "@/lib/common/utils";import { clampInterval, createProcessListLoadCoordinator, DEFAULT_REFRESH_SECONDS, processListExecutionError, processListSessionCount } from "@/lib/database/mysqlProcessList";import { resolveProcessListDriverForConnection, type ProcessRow } from "@/lib/database/processListDrivers";import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { processListSelectionAfterClick } from "@/lib/database/processListSelection";+import { oracleMajorVersion } from "@/lib/database/oracleSessionManagement";import { useTabUiState } from "@/lib/tabs/tabUiState";const props = defineProps<{@@ -41,13 +44,16 @@ const numericKeys = computed(() => new Set(columns.value.filter((column) => coluconst rows = ref<ProcessRow[]>([]);const truncated = ref(false);-const ownSessionId = ref<number | null>(null);+const ownSessionId = ref<number | string | null>(null);const ownNodeId = ref<number | null>(null);+const ownSessionRow = ref<unknown[] | null>(null);+const versionMajor = ref<number | null>(null);const transactionMode = computed(() => driver.value?.mode === "transaction");const transactionIdentityUnavailable = computed(() => transactionMode.value && (ownSessionId.value === null || ownNodeId.value === null));const loading = ref(false);const loadCoordinator = createProcessListLoadCoordinator();const loadError = ref("");+const versionProbeWarning = ref("");const search = ref(restoredUiState.search ?? "");const restoredSortKey = columns.value.some((column) => column.key === restoredUiState.sortKey) ? restoredUiState.sortKey : undefined;const sortKey = ref<string>(restoredSortKey ?? driver.value?.defaultSortKey ?? "time");@@ -63,23 +69,34 @@ const terminateTarget = ref<ProcessRow | null>(null);const terminating = ref(false);const batchSupported = computed(() => driver.value?.supportsBatchCancel === true);// Engines without a terminate statement only expose query cancellation.-const terminateSupported = computed(() => typeof driver.value?.buildTerminateSessionSql === "function");+const terminateSupported = computed(() => typeof driver.value?.buildTerminateSessionSql === "function" || typeof driver.value?.buildTerminateSessionSqlForRow === "function");+const rowAwareTerminate = computed(() => typeof driver.value?.buildTerminateSessionSqlForRow === "function");+const cancelSupported = computed(() => (transactionMode.value ? typeof driver.value?.buildKillTransactionSql === "function" : typeof driver.value?.buildCancelQuerySql === "function"));// Multi-selection serves batch cancel and/or batch terminate; either enables the checkboxes.-const selectionSupported = computed(() => batchSupported.value || terminateSupported.value);-const selectedIds = ref(new Set<number>());+const selectionSupported = computed(() => batchSupported.value || (terminateSupported.value && driver.value?.supportsBatchTerminate !== false));+const selectedIds = ref(new Set<number | string>());// Anchor row for Shift+click range selection, in the current display order.-const selectionAnchorId = ref<number | null>(null);+const selectionAnchorId = ref<number | string | null>(null);const batchTargets = ref<ProcessRow[] | null>(null);const batchTerminateTargets = ref<ProcessRow[] | null>(null);-const batchResult = ref<{ kind: "cancel" | "terminate"; succeeded: number; failures: { id: number; message: string }[] } | null>(null);+const batchResult = ref<{ kind: "cancel" | "terminate"; succeeded: number; failures: { id: number | string; message: string }[] } | null>(null);const refreshing = ref(false);const actionsLocked = computed(() => canceling.value || cancelTarget.value !== null || terminating.value || terminateTarget.value !== null || batchTargets.value !== null || batchTerminateTargets.value !== null);let connectionGeneration = 0;let disposed = false;const fallbackListSql = ref<string | null>(null);+type ManagedClientSession = { id: string; connectionId: string; database: string; active: number; closeRequested: boolean };+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 lockTarget = ref<ProcessRow | null>(null);+const lockColumns = ref<string[]>([]);+const lockRows = ref<unknown[][]>([]);+const lockError = ref("");+const lockTruncated = ref(false);+const loadingLocks = ref(false);+let lockRequestGeneration = 0;trackUiState(() => ({ search: search.value, sortKey: sortKey.value, sortDir: sortDir.value, autoRefresh: autoRefresh.value, intervalSeconds: intervalSeconds.value }));@@ -88,6 +105,39 @@ function openPreview(value: string | number | null) {previewText.value = String(value);}+function closeManagedSession(session: ManagedClientSession) {+ if (!session.closeRequested || session.active > 0) return;+ session.closeRequested = false;+ void api.closeClientConnectionSession(session.connectionId, session.database, session.id).catch(() => undefined);+}++function managedSessionFor(connection: ConnectionConfig, database: string): ManagedClientSession {+ if (!managedClientSession || managedClientSession.connectionId !== connection.id || managedClientSession.database !== database) {+ const previous = managedClientSession;+ managedClientSession = { id: `process-list:${uuid()}`, connectionId: connection.id, database, active: 0, closeRequested: false };+ if (previous) {+ previous.closeRequested = true;+ closeManagedSession(previous);+ }+ }+ return managedClientSession;+}++async function executeProcessQuery(connectionId: string, database: string, sql: string, maxRows: number, activeDriver: NonNullable<typeof driver.value>) {+ const connection = { ...props.connection };+ if (!activeDriver.useClientSession) return api.executeQuery(connectionId, database, sql, undefined, undefined, { maxRows });+ const session = managedSessionFor(connection, database);+ session.active++;+ try {+ const result = await api.executeQuery(connectionId, database, sql, undefined, undefined, { maxRows, clientSessionId: session.id });+ if (result.execution_error) throw new Error(result.error ? formatError(result.error) : String(result.rows[0]?.[0] ?? "Query execution failed"));+ return result;+ } finally {+ session.active--;+ closeManagedSession(session);+ }+}+async function copyPreview() {if (previewText.value === null) return;try {@@ -114,7 +164,7 @@ const filteredRows = computed(() => {});});-const selectableRows = computed(() => (ownSessionId.value === null ? [] : filteredRows.value.filter((row) => !isOwnSession(row) && Number.isInteger(row.id) && row.id > 0)));+const selectableRows = computed(() => (ownSessionId.value === null ? [] : filteredRows.value.filter((row) => !isOwnSession(row) && (typeof row.id === "string" ? /^\d+$/.test(row.id) : Number.isSafeInteger(row.id) && row.id > 0))));const allSelected = computed(() => selectableRows.value.length > 0 && selectableRows.value.every((row) => selectedIds.value.has(row.id)));const partiallySelected = computed(() => selectedIds.value.size > 0 && !allSelected.value);@@ -134,7 +184,7 @@ function clearSelection() {}/** Row checkbox click: a plain click toggles one row, Shift+click extends from the anchor. */-function toggleSelection(id: number, event: MouseEvent) {+function toggleSelection(id: number | string, event: MouseEvent) {if (actionsLocked.value || refreshing.value) return;// The browser toggles the clicked checkbox before this handler runs, so the// next state comes from the selection; both agree because the click is never@@ -166,7 +216,7 @@ async function confirmBatchCancel() {canceling.value = true;let executed = false;try {- const statements = targets.map((row) => ({ id: row.id, sql: activeDriver.buildCancelQuerySql!(row.id) }));+ const statements = targets.map((row) => ({ id: Number(row.id), sql: activeDriver.buildCancelQuerySql!(Number(row.id)) }));const result = await executeWithProductionSqlGuard({connection,database: "",@@ -225,7 +275,7 @@ async function confirmBatchTerminate() {terminating.value = true;let executed = false;try {- const statements = targets.map((row) => ({ id: row.id, sql: buildTerminateSql.call(activeDriver, row.id) }));+ const statements = targets.map((row) => ({ id: Number(row.id), sql: buildTerminateSql.call(activeDriver, Number(row.id)) }));const executeTerminateSql = async (sql: string) => {const results = await api.executeMulti(connection.id, "", sql, undefined, undefined, { maxRows: 1 });const executionError = processListExecutionError(results);@@ -294,19 +344,35 @@ async function load(options: { silent?: boolean } = {}) {refreshing.value = true;if (!options.silent) loading.value = true;loadError.value = "";+ versionProbeWarning.value = "";try {await connectionStore.ensureConnected(connectionId, { skipIfClosedByUser: true });if (!isCurrent()) return;+ if (activeDriver.versionSql && versionMajor.value === null) {+ try {+ const versionResult = await executeProcessQuery(connectionId, activeDriver.database ?? "", activeDriver.versionSql, 1, activeDriver);+ if (!isCurrent()) return;+ const detectedVersion = oracleMajorVersion(String(versionResult.rows?.[0]?.[0] ?? ""));+ if (detectedVersion === null) versionProbeWarning.value = t("processList.oracleVersionUnknown");+ else versionMajor.value = detectedVersion;+ } catch (error) {+ if (!isCurrent()) return;+ versionProbeWarning.value = error instanceof Error ? error.message : String(error);+ }+ if (!isCurrent()) return;+ }if (ownSessionId.value === null) {try {let idResult;+ const ownSql = versionMajor.value === null ? activeDriver.ownSessionSql : (activeDriver.ownSessionSqlForVersion?.(versionMajor.value) ?? activeDriver.ownSessionSql);try {- idResult = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.ownSessionSql, undefined, undefined, { maxRows: 1 });+ idResult = await executeProcessQuery(connectionId, activeDriver.database ?? "", ownSql, 1, activeDriver);} catch (error) {if (!activeDriver.fallbackOwnSessionSql || !activeDriver.shouldUseFallbackOwnSessionSql?.(error)) throw error;- idResult = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackOwnSessionSql, undefined, undefined, { maxRows: 1 });+ idResult = await executeProcessQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackOwnSessionSql, 1, activeDriver);}const ownRow = idResult?.rows?.[0];+ if (isCurrent()) ownSessionRow.value = ownRow ?? null;if (activeDriver.mode === "transaction") {const nodeId = Number(ownRow?.[0]);const sessionId = Number(ownRow?.[1]);@@ -315,21 +381,21 @@ async function load(options: { silent?: boolean } = {}) {ownSessionId.value = sessionId;}} else {- const parsed = Number(ownRow?.[0]);- if (isCurrent() && Number.isInteger(parsed) && parsed > 0) ownSessionId.value = parsed;+ const parsed = activeDriver.ownSessionMatches ? String(ownRow?.[0] ?? "") : Number(ownRow?.[0]);+ if (isCurrent() && (typeof parsed === "string" ? /^\d+$/.test(parsed) : Number.isSafeInteger(parsed) && parsed > 0)) ownSessionId.value = parsed;}} catch {// Non-fatal: without our own id we simply cannot dim the self row.}}if (!isCurrent()) return;- const listSql = fallbackListSql.value ?? activeDriver.listSql;+ const listSql = fallbackListSql.value ?? (versionMajor.value === null ? activeDriver.listSql : (activeDriver.listSqlForVersion?.(versionMajor.value) ?? activeDriver.listSql));let result;try {- result = await api.executeQuery(connectionId, activeDriver.database ?? "", listSql, undefined, undefined, { maxRows: activeDriver.maxRows });+ result = await executeProcessQuery(connectionId, activeDriver.database ?? "", listSql, activeDriver.maxRows, activeDriver);} catch (error) {if (fallbackListSql.value || !activeDriver.fallbackListSql || !activeDriver.shouldUseFallbackListSql?.(error)) throw error;- result = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackListSql, undefined, undefined, { maxRows: activeDriver.maxRows });+ result = await executeProcessQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackListSql, activeDriver.maxRows, activeDriver);// Cache the compatible query so old servers do not fail once per refresh.if (isCurrent()) fallbackListSql.value = activeDriver.fallbackListSql;}@@ -345,6 +411,8 @@ async function load(options: { silent?: boolean } = {}) {truncated.value = false;ownSessionId.value = null;ownNodeId.value = null;+ ownSessionRow.value = null;+ versionMajor.value = null;}loadError.value = activeDriver.mode === "transaction" ? t("processList.transactionLoadFailed", { message: error?.message || String(error) }) : error?.message || String(error);}@@ -358,7 +426,40 @@ async function load(options: { silent?: boolean } = {}) {function isOwnSession(row: ProcessRow): boolean {if (transactionMode.value) return ownNodeId.value !== null && ownSessionId.value !== null && row.nodeId === ownNodeId.value && row.id === ownSessionId.value;- return ownSessionId.value !== null && row.id === ownSessionId.value;+ if (driver.value?.ownSessionMatches) return driver.value.ownSessionMatches(row, ownSessionRow.value);+ return ownSessionId.value !== null && String(row.id) === String(ownSessionId.value);+}++async function showLocks(row: ProcessRow) {+ const activeDriver = driver.value;+ if (!activeDriver?.buildLockDetailsSql || loadingLocks.value || actionsLocked.value) return;+ const requestGeneration = ++lockRequestGeneration;+ const generation = connectionGeneration;+ const connection = { ...props.connection };+ lockTarget.value = row;+ lockColumns.value = [];+ lockRows.value = [];+ lockError.value = "";+ lockTruncated.value = false;+ loadingLocks.value = true;+ try {+ const sql = activeDriver.buildLockDetailsSql(row, versionMajor.value ?? undefined);+ const result = await executeProcessQuery(connection.id, activeDriver.database ?? "", sql, 1000, activeDriver);+ if (disposed || generation !== connectionGeneration || requestGeneration !== lockRequestGeneration) return;+ lockColumns.value = result.columns;+ lockRows.value = result.rows;+ lockTruncated.value = result.truncated === true;+ } catch (error) {+ if (!disposed && generation === connectionGeneration && requestGeneration === lockRequestGeneration) lockError.value = error instanceof Error ? error.message : String(error);+ } finally {+ if (!disposed && generation === connectionGeneration && requestGeneration === lockRequestGeneration) loadingLocks.value = false;+ }+}++function closeLockDialog() {+ lockRequestGeneration++;+ lockTarget.value = null;+ loadingLocks.value = false;}function requestCancel(row: ProcessRow) {@@ -375,7 +476,7 @@ async function confirmCancel() {const isCurrent = () => !disposed && generation === connectionGeneration;canceling.value = true;try {- const cancelSql = transactionMode.value ? activeDriver.buildKillTransactionSql!(target) : activeDriver.buildCancelQuerySql!(target.id);+ const cancelSql = transactionMode.value ? activeDriver.buildKillTransactionSql!(target) : activeDriver.buildCancelQuerySql!(Number(target.id));let usedFallbackCancelSql = false;const executeCancelSql = async (sql: string) => {if (!isCurrent()) return undefined;@@ -404,7 +505,7 @@ async function confirmCancel() {} catch (error) {if (!activeDriver.buildFallbackCancelQuerySql || !activeDriver.shouldUseFallbackCancelQuerySql?.(error)) throw error;usedFallbackCancelSql = true;- return executeCancelSql(activeDriver.buildFallbackCancelQuerySql(target.id));+ return executeCancelSql(activeDriver.buildFallbackCancelQuerySql(Number(target.id)));}},});@@ -422,10 +523,16 @@ async function confirmCancel() {}function requestTerminate(row: ProcessRow) {- if (isOwnSession(row) || actionsLocked.value || refreshing.value || !terminateSupported.value) return;+ if (isOwnSession(row) || (rowAwareTerminate.value && ownSessionId.value === null) || terminateRowDisabledReason(row) || actionsLocked.value || refreshing.value || !terminateSupported.value) return;terminateTarget.value = row;}+function terminateRowDisabledReason(row: ProcessRow): string | undefined {+ const activeDriver = driver.value;+ if (activeDriver?.terminateRowUnavailableReason) return activeDriver.terminateRowUnavailableReason(row);+ return activeDriver?.canTerminateSessionRow?.(row) === false ? "processList.oracleIdentityUnavailable" : undefined;+}+/*** Close the session itself. `KILL QUERY` / `pg_cancel_backend` leave an idle session* connected, so an idle row could never be removed from the list before this action.@@ -434,43 +541,72 @@ async function confirmTerminate() {const target = terminateTarget.value;const activeDriver = driver.value;const buildTerminateSql = activeDriver?.buildTerminateSessionSql;- if (!target || !activeDriver || !buildTerminateSql || terminating.value) return;+ const buildRowTerminateSql = activeDriver?.buildTerminateSessionSqlForRow;+ if (!target || (buildRowTerminateSql && ownSessionId.value === null) || isOwnSession(target) || terminateRowDisabledReason(target) || !activeDriver || (!buildTerminateSql && !buildRowTerminateSql) || terminating.value) return;const connection = { ...props.connection };+ const connectionKey = JSON.stringify(connection);const generation = connectionGeneration;const isCurrent = () => !disposed && generation === connectionGeneration;+ const isCurrentConnection = () => isCurrent() && JSON.stringify(props.connection) === connectionKey;+ const rowAware = !!buildRowTerminateSql;+ const targetKey = activeDriver.rowKey?.(target) ?? String(target.id);terminating.value = true;+ let actionSubmitted = false;try {- const terminateSql = buildTerminateSql.call(activeDriver, target.id);+ const terminateSql = buildRowTerminateSql?.(target, versionMajor.value ?? undefined) ?? buildTerminateSql!.call(activeDriver, Number(target.id));let usedFallbackTerminateSql = false;const executeTerminateSql = async (sql: string) => {- if (!isCurrent()) return undefined;+ if (!isCurrentConnection()) throw new Error(t("processList.oracleConnectionChanged"));+ actionSubmitted = true;+ if (activeDriver.useClientSession) {+ const queryResult = await executeProcessQuery(connection.id, activeDriver.database ?? "", sql, 1, activeDriver);+ const executionError = processListExecutionError([queryResult]);+ if (executionError) throw new Error(executionError);+ return [queryResult];+ }const results = await api.executeMulti(connection.id, "", sql, undefined, undefined, { maxRows: 1 });const executionError = processListExecutionError(results);if (executionError) throw new Error(executionError);return results;};- const result = await executeWithProductionSqlGuard({- connection,- database: "",- sql: terminateSql,- source: t("production.sourceAdmin"),- execute: async () => {- try {- return await executeTerminateSql(terminateSql);- } catch (error) {- if (!activeDriver.buildFallbackTerminateSessionSql || !activeDriver.shouldUseFallbackTerminateSessionSql?.(error)) throw error;- usedFallbackTerminateSql = true;- return executeTerminateSql(activeDriver.buildFallbackTerminateSessionSql(target.id));- }- },- });+ const execute = async () => {+ if (!isCurrentConnection()) throw new Error(t("processList.oracleConnectionChanged"));+ try {+ return await executeTerminateSql(terminateSql);+ } catch (error) {+ if (!buildTerminateSql || !activeDriver.buildFallbackTerminateSessionSql || !activeDriver.shouldUseFallbackTerminateSessionSql?.(error)) throw error;+ usedFallbackTerminateSql = true;+ return executeTerminateSql(activeDriver.buildFallbackTerminateSessionSql(Number(target.id)));+ }+ };+ const result =+ activeDriver.productionGuardScope === "connection"+ ? await executeWithProductionContextGuard({ connection, database: "", reviewText: terminateSql, source: t("production.sourceAdmin"), scope: "connection", execute })+ : await executeWithProductionSqlGuard({ connection, database: "", sql: terminateSql, source: t("production.sourceAdmin"), execute });if (result === undefined || !isCurrent()) return;const terminateResultError = usedFallbackTerminateSql ? activeDriver.fallbackTerminateSessionResultError?.(result) : activeDriver.terminateSessionResultError?.(result);if (terminateResultError) throw new Error(terminateResultError);- toast(t("processList.terminateSuccess", { id: target.id }), 2500);terminateTarget.value = null;+ if (rowAware) {+ terminating.value = false;+ await load({ silent: true });+ if (!isCurrent()) return;+ if (loadError.value || truncated.value) toast(t("processList.oracleTerminateUnknown"), 5000);+ else if (rows.value.some((row) => (activeDriver.rowKey?.(row) ?? String(row.id)) === targetKey)) toast(t("processList.oracleTerminatePending"), 4000);+ else toast(t("processList.terminateSuccess", { id: target.id }), 2500);+ return;+ }+ toast(t("processList.terminateSuccess", { id: target.id }), 2500);} catch (error: any) {- if (isCurrent()) toast(t("processList.terminateFailed", { message: error?.message || String(error) }), 5000);+ if (isCurrent()) {+ if (rowAware && actionSubmitted) {+ terminateTarget.value = null;+ toast(`${t("processList.oracleTerminateUnknown")} ${error instanceof Error ? error.message : String(error)}`, 5000);+ void load({ silent: true });+ } else {+ toast(t("processList.terminateFailed", { message: error?.message || String(error) }), 5000);+ }+ }} finally {terminating.value = false;if (terminateTarget.value === null) void load({ silent: true });@@ -507,19 +643,35 @@ watch(intervalSeconds, () => {});watch(- () => props.connection.id,+ () => JSON.stringify(props.connection),() => {connectionGeneration++;+ if (managedClientSession) {+ managedClientSession.closeRequested = true;+ closeManagedSession(managedClientSession);+ managedClientSession = null;+ }clearSelection();batchTargets.value = null;batchTerminateTargets.value = null;batchResult.value = null;cancelTarget.value = null;+ terminateTarget.value = null;fallbackListSql.value = null;rows.value = [];truncated.value = false;ownSessionId.value = null;ownNodeId.value = null;+ ownSessionRow.value = null;+ versionMajor.value = null;+ versionProbeWarning.value = "";+ lockTarget.value = null;+ lockColumns.value = [];+ lockRows.value = [];+ lockError.value = "";+ lockTruncated.value = false;+ loadingLocks.value = false;+ lockRequestGeneration++;search.value = "";sortKey.value = driver.value?.defaultSortKey ?? "time";sortDir.value = "desc";@@ -532,6 +684,11 @@ onBeforeUnmount(() => {disposed = true;connectionGeneration++;stopTimer();+ if (managedClientSession) {+ managedClientSession.closeRequested = true;+ closeManagedSession(managedClientSession);+ managedClientSession = null;+ }});</script>@@ -567,7 +724,7 @@ onBeforeUnmount(() => {{{ t("processList.batchCancel", { count: selectedIds.size }) }}</Button><Button- v-if="terminateSupported"+ v-if="terminateSupported && driver?.supportsBatchTerminate !== false"variant="destructive"size="sm"class="h-7 gap-1.5 px-2 text-xs"@@ -602,8 +759,10 @@ onBeforeUnmount(() => {<div v-if="transactionMode" class="border-b bg-muted/10 px-3 py-2 text-xs text-muted-foreground">{{ t("processList.transactionScope") }}</div><div v-if="selectionSupported && ownSessionId === null && !refreshing" class="border-b px-3 py-2 text-xs text-muted-foreground">{{ t("processList.batchNeedsSession") }}</div>+ <div v-else-if="rowAwareTerminate && ownSessionId === null && !refreshing" class="border-b px-3 py-2 text-xs text-muted-foreground">{{ t("processList.batchNeedsSession") }}</div><div v-if="transactionIdentityUnavailable && !refreshing && !loadError" class="border-b px-3 py-2 text-xs text-muted-foreground">{{ t("processList.transactionNeedsSession") }}</div>+ <div v-if="versionProbeWarning" class="border-b bg-muted/50 px-3 py-2 text-xs text-muted-foreground">{{ versionProbeWarning }}</div><div v-if="loadError" class="border-b bg-destructive/10 px-3 py-2 text-xs text-destructive">{{ loadError }}</div><div class="min-h-0 flex-1 overflow-auto">@@ -639,7 +798,7 @@ onBeforeUnmount(() => {type="checkbox"class="h-3.5 w-3.5 accent-primary":checked="selectedIds.has(row.id)"- :disabled="actionsLocked || refreshing || ownSessionId === null || isOwnSession(row) || !Number.isInteger(row.id) || row.id <= 0"+ :disabled="actionsLocked || refreshing || ownSessionId === null || isOwnSession(row) || typeof row.id !== 'number' || !Number.isSafeInteger(row.id) || row.id <= 0":aria-label="t('processList.selectSession', { id: row.id })"@click="toggleSelection(row.id, $event as MouseEvent)"/>@@ -660,7 +819,12 @@ 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?.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") }}+ </Button><Button+ v-if="cancelSupported"variant="ghost"size="sm"class="h-6 gap-1 px-1.5 text-[11px] text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"@@ -676,8 +840,8 @@ onBeforeUnmount(() => {variant="ghost"size="sm"class="h-6 gap-1 px-1.5 text-[11px] text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"- :disabled="isOwnSession(row) || actionsLocked || refreshing"- :title="isOwnSession(row) ? t('processList.cannotTerminateSelf') : t('processList.terminate')"+ :disabled="(rowAwareTerminate && ownSessionId === null) || isOwnSession(row) || !!terminateRowDisabledReason(row) || actionsLocked || refreshing"+ :title="isOwnSession(row) ? t('processList.cannotTerminateSelf') : terminateRowDisabledReason(row) ? t(terminateRowDisabledReason(row) ?? '') : t('processList.terminate')"@click="requestTerminate(row)"><PlugZap class="h-3.5 w-3.5" />@@ -686,7 +850,7 @@ onBeforeUnmount(() => {</span></td></tr>- <tr v-if="!loading && filteredRows.length === 0 && (!transactionMode || !loadError)">+ <tr v-if="!loading && filteredRows.length === 0 && !loadError"><td :colspan="columns.length + 1 + (selectionSupported ? 1 : 0)" class="px-3 py-10 text-center text-muted-foreground">{{ search ? t("grid.noSearchResults") : t(transactionMode ? "processList.transactionEmpty" : "processList.empty") }}</td>@@ -741,6 +905,20 @@ onBeforeUnmount(() => {<p v-if="terminateTarget" class="text-sm text-muted-foreground">{{ t("processList.terminateConfirm", { id: terminateTarget.id, user: terminateTarget.user }) }}</p>+ <dl v-if="terminateTarget && driver?.buildTerminateSessionSqlForRow" class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded border bg-muted/20 p-3 text-xs">+ <template v-for="key in ['container', 'instance', 'serial', 'auditSession', 'logonTime', 'tenant', 'server', 'host', 'proxySessionId']" :key="key">+ <template v-if="terminateTarget[key] !== undefined && terminateTarget[key] !== null">+ <dt class="text-muted-foreground">+ {{+ t(+ `processList.${key === "container" ? "oracleContainer" : key === "instance" ? "oracleInstance" : key === "serial" ? "oracleSerial" : key === "auditSession" ? "oracleAuditSession" : key === "logonTime" ? "oracleLogonTime" : key === "tenant" ? "oracleTenant" : key === "server" ? "oracleNode" : key === "proxySessionId" ? "oracleProxySession" : "colHost"}`,+ )+ }}+ </dt>+ <dd class="break-all font-mono">{{ terminateTarget[key] }}</dd>+ </template>+ </template>+ </dl><DialogFooter><Button variant="outline" :disabled="terminating" @click="terminateTarget = null">{{ t("dangerDialog.cancel") }}</Button><Button variant="destructive" :disabled="terminating" @click="confirmTerminate">@@ -751,6 +929,36 @@ onBeforeUnmount(() => {</DialogContent></Dialog>+ <Dialog :open="lockTarget !== null" @update:open="(open) => !open && closeLockDialog()">+ <DialogContent class="max-h-[min(80vh,700px)] max-w-5xl overflow-hidden">+ <DialogHeader+ ><DialogTitle>{{ t("processList.oracleLockDetails") }} · {{ lockTarget?.id }}</DialogTitle></DialogHeader+ >+ <p v-if="lockTarget" class="text-xs text-muted-foreground">{{ t("processList.oracleLockTarget", { user: lockTarget.user, identity: driver?.rowKey?.(lockTarget) ?? lockTarget.id }) }}</p>+ <div v-if="loadingLocks" class="flex items-center gap-2 py-8 text-sm text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />{{ t("common.loading") }}</div>+ <p v-else-if="lockError" class="rounded border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">{{ lockError }}</p>+ <p v-else-if="lockRows.length === 0" class="py-8 text-center text-sm text-muted-foreground">{{ t("processList.oracleLockDetailsEmpty") }}</p>+ <div v-else class="max-h-[55vh] overflow-auto rounded border">+ <p v-if="lockTruncated" class="border-b bg-muted/30 p-2 text-xs text-muted-foreground">{{ t("processList.oracleLockDetailsTruncated") }}</p>+ <table class="w-full border-collapse text-xs">+ <thead class="sticky top-0 bg-muted/60">+ <tr>+ <th v-for="column in lockColumns" :key="column" class="whitespace-nowrap px-2 py-1.5 text-left font-medium">{{ column }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(row, index) in lockRows" :key="index" class="border-t">+ <td v-for="(value, columnIndex) in row" :key="columnIndex" class="max-w-sm break-all px-2 py-1.5 font-mono">{{ value === null || value === undefined ? "—" : value }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ <DialogFooter+ ><Button variant="outline" @click="closeLockDialog">{{ t("common.close") }}</Button></DialogFooter+ >+ </DialogContent>+ </Dialog>+<Dialog:open="batchTargets !== null"@update:open="diff --git a/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts b/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.tsindex 5b64270b21..c2923558d7 100644--- a/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts+++ b/apps/desktop/src/components/admin/__tests__/ProcessListPanel.spec.ts@@ -1,16 +1,40 @@// @vitest-environment happy-dom-import { createApp, defineComponent, h, nextTick, type App, type Component } from "vue";+import { createApp, defineComponent, h, nextTick, reactive, type App, type Component } from "vue";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { ConnectionConfig } from "@/types/database";+import zhCN from "@/i18n/locales/zh-CN";import { PG_PROCESS_LIST_SQL } from "@/lib/database/postgresProcessList";import { XUGU_OWN_SESSION_SQL, XUGU_TRANSACTION_LIST_SQL } from "@/lib/database/xuguProcessList";+import { buildOceanbaseSessionListSql, OCEANBASE_OWN_SESSION_SQL, buildOracleOwnSessionSql, buildOracleSessionListSql, ORACLE_SESSION_VERSION_SQL } from "@/lib/database/oracleSessionManagement";const mocks = vi.hoisted(() => ({ensureConnected: vi.fn(),executeQuery: vi.fn(),executeMulti: vi.fn(),+ closeClientConnectionSession: vi.fn(),+ contextGuard: vi.fn(),+ contextGuardGate: null as null | (() => Promise<void>),toast: vi.fn(),+ oceanbaseRows: [] as unknown[][],+ oceanbaseTerminated: false,+ oceanbaseKeepTerminatedRow: false,+ oceanbaseListFailure: "",+ oceanbaseListTruncated: false,+ oceanbaseLockFailure: "",+ oceanbaseLockRows: [] as unknown[][],+ oceanbaseLockTruncated: false,+ oceanbaseLockGate: null as null | (() => Promise<void>),+ oceanbaseTerminateFailure: "",+ oceanbaseTargetChanged: false,+ oracleVersionValue: "19.0.0.0.0",+ oracleVersionFailure: "",+ oracleVersionGate: null as null | (() => Promise<void>),+ oracleListFailure: "",+ oracleTargetChanged: false,+ oracleTargetMissing: false,+ localeMessages: null as Record<string, unknown> | null,+ executionErrorSql: "",}));// Flipped by the driver mock to simulate engines without a terminate statement.@@ -60,7 +84,15 @@ function dialogSurface(): Component {vi.mock("vue-i18n", () => ({useI18n: () => ({- t: (key: string, values?: Record<string, unknown>) => (values === undefined ? key : `${key}:${Object.values(values).join(",")}`),+ t: (key: string, values?: Record<string, unknown>) => {+ const message = mocks.localeMessages?.[key.split(".")[0]!] as Record<string, unknown> | undefined;+ const resolved = key+ .split(".")+ .slice(1)+ .reduce<unknown>((current, part) => (current && typeof current === "object" ? (current as Record<string, unknown>)[part] : undefined), message);+ if (typeof resolved !== "string") return values === undefined ? key : `${key}:${Object.values(values).join(",")}`;+ return Object.entries(values ?? {}).reduce((text, [name, value]) => text.replaceAll(`{${name}}`, String(value)), resolved);+ },}),}));vi.mock("@lucide/vue", () => {@@ -81,9 +113,14 @@ 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 }));+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery, executeMulti: mocks.executeMulti, closeClientConnectionSession: mocks.closeClientConnectionSession }));vi.mock("@/lib/database/productionExecutionGuard", () => ({executeWithProductionSqlGuard: (options: { execute: () => Promise<unknown> }) => options.execute(),+ executeWithProductionContextGuard: async (options: { execute: () => Promise<unknown> }) => {+ mocks.contextGuard(options);+ if (mocks.contextGuardGate) await mocks.contextGuardGate();+ return options.execute();+ },}));vi.mock("@/lib/tabs/tabUiState", () => ({ useTabUiState: () => ({ initialState: {}, track: () => {} }) }));vi.mock("@/lib/database/processListDrivers", async (importOriginal) => {@@ -132,6 +169,34 @@ const xuguConnection: ConnectionConfig = {password: "",};+const oracleConnection: ConnectionConfig = {+ id: "oracle-1",+ name: "Oracle",+ db_type: "oracle",+ host: "localhost",+ port: 1521,+ username: "APP",+ password: "",+};++const oceanbaseConnection: ConnectionConfig = {+ id: "oceanbase-1",+ name: "OceanBase",+ db_type: "oceanbase-oracle",+ host: "localhost",+ port: 2881,+ username: "APP",+ password: "",+};++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"]);+ return { columns: [], rows };+}+function xuguTransactionResult() {return {columns: ["NODE_ID", "TRANSACTION_ID", "SESSION_ID", "USER_NAME", "DB_NAME", "CLIENT_IP", "START_TIME"],@@ -171,15 +236,91 @@ beforeEach(() => {driverState.stripTerminate = false;mocks.ensureConnected.mockReset().mockResolvedValue(undefined);mocks.executeQuery.mockReset().mockImplementation(async (_connectionId: string, _database: string, sql: string) => {+ if (mocks.executionErrorSql && sql.includes(mocks.executionErrorSql)) return { columns: ["Error"], rows: [["legacy error row"]], execution_error: true, error: { detail: "ORA-01031: managed read denied" } };if (sql === "SELECT CONNECTION_ID()") return { columns: ["CONNECTION_ID()"], rows: [[5]] };if (sql === "SHOW FULL PROCESSLIST") return mysqlListResult();if (sql === "SELECT pg_backend_pid()") return { columns: ["pg_backend_pid"], rows: [[5]] };if (sql === PG_PROCESS_LIST_SQL) return postgresListResult();if (sql === XUGU_OWN_SESSION_SQL) return { columns: ["NODEID", "SESSION_ID"], rows: [[1, 5]] };if (sql === XUGU_TRANSACTION_LIST_SQL) return xuguTransactionResult();+ if (sql === ORACLE_SESSION_VERSION_SQL) {+ const failure = mocks.oracleVersionFailure;+ const value = mocks.oracleVersionValue;+ const gate = mocks.oracleVersionGate;+ mocks.oracleVersionGate = null;+ if (gate) await gate();+ if (failure) throw new Error(failure);+ return { columns: ["VERSION"], rows: [[value]] };+ }+ if (sql === buildOracleOwnSessionSql(false) || sql === buildOracleOwnSessionSql(true)) return { columns: [], rows: [["5", "1", "3"]] };+ if (sql === buildOracleSessionListSql(false) || sql === buildOracleSessionListSql(true)) {+ if (mocks.oracleListFailure) throw new Error(mocks.oracleListFailure);+ return oracleListResult();+ }+ if (sql.includes("FROM GV$LOCK l JOIN GV$SESSION s"))+ return { columns: ["CONTAINER_ID", "INSTANCE_ID", "SESSION_ID", "LOCK_TYPE", "ID1", "ID2", "HELD_MODE", "REQUESTED_MODE", "BLOCKING", "SESSION_USER", "SESSION_STATUS", "BLOCKER"], rows: [["3", "2", "21", "TX", "100", "200", "6", "0", "1", "OTHER", "INACTIVE", "—"]] };+ if (sql.includes("ALTER SYSTEM KILL SESSION")) {+ if (oracleTerminateError) throw new Error(oracleTerminateError);+ if (mocks.oracleTargetMissing) throw new Error("ORA-20002: Session identity changed; target no longer exists");+ if (mocks.oracleTargetChanged) throw new Error("ORA-20002: Session identity changed; refresh the list");+ oracleTerminated = true;+ return { columns: [], rows: [] };+ }+ if (sql === OCEANBASE_OWN_SESSION_SQL) return { columns: ["ID", "USER", "TENANT"], rows: [["5", "APP", "tenant_a"]] };+ if (sql === buildOceanbaseSessionListSql()) {+ if (mocks.oceanbaseListFailure) throw new Error(mocks.oceanbaseListFailure);+ return { columns: [], rows: mocks.oceanbaseTerminated && !mocks.oceanbaseKeepTerminatedRow ? mocks.oceanbaseRows.filter((row) => String(row[0]) !== "21") : mocks.oceanbaseRows, truncated: mocks.oceanbaseListTruncated };+ }+ if (sql.includes("FROM GV$OB_LOCKS l")) {+ if (mocks.oceanbaseLockFailure) throw new Error(mocks.oceanbaseLockFailure);+ const rows = mocks.oceanbaseLockRows;+ const gate = mocks.oceanbaseLockGate;+ mocks.oceanbaseLockGate = null;+ if (gate) await gate();+ return {+ columns: ["SERVER_IP", "SERVER_PORT", "TENANT_ID", "TRANS_ID", "SESSION_ID", "TYPE", "ID1", "ID2", "ID3", "LMODE", "REQUEST", "CTIME", "BLOCK", "SESSION_USER", "SESSION_STATE"],+ rows,+ truncated: mocks.oceanbaseLockTruncated,+ };+ }+ if (sql.includes("EXECUTE IMMEDIATE 'KILL CONNECTION")) {+ if (mocks.oceanbaseTerminateFailure) throw new Error(mocks.oceanbaseTerminateFailure);+ if (mocks.oceanbaseTargetChanged) throw new Error("ORA-20001: Session identity changed or is not directly addressable");+ mocks.oceanbaseTerminated = true;+ return { columns: [], rows: [] };+ }return { columns: [], rows: [] };});mocks.executeMulti.mockReset().mockResolvedValue([{ columns: [], rows: [] }]);+ mocks.closeClientConnectionSession.mockReset().mockResolvedValue(undefined);+ mocks.contextGuard.mockReset();+ mocks.contextGuardGate = null;+ mocks.toast.mockReset();+ oracleTerminated = false;+ 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"],+ ["22", "PROXY", "tenant_a", "proxyhost", "db", "Query", "5", "active", "SELECT 3", "99", "127.0.0.2", "2882"],+ ];+ mocks.oceanbaseTerminated = false;+ mocks.oceanbaseKeepTerminatedRow = false;+ mocks.oceanbaseListFailure = "";+ mocks.oceanbaseListTruncated = false;+ mocks.oceanbaseLockFailure = "";+ mocks.oceanbaseLockRows = [["127.0.0.1", "2882", "7", "900", "21", "TX", "100", "200", "300", "6", "0", "10", "1", "OTHER", "WAITING"]];+ mocks.oceanbaseLockTruncated = false;+ mocks.oceanbaseLockGate = null;+ mocks.oceanbaseTerminateFailure = "";+ mocks.oceanbaseTargetChanged = false;+ mocks.oracleVersionValue = "19.0.0.0.0";+ mocks.oracleVersionFailure = "";+ mocks.oracleVersionGate = null;+ mocks.oracleListFailure = "";+ mocks.oracleTargetChanged = false;+ mocks.oracleTargetMissing = false;+ mocks.localeMessages = null;+ mocks.executionErrorSql = "";root = document.createElement("div");document.body.appendChild(root);});@@ -220,6 +361,36 @@ async function mountPanel(connection: ConnectionConfig) {await nextTick();}+async function mountOceanbasePanel() {+ app = createApp(ProcessListPanel, { connection: oceanbaseConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.querySelector("tbody")?.textContent).toContain("21"));+ await nextTick();+}++async function mountOraclePanel() {+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.querySelector("tbody")?.textContent).toContain("21"));+ await nextTick();+}++async function mountReactivePanel(connection: ConnectionConfig) {+ const reactiveConnection = reactive({ ...connection });+ const Wrapper = defineComponent({ setup: () => () => h(ProcessListPanel, { connection: reactiveConnection }) });+ app = createApp(Wrapper);+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("21"));+ await nextTick();+ return reactiveConnection;+}++function processRow(id: string): HTMLTableRowElement {+ const row = [...(root?.querySelectorAll<HTMLTableRowElement>("tbody tr") ?? [])].find((candidate) => candidate.querySelector("td")?.textContent?.trim().match(/^\d+/)?.[0] === id);+ expect(row, `session row ${id}`).toBeDefined();+ return row!;+}+async function selectSessions(...ids: number[]) {for (const id of ids) {sessionCheckbox(id)?.dispatchEvent(new MouseEvent("click", { bubbles: true }));@@ -235,6 +406,378 @@ async function mountXuguPanel() {}describe("ProcessListPanel batch terminate", () => {+ it.each([+ ["Oracle", oracleConnection, buildOracleSessionListSql(false)],+ ["OceanBase Oracle", oceanbaseConnection, buildOceanbaseSessionListSql()],+ ])("reports a resolved execution error from the %s session list instead of an empty result", async (_label, connection, sql) => {+ mocks.executionErrorSql = sql;+ app = createApp(ProcessListPanel, { connection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: managed read denied"));+ expect(root?.textContent).not.toContain("processList.empty");+ expect(root?.querySelector("tbody")?.textContent).not.toContain("legacy error row");+ });++ it.each([+ ["Oracle", oracleConnection, "FROM GV$LOCK l JOIN GV$SESSION s"],+ ["OceanBase Oracle", oceanbaseConnection, "FROM GV$OB_LOCKS l"],+ ])("reports a resolved execution error from %s lock details without rendering it as a lock", async (_label, connection, sql) => {+ if (connection.db_type === "oracle") await mountOraclePanel();+ else await mountOceanbasePanel();+ mocks.executionErrorSql = sql;+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.oracleLockDetails"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: managed read denied"));+ expect(root?.textContent).not.toContain("processList.oracleLockDetailsEmpty");+ expect(root?.querySelector("[data-dialog]")?.textContent).not.toContain("legacy error row");+ expect(processRow("21").textContent).toContain("OTHER");+ });++ it("uses the CON_ID-scoped Oracle query when version detection is unknown or denied", async () => {+ mocks.oracleVersionValue = "Oracle Database 19c";+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.querySelector("tbody")?.textContent).toContain("21"));+ expect(root?.textContent).toContain("processList.oracleVersionUnknown");+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(false))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(false))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(true))).toBe(false);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(true))).toBe(false);++ app.unmount();+ app = null;+ root!.innerHTML = "";+ mocks.executeQuery.mockClear();+ mocks.oracleVersionFailure = "ORA-01031: insufficient privileges";+ await mountOraclePanel();+ expect(root?.textContent).toContain("ORA-01031: insufficient privileges");+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(false))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(false))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(true))).toBe(false);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(true))).toBe(false);++ app?.unmount();+ app = null;+ root!.innerHTML = "";+ mocks.executeQuery.mockClear();+ mocks.oracleListFailure = "ORA-00904: CON_ID invalid identifier";+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-00904: CON_ID invalid identifier"));+ expect(root?.textContent).toContain("ORA-01031: insufficient privileges");+ expect(root?.textContent).not.toContain("processList.empty");+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(false))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(true))).toBe(false);+ });++ it("uses the legacy Oracle query only after explicitly detecting a pre-12c version", async () => {+ mocks.oracleVersionValue = "11.2.0.4.0";+ await mountOraclePanel();+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(true))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(true))).toBe(true);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(false))).toBe(false);+ });++ it.each([+ ["late 11g result", "11.2.0.4.0", ""],+ ["late probe rejection", "19.0.0.0.0", "ORA-01031: stale probe denied"],+ ])("discards %s after the Oracle connection changes", async (_label, oldVersion, oldFailure) => {+ let releaseProbe!: () => void;+ mocks.oracleVersionValue = oldVersion;+ mocks.oracleVersionFailure = oldFailure;+ mocks.oracleVersionGate = () => new Promise<void>((resolve) => (releaseProbe = resolve));+ const liveConnection = reactive({ ...oracleConnection });+ const Wrapper = defineComponent({ setup: () => () => h(ProcessListPanel, { connection: liveConnection }) });+ app = createApp(Wrapper);+ app.mount(root!);+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.some((call) => call[2] === ORACLE_SESSION_VERSION_SQL)).toBe(true));++ liveConnection.host = "replacement-host";+ mocks.oracleVersionValue = "19.0.0.0.0";+ mocks.oracleVersionFailure = "";+ await nextTick();+ releaseProbe();++ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(false))).toBe(true));+ expect(mocks.executeQuery.mock.calls.filter((call) => call[2] === ORACLE_SESSION_VERSION_SQL)).toHaveLength(2);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleSessionListSql(true))).toBe(false);+ expect(mocks.executeQuery.mock.calls.some((call) => call[2] === buildOracleOwnSessionSql(true))).toBe(false);+ expect(root?.textContent).not.toContain("ORA-01031: stale probe denied");+ });++ it("rejects a changed Oracle target identity and never reports it as terminated", async () => {+ await mountOraclePanel();+ const targetRow = processRow("21");+ targetRow.querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ mocks.oracleTargetChanged = true;+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("ORA-20002: Session identity changed"), 5000));+ const sql = mocks.executeQuery.mock.calls.map((call) => String(call[2])).find((statement) => statement.includes("ALTER SYSTEM KILL SESSION"));+ expect(sql).toContain("SID = 21 AND SERIAL# = 42 AND INST_ID = 2 AND CON_ID = 3");+ expect(sql).toContain("AUDSID = 700");+ expect(oracleTerminated).toBe(false);+ expect(mocks.toast).not.toHaveBeenCalledWith("processList.terminateSuccess:21", 2500);+ });++ it("does not report a vanished Oracle session as terminated", async () => {+ await mountOraclePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ mocks.oracleTargetMissing = true;+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("target no longer exists"), 5000));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("ALTER SYSTEM KILL SESSION"))).toBe(true);+ expect(oracleTerminated).toBe(false);+ expect(mocks.toast).not.toHaveBeenCalledWith("processList.terminateSuccess:21", 2500);+ });++ it("does not submit a confirmed Oracle termination after same-ID connection configuration changes", async () => {+ const liveConnection = await mountReactivePanel(oracleConnection);+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ liveConnection.host = "replacement-host";+ await nextTick();+ expect(findDialogButton("processList.terminate")).toBeUndefined();+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("ALTER SYSTEM KILL SESSION"))).toBe(false);+ });++ it("renders the terminate action from the actual zh-CN message table", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ await mountReactivePanel(oracleConnection);+ processRow("21").querySelector<HTMLButtonElement>('button[title="终止会话"]')?.click();+ await nextTick();+ expect(findDialogButton("终止会话")).toBeDefined();+ expect(mocks.contextGuard).not.toHaveBeenCalled();+ });++ it("consumes OceanBase sessions and locks, filters and refreshes rows, and terminates one supported session", async () => {+ mocks.oceanbaseListTruncated = true;+ await mountOceanbasePanel();+ expect(root?.textContent).toContain("processList.sessionCount:3+");+ const filter = root?.querySelector<HTMLInputElement>('input[placeholder="processList.filter"]');+ expect(filter).toBeDefined();+ filter!.value = "OTHER";+ filter!.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ expect(processRow("21").textContent).toContain("OTHER");+ expect(root?.querySelectorAll("tbody tr")).toHaveLength(1);+ filter!.value = "";+ filter!.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();++ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.oracleLockDetails"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("TX"));+ expect(root?.textContent).toContain("processList.oracleLockTarget");+ const lockCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("FROM GV$OB_LOCKS"));+ expect(lockCall?.[5]).toMatchObject({ clientSessionId: expect.stringMatching(/^process-list:/) });++ const sessionIds = mocks.executeQuery.mock.calls.map((call) => (call[5] as { clientSessionId?: string } | undefined)?.clientSessionId);+ expect(new Set(sessionIds).size).toBe(1);+ const queryCount = mocks.executeQuery.mock.calls.filter((call) => call[2] === buildOceanbaseSessionListSql()).length;+ mocks.oceanbaseRows[1]![1] = "UPDATED";+ gridButtons()+ .find((button) => button.textContent?.trim() === "grid.refresh")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("UPDATED"));+ expect(mocks.executeQuery.mock.calls.filter((call) => call[2] === buildOceanbaseSessionListSql()).length).toBeGreaterThan(queryCount);++ const proxyTerminate = processRow("22").querySelector<HTMLButtonElement>('button[title="processList.oracleProxyUnsupported"]');+ expect(proxyTerminate?.disabled).toBe(true);+ expect(processRow("5").querySelector<HTMLButtonElement>('button[title="processList.cannotTerminateSelf"]')?.disabled).toBe(true);+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("processList.oracleTenant");+ expect(root?.textContent).toContain("processList.oracleNode");+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("processList.oracleTerminateUnknown", 5000));+ const killCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("EXECUTE IMMEDIATE 'KILL CONNECTION"));+ expect(killCall?.[2]).toContain(`ID = 21 AND "USER" = 'UPDATED' AND TENANT = 'tenant_a'`);+ expect(killCall?.[5]).toMatchObject({ clientSessionId: expect.stringMatching(/^process-list:/) });+ expect(mocks.contextGuard.mock.calls.at(-1)?.[0]).toMatchObject({ scope: "connection", reviewText: expect.stringContaining("KILL CONNECTION") });+ const managementSessionId = sessionIds[0];+ app?.unmount();+ app = null;+ expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(oceanbaseConnection.id, "", managementSessionId);+ });++ it("renders OceanBase lock labels from the actual zh-CN message table", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ mocks.oceanbaseLockTruncated = true;+ await mountOceanbasePanel();+ const lockButton = processRow("21").querySelector<HTMLButtonElement>('button[title="锁详情"]');+ expect(lockButton?.textContent).toContain("锁详情");+ lockButton?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("目标会话:OTHER ·"));+ expect(root?.textContent).toContain("锁记录已截断;显示结果可能不完整。");+ expect(root?.textContent).not.toContain("processList.oracleLockDetails");+ });++ it("renders the OceanBase empty lock message from the actual zh-CN table", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ mocks.oceanbaseLockRows = [];+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="锁详情"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("此会话没有可见的锁记录。"));+ });++ it("clears a closed lock request and ignores its late response after reopening", async () => {+ let release!: () => void;+ mocks.oceanbaseLockRows = [["127.0.0.1", "2882", "7", "900", "21", "TX", "100", "200", "300", "6", "0", "10", "1", "OLD", "WAITING"]];+ mocks.oceanbaseLockGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountOceanbasePanel();+ const lockButton = processRow("21").querySelector<HTMLButtonElement>('button[title="processList.oracleLockDetails"]')!;+ lockButton.click();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM GV$OB_LOCKS l")).length).toBe(1));+ root?.querySelector<HTMLButtonElement>("[data-dialog] button")?.click();+ await nextTick();+ expect(lockButton.disabled).toBe(false);++ mocks.oceanbaseLockRows = [["127.0.0.1", "2882", "7", "901", "21", "TX", "101", "201", "301", "6", "0", "10", "1", "FRESH", "WAITING"]];+ lockButton.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("FRESH"));+ release();+ await nextTick();+ expect(root?.textContent).toContain("FRESH");+ expect(root?.textContent).not.toContain("OLD");+ });++ it("does not report termination success when the truncated refresh omits the target", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ mocks.oceanbaseListTruncated = true;+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="终止会话"]')?.click();+ await nextTick();+ findDialogButton("终止会话")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("终止请求结果不明。请刷新会话列表确认状态,不要重复提交。", 5000));+ expect(mocks.toast).not.toHaveBeenCalledWith("processList.terminateSuccess:21", 2500);+ });++ it("uses the existing pending message when the terminated row remains in the refreshed list", async () => {+ mocks.localeMessages = zhCN as Record<string, unknown>;+ mocks.oceanbaseKeepTerminatedRow = true;+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="终止会话"]')?.click();+ await nextTick();+ findDialogButton("终止会话")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("终止请求已接受,会话仍在回滚或尚未退出。刷新以查看状态。", 4000));+ });++ it("keeps an OceanBase list permission failure distinct from confirmed empty results", async () => {+ mocks.oceanbaseListFailure = "ORA-01031: process list denied";+ app = createApp(ProcessListPanel, { connection: oceanbaseConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: process list denied"));+ expect(root?.textContent).not.toContain("processList.empty");+ });++ it("preserves the OceanBase session list when lock details are denied", async () => {+ mocks.oceanbaseLockFailure = "ORA-01031: locks denied";+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.oracleLockDetails"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: locks denied"));+ expect(root?.textContent).toContain("OTHER");+ expect(root?.textContent).not.toContain("processList.oracleLockDetailsEmpty");+ });++ it("shows an empty OceanBase result only when the query completed without an error", async () => {+ mocks.oceanbaseRows = [];+ app = createApp(ProcessListPanel, { connection: oceanbaseConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.empty"));+ expect(root?.textContent).not.toContain("ORA-01031");+ });++ it("preserves an OceanBase termination permission denial instead of reporting success", async () => {+ mocks.oceanbaseTerminateFailure = "ORA-01031: KILL CONNECTION denied";+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("ORA-01031: KILL CONNECTION denied"), 5000));+ expect(mocks.toast).not.toHaveBeenCalledWith("processList.terminateSuccess:21", 2500);+ });++ it("does not report an OceanBase session with changed tenant/node identity as terminated", async () => {+ await mountOceanbasePanel();+ processRow("21").querySelector<HTMLButtonElement>('button[title="processList.terminate"]')?.click();+ await nextTick();+ mocks.oceanbaseTargetChanged = true;+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("ORA-20001: Session identity changed"), 5000));+ const sql = mocks.executeQuery.mock.calls.map((call) => String(call[2])).find((statement) => statement.includes("EXECUTE IMMEDIATE 'KILL CONNECTION"));+ expect(sql).toContain(`ID = 21 AND "USER" = 'OTHER' AND TENANT = 'tenant_a'`);+ expect(sql).toContain("SVR_IP = '127.0.0.1' AND SVR_PORT = 2882");+ expect(mocks.oceanbaseTerminated).toBe(false);+ expect(mocks.toast).not.toHaveBeenCalledWith("processList.terminateSuccess:21", 2500);+ });++ it("terminates one Oracle row through the independent managed session and reads the row back", async () => {+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("21"));+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleSerial"));++ expect(gridButtons().some((button) => button.textContent?.trim() === "processList.kill")).toBe(false);+ const terminateButtons = gridButtons().filter((button) => button.textContent?.trim() === "processList.terminate");+ expect(terminateButtons).toHaveLength(2);+ expect(terminateButtons[0]?.disabled).toBe(true);+ expect(terminateButtons[1]?.disabled).toBe(false);++ terminateButtons[1]?.click();+ await nextTick();+ expect(root?.textContent).toContain("processList.oracleContainer");+ expect(root?.textContent).toContain("processList.oracleInstance");+ expect(root?.textContent).toContain("processList.oracleSerial");+ findDialogButton("processList.terminate")?.click();++ await vi.waitFor(() => expect(oracleTerminated).toBe(true));+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("processList.terminateSuccess:21", 2500));+ const actionCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("ALTER SYSTEM KILL SESSION"));+ expect(actionCall?.[2]).toContain("CON_ID = 3");+ expect(actionCall?.[2]).toContain("SERIAL# = 42");+ const actionSession = (actionCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(actionSession).toBeTruthy();+ expect(actionSession).toMatch(/^process-list:/);+ expect(mocks.executeQuery.mock.calls.every((call) => (call[5] as { clientSessionId?: string } | undefined)?.clientSessionId === actionSession)).toBe(true);+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("GV$SESSION")).every((call) => (call[5] as { clientSessionId?: string })?.clientSessionId === actionSession)).toBe(true);+ expect(mocks.contextGuard.mock.calls[0]?.[0]).toMatchObject({ scope: "connection", database: "", source: "production.sourceAdmin" });+ app?.unmount();+ app = null;+ expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(oracleConnection.id, "", actionSession);+ });++ it("preserves the database denial when termination outcome is unknown", async () => {+ oracleTerminateError = "ORA-01031: insufficient privileges";+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("21"));+ gridButtons()+ .filter((button) => button.textContent?.trim() === "processList.terminate")[1]+ ?.click();+ await nextTick();+ findDialogButton("processList.terminate")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("ORA-01031: insufficient privileges"), 5000));+ expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("processList.oracleTerminateUnknown"), 5000);+ });++ it("opens lock details for the selected Oracle session using the managed session", async () => {+ app = createApp(ProcessListPanel, { connection: oracleConnection });+ app.mount(root!);+ await vi.waitFor(() => expect(root?.textContent).toContain("21"));++ const lockButtons = gridButtons().filter((button) => button.textContent?.trim() === "processList.oracleLockDetails");+ expect(lockButtons).toHaveLength(2);+ lockButtons[1]?.click();++ await vi.waitFor(() => expect(root?.textContent).toContain("TX"));+ expect(root?.textContent).toContain("processList.oracleLockTarget");+ const lockQuery = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("FROM GV$LOCK l JOIN GV$SESSION s"));+ expect(lockQuery?.[2]).toContain("l.CON_ID = 3");+ const managedSession = (lockQuery?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(managedSession).toBeTruthy();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("GV$SESSION")).every((call) => (call[5] as { clientSessionId?: string })?.clientSessionId === managedSession)).toBe(true);+ });+it("terminates every selected session one by one after confirmation", async () => {await mountPanel(mysqlConnection);await selectSessions(11, 12);diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 8221ba8194..5d8697f1f4 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -117,6 +117,7 @@ import { prepareOracleTableRename, executeOracleTableRename, OracleTableRenameFaimport OracleTableRenamePreview from "@/components/objects/OracleTableRenamePreview.vue";import OracleRoutineRenamePreview from "@/components/objects/OracleRoutineRenamePreview.vue";import OraclePackageSaveAsDialog from "@/components/objects/OraclePackageSaveAsDialog.vue";+import OracleInvalidObjectsDialog from "@/components/objects/OracleInvalidObjectsDialog.vue";import { executeOraclePackageSaveAs, OraclePackageSaveAsFailure, prepareOraclePackageSaveAs, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";import { autoRevealExportedPathIfConfigured, promptExportSavePath } from "@/lib/export/exportPath";@@ -198,8 +199,10 @@ import { metadataLoadBudgetMs } from "@/lib/metadata/metadataLoadBudget";import { loadObjectDdl, type ObjectDdlRequest } from "@/lib/metadata/objectDdlCache";import { loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";import { invalidateObjectMetadataCache } from "@/lib/metadata/objectMetadataCache";-import { invalidateObjectDdl } from "@/lib/metadata/objectDdlCache";+import { invalidateObjectDdl, invalidateObjectDdlCache } from "@/lib/metadata/objectDdlCache";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import { completeOracleInvalidObjectCompile, type OracleInvalidObjectCompileScope } from "@/lib/database/oracleInvalidObjectCacheRefresh";+import { oracleInvalidObjectSourceKind } from "@/lib/database/oracleInvalidObjects";import { eventEditorInstanceKey, resolveInitialEventEditorRequest } from "@/lib/table/eventEditorRequest";import { createLocateTabMenuItem } from "@/lib/tabs/tabMenu";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -250,6 +253,10 @@ const refreshTooltip = computed(() => {const firebirdManagerOpen = ref(false);const schemas = ref<string[]>([]);const selectedSchema = ref<string | undefined>(props.schema);+const oracleInvalidObjectsOpen = ref(false);+let invalidObjectsDialogGeneration = 0;+let invalidObjectSourceRequestGeneration = 0;+let objectBrowserUnmounted = false;const rows = ref<ObjectBrowserRow[]>([]);const rootRef = ref<HTMLElement>();const search = ref(props.initialSearchQuery ?? "");@@ -350,9 +357,21 @@ const sidePanelGuard = createSidePanelRequestGuard();const sidePanelRef = ref<InstanceType<typeof CustomTypeInfoPanel> | null>(null);const tableMetadataCapabilities = computed<TableMetadataCapabilities>(() => getTableMetadataCapabilities(effectiveDatabaseType.value));const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type);+const oracleInvalidObjectsSupported = computed(() => effectiveDatabaseType.value === "oracle" || effectiveDatabaseType.value === "oceanbase-oracle");const usesServerObjectPaging = computed(() => props.connection.db_type === "oceanbase-oracle");const objectPageSize = computed(() => Math.max(1, Math.min(10_000, Math.floor(settingsStore.desktopSettings?.sidebar_table_page_size || 500))));const isGaussdbM = computed(() => effectiveDatabaseType.value === "gaussdb" && props.connection.driver_profile?.toLowerCase() === "gaussdb-m");++function setOracleInvalidObjectsOpen(open: boolean) {+ if (oracleInvalidObjectsOpen.value !== open) invalidObjectsDialogGeneration++;+ oracleInvalidObjectsOpen.value = open;+}++watch(+ () => [props.connection.id, JSON.stringify(props.connection), props.database, props.catalog, selectedSchema.value] as const,+ () => invalidObjectsDialogGeneration++,+ { flush: "sync" },+);const isVictoriaMetrics = computed(() => effectiveDatabaseType.value === "victoriametrics");const isMongodb = computed(() => props.connection.db_type === "mongodb");// Neither VictoriaMetrics series nor NebulaGraph tag/edge metadata has table byte-size stats.@@ -1879,6 +1898,81 @@ async function openSource(row: ObjectBrowserRow) {await loadSourcePanel(row);}+async function openInvalidObjectSource(object: { owner: string; name: string; type: string }) {+ const objectType = oracleInvalidObjectSourceKind(object.type);+ if (!objectType) return;+ const dialogGeneration = invalidObjectsDialogGeneration;+ const requestGeneration = ++invalidObjectSourceRequestGeneration;+ const connection = { ...props.connection };+ const connectionKey = JSON.stringify(connection);+ const database = props.database;+ const catalog = props.catalog;+ const schema = selectedSchema.value || database;+ const isCurrentRequest = () =>+ !objectBrowserUnmounted &&+ requestGeneration === invalidObjectSourceRequestGeneration &&+ dialogGeneration === invalidObjectsDialogGeneration &&+ oracleInvalidObjectsOpen.value &&+ props.connection.id === connection.id &&+ JSON.stringify(props.connection) === connectionKey &&+ props.database === database &&+ props.catalog === catalog &&+ (selectedSchema.value || props.database) === schema;+ if (objectType === "TYPE" || objectType === "TYPE_BODY" || objectType === "TRIGGER") {+ try {+ const source = await api.getObjectSource(connection.id, database, object.owner, object.name, objectType);+ if (!isCurrentRequest()) return;+ if (!source.source?.trim()) throw new Error(t("processList.oracleInvalidObjects.sourceUnavailable"));+ const tabId = queryStore.createTab(connection.id, database, `Repair - ${object.name}`, "query", object.owner, undefined, catalog);+ queryStore.updateSql(tabId, source.source);+ setOracleInvalidObjectsOpen(false);+ } catch (error) {+ if (isCurrentRequest()) toast(t("processList.oracleInvalidObjects.sourceLoadFailed", { message: error instanceof Error ? error.message : String(error) }), 5000);+ }+ return;+ }+ const connectionId = connection.id;+ const tabId = queryStore.openObjectSourceTabPending({+ connectionId,+ database,+ title: `Source - ${object.name}`,+ schema: object.owner,+ catalog,+ initialEditing: true,+ request: { name: object.name, objectType },+ });+ const sourceLoadResult = await new Promise<{ error?: string }>((resolve) => {+ const getResult = () => {+ const tab = queryStore.tabs.find((candidate) => candidate.id === tabId);+ if (!tab) return { error: t("processList.oracleInvalidObjects.sourceUnavailable") };+ if (tab.sourceLoad?.error) return { error: tab.sourceLoad.error };+ if (!tab.sourceLoad && tab.objectSource) return {};+ return null;+ };+ const stop = watch(+ getResult,+ (result) => {+ if (!result) return;+ stop();+ resolve(result);+ },+ { flush: "sync" },+ );+ const initial = getResult();+ if (initial) {+ stop();+ resolve(initial);+ }+ });+ if (!isCurrentRequest()) return;+ const tab = queryStore.tabs.find((candidate) => candidate.id === tabId);+ if (sourceLoadResult.error || !tab?.objectSource) {+ toast(t("processList.oracleInvalidObjects.sourceLoadFailed", { message: sourceLoadResult.error || tab?.sourceLoad?.error || t("processList.oracleInvalidObjects.sourceUnavailable") }), 5000);+ return;+ }+ setOracleInvalidObjectsOpen(false);+}+let sourceIdentity: SourceIdentitySnapshot | undefined;async function loadSourcePanel(row: ObjectBrowserRow, options?: { preserveEditing?: boolean }) {@@ -3680,6 +3774,21 @@ async function compileXuguObject(row: ObjectBrowserRow) {}}+async function refreshAfterInvalidObjectCompile(scope: OracleInvalidObjectCompileScope) {+ await completeOracleInvalidObjectCompile(+ scope,+ () => ({ connectionId: props.connection.id, database: props.database, schema: selectedSchema.value || props.database }),+ async (completed) => {+ await invalidateObjectDdlCache(completed);+ invalidateObjectBrowserRowsCache(completed);+ },+ async (current) => {+ if (objectBrowserUnmounted) return;+ await Promise.all([reload(), connectionStore.refreshObjectListTreeNode(current.connectionId, current.database, current.schema)]);+ },+ );+}+async function compileDamengView(row: ObjectBrowserRow) {if (effectiveDatabaseType.value !== "dameng" || row.type !== "VIEW") return;const schema = row.schema || selectedSchema.value;@@ -4368,6 +4477,9 @@ function matchesRefreshScope(scope: { schema?: string; catalog?: string }): booldefineExpose({ focusSearch, refresh, matchesRefreshScope });onBeforeUnmount(() => {+ objectBrowserUnmounted = true;+ invalidObjectsDialogGeneration++;+ invalidObjectSourceRequestGeneration++;clearTimeout(objectSearchTimer);sidePanelGuard.bump();objectBrowserRowsLoadGuard.invalidate();@@ -4719,10 +4831,21 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {@confirm="cloneDialog.confirm"/><FirebirdObjectManager v-if="effectiveDatabaseType === 'firebird'" v-model:open="firebirdManagerOpen" :connection-id="connection.id" :database="database" />+ <OracleInvalidObjectsDialog+ v-if="oracleInvalidObjectsSupported"+ :open="oracleInvalidObjectsOpen"+ :connection="connection"+ :database="database"+ :schema="selectedSchema || database"+ @update:open="setOracleInvalidObjectsOpen"+ @open-source="openInvalidObjectSource"+ @compile-finished="refreshAfterInvalidObjectCompile"+ /><div ref="rootRef" data-object-browser-root class="flex h-full min-h-0 min-w-0 flex-col bg-background outline-none" tabindex="0" @keydown="onObjectBrowserKeydown"><SidebarMenuPreferencesDialog v-if="sidebarMenuPreferences" v-model:open="sidebarMenuPreferencesOpen" :scope="sidebarMenuPreferences.scope" :items="sidebarMenuPreferences.items" /><div v-if="!isEventEditor" ref="toolbarRef" class="flex h-10 shrink-0 items-center gap-2 overflow-hidden border-b px-3"><Button v-if="effectiveDatabaseType === 'firebird'" variant="outline" size="sm" @click="firebirdManagerOpen = true">{{ t("tree.firebirdObjectManager") }}</Button>+ <Button v-if="oracleInvalidObjectsSupported" variant="ghost" size="sm" class="h-7 gap-1.5 px-2 text-xs" @click="setOracleInvalidObjectsOpen(true)">{{ t("processList.oracleInvalidObjects.title") }}</Button><div class="flex min-w-12 items-center gap-2"><span class="inline-flex max-w-[14rem] min-w-0 items-center rounded border border-border bg-muted/50 px-2 py-0.5 text-xs font-medium truncate" :title="selectedSchema || props.database">{{ selectedSchema || props.database }}diff --git a/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vue b/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vuenew file mode 100644index 0000000000..1b639bdf17--- /dev/null+++ b/apps/desktop/src/components/objects/OracleInvalidObjectsDialog.vue@@ -0,0 +1,1257 @@+<script setup lang="ts">+import { computed, nextTick, onBeforeUnmount, reactive, ref, shallowRef, watch } from "vue";+import { AlertTriangle, ChevronDown, Circle, CircleHelp, CircleMinus, CircleX, Clock, Loader2, RefreshCw, Wrench } from "@lucide/vue";+import { useI18n } from "vue-i18n";+import { DynamicScroller, DynamicScrollerItem } from "vue-virtual-scroller";+import "vue-virtual-scroller/dist/vue-virtual-scroller.css";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import type { ConnectionConfig, DatabaseType } from "@/types/database";+import * as api from "@/lib/backend/api";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import { uuid } from "@/lib/common/utils";+import { formatError, normalizeBackendError } from "@/lib/backend/errorUtils";+import { oracleWriteRejected } from "@/lib/database/oracleSecurity";+import {+ oracleCompileUnsupportedReason,+ oracleInvalidObjectSourceKind,+ buildOracleCompileSql,+ buildOracleInvalidObjectsSql,+ buildOracleObjectErrorsSql,+ buildOracleObjectIdentitySql,+ buildOracleObjectStatusSql,+ mapOracleInvalidObjects,+ mapOracleObjectErrors,+ readAllOracleInvalidObjects,+ type OracleInvalidObject,+ type OracleObjectError,+} from "@/lib/database/oracleInvalidObjects";++const props = defineProps<{ open: boolean; connection: ConnectionConfig; database: string; schema: string }>();+const emit = defineEmits<{+ "update:open": [open: boolean];+ "open-source": [object: OracleInvalidObject];+ "compile-finished": [scope: { connectionId: string; database: string; schema: string }];+}>();+const { t } = useI18n();+const objects = ref<OracleInvalidObject[]>([]);+const selected = ref<OracleInvalidObject | null>(null);+const selectedObjects = ref(new Map<string, OracleInvalidObject>());+const currentView = ref<"list" | "detail">("list");+const detailReturnKey = ref("");+const nameFilter = ref("");+const typeFilter = ref<Set<string> | null>(null);+const fullObjects = ref<OracleInvalidObject[]>([]);+const unverifiedKeys = ref(new Set<string>());+const rowResults = ref(new Map<string, BatchItem>());+const fullReadState = ref<"idle" | "reading" | "complete" | "error" | "stopped">("idle");+const fullReadError = ref("");+const fullReadGeneration = ref(0);+const verifyMissingOnNextRead = ref(false);+const errors = ref<OracleObjectError[]>([]);+const errorsTruncated = ref(false);+const loadError = ref("");+const errorLoadError = ref("");+const loading = ref(false);+const compiling = ref(false);+const truncated = ref(false);+const outcome = ref("");+const fullReadCount = ref(0);+const generation = ref(0);+type ManagedSession = { id: string; connectionId: string; database: string; active: number; closeRequested: boolean; closed: boolean };+type ExecutionScope = { connection: ConnectionConfig; connectionKey: string; database: string; schema: string; generation: number; session: ManagedSession };+type BatchStatus = "pending" | "running" | "unsupported" | "valid" | "still-invalid" | "already-valid" | "target-changed" | "deleted" | "failed" | "unknown" | "not-run";+type BatchItem = { object: OracleInvalidObject; sql?: string; unsupportedReason?: "unsupported-type" | "unsupported-on-engine"; status: BatchStatus; message?: string; errors?: OracleObjectError[]; errorsTruncated?: boolean; diagnosticError?: string };+type BatchRun = {+ id: string;+ scope: ExecutionScope;+ state: "running" | "complete";+ readCount: number;+ items: BatchItem[];+ stopRequested: boolean;+ submittedAny: boolean;+ currentName: string;+ readError: string;+ remaining?: OracleInvalidObject[];+ remainingError: string;+};+const batchRun = ref<BatchRun | null>(null);+const batchSupportedCount = computed(() => batchRun.value?.items.filter((item) => !!item.sql).length ?? 0);+const batchSkippedCount = computed(() => batchRun.value?.items.filter((item) => !item.sql || item.status === "not-run").length ?? 0);+const batchHandledCount = computed(() => batchRun.value?.items.filter((item) => item.status !== "pending" && item.status !== "running" && item.status !== "unsupported").length ?? 0);+const batchValidCount = computed(() => batchRun.value?.items.filter((item) => item.status === "valid" || item.status === "already-valid").length ?? 0);+const batchStillInvalidCount = computed(() => batchRun.value?.items.filter((item) => item.status === "still-invalid").length ?? 0);+const batchFailureCount = computed(() => batchRun.value?.items.filter((item) => item.status === "failed" || item.status === "unknown" || item.status === "target-changed" || item.status === "deleted").length ?? 0);+let batchExecutionGeneration = 0;+function newManagedSession(connectionId: string, database: string): ManagedSession {+ return { id: `invalid-objects:${uuid()}`, connectionId, database, active: 0, closeRequested: false, closed: false };+}+let managedSession: ManagedSession | null = null;+let sessionDrainWaiters: Array<() => void> = [];+const displayedObjects = computed(() => objects.value);+const filteredObjects = computed(() => displayedObjects.value.filter(matchesFilters));+const availableTypes = computed(() => [...new Set([...objects.value.map((object) => object.type), ...(typeFilter.value ?? [])])].sort());+const hasFilters = computed(() => nameFilter.value !== "" || typeFilter.value !== null);+const selectedCount = computed(() => selectedObjects.value.size);+const selectedSupportedCount = computed(() => [...selectedObjects.value.values()].filter(canCompileObject).length);+const completeMatchingObjects = computed(() => {+ const completeObjects = new Map(fullObjects.value.map((object) => [selectionKey(object), object]));+ return filteredObjects.value.flatMap((object) => {+ const current = completeObjects.get(selectionKey(object));+ return current && sameObject(object, current) && object.lastDdlTime === current.lastDdlTime && !unverifiedKeys.value.has(selectionKey(object)) ? [current] : [];+ });+});+const allSupportedCount = computed(() => completeMatchingObjects.value.filter(canCompileObject).length);+const allSelectedInFilter = computed(() => {+ const supported = filteredObjects.value.filter(canCompileObject);+ return supported.length > 0 && supported.every((object) => selectedObjects.value.has(selectionKey(object)));+});+const someSelectedInFilter = computed(() => filteredObjects.value.some((object) => selectedObjects.value.has(selectionKey(object))) && !allSelectedInFilter.value);+let singleCompilationGeneration = 0;+let diagnosticGeneration = 0;+let listLoadGeneration = 0;+const databaseType = computed(() => (effectiveDatabaseTypeForConnection(props.connection) ?? props.connection.db_type) as DatabaseType);+type ListCache = { keys: Array<string | number>; sizes: Array<number | null> };+type ListScroller = {+ $el: HTMLElement;+ findItemIndex: (offset: number) => number;+ getItemOffset: (index: number) => number;+ scrollToItem: (index: number, options?: { align: "nearest" }) => void;+ scrollToPosition: (position: number) => void;+ cacheSnapshot: ListCache;+};+type ListViewport = { key: string; index: number; offset: number; focusedKey?: string; focusedControl?: "checkbox" | "name" };+const listScroller = ref<ListScroller | null>(null);+const listCache = shallowRef<ListCache>();+let detailViewport: ListViewport | null = null;+let viewportGeneration = 0;++function isCurrent(token: number): boolean {+ return token === generation.value && props.open;+}++function selectionKey(object: OracleInvalidObject): string {+ return `${object.owner}:${object.objectId}`;+}++function sameObject(left: OracleInvalidObject, right: OracleInvalidObject): boolean {+ return selectionKey(left) === selectionKey(right) && left.name === right.name && left.type === right.type;+}++function renderKey(object: OracleInvalidObject): string {+ return JSON.stringify([object.owner, object.name, object.type, object.objectId]);+}++function matchesFilters(object: OracleInvalidObject): boolean {+ return object.name.toLowerCase().includes(nameFilter.value.toLowerCase()) && (typeFilter.value === null || typeFilter.value.has(object.type));+}++function captureViewport(): ListViewport | null {+ const scroller = listScroller.value;+ if (!scroller || currentView.value !== "list" || filteredObjects.value.length === 0) return null;+ const index = Math.min(Math.max(0, scroller.findItemIndex(scroller.$el.scrollTop)), filteredObjects.value.length - 1);+ const object = filteredObjects.value[index]!;+ const focused = scroller.$el.contains(document.activeElement) ? (document.activeElement as HTMLElement) : null;+ return { key: renderKey(object), index, offset: scroller.$el.scrollTop - scroller.getItemOffset(index), focusedKey: focused?.closest<HTMLElement>("[data-row-key]")?.dataset.rowKey, focusedControl: focused?.tagName === "INPUT" ? "checkbox" : "name" };+}++async function restoreViewport(viewport: ListViewport | null, focusKey?: string, control: "checkbox" | "name" = "name") {+ if (!viewport) return;+ const requestId = ++viewportGeneration;+ const token = generation.value;+ await nextTick();+ if (!isCurrent(token) || requestId !== viewportGeneration || currentView.value !== "list") return;+ const rows = filteredObjects.value;+ if (rows.length === 0) {+ if (focusKey) document.querySelector<HTMLElement>("[data-list-heading]")?.focus();+ return;+ }+ const anchorIndex = rows.findIndex((object) => renderKey(object) === viewport.key);+ const index = anchorIndex >= 0 ? anchorIndex : Math.min(viewport.index, rows.length - 1);+ listScroller.value?.scrollToPosition(Math.max(0, (listScroller.value?.getItemOffset(index) ?? 0) + viewport.offset));+ if (!focusKey) return;+ const focusIndex = rows.findIndex((object) => renderKey(object) === focusKey);+ const targetIndex = focusIndex >= 0 ? focusIndex : index;+ listScroller.value?.scrollToItem(targetIndex, { align: "nearest" });+ await nextTick();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ if (!isCurrent(token) || requestId !== viewportGeneration || currentView.value !== "list") return;+ const row = Array.from(listScroller.value?.$el.querySelectorAll<HTMLElement>("[data-row-key]") ?? []).find((element) => element.dataset.rowKey === renderKey(rows[targetIndex]!));+ (row?.querySelector<HTMLElement>(control === "checkbox" ? "input:not(:disabled)" : "[data-object-key]") ?? row?.querySelector<HTMLElement>("[data-object-key]") ?? document.querySelector<HTMLElement>("[data-list-heading]"))?.focus({ preventScroll: true });+}++function keepViewport(viewport: ListViewport | null) {+ const focusedRemoved = viewport?.focusedKey && !filteredObjects.value.some((object) => renderKey(object) === viewport.focusedKey);+ void restoreViewport(viewport, focusedRemoved ? viewport.focusedKey : undefined, viewport?.focusedControl);+}++function resetFilterSelection() {+ selectedObjects.value = new Map();+ viewportGeneration++;+ detailViewport = null;+ void nextTick(() => listScroller.value?.scrollToPosition(0));+}++function setNameFilter(value: string | number) {+ if (compiling.value) return;+ resetFilterSelection();+ nameFilter.value = String(value);+}++function setTypeFilter(type: string, checked: boolean) {+ if (compiling.value) return;+ resetFilterSelection();+ const next = new Set(typeFilter.value ?? availableTypes.value);+ if (checked) next.add(type);+ else next.delete(type);+ typeFilter.value = next;+}++function setAllTypes(checked: boolean) {+ if (compiling.value) return;+ resetFilterSelection();+ typeFilter.value = checked ? null : new Set();+}++function clearFilters() {+ if (compiling.value) return;+ resetFilterSelection();+ nameFilter.value = "";+ typeFilter.value = null;+}++function onRowTab(event: KeyboardEvent, object: OracleInvalidObject, control: "checkbox" | "name") {+ if (event.ctrlKey || event.altKey || event.metaKey) return;+ if ((!event.shiftKey && control === "checkbox") || (event.shiftKey && control === "name" && !compiling.value && canCompileObject(object))) return;+ const index = filteredObjects.value.findIndex((row) => sameObject(row, object)) + (event.shiftKey ? -1 : 1);+ const next = filteredObjects.value[index];+ if (!next) return;+ event.preventDefault();+ const viewport = captureViewport();+ if (!viewport) return;+ const nextControl = !event.shiftKey && !compiling.value && canCompileObject(next) ? "checkbox" : "name";+ void restoreViewport(viewport, renderKey(next), nextControl);+}++function canCompileObject(object: OracleInvalidObject): boolean {+ return !unverifiedKeys.value.has(selectionKey(object)) && !oracleCompileUnsupportedReason(databaseType.value, object.type);+}++function removeValidObject(object: OracleInvalidObject) {+ const viewport = captureViewport();+ objects.value = objects.value.filter((current) => !sameObject(current, object));+ fullObjects.value = fullObjects.value.filter((current) => !sameObject(current, object));+ selectedObjects.value.delete(selectionKey(object));+ unverifiedKeys.value.delete(selectionKey(object));+ rowResults.value.delete(selectionKey(object));+ keepViewport(viewport);+}++function mergeDictionaryRows(rows: OracleInvalidObject[], complete: boolean, acceptChangedIdentity = false) {+ const viewport = captureViewport();+ const incoming = new Map(rows.map((object) => [selectionKey(object), object]));+ const merged: OracleInvalidObject[] = [];+ const unverified = new Set(unverifiedKeys.value);+ for (const previous of objects.value) {+ const key = selectionKey(previous);+ const current = incoming.get(key);+ if (current && sameObject(previous, current)) {+ const result = rowResults.value.get(key);+ const changed = previous.lastDdlTime !== current.lastDdlTime;+ if (result && (changed || unverified.has(key)) && !acceptChangedIdentity) {+ merged.push(previous);+ unverified.add(key);+ } else {+ merged.push(current);+ unverified.delete(key);+ }+ incoming.delete(key);+ } else if (current) {+ // The ID now describes another name/type; require explicit refresh before rebinding it.+ if (acceptChangedIdentity) {+ merged.push(current);+ rowResults.value.delete(key);+ unverified.delete(key);+ } else {+ merged.push(previous);+ unverified.add(key);+ }+ incoming.delete(key);+ } else {+ merged.push(previous);+ if (complete) unverified.add(key);+ }+ }+ merged.push(...incoming.values());+ objects.value = merged;+ unverifiedKeys.value = unverified;+ const current = new Map(merged.map((object) => [selectionKey(object), object]));+ selectedObjects.value = new Map(+ [...selectedObjects.value].filter(([key, previous]) => {+ const refreshed = current.get(key);+ return refreshed && matchesFilters(refreshed) && canCompileObject(refreshed) && sameObject(refreshed, previous) && refreshed.lastDdlTime === previous.lastDdlTime;+ }),+ );+ keepViewport(viewport);+}++function waitForSessionDrain(session: ManagedSession): Promise<void> {+ if (session.active === 0) return Promise.resolve();+ return new Promise((resolve) => {+ const check = () => {+ if (session.active === 0) {+ sessionDrainWaiters = sessionDrainWaiters.filter((waiter) => waiter !== check);+ resolve();+ }+ };+ sessionDrainWaiters.push(check);+ });+}++function ensureManagedSession(connectionId: string, database: string): ManagedSession {+ if (!managedSession || managedSession.connectionId !== connectionId || managedSession.database !== database || managedSession.closeRequested || managedSession.closed) rotateManagedSession(connectionId, database);+ return managedSession!;+}++function captureExecutionScope(): ExecutionScope {+ const connection = { ...props.connection };+ const database = props.database;+ return { connection, connectionKey: JSON.stringify(connection), database, schema: props.schema, generation: generation.value, session: ensureManagedSession(connection.id, database) };+}++function scopeIsCurrent(scope: ExecutionScope): boolean {+ return isCurrent(scope.generation) && props.connection.id === scope.connection.id && JSON.stringify(props.connection) === scope.connectionKey && props.database === scope.database && props.schema === scope.schema;+}++async function query(sql: string, maxRows = 501, scope?: ExecutionScope, allowExecutionError = false) {+ const connectionId = scope?.connection.id ?? props.connection.id;+ const database = scope?.database ?? props.database;+ const schema = scope?.schema ?? props.schema;+ const session = scope?.session ?? ensureManagedSession(connectionId, database);+ session.active++;+ try {+ const result = await api.executeQuery(connectionId, database, sql, schema, undefined, { maxRows, clientSessionId: session.id });+ if (!allowExecutionError && result.execution_error) throw new Error(result.error ? formatError(result.error) : String(result.rows[0]?.[0] ?? "Database query failed"));+ return result;+ } finally {+ session.active--;+ if (session.active === 0) sessionDrainWaiters.slice().forEach((waiter) => waiter());+ closeManagedSession(session);+ }+}++function closeManagedSession(session: ManagedSession) {+ if (!session.closeRequested || session.active > 0 || session.closed) return;+ session.closeRequested = false;+ session.closed = true;+ void api.closeClientConnectionSession(session.connectionId, session.database, session.id).catch(() => undefined);+}++function retireManagedSession() {+ const previous = managedSession;+ managedSession = null;+ if (!previous) return;+ previous.closeRequested = true;+ closeManagedSession(previous);+}++function rotateManagedSession(connectionId: string, database: string) {+ retireManagedSession();+ managedSession = newManagedSession(connectionId, database);+}++function closeCurrentManagedSession() {+ if (!managedSession) return;+ managedSession.closeRequested = true;+ closeManagedSession(managedSession);+}++async function loadList(existingToken?: number, options?: { allowLastDdlTimeChange?: boolean; preserveSelected?: boolean; loadDiagnostics?: boolean }) {+ const token = existingToken ?? ++generation.value;+ const readId = ++listLoadGeneration;+ loading.value = true;+ loadError.value = "";+ if (options?.loadDiagnostics !== false) {+ errorLoadError.value = "";+ errorsTruncated.value = false;+ outcome.value = "";+ }+ try {+ const result = await query(buildOracleInvalidObjectsSql(props.schema, 501), 501);+ if (!isCurrent(token) || readId !== listLoadGeneration) return;+ const rows = mapOracleInvalidObjects(result.rows, props.schema);+ mergeDictionaryRows(rows, false, verifyMissingOnNextRead.value);+ truncated.value = result.truncated === true || rows.length >= 501;+ if (selected.value) {+ const previous = selected.value;+ const refreshed = rows.find((row) => sameObject(row, previous)) ?? null;+ if (!refreshed || refreshed.name !== previous.name || refreshed.type !== previous.type || (!options?.allowLastDdlTimeChange && refreshed.lastDdlTime !== previous.lastDdlTime)) {+ if (refreshed) outcome.value = t("processList.oracleInvalidObjects.targetChanged");+ }+ selected.value = refreshed ?? (options?.preserveSelected ? previous : null);+ }+ if (options?.loadDiagnostics !== false) {+ if (selected.value) await loadErrors(selected.value, token);+ else {+ errors.value = [];+ errorsTruncated.value = false;+ }+ }+ if (isCurrent(token) && readId === listLoadGeneration && !compiling.value) void startFullRead(token);+ } catch (error) {+ if (isCurrent(token) && readId === listLoadGeneration) {+ loadError.value = error instanceof Error ? error.message : String(error);+ }+ } finally {+ if (isCurrent(token) && readId === listLoadGeneration) loading.value = false;+ }+}++async function startFullRead(token = generation.value) {+ if (!isCurrent(token) || compiling.value) return;+ const readId = ++fullReadGeneration.value;+ const scope = captureExecutionScope();+ fullReadState.value = "reading";+ fullReadError.value = "";+ fullReadCount.value = 0;+ try {+ const all = await readAllOracleInvalidObjects((sql, maxRows) => query(sql, maxRows, scope), scope.schema, {+ isCurrent: () => isCurrent(token) && fullReadGeneration.value === readId && !compiling.value,+ onProgress: (count) => {+ if (isCurrent(token) && fullReadGeneration.value === readId) fullReadCount.value = count;+ },+ });+ if (!isCurrent(token) || fullReadGeneration.value !== readId || compiling.value) return;+ const verifyMissing = verifyMissingOnNextRead.value;+ verifyMissingOnNextRead.value = false;+ fullObjects.value = all;+ mergeDictionaryRows(all, true, verifyMissing);+ if (verifyMissing) {+ for (const key of unverifiedKeys.value) {+ if (!isCurrent(token) || fullReadGeneration.value !== readId || compiling.value) return;+ const object = objects.value.find((row) => selectionKey(row) === key);+ if (!object) continue;+ try {+ const status = await readObjectStatus(scope, object);+ if (!isCurrent(token) || fullReadGeneration.value !== readId || compiling.value) return;+ const row = status.rows.length === 1 ? status.rows[0] : undefined;+ if (row && String(row[0] ?? "") === object.objectId && String(row[2] ?? "") === "VALID") {+ removeValidObject(object);+ } else if (row && String(row[0] ?? "") === object.objectId && String(row[2] ?? "") === "INVALID") {+ const refreshed = { ...object, lastDdlTime: String(row[1] ?? object.lastDdlTime) };+ objects.value = objects.value.map((current) => (sameObject(current, object) ? refreshed : current));+ fullObjects.value.push(refreshed);+ unverifiedKeys.value.delete(key);+ } else {+ const result = rowResults.value.get(key);+ if (result) {+ result.status = row ? "target-changed" : "deleted";+ result.message = t(row ? "processList.oracleInvalidObjects.batchTargetChanged" : "processList.oracleInvalidObjects.batchDeleted");+ }+ }+ } catch {+ // Keep unconfirmed rows visible and unselectable after a failed read-only check.+ }+ }+ }+ if (!isCurrent(token) || fullReadGeneration.value !== readId || compiling.value) return;+ fullReadState.value = "complete";+ } catch (error) {+ if (!isCurrent(token) || fullReadGeneration.value !== readId || compiling.value) return;+ fullReadState.value = "error";+ fullReadError.value = writeErrorMessage(error);+ }+}++async function loadErrors(object: OracleInvalidObject, token = generation.value) {+ const requestId = ++diagnosticGeneration;+ errorLoadError.value = "";+ errors.value = [];+ errorsTruncated.value = false;+ try {+ const result = await readObjectErrors(captureExecutionScope(), object);+ if (!isCurrent(token) || requestId !== diagnosticGeneration || selectionKey(selected.value ?? object) !== selectionKey(object)) return;+ errors.value = result.errors;+ errorsTruncated.value = result.truncated;+ } catch (error) {+ if (isCurrent(token) && requestId === diagnosticGeneration && selectionKey(selected.value ?? object) === selectionKey(object)) errorLoadError.value = error instanceof Error ? error.message : String(error);+ }+}++function selectObject(object: OracleInvalidObject) {+ diagnosticGeneration++;+ selected.value = object;+ const previousResult = rowBatchItem(object);+ errors.value = previousResult?.errors ?? [];+ errorsTruncated.value = previousResult?.errorsTruncated ?? false;+ errorLoadError.value = previousResult?.diagnosticError ?? "";+ outcome.value = previousResult?.message ?? "";+ if (!compiling.value && !previousResult?.errors?.length && !previousResult?.diagnosticError && !unverifiedKeys.value.has(selectionKey(object))) void loadErrors(object);+}++class BatchWriteError extends Error {+ constructor(+ readonly value: unknown,+ readonly unknown: boolean,+ ) {+ super(writeErrorMessage(value));+ }+}++class IncompleteObjectStatusError extends Error {}++function writeErrorMessage(value: unknown): string {+ if (value && typeof value === "object" && "execution_error" in value) {+ const result = value as { error?: unknown; rows?: unknown[][] };+ return result.error ? formatError(result.error) : String(result.rows?.[0]?.[0] ?? "Database execution failed");+ }+ return formatError(value);+}++function knownWriteRejection(value: unknown): boolean {+ const backendError = normalizeBackendError(value);+ if (backendError?.operationOutcome === "not_started") return true;+ const message = backendError?.detail ?? writeErrorMessage(value);+ return oracleWriteRejected(message, true);+}++function objectIdentityMatches(object: OracleInvalidObject, row: unknown[] | undefined): boolean {+ return !!row && String(row[0] ?? "") === object.objectId && String(row[1] ?? "") === object.lastDdlTime;+}++function objectIdMatches(object: OracleInvalidObject, row: unknown[] | undefined): boolean {+ return !!row && String(row[0] ?? "") === object.objectId;+}++function objectDdlTimeMatches(object: OracleInvalidObject, row: unknown[] | undefined): boolean {+ return !!row && String(row[1] ?? "") === object.lastDdlTime;+}++async function readObjectStatus(scope: ExecutionScope, object: OracleInvalidObject) {+ const result = await query(buildOracleObjectStatusSql(object.owner, object), 2, scope);+ if (result.truncated === true) throw new IncompleteObjectStatusError();+ return result;+}++async function readObjectErrors(scope: ExecutionScope, object: OracleInvalidObject) {+ const result = await query(buildOracleObjectErrorsSql(object.owner, object), 1000, scope);+ return {+ errors: mapOracleObjectErrors(result.rows),+ truncated: result.truncated === true || result.rows.length >= 1000,+ };+}++async function submitCompile(scope: ExecutionScope, sql: string) {+ try {+ const result = await query(sql, 1, scope, true);+ if (result.execution_error) throw new BatchWriteError(result, !knownWriteRejection(result));+ return result;+ } catch (error) {+ if (error instanceof BatchWriteError) throw error;+ throw new BatchWriteError(error, !knownWriteRejection(error));+ }+}++const unsupportedReason = computed(() => (selected.value ? oracleCompileUnsupportedReason(databaseType.value, selected.value.type) : "unsupported-type"));+const singleTargetPresent = computed(() => {+ if (!selected.value) return false;+ return canCompileObject(selected.value) && objects.value.some((object) => sameObject(object, selected.value!));+});++async function compileSingle() {+ const target = selected.value ? { ...selected.value } : null;+ if (!target || unsupportedReason.value || compiling.value) return;+ const scope = captureExecutionScope();+ let sql: string;+ try {+ sql = buildOracleCompileSql(databaseType.value, target.owner, target);+ } catch (error) {+ outcome.value = writeErrorMessage(error);+ return;+ }+ const executionGeneration = ++singleCompilationGeneration;+ const token = scope.generation;+ const connection = scope.connection;+ const database = scope.database;+ const schema = scope.schema;+ const item: BatchItem = reactive({ object: target, sql, status: "pending", errors: [...errors.value], errorsTruncated: errorsTruncated.value, diagnosticError: errorLoadError.value });+ rowResults.value.set(selectionKey(target), item);+ batchRun.value = null;+ let actionSubmitted = false;+ compiling.value = true;+ outcome.value = "";+ listLoadGeneration++;+ diagnosticGeneration++;+ loading.value = false;+ fullReadGeneration.value++;+ if (fullReadState.value === "reading" || fullReadState.value === "complete") fullReadState.value = "stopped";+ try {+ await waitForSessionDrain(scope.session);+ if (!scopeIsCurrent(scope)) return;+ const result = await executeWithProductionSqlGuard({+ connection,+ database: scope.schema,+ sql,+ source: t("production.sourceAdmin"),+ execute: async () => {+ if (!scopeIsCurrent(scope)) throw new Error(t("processList.oracleInvalidObjects.targetChanged"));+ item.status = "running";+ const identity = await query(buildOracleObjectIdentitySql(target.owner, target), 2, scope);+ if (!scopeIsCurrent(scope)) return undefined;+ if (identity.truncated === true || identity.rows.length > 1) {+ item.status = "unknown";+ item.message = t("processList.oracleInvalidObjects.batchIdentityUnknown");+ unverifiedKeys.value.add(selectionKey(target));+ return undefined;+ }+ const row = identity.rows[0];+ if (!objectIdentityMatches(target, row)) {+ item.status = "target-changed";+ unverifiedKeys.value.add(selectionKey(target));+ await loadList(token, { preserveSelected: true, loadDiagnostics: false });+ if (!scopeIsCurrent(scope)) return undefined;+ item.message = t("processList.oracleInvalidObjects.targetChanged");+ return undefined;+ }+ actionSubmitted = true;+ try {+ return await submitCompile(scope, sql);+ } catch (error) {+ if (error instanceof BatchWriteError && !error.unknown) actionSubmitted = false;+ throw error;+ }+ },+ });+ if (!scopeIsCurrent(scope)) return;+ if (result === undefined) {+ if (item.status === "pending") {+ item.status = "not-run";+ item.message = t("processList.oracleInvalidObjects.batchGuardDeclined");+ }+ return;+ }+ const statusResult = await readObjectStatus(scope, target);+ if (!scopeIsCurrent(scope)) return;+ const statusRow = statusResult.rows.length === 1 ? statusResult.rows[0] : undefined;+ // Compilation is DDL and can update LAST_DDL_TIME on the same object.+ // OBJECT_ID distinguishes a replacement; the preflight above still checks both fields.+ const sameObject = statusRow && String(statusRow[0]) === target.objectId;+ const status = sameObject ? String(statusRow[2] ?? "") : "";+ if (sameObject && status === "VALID") {+ item.status = "valid";+ removeValidObject(target);+ } else if (sameObject && status === "INVALID") {+ item.status = "still-invalid";+ updateInvalidObject(item, statusRow!);+ } else {+ item.status = !statusRow ? "deleted" : sameObject ? "unknown" : "target-changed";+ unverifiedKeys.value.add(selectionKey(target));+ }+ if (sameObject && (status === "VALID" || status === "INVALID")) {+ try {+ const diagnostics = await readObjectErrors(scope, target);+ if (!scopeIsCurrent(scope)) return;+ item.errors = diagnostics.errors;+ item.errorsTruncated = diagnostics.truncated;+ item.diagnosticError = "";+ } catch (error) {+ if (!scopeIsCurrent(scope)) return;+ item.diagnosticError = writeErrorMessage(error);+ }+ }+ await loadList(token, { allowLastDdlTimeChange: true, preserveSelected: true, loadDiagnostics: false });+ if (!scopeIsCurrent(scope)) return;+ item.message = !statusRow+ ? t("processList.oracleInvalidObjects.compileGone")+ : !sameObject+ ? t("processList.oracleInvalidObjects.targetChanged")+ : status === "VALID"+ ? t("processList.oracleInvalidObjects.compileValid")+ : status === "INVALID"+ ? t("processList.oracleInvalidObjects.compileStillInvalid")+ : t("processList.oracleInvalidObjects.compileUnknown");+ } catch (error) {+ if (scopeIsCurrent(scope)) {+ if (actionSubmitted) {+ item.status = "unknown";+ unverifiedKeys.value.add(selectionKey(target));+ await loadList(token, { allowLastDdlTimeChange: true, preserveSelected: true, loadDiagnostics: false });+ if (!scopeIsCurrent(scope)) return;+ item.message =+ error instanceof BatchWriteError && !error.unknown+ ? t("processList.oracleInvalidObjects.compileFailed", { message: writeErrorMessage(error.value) })+ : error instanceof IncompleteObjectStatusError+ ? t("processList.oracleInvalidObjects.compileUnknown")+ : `${t("processList.oracleInvalidObjects.compileUnknown")} ${writeErrorMessage(error)}`;+ } else {+ item.status = "failed";+ item.message = t("processList.oracleInvalidObjects.compileFailed", { message: writeErrorMessage(error instanceof BatchWriteError ? error.value : error) });+ }+ }+ } finally {+ if (actionSubmitted) emit("compile-finished", { connectionId: connection.id, database, schema });+ if (singleCompilationGeneration === executionGeneration && scopeIsCurrent(scope)) {+ if (selected.value && sameObject(selected.value, target)) {+ outcome.value = item.message ?? "";+ errors.value = item.errors ?? [];+ errorsTruncated.value = item.errorsTruncated ?? false;+ errorLoadError.value = item.diagnosticError ?? "";+ }+ compiling.value = false;+ if (currentView.value === "detail" && selected.value && !sameObject(selected.value, target) && !unverifiedKeys.value.has(selectionKey(selected.value)) && !rowBatchItem(selected.value)) void loadErrors(selected.value, token);+ void startFullRead(token);+ }+ }+}++function batchIsCurrent(run: BatchRun): boolean {+ return batchRun.value?.id === run.id && scopeIsCurrent(run.scope);+}++function buildBatchItems(objects: OracleInvalidObject[]): BatchItem[] {+ return objects.map((object) => {+ const unsupportedReason = oracleCompileUnsupportedReason(databaseType.value, object.type);+ if (unsupportedReason) return { object, unsupportedReason, status: "unsupported" };+ try {+ return { object, sql: buildOracleCompileSql(databaseType.value, object.owner, object), status: "pending" };+ } catch (error) {+ return { object, unsupportedReason: "unsupported-type", status: "unsupported", message: formatError(error) };+ }+ });+}++function readBatchPlan() {+ void startFullRead();+}++function toggleObjectSelection(object: OracleInvalidObject, checked: boolean) {+ if (compiling.value || unverifiedKeys.value.has(selectionKey(object)) || oracleCompileUnsupportedReason(databaseType.value, object.type)) return;+ const next = new Map(selectedObjects.value);+ if (checked) next.set(selectionKey(object), { ...object });+ else next.delete(selectionKey(object));+ selectedObjects.value = next;+}++function toggleFilteredSelection(checked: boolean) {+ if (compiling.value) return;+ const next = new Map(selectedObjects.value);+ for (const object of filteredObjects.value) {+ if (!canCompileObject(object)) continue;+ const key = selectionKey(object);+ if (checked) next.set(key, { ...object });+ else next.delete(key);+ }+ selectedObjects.value = next;+}++function showDetail(object: OracleInvalidObject) {+ detailViewport = captureViewport();+ listCache.value = listScroller.value?.cacheSnapshot;+ detailReturnKey.value = renderKey(object);+ currentView.value = "detail";+ selectObject(object);+}++function returnFromDetail() {+ currentView.value = "list";+ void restoreViewport(detailViewport, detailReturnKey.value);+}++function refreshCurrentList() {+ if (compiling.value) return;+ fullReadGeneration.value++;+ fullReadState.value = "idle";+ fullReadError.value = "";+ verifyMissingOnNextRead.value = true;+ batchRun.value = null;+ selectedObjects.value = new Map();+ generation.value++;+ void loadList();+}++function stopBatch() {+ const run = batchRun.value;+ if (!run) return;+ if (run.state === "running") run.stopRequested = true;+}++function classifyBatchWriteFailure(error: unknown): "failed" | "unknown" {+ if (error instanceof BatchWriteError) return error.unknown ? "unknown" : "failed";+ return knownWriteRejection(error) ? "failed" : "unknown";+}++async function readBatchObjectErrors(run: BatchRun, item: BatchItem): Promise<void> {+ try {+ const result = await readObjectErrors(run.scope, item.object);+ if (!batchIsCurrent(run)) return;+ item.errors = result.errors;+ item.errorsTruncated = result.truncated;+ } catch (error) {+ if (batchIsCurrent(run)) item.diagnosticError = writeErrorMessage(error);+ }+}++async function refreshBatchRemainder(run: BatchRun) {+ try {+ const remaining = await readAllOracleInvalidObjects((sql, maxRows) => query(sql, maxRows, run.scope), run.scope.schema, { isCurrent: () => scopeIsCurrent(run.scope) });+ if (!batchIsCurrent(run)) return;+ run.remaining = remaining;+ run.remainingError = "";+ fullObjects.value = remaining;+ mergeDictionaryRows(remaining, true);+ fullReadState.value = "complete";+ fullReadError.value = "";+ truncated.value = false;+ loadError.value = "";+ } catch (error) {+ if (!batchIsCurrent(run)) return;+ run.remainingError = writeErrorMessage(error);+ fullReadState.value = "error";+ fullReadError.value = run.remainingError;+ loadError.value = run.remainingError;+ }+}++async function executeBatchItem(run: BatchRun, item: BatchItem): Promise<boolean> {+ const object = item.object;+ if (!batchIsCurrent(run) || !item.sql) return false;+ if (run.stopRequested) {+ item.status = "not-run";+ return false;+ }+ item.status = "running";+ run.currentName = `${object.owner}.${object.name}`;+ let before;+ try {+ before = await readObjectStatus(run.scope, object);+ } catch (error) {+ if (batchIsCurrent(run)) {+ item.status = error instanceof IncompleteObjectStatusError ? "unknown" : "failed";+ item.message = error instanceof IncompleteObjectStatusError ? t("processList.oracleInvalidObjects.batchIdentityUnknown") : writeErrorMessage(error);+ unverifiedKeys.value.add(selectionKey(object));+ }+ return true;+ }+ if (!batchIsCurrent(run)) return false;+ if (run.stopRequested) {+ item.status = "not-run";+ return false;+ }+ if (before.rows.length === 0) {+ item.status = "deleted";+ item.message = t("processList.oracleInvalidObjects.batchDeleted");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (before.rows.length !== 1) {+ item.status = "unknown";+ item.message = t("processList.oracleInvalidObjects.batchIdentityUnknown");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ const beforeStatus = before.rows[0]![2];+ if (!objectIdMatches(object, before.rows[0])) {+ item.status = "target-changed";+ item.message = t("processList.oracleInvalidObjects.batchTargetChanged");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (beforeStatus === "VALID") {+ item.status = "already-valid";+ item.message = t("processList.oracleInvalidObjects.batchAlreadyValid");+ removeValidObject(object);+ return true;+ }+ if (beforeStatus !== "INVALID") {+ item.status = "unknown";+ item.message = t("processList.oracleInvalidObjects.batchIdentityUnknown");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (!objectDdlTimeMatches(object, before.rows[0])) {+ item.status = "target-changed";+ item.message = t("processList.oracleInvalidObjects.batchTargetChanged");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (!batchIsCurrent(run) || run.stopRequested) return false;++ const previouslySubmitted = run.submittedAny;+ run.submittedAny = true;+ try {+ await submitCompile(run.scope, item.sql);+ } catch (error) {+ if (!batchIsCurrent(run)) return false;+ const status = classifyBatchWriteFailure(error);+ if (status === "failed") run.submittedAny = previouslySubmitted;+ item.status = status;+ item.message = writeErrorMessage(error);+ if (status === "unknown") unverifiedKeys.value.add(selectionKey(object));+ return status !== "unknown";+ }+ if (!batchIsCurrent(run)) return false;+ let after;+ try {+ after = await readObjectStatus(run.scope, object);+ } catch (error) {+ if (batchIsCurrent(run)) {+ item.status = "unknown";+ item.message = error instanceof IncompleteObjectStatusError ? t("processList.oracleInvalidObjects.compileUnknown") : `${t("processList.oracleInvalidObjects.compileUnknown")} ${writeErrorMessage(error)}`;+ unverifiedKeys.value.add(selectionKey(object));+ }+ return false;+ }+ if (!batchIsCurrent(run)) return false;+ if (after.rows.length === 0) {+ item.status = "deleted";+ item.message = t("processList.oracleInvalidObjects.batchDeleted");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (after.rows.length !== 1) {+ item.status = "unknown";+ item.message = t("processList.oracleInvalidObjects.compileUnknown");+ unverifiedKeys.value.add(selectionKey(object));+ return false;+ }+ const [afterId, , afterStatus] = after.rows[0]!;+ if (String(afterId ?? "") !== object.objectId) {+ item.status = "target-changed";+ item.message = t("processList.oracleInvalidObjects.batchTargetChanged");+ unverifiedKeys.value.add(selectionKey(object));+ return true;+ }+ if (afterStatus === "VALID") {+ item.status = "valid";+ item.message = t("processList.oracleInvalidObjects.compileValid");+ removeValidObject(object);+ } else if (afterStatus === "INVALID") {+ item.status = "still-invalid";+ item.message = t("processList.oracleInvalidObjects.compileStillInvalid");+ updateInvalidObject(item, after.rows[0]!);+ await readBatchObjectErrors(run, item);+ } else {+ item.status = "unknown";+ item.message = t("processList.oracleInvalidObjects.compileUnknown");+ unverifiedKeys.value.add(selectionKey(object));+ return false;+ }+ return true;+}++async function startBatchCompile(mode: "selected" | "all") {+ if (!props.open || compiling.value || (!managedSession && mode !== "all")) return;+ const stableObjects = objects.value;+ const targets =+ mode === "all"+ ? fullReadState.value === "complete"+ ? completeMatchingObjects.value.map((object) => ({ ...object }))+ : []+ : stableObjects.filter((object) => selectedObjects.value.has(selectionKey(object)) && canCompileObject(object)).map((object) => ({ ...selectedObjects.value.get(selectionKey(object))! }));+ if (targets.length === 0) return;+ const scope = captureExecutionScope();+ const frozenItems = buildBatchItems(targets);+ const executionGeneration = ++batchExecutionGeneration;+ const run: BatchRun = reactive({+ id: uuid(),+ scope,+ state: "running",+ readCount: targets.length,+ items: frozenItems,+ stopRequested: false,+ submittedAny: false,+ currentName: "",+ readError: "",+ remainingError: "",+ });+ batchRun.value = run;+ for (const item of run.items) rowResults.value.set(selectionKey(item.object), item);+ compiling.value = true;+ listLoadGeneration++;+ diagnosticGeneration++;+ loading.value = false;+ fullReadGeneration.value++;+ if (fullReadState.value === "reading" || fullReadState.value === "complete") fullReadState.value = "stopped";+ const queue = run.items.filter((item) => !!item.sql);+ const auditSql = queue.map((item) => item.sql).join(";\n");+ try {+ await waitForSessionDrain(scope.session);+ if (!batchIsCurrent(run)) return;+ const guarded = await executeWithProductionSqlGuard({+ connection: scope.connection,+ database: scope.schema,+ sql: auditSql,+ source: t("production.sourceAdmin"),+ execute: async () => {+ for (const item of queue) {+ if (!batchIsCurrent(run) || run.stopRequested) break;+ const keepGoing = await executeBatchItem(run, item);+ if (!keepGoing) break;+ }+ return true;+ },+ });+ if (!batchIsCurrent(run)) return;+ if (guarded === undefined) {+ for (const item of queue) if (item.status === "pending" || item.status === "running") item.status = "not-run";+ run.readError = t("processList.oracleInvalidObjects.batchGuardDeclined");+ } else {+ for (const item of queue) if (item.status === "pending" || item.status === "running") item.status = "not-run";+ }+ run.state = "complete";+ run.currentName = "";+ await refreshBatchRemainder(run);+ } catch (error) {+ if (!batchIsCurrent(run)) return;+ run.readError = writeErrorMessage(error);+ for (const item of queue) if (item.status === "pending" || item.status === "running") item.status = "not-run";+ run.state = "complete";+ await refreshBatchRemainder(run);+ } finally {+ if (run.submittedAny) emit("compile-finished", { connectionId: scope.connection.id, database: scope.database, schema: scope.schema });+ if (batchExecutionGeneration === executionGeneration && scopeIsCurrent(scope)) compiling.value = false;+ }+}++function batchStatusLabel(status: BatchStatus): string {+ return t(`processList.oracleInvalidObjects.batchStatus.${status}`);+}++function rowBatchItem(object: OracleInvalidObject): BatchItem | undefined {+ const item = rowResults.value.get(selectionKey(object));+ return item && sameObject(item.object, object) ? item : undefined;+}++function updateInvalidObject(item: BatchItem, status: unknown[]) {+ const refreshed = { ...item.object, lastDdlTime: String(status[1] ?? item.object.lastDdlTime) };+ objects.value = objects.value.map((object) => (sameObject(object, item.object) ? refreshed : object));+ item.object = refreshed;+}++function rowStatus(object: OracleInvalidObject): BatchStatus | "invalid" {+ return rowBatchItem(object)?.status ?? (unverifiedKeys.value.has(selectionKey(object)) ? "unknown" : oracleCompileUnsupportedReason(databaseType.value, object.type) ? "unsupported" : "invalid");+}++function rowStatusLabel(object: OracleInvalidObject): string {+ const status = rowStatus(object);+ return status === "invalid" ? "INVALID" : batchStatusLabel(status);+}++function close() {+ generation.value++;+ emit("update:open", false);+}++watch(+ () => [props.open, JSON.stringify(props.connection), props.database, props.schema] as const,+ ([open], previous) => {+ const scopeChanged = !!previous && (previous[1] !== JSON.stringify(props.connection) || previous[2] !== props.database || previous[3] !== props.schema);+ if (scopeChanged || !open) {+ singleCompilationGeneration++;+ batchExecutionGeneration++;+ batchRun.value = null;+ compiling.value = false;+ fullReadGeneration.value++;+ fullReadState.value = "idle";+ fullReadError.value = "";+ fullObjects.value = [];+ unverifiedKeys.value = new Set();+ rowResults.value = new Map();+ verifyMissingOnNextRead.value = false;+ objects.value = [];+ selected.value = null;+ errors.value = [];+ errorsTruncated.value = false;+ diagnosticGeneration++;+ selectedObjects.value = new Map();+ currentView.value = "list";+ nameFilter.value = "";+ typeFilter.value = null;+ listCache.value = undefined;+ detailViewport = null;+ viewportGeneration++;+ }+ if (previous && (previous[1] !== JSON.stringify(props.connection) || previous[2] !== props.database)) retireManagedSession();+ if (open) void loadList();+ else {+ generation.value++;+ objects.value = [];+ errors.value = [];+ errorsTruncated.value = false;+ selected.value = null;+ selectedObjects.value = new Map();+ outcome.value = "";+ closeCurrentManagedSession();+ }+ },+ { immediate: true },+);++onBeforeUnmount(() => {+ generation.value++;+ singleCompilationGeneration++;+ batchExecutionGeneration++;+ batchRun.value = null;+ closeCurrentManagedSession();+});+</script>++<template>+ <Dialog :open="open" @update:open="(value) => !value && close()">+ <DialogContent class="h-[min(85vh,760px)] max-h-[min(85vh,760px)] w-[calc(100vw-2rem)] max-w-5xl flex flex-col gap-0 overflow-hidden p-0" @interact-outside="(event) => compiling && event.preventDefault()" @escape-key-down="(event) => compiling && event.preventDefault()">+ <DialogHeader class="shrink-0 border-b px-5 py-4">+ <DialogTitle>{{ t("processList.oracleInvalidObjects.title") }} · {{ connection.name }} · {{ schema }}</DialogTitle>+ </DialogHeader>+ <section v-if="currentView === 'list'" class="flex min-h-0 flex-1 flex-col overflow-hidden" :aria-label="t('processList.oracleInvalidObjects.listLabel')" data-list-heading tabindex="-1">+ <div class="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b px-3 py-2 text-xs">+ <span class="text-muted-foreground"+ >{{ hasFilters ? t("processList.oracleInvalidObjects.filterCount", { matched: filteredObjects.length, total: displayedObjects.length }) : t("processList.oracleInvalidObjects.listCount", { count: displayedObjects.length })+ }}<span v-if="fullReadState !== 'complete'"> · {{ t("processList.oracleInvalidObjects.currentlyLoaded") }}</span> · {{ t("processList.oracleInvalidObjects.batchSelectedCount", { count: selectedCount }) }}</span+ >+ <div class="flex flex-wrap items-center gap-1">+ <Button variant="destructive" size="sm" class="h-7 px-2 text-xs" :disabled="selectedSupportedCount === 0 || compiling" @click="startBatchCompile('selected')">{{ t("processList.oracleInvalidObjects.batchCompileSelected", { count: selectedSupportedCount }) }}</Button>+ <Button variant="outline" size="sm" class="h-7 gap-1 px-2 text-xs" :disabled="fullReadState !== 'complete' || allSupportedCount === 0 || compiling" @click="startBatchCompile('all')"+ ><Wrench class="h-3.5 w-3.5" />{{+ fullReadState === "complete"+ ? t(hasFilters ? "processList.oracleInvalidObjects.batchCompileFiltered" : "processList.oracleInvalidObjects.batchCompileAll", { count: allSupportedCount })+ : t(hasFilters ? "processList.oracleInvalidObjects.compileFiltered" : "processList.oracleInvalidObjects.compileAll")+ }}</Button+ >+ <Button variant="ghost" size="icon" class="h-7 w-7" :title="t('common.refresh')" :disabled="loading || compiling" @click="refreshCurrentList"><RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading || fullReadState === 'reading' }" /></Button>+ <Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="compiling" @click="close">{{ t("common.close") }}</Button>+ </div>+ </div>+ <div class="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2 text-xs">+ <label class="flex min-w-40 flex-1 items-center gap-2">+ <span class="shrink-0 text-muted-foreground">{{ t("processList.oracleInvalidObjects.nameFilterLabel") }}</span>+ <Input type="search" class="h-8 text-xs" :model-value="nameFilter" :aria-label="t('processList.oracleInvalidObjects.filterName')" :placeholder="t('processList.oracleInvalidObjects.filterName')" :disabled="compiling" @update:model-value="setNameFilter" />+ </label>+ <DropdownMenu>+ <DropdownMenuTrigger as-child>+ <Button variant="outline" size="sm" class="h-8 gap-1 text-xs" :disabled="compiling"+ >{{ t("processList.oracleInvalidObjects.filterTypes") }} · {{ typeFilter === null ? t("processList.oracleInvalidObjects.allTypes") : t("processList.oracleInvalidObjects.selectedTypeCount", { count: typeFilter.size }) }}<ChevronDown class="h-3.5 w-3.5"+ /></Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" class="min-w-44 max-h-72 overflow-y-auto">+ <DropdownMenuCheckboxItem :model-value="typeFilter === null" :disabled="compiling" @select.prevent @update:model-value="setAllTypes($event === true)">{{ t("processList.oracleInvalidObjects.allTypes") }}</DropdownMenuCheckboxItem>+ <DropdownMenuSeparator />+ <DropdownMenuCheckboxItem v-for="type in availableTypes" :key="type" :model-value="typeFilter === null || typeFilter.has(type)" :disabled="compiling" @select.prevent @update:model-value="setTypeFilter(type, $event === true)">{{ type }}</DropdownMenuCheckboxItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <Button variant="ghost" size="sm" class="h-8 px-2 text-xs" :disabled="compiling || !hasFilters" @click="clearFilters">{{ t("processList.oracleInvalidObjects.clearFilters") }}</Button>+ </div>+ <p class="shrink-0 border-b px-3 py-1.5 text-[11px] text-muted-foreground">{{ t("processList.oracleInvalidObjects.ddlWarning") }}</p>+ <div v-if="batchRun" class="flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2 text-xs" role="status" aria-live="polite">+ <span v-if="batchRun.state === 'running'" class="min-w-0 flex-1 break-words">{{+ batchRun.stopRequested ? t("processList.oracleInvalidObjects.batchStopping") : t("processList.oracleInvalidObjects.batchProgress", { handled: batchHandledCount, total: batchSupportedCount, current: batchRun.currentName || t("processList.oracleInvalidObjects.batchRunning") })+ }}</span>+ <span v-else class="min-w-0 flex-1 break-words"+ >{{ t("processList.oracleInvalidObjects.batchSummary", { valid: batchValidCount, stillInvalid: batchStillInvalidCount, failed: batchFailureCount, skipped: batchSkippedCount })+ }}<span v-if="batchRun.remaining"> · {{ t("processList.oracleInvalidObjects.batchRemaining", { count: batchRun.remaining.length }) }}</span+ ><span v-else-if="batchRun.remainingError" class="text-destructive"> · {{ t("processList.oracleInvalidObjects.batchRemainingUnknown", { message: batchRun.remainingError }) }}</span></span+ >+ <Button v-if="batchRun.state === 'running'" variant="outline" size="sm" class="shrink-0" :disabled="batchRun.stopRequested" @click="stopBatch">{{ t("processList.oracleInvalidObjects.batchStop") }}</Button>+ </div>+ <p v-if="batchRun?.readError" class="shrink-0 border-b px-3 py-2 text-xs text-destructive" role="alert">{{ batchRun.readError }}</p>+ <div v-if="loadError" class="m-3 shrink-0 break-words rounded border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">{{ loadError }}</div>+ <p v-else-if="fullReadState === 'reading'" class="shrink-0 border-b px-3 py-2 text-xs text-muted-foreground" role="status" aria-live="polite">{{ t("processList.oracleInvalidObjects.batchReadProgress", { count: fullReadCount }) }}</p>+ <p v-else-if="fullReadState === 'error'" class="shrink-0 break-words border-b px-3 py-2 text-xs text-destructive" role="alert">+ {{ t("processList.oracleInvalidObjects.batchReadFailed") }} · {{ fullReadError }} <Button variant="ghost" size="sm" class="h-6 px-1" @click="readBatchPlan">{{ t("processList.oracleInvalidObjects.batchRetryRead") }}</Button>+ </p>+ <label class="flex shrink-0 cursor-pointer items-center gap-2 border-b px-4 py-2 text-xs font-medium">+ <input type="checkbox" :checked="allSelectedInFilter" :indeterminate.prop="someSelectedInFilter" :disabled="compiling || !filteredObjects.some(canCompileObject)" @change="toggleFilteredSelection(($event.target as HTMLInputElement).checked)" />+ {{ t("processList.oracleInvalidObjects.batchSelectFiltered") }}+ </label>+ <p v-if="!loading && displayedObjects.length === 0 && !loadError" class="px-4 py-8 text-center text-sm text-muted-foreground">{{ t("processList.oracleInvalidObjects.empty") }}</p>+ <p v-else-if="filteredObjects.length === 0 && displayedObjects.length > 0" class="px-4 py-8 text-center text-sm text-muted-foreground">{{ t("processList.oracleInvalidObjects.noFilterMatches") }}</p>+ <DynamicScroller v-if="filteredObjects.length > 0" ref="listScroller" data-object-scroller class="min-h-0 flex-1 overflow-x-hidden" :items="filteredObjects" :min-item-size="44" :buffer="400" :skip-hover="true" :key-field="renderKey" :cache="listCache">+ <template #default="{ item: object, index, active }">+ <DynamicScrollerItem :item="object" :active="active" :index="index">+ <div :data-row-key="renderKey(object)" :inert="!active" :aria-hidden="!active || undefined" class="flex min-w-0 items-center gap-1 border-b px-2 py-1.5">+ <label class="inline-flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center">+ <input+ type="checkbox"+ :aria-label="`${object.name} ${object.type}`"+ :checked="selectedObjects.has(selectionKey(object))"+ :disabled="compiling || unverifiedKeys.has(selectionKey(object)) || !!oracleCompileUnsupportedReason(databaseType, object.type)"+ @change="toggleObjectSelection(object, ($event.target as HTMLInputElement).checked)"+ @keydown.tab="onRowTab($event, object, 'checkbox')"+ />+ </label>+ <Button+ variant="ghost"+ class="h-auto min-w-0 flex-1 justify-start whitespace-normal break-all px-1 py-1 text-left text-xs font-medium"+ :aria-label="`${object.name} ${object.type}`"+ :data-object-key="selectionKey(object)"+ @click="showDetail(object)"+ @keydown.tab="onRowTab($event, object, 'name')"+ >{{ object.name }}</Button+ >+ <span class="shrink-0 text-xs text-muted-foreground">{{ object.type }}</span>+ <span role="img" :aria-label="rowStatusLabel(object)" :title="rowStatusLabel(object)" class="inline-flex h-5 w-5 shrink-0 items-center justify-center" :class="rowStatus(object) === 'failed' ? 'text-destructive' : 'text-muted-foreground'">+ <Loader2 v-if="rowStatus(object) === 'running'" class="h-4 w-4 animate-spin" aria-hidden="true" />+ <Clock v-else-if="rowStatus(object) === 'pending' || rowStatus(object) === 'not-run'" class="h-4 w-4" aria-hidden="true" />+ <CircleX v-else-if="rowStatus(object) === 'failed'" class="h-4 w-4" aria-hidden="true" />+ <CircleHelp v-else-if="rowStatus(object) === 'unknown'" class="h-4 w-4" aria-hidden="true" />+ <CircleMinus v-else-if="rowStatus(object) === 'unsupported'" class="h-4 w-4" aria-hidden="true" />+ <Circle v-else-if="rowStatus(object) === 'invalid'" class="h-4 w-4" aria-hidden="true" />+ <AlertTriangle v-else class="h-4 w-4" aria-hidden="true" />+ </span>+ </div>+ </DynamicScrollerItem>+ </template>+ </DynamicScroller>+ <p v-if="truncated && fullReadState !== 'complete'" class="shrink-0 border-t px-3 py-2 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.truncated") }}</p>+ </section>+ <section v-else-if="currentView === 'detail' && selected" class="flex min-h-0 flex-1 flex-col overflow-hidden">+ <div class="flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3">+ <div class="min-w-0">+ <div class="break-all text-sm font-semibold">{{ selected.owner }}.{{ selected.name }}</div>+ <div class="mt-1 text-xs text-muted-foreground">{{ selected.type }} · {{ t("processList.oracleInvalidObjects.objectId", { id: selected.objectId }) }}</div>+ </div>+ <Button v-if="oracleInvalidObjectSourceKind(selected.type)" variant="outline" size="sm" class="h-7 shrink-0 gap-1.5 text-xs" :disabled="compiling" @click="emit('open-source', selected)"><Wrench class="h-3.5 w-3.5" />{{ t("processList.oracleInvalidObjects.openSource") }}</Button>+ </div>+ <div class="min-h-0 flex-1 overflow-auto px-4 py-3">+ <div class="mb-2 text-xs font-medium">{{ t("processList.oracleInvalidObjects.errorsTitle") }}</div>+ <div v-if="errorLoadError" class="rounded border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">{{ errorLoadError }}</div>+ <p v-if="!errorLoadError && errorsTruncated" class="mb-2 rounded border bg-muted/30 p-2 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.errorsTruncated") }}</p>+ <p v-if="!errorLoadError && errors.length === 0 && !compiling" class="py-4 text-xs text-muted-foreground">{{ t("processList.oracleInvalidObjects.noErrors") }}</p>+ <div v-if="!errorLoadError && errors.length > 0" class="overflow-auto rounded border">+ <table class="w-full border-collapse text-xs">+ <thead class="sticky top-0 bg-muted/60">+ <tr>+ <th class="px-2 py-1.5 text-left">{{ t("processList.oracleInvalidObjects.line") }}</th>+ <th class="px-2 py-1.5 text-left">{{ t("processList.oracleInvalidObjects.position") }}</th>+ <th class="px-2 py-1.5 text-left">{{ t("processList.oracleInvalidObjects.message") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="error in errors" :key="error.sequence" class="border-t align-top">+ <td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ error.line }}</td>+ <td class="whitespace-nowrap px-2 py-1.5 font-mono">{{ error.position }}</td>+ <td class="break-words px-2 py-1.5 font-mono">{{ error.text }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ <p v-if="unsupportedReason" class="mt-3 flex items-start gap-2 rounded border bg-muted/30 p-3 text-xs text-muted-foreground">+ <AlertTriangle class="mt-0.5 h-3.5 w-3.5 shrink-0" />{{ t(unsupportedReason === "unsupported-on-engine" ? "processList.oracleInvalidObjects.unsupportedOnEngine" : "processList.oracleInvalidObjects.unsupportedType") }}+ </p>+ <details v-if="selected && !unsupportedReason" class="mt-3 text-xs">+ <summary class="cursor-pointer text-muted-foreground">{{ t("processList.oracleInvalidObjects.batchSqlDetails") }}</summary>+ <pre class="mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/30 p-2 font-mono">{{ buildOracleCompileSql(databaseType, selected.owner, selected) }}</pre>+ </details>+ <p v-if="outcome" class="mt-3 rounded border bg-muted/20 p-3 text-xs" role="status">{{ outcome }}</p>+ </div>+ <DialogFooter class="mx-0 mb-0 shrink-0 border-t px-4 py-3">+ <Button variant="outline" @click="returnFromDetail">{{ t("processList.oracleInvalidObjects.batchCurrentList") }}</Button>+ <Button variant="outline" :disabled="compiling" @click="close">{{ t("common.close") }}</Button>+ <Button variant="destructive" :disabled="!!unsupportedReason || compiling || !!loadError || !singleTargetPresent" @click="compileSingle"><Loader2 v-if="compiling" class="mr-1.5 h-3.5 w-3.5 animate-spin" />{{ t("processList.oracleInvalidObjects.compile") }}</Button>+ </DialogFooter>+ </section>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.tsindex fcd95bf93a..e7613ab77f 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts@@ -3,7 +3,7 @@import { createApp, defineComponent, h, ref, nextTick, type App } from "vue";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";-import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import { getCachedObjectBrowserRows, invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import { freezeSourceIdentities } from "@/lib/table/objectSourceIdentity";import type { ConnectionConfig } from "@/types/database";@@ -16,6 +16,16 @@ const mocks = vi.hoisted(() => ({executeQuery: vi.fn(),ensureConnected: vi.fn(),toast: vi.fn(),+ sourceTabs: [] as Array<{ id: string; sourceLoad?: { error?: string }; objectSource?: unknown }>,+ openObjectSourceTabPending: vi.fn(),+ sourceLoadFailure: "",+ deferSourceTabLoad: false,+ finishSourceTabLoad: undefined as (() => void) | undefined,+ invalidObjectType: "PROCEDURE",+ deleteSchemaCachePrefix: vi.fn(),+ refreshObjectListTreeNode: vi.fn(),+ createTab: vi.fn(),+ updateSql: vi.fn(),}));vi.mock("@/lib/backend/api", () => ({@@ -26,6 +36,7 @@ vi.mock("@/lib/backend/api", () => ({buildEditableObjectSource: (...args: unknown[]) => mocks.buildEditableObjectSource(...args),buildExecutableObjectSourceStatements: (...args: unknown[]) => mocks.buildExecutableObjectSourceStatements(...args),executeQuery: (...args: unknown[]) => mocks.executeQuery(...args),+ deleteSchemaCachePrefix: (...args: unknown[]) => mocks.deleteSchemaCachePrefix(...args),}));vi.mock("@/lib/database/productionExecutionGuard", () => ({executeWithProductionSqlGuard: async ({ execute }: { execute: () => Promise<unknown> }) => execute(),@@ -36,11 +47,54 @@ vi.mock("@/stores/connectionStore", () => ({ensureConnected: mocks.ensureConnected,getConfig: () => connection,orderByPinnedTreeNodes: (rows: unknown[]) => rows,+ refreshObjectListTreeNode: mocks.refreshObjectListTreeNode,}),}));-vi.mock("@/stores/queryStore", () => ({- useQueryStore: () => ({ openObjectSourceTabPending: vi.fn() }),-}));+vi.mock("@/stores/queryStore", async () => {+ const { reactive } = await import("vue");+ const tabs = reactive(mocks.sourceTabs);+ mocks.openObjectSourceTabPending.mockImplementation(() => {+ const tab = reactive({ id: "source-1", sourceLoad: {} as { error?: string } | undefined, objectSource: undefined as unknown });+ tabs.push(tab);+ const finish = () => {+ if (mocks.sourceLoadFailure) tab.sourceLoad!.error = mocks.sourceLoadFailure;+ else {+ tab.sourceLoad = undefined;+ tab.objectSource = { name: "P_BAD", objectType: "PROCEDURE" };+ }+ };+ mocks.finishSourceTabLoad = finish;+ if (!mocks.deferSourceTabLoad) setTimeout(finish, 0);+ return tab.id;+ });+ return {+ useQueryStore: () => ({+ tabs,+ openObjectSourceTabPending: (...args: unknown[]) => mocks.openObjectSourceTabPending(...args),+ createTab: mocks.createTab,+ updateSql: mocks.updateSql,+ }),+ };+});+vi.mock("@/components/objects/OracleInvalidObjectsDialog.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ props: { open: Boolean },+ emits: ["update:open", "open-source", "compile-finished"],+ setup(props, { emit }) {+ return () =>+ props.open+ ? h("div", { "data-invalid-object-dialog": "" }, [+ h("button", { onClick: () => emit("open-source", { owner: "APP", name: "P_BAD", type: mocks.invalidObjectType }) }, "open-source"),+ h("button", { "data-compile-finished": "", onClick: () => emit("compile-finished", { connectionId: "oracle-source", database: "ORCL", schema: "APP_A" }) }, "compile-finished"),+ h("button", { onClick: () => emit("update:open", false) }, "close-dialog"),+ ])+ : null;+ },+ }),+ };+});vi.mock("@/stores/settingsStore", () => ({useSettingsStore: () => ({editorSettings: {@@ -51,7 +105,7 @@ vi.mock("@/stores/settingsStore", () => ({},}),}));-vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key, locale: ref("en-US") }) }));+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values === undefined ? key : `${key}:${Object.values(values).join(",")}`), locale: ref("en-US") }) }));vi.mock("@/i18n", async () => {const { default: en } = await import("@/i18n/locales/en");return { default: { install: () => undefined, global: { t: (key: string) => en.objects[key.split(".")[1] as keyof typeof en.objects] || key } } };@@ -94,6 +148,15 @@ const connection = {url_params: null,transport_layers: [],} as unknown as ConnectionConfig;+const oracleConnection = {+ id: "oracle-source",+ name: "Oracle",+ db_type: "oracle",+ host: "localhost",+ port: 1521,+ username: "APP",+ password: "",+} as ConnectionConfig;const VIEW_NAME = "v_demo";const VIEW_SQL = "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v_demo` AS select 1 AS `id`";@@ -104,6 +167,11 @@ const mountedApps: Array<{ app: App; host: HTMLElement }> = [];beforeEach(() => {vi.clearAllMocks();+ mocks.sourceTabs.splice(0);+ mocks.sourceLoadFailure = "";+ mocks.deferSourceTabLoad = false;+ mocks.finishSourceTabLoad = undefined;+ mocks.invalidObjectType = "PROCEDURE";mocks.listObjects.mockResolvedValue([{ name: VIEW_NAME, schema: "app", object_type: "VIEW" }]);mocks.listSchemas.mockResolvedValue([]);mocks.getObjectSource.mockResolvedValue({ source: VIEW_SQL, editable: true });@@ -111,6 +179,9 @@ beforeEach(() => {mocks.buildExecutableObjectSourceStatements.mockResolvedValue([ALTER_SQL]);mocks.executeQuery.mockResolvedValue({ columns: [], rows: [] });mocks.ensureConnected.mockResolvedValue(undefined);+ mocks.deleteSchemaCachePrefix.mockReset().mockResolvedValue(undefined);+ mocks.refreshObjectListTreeNode.mockResolvedValue(undefined);+ mocks.createTab.mockReturnValue("repair-1");invalidateObjectBrowserRowsCache({});});@@ -123,16 +194,27 @@ afterEach(() => {invalidateObjectBrowserRowsCache({});});-async function mountBrowser() {+async function mountBrowser(browserConnection = connection, database = "app") {const host = document.createElement("div");document.body.append(host);- const app = createApp({ setup: () => () => h(ObjectBrowser, { connection, database: "app" }) });+ const app = createApp({ setup: () => () => h(ObjectBrowser, { connection: browserConnection, database }) });mountedApps.push({ app, host });app.mount(host);await vi.waitFor(() => expect(host.textContent).toContain(VIEW_NAME));return host;}+async function mountOracleBrowserWithSchema() {+ const schema = ref("APP_A");+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({ setup: () => () => h(ObjectBrowser, { connection: oracleConnection, database: "ORCL", schema: schema.value }) });+ mountedApps.push({ app, host });+ app.mount(host);+ await vi.waitFor(() => expect(host.textContent).toContain(VIEW_NAME));+ return { host, schema };+}+function rowFor(host: HTMLElement, name: string): HTMLElement {const row = [...host.querySelectorAll<HTMLElement>(".grid.h-\\[34px\\]")].find((element) => element.textContent?.includes(name));expect(row, name).toBeDefined();@@ -163,6 +245,165 @@ async function clickRow(host: HTMLElement, name: string) {}describe("ObjectBrowser view source save", () => {+ it("invalidates completed compile caches but does not refresh an unmounted browser", async () => {+ let release!: () => void;+ mocks.listSchemas.mockResolvedValue(["APP_A", "APP_B"]);+ const ddlPrefix = "object-ddl:v1:oracle-source:ORCL:APP_A:";+ mocks.deleteSchemaCachePrefix.mockImplementation(async (prefix: string) => {+ if (prefix === ddlPrefix) await new Promise<void>((resolve) => (release = resolve));+ });+ const { host } = await mountOracleBrowserWithSchema();+ const scope = { connectionId: oracleConnection.id, database: "ORCL", schema: "APP_A" };+ expect(getCachedObjectBrowserRows(scope)).toBeDefined();+ const listCalls = mocks.listObjects.mock.calls.length;+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-compile-finished]")?.click();+ await vi.waitFor(() => expect(mocks.deleteSchemaCachePrefix).toHaveBeenCalledWith(ddlPrefix));+ const mounted = mountedApps.splice(+ mountedApps.findIndex((item) => item.host === host),+ 1,+ )[0]!;+ mounted.app.unmount();+ release();+ await vi.waitFor(() => expect(getCachedObjectBrowserRows(scope)).toBeUndefined());+ expect(mocks.listObjects).toHaveBeenCalledTimes(listCalls);+ expect(mocks.refreshObjectListTreeNode).not.toHaveBeenCalled();+ host.remove();+ });++ it("still refreshes the mounted browser after compile cache invalidation", async () => {+ mocks.listSchemas.mockResolvedValue(["APP_A", "APP_B"]);+ const { host } = await mountOracleBrowserWithSchema();+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-compile-finished]")?.click();+ await vi.waitFor(() => expect(mocks.refreshObjectListTreeNode).toHaveBeenCalledWith(oracleConnection.id, "ORCL", "APP_A"));+ });++ it.each(["INDEX", "JAVA CLASS"])("does not dispatch unsupported %s to a source tab", async (type) => {+ mocks.invalidObjectType = type;+ const host = await mountBrowser(oracleConnection, "ORCL");+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await nextTick();+ expect(mocks.openObjectSourceTabPending).not.toHaveBeenCalled();+ expect(mocks.getObjectSource).not.toHaveBeenCalled();+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ });++ it.each([+ ["PACKAGE BODY", "PACKAGE_BODY"],+ ["MATERIALIZED VIEW", "MATERIALIZED_VIEW"],+ ])("opens supported %s through the normalized source-tab request", async (type, kind) => {+ mocks.invalidObjectType = type;+ const host = await mountBrowser(oracleConnection, "ORCL");+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ expect(mocks.openObjectSourceTabPending).toHaveBeenCalledWith(expect.objectContaining({ request: { name: "P_BAD", objectType: kind } }));+ await vi.waitFor(() => expect(host.querySelector("[data-invalid-object-dialog]")).toBeNull());+ });++ it.each([+ ["TYPE", "TYPE"],+ ["TYPE BODY", "TYPE_BODY"],+ ["TRIGGER", "TRIGGER"],+ ])("keeps the supported %s repair path usable", async (type, kind) => {+ mocks.invalidObjectType = type;+ const source = `CREATE OR REPLACE ${type} P_BAD`;+ mocks.getObjectSource.mockResolvedValueOnce({ source, editable: true });+ const host = await mountBrowser(oracleConnection, "ORCL");+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"))?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(mocks.updateSql).toHaveBeenCalledWith("repair-1", source));+ expect(mocks.getObjectSource).toHaveBeenCalledWith(oracleConnection.id, "ORCL", "APP", "P_BAD", kind);+ expect(mocks.createTab).toHaveBeenCalledWith(oracleConnection.id, "ORCL", "Repair - P_BAD", "query", "APP", undefined, undefined);+ expect(mocks.openObjectSourceTabPending).not.toHaveBeenCalled();+ expect(host.querySelector("[data-invalid-object-dialog]")).toBeNull();+ });++ it("closes the invalid-object dialog after its source tab loads", async () => {+ const host = await mountBrowser(oracleConnection, "ORCL");+ const opener = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"));+ opener?.click();+ await nextTick();+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(host.querySelector("[data-invalid-object-dialog]")).toBeNull());+ });++ it("keeps invalid-object diagnostics open and reports source-load failure", async () => {+ mocks.sourceLoadFailure = "ORA-00942: source unavailable";+ const host = await mountBrowser(oracleConnection, "ORCL");+ const opener = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"));+ opener?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith(expect.stringContaining("ORA-00942: source unavailable"), 5000));+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ });++ it("does not close or toast into the current dialog when the schema changes during source loading", async () => {+ mocks.deferSourceTabLoad = true;+ const { host, schema } = await mountOracleBrowserWithSchema();+ const opener = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"));+ opener?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(mocks.finishSourceTabLoad).toBeTypeOf("function"));+ schema.value = "APP_B";+ await nextTick();+ mocks.finishSourceTabLoad?.();+ await nextTick();+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ expect(mocks.toast).not.toHaveBeenCalled();+ });++ it("does not let a source request from a closed dialog close its reopened replacement", async () => {+ mocks.deferSourceTabLoad = true;+ const host = await mountBrowser(oracleConnection, "ORCL");+ const opener = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"));+ opener?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(mocks.finishSourceTabLoad).toBeTypeOf("function"));+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button:last-child")?.click();+ await nextTick();+ opener?.click();+ await nextTick();+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ mocks.finishSourceTabLoad?.();+ await nextTick();+ expect(host.querySelector("[data-invalid-object-dialog]")).not.toBeNull();+ expect(mocks.toast).not.toHaveBeenCalled();+ });++ it("does not create a repair tab or toast when an Oracle TYPE source request returns after unmount", async () => {+ let release!: (value: { source: string; editable: boolean }) => void;+ mocks.invalidObjectType = "TYPE";+ mocks.getObjectSource.mockReturnValueOnce(new Promise((resolve) => (release = resolve)));+ const host = await mountBrowser(oracleConnection, "ORCL");+ const opener = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("processList.oracleInvalidObjects.title"));+ opener?.click();+ await nextTick();+ host.querySelector<HTMLButtonElement>("[data-invalid-object-dialog] button")?.click();+ await vi.waitFor(() => expect(mocks.getObjectSource).toHaveBeenCalledWith(oracleConnection.id, "ORCL", "APP", "P_BAD", "TYPE"));+ const mounted = mountedApps.splice(+ mountedApps.findIndex((item) => item.host === host),+ 1,+ )[0]!;+ mounted.app.unmount();+ release({ source: "CREATE TYPE P_BAD AS OBJECT (...)", editable: true });+ await Promise.resolve();+ await nextTick();+ expect(mocks.openObjectSourceTabPending).not.toHaveBeenCalled();+ expect(mocks.toast).not.toHaveBeenCalled();+ host.remove();+ });+it("does not dispatch a save whose source identity changed during SQL construction", async () => {const host = await mountBrowser();vi.useFakeTimers();diff --git a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.tsindex 1b3f2f8737..6bf4836cb8 100644--- a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts@@ -17,6 +17,7 @@ const packageSaveAs = vi.hoisted(() => ({ prepare: vi.fn(), execute: vi.fn() }))vi.mock("@/lib/backend/api", async (importOriginal) => ({...(await importOriginal<typeof import("@/lib/backend/api")>()),...backend,+ closeClientConnectionSession: vi.fn().mockResolvedValue(true),listPlugins: vi.fn().mockResolvedValue([]),saveSchemaCache: vi.fn().mockResolvedValue(undefined),loadSchemaCache: vi.fn().mockResolvedValue(null),diff --git a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.ts b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.tsnew file mode 100644index 0000000000..d38892439f--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.guard.spec.ts@@ -0,0 +1,184 @@+// @vitest-environment happy-dom++import { createApp, defineComponent, h, nextTick, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import OracleInvalidObjectsDialog from "../OracleInvalidObjectsDialog.vue";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { useReadOnlyUnlockStore } from "@/stores/readOnlyUnlockStore";++const mocks = vi.hoisted(() => ({ query: vi.fn(), close: vi.fn(), unlockState: vi.fn(), unlock: vi.fn(), lock: vi.fn(), finished: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({+ executeQuery: mocks.query,+ closeClientConnectionSession: mocks.close,+ connectionWriteUnlockState: mocks.unlockState,+ unlockConnectionWrites: mocks.unlock,+ lockConnectionWrites: mocks.lock,+}));+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join(",")}` : key) }) }));++function passthrough(tag: string) {+ return defineComponent({+ inheritAttrs: false,+ setup:+ (_, { attrs, slots }) =>+ () =>+ h(tag, attrs, slots.default?.()),+ });+}+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));+vi.mock("@/components/ui/dialog", () => ({ Dialog: passthrough("div"), DialogContent: passthrough("div"), DialogHeader: passthrough("div"), DialogTitle: passthrough("div"), DialogFooter: passthrough("div") }));++const connection = { id: "invalid-real-guard", name: "Oracle guard fixture", db_type: "oceanbase-oracle" as const, host: "localhost", port: 2883, username: "APP", password: "" };+let app: App<Element> | undefined;+let root: HTMLDivElement;++beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(300);+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(600);+ setActivePinia(createPinia());+ const objects = [+ { name: "P_ONE", id: "101", status: "INVALID" },+ { name: "P_TWO", id: "102", status: "INVALID" },+ ];+ const columns = ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "LAST_DDL_TIME"];+ const time = "2026-10-20 09:00:00";+ mocks.query.mockReset().mockImplementation(async (_connectionId: string, _database: string, sql: string) => {+ if (sql.includes("OBJECT_ID >") || sql.includes("FROM (SELECT OWNER")) {+ const cursor = BigInt(sql.match(/OBJECT_ID > (\d+)/)?.[1] ?? "0");+ return { columns, rows: objects.filter((object) => object.status === "INVALID" && BigInt(object.id) > cursor).map((object) => ["APP", object.name, "PROCEDURE", object.id, time]) };+ }+ if (sql.startsWith("ALTER ")) {+ const name = sql.match(/\."([^"]+)"/)?.[1];+ const object = objects.find((item) => item.name === name);+ if (object) object.status = "VALID";+ return { columns: [], rows: [] };+ }+ if (sql.includes("STATUS FROM ALL_OBJECTS")) {+ const name = sql.match(/OBJECT_NAME = '([^']+)'/)?.[1];+ const object = objects.find((item) => item.name === name);+ return { columns: ["OBJECT_ID", "LAST_DDL_TIME", "STATUS"], rows: object ? [[object.id, time, object.status]] : [] };+ }+ return { columns: [], rows: [] };+ });+ mocks.close.mockReset().mockResolvedValue(undefined);+ mocks.unlockState.mockReset().mockResolvedValue(0);+ mocks.unlock.mockReset().mockResolvedValue(60_000);+ mocks.lock.mockReset().mockResolvedValue(undefined);+ mocks.finished.mockReset();+ root = document.createElement("div");+ document.body.append(root);+});++afterEach(async () => {+ app?.unmount();+ app = undefined;+ useReadOnlyUnlockStore().cancel();+ useProductionSafetyStore().cancel();+ await useReadOnlyUnlockStore().lockNow(connection.id);+ root.remove();+ setActivePinia(undefined);+ vi.restoreAllMocks();+});++async function mount(readOnly: boolean, production: boolean) {+ app = createApp({ render: () => h(OracleInvalidObjectsDialog, { open: true, connection: { ...connection, read_only: readOnly, is_production: production }, database: "ORCL", schema: "APP", onCompileFinished: mocks.finished }) });+ app.use(createPinia());+ app.mount(root);+ await vi.waitFor(() => expect(button("batchCompileAll")?.disabled).toBe(false));+}++function button(key: string): HTMLButtonElement | undefined {+ return [...root.querySelectorAll("button")].find((element) => element.textContent?.includes(key));+}++function writes(): string[] {+ return mocks.query.mock.calls.map((call) => String(call[2])).filter((sql) => sql.startsWith("ALTER "));+}++describe("invalid object actions through the real production execution guard", () => {+ it("rejects a real read-only request without submitting DDL", async () => {+ await mount(true, false);+ button("batchCompileAll")!.click();+ await vi.waitFor(() => expect(useReadOnlyUnlockStore().pending?.sql).toContain('"P_ONE"'));+ expect(writes()).toEqual([]);+ useReadOnlyUnlockStore().cancel();+ await vi.waitFor(() => expect(root.textContent).toContain("batchGuardDeclined"));+ expect(writes()).toEqual([]);+ expect(mocks.unlock).not.toHaveBeenCalled();+ expect(mocks.finished).not.toHaveBeenCalled();+ });++ it("uses one real read-only authorization for the complete frozen batch", async () => {+ await mount(true, false);+ button("batchCompileAll")!.click();+ await vi.waitFor(() => expect(useReadOnlyUnlockStore().pending).toBeTruthy());+ await useReadOnlyUnlockStore().confirm(60);+ await vi.waitFor(() => expect(mocks.finished).toHaveBeenCalledOnce());+ expect(writes()).toEqual(['ALTER PROCEDURE "APP"."P_ONE" COMPILE', 'ALTER PROCEDURE "APP"."P_TWO" COMPILE']);+ expect(mocks.unlock).toHaveBeenCalledExactlyOnceWith(connection.id, 60);+ expect(useProductionSafetyStore().pending).toBeUndefined();+ });++ it("rejects the real production confirmation with zero writes", async () => {+ await mount(false, true);+ button("batchCompileAll")!.click();+ await vi.waitFor(() => expect(useProductionSafetyStore().pending?.sql).toContain('"P_TWO"'));+ expect(writes()).toEqual([]);+ useProductionSafetyStore().cancel();+ await vi.waitFor(() => expect(root.textContent).toContain("batchGuardDeclined"));+ expect(writes()).toEqual([]);+ expect(mocks.finished).not.toHaveBeenCalled();+ });++ it("reviews and executes only the selected snapshot through the real production guard", async () => {+ await mount(false, true);+ root.querySelector<HTMLInputElement>('input[aria-label="P_ONE PROCEDURE"]')!.click();+ await nextTick();+ button("batchCompileSelected")!.click();+ await vi.waitFor(() => expect(useProductionSafetyStore().pending).toBeTruthy());+ expect(useProductionSafetyStore().pending!.sql).toBe('ALTER PROCEDURE "APP"."P_ONE" COMPILE');+ const unselected = root.querySelector<HTMLInputElement>('input[aria-label="P_TWO PROCEDURE"]')!;+ expect(unselected.disabled).toBe(true);+ unselected.click();+ useProductionSafetyStore().confirm();+ await vi.waitFor(() => expect(mocks.finished).toHaveBeenCalledOnce());+ expect(writes()).toEqual(['ALTER PROCEDURE "APP"."P_ONE" COMPILE']);+ expect(root.querySelector('button[aria-label="P_ONE PROCEDURE"]')).toBeNull();+ expect(root.querySelector('button[aria-label="P_TWO PROCEDURE"]')).toBeTruthy();+ });++ it("freezes the filtered complete scope and disables filters while production approval is pending", async () => {+ await mount(false, true);+ const filter = root.querySelector<HTMLInputElement>('input[type="search"]')!;+ filter.value = "p_one";+ filter.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ button("batchCompileFiltered:1")!.click();+ await vi.waitFor(() => expect(useProductionSafetyStore().pending).toBeTruthy());+ expect(useProductionSafetyStore().pending!.sql).toBe('ALTER PROCEDURE "APP"."P_ONE" COMPILE');+ expect(filter.disabled).toBe(true);+ expect(button("filterTypes")!.disabled).toBe(true);+ expect(button("clearFilters")!.disabled).toBe(true);+ expect(writes()).toEqual([]);+ useProductionSafetyStore().confirm();+ await vi.waitFor(() => expect(mocks.finished).toHaveBeenCalledOnce());+ expect(writes()).toEqual(['ALTER PROCEDURE "APP"."P_ONE" COMPILE']);+ expect(filter.value).toBe("p_one");+ expect(root.textContent).toContain("noFilterMatches");+ });++ it("still requires production approval after read-only access has been granted", async () => {+ await mount(true, true);+ button("batchCompileAll")!.click();+ await vi.waitFor(() => expect(useReadOnlyUnlockStore().pending).toBeTruthy());+ expect(useProductionSafetyStore().pending).toBeUndefined();+ await useReadOnlyUnlockStore().confirm(60);+ await vi.waitFor(() => expect(useProductionSafetyStore().pending).toBeTruthy());+ expect(writes()).toEqual([]);+ useProductionSafetyStore().cancel();+ await vi.waitFor(() => expect(root.textContent).toContain("batchGuardDeclined"));+ expect(writes()).toEqual([]);+ expect(mocks.unlock).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.ts b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.tsnew file mode 100644index 0000000000..4182ed58d1--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/OracleInvalidObjectsDialog.spec.ts@@ -0,0 +1,1832 @@+// @vitest-environment happy-dom++import { createApp, defineComponent, h, nextTick, ref, type App, type Component } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig } from "@/types/database";+import OracleInvalidObjectsDialog from "@/components/objects/OracleInvalidObjectsDialog.vue";++const mocks = vi.hoisted(() => ({+ executeQuery: vi.fn(),+ closeClientConnectionSession: vi.fn(),+ compileFinished: vi.fn(),+ guard: vi.fn(),+ executeAllowed: true,+ guardGate: null as null | (() => Promise<void>),+ identityChangedAfterGuard: false,+ failStatusReadback: false,+ statusReadbackErrorMode: "throw" as "throw" | "result",+ statusMissingAfterCompile: false,+ truncateBatchStatusBefore: false,+ truncateBatchStatusAfter: false,+ truncateSingleIdentity: false,+ truncateSingleStatusAfter: false,+ compileGate: null as null | (() => Promise<void>),+ batchStatusGate: null as null | (() => Promise<void>),+ batchPageGate: null as null | (() => Promise<void>),+ diagnosticGate: null as null | (() => Promise<void>),+ listGate: null as null | (() => Promise<void>),+ diagnosticTexts: {} as Record<string, string>,+ definiteBatchFailureName: "",+ definiteBatchFailureMode: "result" as "result" | "throw",+ batchObjects: [] as unknown[][],+ batchMode: false,+ batchStatuses: {} as Record<string, string>,+ missingBatchStatusName: "",+ batchObjectIds: {} as Record<string, string>,+ batchTimes: {} as Record<string, string>,+ failBatchPage: false,+ failRemainingAfterWrite: false,+ batchDdlSubmitted: false,+ failBatchCompileName: "",+ unknownBatchCompileName: "",+ unknownBatchCompileResultName: "",+ truncatedErrors: false,+ failCompile: false,+ failInvalidObjectList: false,+ postCompileListGate: null as null | (() => Promise<void>),+ singlePreflightSeen: false,+}));++function passthrough(tag: string): Component {+ return defineComponent({+ inheritAttrs: false,+ setup(_, { attrs, slots }) {+ return () => h(tag, attrs, slots.default?.());+ },+ });+}++vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values === undefined ? key : `${key}:${Object.values(values).join(",")}`) }) }));+vi.mock("@lucide/vue", () => {+ const Icon = passthrough("span");+ return { AlertTriangle: Icon, CheckIcon: Icon, ChevronDown: Icon, Circle: Icon, CircleHelp: Icon, CircleMinus: Icon, CircleX: Icon, Clock: Icon, Loader2: Icon, RefreshCw: Icon, Wrench: Icon };+});+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));+vi.mock("@/components/ui/dialog", () => ({ Dialog: passthrough("div"), DialogContent: passthrough("div"), DialogFooter: passthrough("div"), DialogHeader: passthrough("div"), DialogTitle: passthrough("div") }));+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery, closeClientConnectionSession: mocks.closeClientConnectionSession }));+vi.mock("@/lib/database/productionExecutionGuard", () => ({+ executeWithProductionSqlGuard: async (options: { execute: () => Promise<unknown> }) => {+ mocks.guard(options);+ if (mocks.guardGate) await mocks.guardGate();+ return mocks.executeAllowed ? options.execute() : undefined;+ },+}));++const connection: ConnectionConfig = { id: "oracle-invalid-1", name: "Oracle", db_type: "oracle", host: "localhost", port: 1521, username: "APP", password: "" };+let app: App<Element> | null = null;+let root: HTMLDivElement | null = null;+let compiled = false;+let compileStatus = "VALID";+let objectIdAfterCompile = "9";+let errorsReloadedAfterCompile = false;++beforeEach(() => {+ // Geometry is the external browser boundary; the installed virtual scroller stays real.+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(300);+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(600);+ compiled = false;+ mocks.singlePreflightSeen = false;+ compileStatus = "VALID";+ objectIdAfterCompile = "9";+ errorsReloadedAfterCompile = false;+ mocks.guardGate = null;+ mocks.identityChangedAfterGuard = false;+ mocks.failStatusReadback = false;+ mocks.statusReadbackErrorMode = "throw";+ mocks.statusMissingAfterCompile = false;+ mocks.truncateBatchStatusBefore = false;+ mocks.truncateBatchStatusAfter = false;+ mocks.truncateSingleIdentity = false;+ mocks.truncateSingleStatusAfter = false;+ mocks.compileGate = null;+ mocks.batchStatusGate = null;+ mocks.batchPageGate = null;+ mocks.diagnosticGate = null;+ mocks.listGate = null;+ mocks.diagnosticTexts = {};+ mocks.definiteBatchFailureName = "";+ mocks.definiteBatchFailureMode = "result";+ mocks.batchObjects = [+ ["APP", "P_OK", "PROCEDURE", "8", "2026-10-20 09:00:00"],+ ["APP", "P_BAD", "PROCEDURE", "9", "2026-10-20 09:00:00"],+ ["APP", "V_SKIP", "VIEW", "10", "2026-10-20 09:00:00"],+ ];+ mocks.batchMode = false;+ mocks.batchStatuses = {};+ mocks.missingBatchStatusName = "";+ mocks.batchObjectIds = {};+ mocks.batchTimes = {};+ mocks.failBatchPage = false;+ mocks.failRemainingAfterWrite = false;+ mocks.batchDdlSubmitted = false;+ mocks.failBatchCompileName = "";+ mocks.unknownBatchCompileName = "";+ mocks.unknownBatchCompileResultName = "";+ mocks.truncatedErrors = false;+ mocks.failCompile = false;+ mocks.failInvalidObjectList = false;+ mocks.postCompileListGate = null;+ mocks.executeAllowed = true;+ mocks.guard.mockReset();+ mocks.closeClientConnectionSession.mockReset().mockResolvedValue(undefined);+ mocks.compileFinished.mockReset();+ mocks.executeQuery.mockReset().mockImplementation(async (_connectionId: string, _database: string, sql: string) => {+ const dictionaryRows = () =>+ mocks.batchObjects.flatMap((row) => {+ const name = String(row[1]);+ const typeKey = `${name}:${row[2]}`;+ const status = compiled && name === "P_BAD" ? compileStatus : (mocks.batchStatuses[typeKey] ?? mocks.batchStatuses[name] ?? "INVALID");+ if (status !== "INVALID" || (compiled && name === "P_BAD" && mocks.statusMissingAfterCompile)) return [];+ return [[row[0], row[1], row[2], compiled && name === "P_BAD" ? objectIdAfterCompile : (mocks.batchObjectIds[typeKey] ?? mocks.batchObjectIds[name] ?? row[3]), compiled && name === "P_BAD" ? "2026-10-20 09:01:00" : (mocks.batchTimes[typeKey] ?? mocks.batchTimes[name] ?? row[4])]];+ });+ if (sql.includes("OBJECT_ID >")) {+ if (mocks.batchPageGate) {+ const gate = mocks.batchPageGate;+ mocks.batchPageGate = null;+ await gate();+ }+ mocks.batchMode = true;+ const cursor = BigInt(sql.match(/OBJECT_ID > (\d+)/)?.[1] ?? "0");+ if (mocks.failRemainingAfterWrite && mocks.batchDdlSubmitted) throw new Error("remaining list denied");+ if (mocks.failBatchPage && cursor > 0n) throw new Error("middle page failed");+ return {+ columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "LAST_DDL_TIME"],+ rows: dictionaryRows()+ .filter((row) => BigInt(String(row[3])) > cursor)+ .sort((a, b) => (BigInt(String(a[3])) < BigInt(String(b[3])) ? -1 : 1))+ .slice(0, 500),+ };+ }+ if (sql.includes("FROM (SELECT OWNER")) {+ if (mocks.listGate) {+ const gate = mocks.listGate;+ mocks.listGate = null;+ await gate();+ }+ if (compiled && mocks.postCompileListGate) {+ const gate = mocks.postCompileListGate;+ mocks.postCompileListGate = null;+ await gate();+ }+ if (mocks.failInvalidObjectList) throw new Error("ORA-01031: insufficient privileges");+ const rows = dictionaryRows();+ return { columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "LAST_DDL_TIME"], rows: rows.slice(0, 501) };+ }+ if (sql.includes("FROM ALL_ERRORS")) {+ if (mocks.diagnosticGate) {+ const gate = mocks.diagnosticGate;+ mocks.diagnosticGate = null;+ await gate();+ return { columns: [], rows: [[1, 3, 7, "late A diagnostics"]] };+ }+ if (compiled) errorsReloadedAfterCompile = true;+ const name = sql.match(/NAME = '([^']+)'/)?.[1] ?? "";+ return { columns: [], rows: mocks.truncatedErrors ? Array.from({ length: 1000 }, (_, index) => [index + 1, index + 1, 1, "invalid identifier"]) : [[1, 3, 7, mocks.diagnosticTexts[name] ?? (compiled ? "still invalid after compile" : "invalid identifier")]] };+ }+ if (sql.includes("STATUS = 'INVALID'")) {+ mocks.singlePreflightSeen = true;+ return { columns: [], rows: [[mocks.identityChangedAfterGuard ? 10 : 9, "2026-10-20 09:00:00"]], truncated: mocks.truncateSingleIdentity };+ }+ if (sql.includes("ALTER PROCEDURE") && mocks.singlePreflightSeen) {+ if (mocks.failCompile) throw new Error("ORA-01031: insufficient privileges");+ if (mocks.compileGate) await mocks.compileGate();+ compiled = true;+ return { columns: [], rows: [] };+ }+ if (sql.startsWith("ALTER ")) {+ const name = sql.match(/\."([^"]+)"/)?.[1] ?? "";+ const rejectedBackendError = {+ version: 1,+ code: "DBX-JDBC-4001",+ messageKey: "backendErrors.jdbc.sqlFailed",+ messageParams: {},+ source: "jdbcAgent",+ operationOutcome: "not_started",+ detail: "Request rejected before database execution",+ };+ if (name === mocks.definiteBatchFailureName) {+ if (mocks.definiteBatchFailureMode === "throw") throw { name: "BackendErrorException", backendError: rejectedBackendError };+ return { columns: ["Error"], rows: [["request rejected"]], execution_error: true, error: rejectedBackendError };+ }+ if (name === mocks.unknownBatchCompileName) throw new Error("connection lost during DDL");+ if (name === mocks.unknownBatchCompileResultName) return { columns: ["Error"], rows: [["result unavailable"]], execution_error: true, error: { detail: "result unavailable", operationOutcome: "unknown" } };+ if (name === mocks.failBatchCompileName) return { columns: ["Error"], rows: [["ORA-01031: insufficient privileges"]], execution_error: true, error: { detail: "ORA-01031: insufficient privileges", operationOutcome: "not_started" } };+ if (mocks.compileGate) await mocks.compileGate();+ if (mocks.singlePreflightSeen) {+ compiled = true;+ mocks.singlePreflightSeen = false;+ } else {+ const matches = mocks.batchObjects.filter((row) => row[1] === name);+ const target = matches.find((row) => String(row[2]).endsWith(" BODY") === /\bCOMPILE BODY\b/.test(sql));+ const key = matches.length > 1 ? `${name}:${target?.[2]}` : name;+ mocks.batchStatuses[key] = name === "P_BAD" ? "INVALID" : "VALID";+ mocks.batchTimes[key] = "2026-10-20 09:01:00";+ }+ mocks.batchDdlSubmitted = true;+ return { columns: [], rows: [] };+ }+ if (sql.includes("STATUS FROM ALL_OBJECTS")) {+ const targetName = sql.match(/OBJECT_NAME = '([^']+)'/)?.[1] ?? "";+ if (compiled && targetName === "P_BAD") {+ if (mocks.failStatusReadback) {+ if (mocks.statusReadbackErrorMode === "result") return { columns: ["Error"], rows: [["ORA-01031: insufficient privileges"]], execution_error: true, error: { detail: "ORA-01031: insufficient privileges" } };+ throw new Error("ORA-01031: insufficient privileges while reading status");+ }+ return { columns: [], rows: mocks.statusMissingAfterCompile ? [] : [[objectIdAfterCompile, "2026-10-20 09:01:00", compileStatus]], truncated: mocks.truncateSingleStatusAfter };+ }+ if (mocks.batchMode) {+ const name = sql.match(/OBJECT_NAME = '([^']+)'/)?.[1] ?? "";+ if (mocks.batchStatusGate) {+ const gate = mocks.batchStatusGate;+ mocks.batchStatusGate = null;+ await gate();+ }+ const type = sql.match(/OBJECT_TYPE = '([^']+)'/)?.[1] ?? "";+ const item = mocks.batchObjects.find((row) => row[1] === name && row[2] === type);+ if (!item || name === mocks.missingBatchStatusName) return { columns: ["OBJECT_ID", "LAST_DDL_TIME", "STATUS"], rows: [] };+ return {+ columns: ["OBJECT_ID", "LAST_DDL_TIME", "STATUS"],+ rows: [[mocks.batchObjectIds[`${name}:${type}`] ?? mocks.batchObjectIds[name] ?? item[3], mocks.batchTimes[`${name}:${type}`] ?? mocks.batchTimes[name] ?? item[4], mocks.batchStatuses[`${name}:${type}`] ?? mocks.batchStatuses[name] ?? "INVALID"]],+ truncated: mocks.batchDdlSubmitted ? mocks.truncateBatchStatusAfter : mocks.truncateBatchStatusBefore,+ };+ }+ const name = sql.match(/OBJECT_NAME = '([^']+)'/)?.[1] ?? "";+ const item = mocks.batchObjects.find((row) => row[1] === name);+ if (!item) return { columns: [], rows: [] };+ return { columns: ["OBJECT_ID", "LAST_DDL_TIME", "STATUS"], rows: [[item[3], item[4], mocks.batchStatuses[name] ?? "INVALID"]] };+ }+ return { columns: [], rows: [] };+ });+ root = document.createElement("div");+ document.body.appendChild(root);+});++afterEach(() => {+ app?.unmount();+ app = null;+ root?.remove();+ root = null;+ document.body.innerHTML = "";+ vi.restoreAllMocks();+});++function dialogButtons(): HTMLButtonElement[] {+ return Array.from(root?.querySelectorAll("button") ?? []);+}++function listRow(name: string, type = "PROCEDURE"): HTMLElement | null {+ return Array.from(root?.querySelectorAll<HTMLButtonElement>(`button[aria-label="${name} ${type}"]`) ?? []).find((button) => !button.closest("[inert]"))?.parentElement ?? null;+}++function statusLabels(): string[] {+ return Array.from(root?.querySelectorAll('[role="img"][aria-label]') ?? [])+ .filter((element) => !element.closest("[inert]"))+ .map((element) => element.getAttribute("aria-label")!);+}++async function openDetails(name: string, type = "PROCEDURE") {+ const button = root?.querySelector<HTMLButtonElement>(`button[aria-label="${name} ${type}"]`);+ expect(button).toBeTruthy();+ button!.click();+ await nextTick();+}++async function filterByName(value: string) {+ const input = root?.querySelector<HTMLInputElement>('input[aria-label="processList.oracleInvalidObjects.filterName"]');+ expect(input).toBeTruthy();+ input!.value = value;+ input!.dispatchEvent(new Event("input", { bubbles: true }));+ await nextTick();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ await nextTick();+}++async function scrollToRow(index: number, name: string) {+ const scroller = root?.querySelector<HTMLElement>("[data-object-scroller]");+ expect(scroller).toBeTruthy();+ scroller!.scrollTop = index * 44;+ scroller!.dispatchEvent(new Event("scroll"));+ await vi.waitFor(() => expect(listRow(name)).not.toBeNull());+}++async function setTypeOption(type: string, checked: boolean) {+ let option = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]')).find((element) => element.textContent?.trim() === type);+ if (!option) {+ const trigger = dialogButtons().find((button) => button.textContent?.includes("filterTypes"));+ expect(trigger).toBeTruthy();+ trigger!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await vi.waitFor(() => {+ option = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]')).find((element) => element.textContent?.trim() === type);+ expect(option).toBeTruthy();+ });+ }+ if ((option!.getAttribute("aria-checked") === "true") !== checked) option!.click();+ await nextTick();+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+}++async function closeTypeMenu() {+ document.querySelector<HTMLElement>('[role="menuitemcheckbox"]')?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ await nextTick();+}++async function waitForBatch() {+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+}++async function mountDialog(connectionState = ref(connection), databaseState = ref("ORCL"), initiallyOpen = true, schemaState = ref("APP"), waitForFullRead = true) {+ const open = ref(initiallyOpen);+ const Wrapper = defineComponent({+ setup() {+ return () =>+ h("div", [+ h(+ "button",+ {+ "data-test-open": true,+ onClick: () => {+ open.value = true;+ },+ },+ "reopen",+ ),+ h(+ "button",+ {+ "data-test-close": true,+ onClick: () => {+ open.value = false;+ },+ },+ "dismiss",+ ),+ h(OracleInvalidObjectsDialog, {+ open: open.value,+ connection: connectionState.value,+ database: databaseState.value,+ schema: schemaState.value,+ onCompileFinished: mocks.compileFinished,+ "onUpdate:open": (value: boolean) => {+ open.value = value;+ },+ }),+ ]);+ },+ });+ app = createApp(Wrapper);+ app.mount(root!);+ if (initiallyOpen) {+ await vi.waitFor(() => expect(root?.textContent?.includes(String(mocks.batchObjects[0]?.[1] ?? "P_BAD")) || root?.textContent?.includes("ORA-01031")).toBe(true));+ if (waitForFullRead && !mocks.failBatchPage && !mocks.failInvalidObjectList) await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll"))).toBeTruthy());+ }+ return { open, connectionState, databaseState };+}++describe("OracleInvalidObjectsDialog production flow", () => {+ it.each(["INDEX", "JAVA CLASS"])("keeps %s diagnostics but does not offer an unsupported source editor", async (type) => {+ mocks.batchObjects = [["APP", "UNSUPPORTED_OBJECT", type, "11", "time"]];+ await mountDialog();+ await openDetails("UNSUPPORTED_OBJECT", type);+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ expect(dialogButtons().find((button) => button.textContent?.includes("oracleInvalidObjects.openSource"))).toBeUndefined();+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.unsupportedType");+ });++ it("keeps a supported source action independent of engine compile support", async () => {+ mocks.batchObjects = [["APP", "V_ONLY", "VIEW", "11", "time"]];+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ await openDetails("V_ONLY", "VIEW");+ const source = dialogButtons().find((button) => button.textContent?.includes("oracleInvalidObjects.openSource"));+ expect(source).toBeDefined();+ expect(source?.disabled).toBe(false);+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.unsupportedOnEngine");+ });++ it("filters names without case sensitivity and compiles only the complete matching scope", async () => {+ mocks.batchObjects = [+ ["APP", "P_KEEP_FIRST", "PROCEDURE", "11", "time"],+ ["APP", "P_KEEP_SECOND", "PROCEDURE", "12", "time"],+ ["APP", "P_OTHER", "PROCEDURE", "13", "time"],+ ];+ await mountDialog();+ root?.querySelector<HTMLInputElement>('input[aria-label="P_OTHER PROCEDURE"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:1");+ await filterByName("p_keep");+ expect(root?.textContent).toContain("batchSelectedCount:0");+ expect(listRow("P_OTHER")).toBeNull();+ expect(listRow("P_KEEP_FIRST")).not.toBeNull();+ expect(dialogButtons().some((button) => button.textContent?.includes("batchNextPage"))).toBe(false);+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileFiltered:2"))+ ?.click();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]))).toEqual(['ALTER PROCEDURE "APP"."P_KEEP_FIRST" COMPILE REUSE SETTINGS', 'ALTER PROCEDURE "APP"."P_KEEP_SECOND" COMPILE REUSE SETTINGS']);+ });++ it.each(["%", "_", "[", " "])("treats %s in the name filter as literal text and clears an empty result without querying", async (literal) => {+ mocks.batchObjects = [+ ["APP", `P${literal}MATCH`, "PROCEDURE", "11", "time"],+ ["APP", "PXMATCH", "PROCEDURE", "12", "time"],+ ];+ await mountDialog();+ const queriesBefore = mocks.executeQuery.mock.calls.length;+ await filterByName(literal);+ expect(listRow(`P${literal}MATCH`)).not.toBeNull();+ expect(listRow("PXMATCH")).toBeNull();+ await filterByName("missing-name");+ expect(root?.textContent).toContain("noFilterMatches");+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileFiltered:0"))?.disabled).toBe(true);+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.clearFilters")+ ?.click();+ await nextTick();+ expect(listRow(`P${literal}MATCH`)).not.toBeNull();+ expect(listRow("PXMATCH")).not.toBeNull();+ expect(root?.textContent).toContain("batchSelectedCount:0");+ expect(mocks.executeQuery).toHaveBeenCalledTimes(queriesBefore);+ });++ it("intersects name and type filters, treats zero types as empty and compiles only the package body", async () => {+ mocks.batchObjects = [+ ["APP", "PKG_KEEP", "PACKAGE", "11", "time"],+ ["APP", "PKG_KEEP", "PACKAGE BODY", "12", "time"],+ ["APP", "P_OTHER", "PROCEDURE", "13", "time"],+ ["APP", "V_SKIP", "VIEW", "14", "time"],+ ];+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ await filterByName("pkg");+ await setTypeOption("processList.oracleInvalidObjects.allTypes", false);+ expect(root?.textContent).toContain("noFilterMatches");+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileFiltered:0"))?.disabled).toBe(true);+ await setTypeOption("PACKAGE BODY", true);+ await closeTypeMenu();+ expect(listRow("PKG_KEEP", "PACKAGE")).toBeNull();+ expect(listRow("PKG_KEEP", "PACKAGE BODY")).not.toBeNull();+ expect(root?.textContent).toContain("filterCount:1,4");+ root?.querySelector<HTMLInputElement>('label input[type="checkbox"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:1");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileFiltered:1"))+ ?.click();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]))).toEqual(['ALTER PACKAGE "APP"."PKG_KEEP" COMPILE BODY']);+ });++ it.each([false, true])("keeps a newly discovered type within the user's explicit type intent (%s)", async (explicit) => {+ mocks.batchObjects = [["APP", "P_ONLY", "PROCEDURE", "11", "time"]];+ let release!: () => void;+ mocks.batchPageGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountDialog(ref(connection), ref("ORCL"), true, ref("APP"), false);+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ if (explicit) {+ await setTypeOption("processList.oracleInvalidObjects.allTypes", false);+ await setTypeOption("PROCEDURE", true);+ await closeTypeMenu();+ }+ mocks.batchObjects.push(["APP", "F_NEW", "FUNCTION", "12", "time"]);+ release();+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.includes(explicit ? "batchCompileFiltered:1" : "batchCompileAll:2"))?.disabled).toBe(false));+ expect(!!listRow("F_NEW", "FUNCTION")).toBe(!explicit);+ expect(root?.textContent).toContain("batchSelectedCount:0");+ });++ it("selects every matching executable object across virtual windows without selecting hidden names", async () => {+ mocks.batchObjects = [...Array.from({ length: 201 }, (_, index) => ["APP", `P_MATCH_${index}`, "PROCEDURE", String(index + 1), "time"]), ["APP", "P_OTHER", "PROCEDURE", "999", "time"]];+ mocks.executeAllowed = false;+ await mountDialog();+ await filterByName("P_MATCH_");+ expect(root?.querySelectorAll("[data-row-key]").length).toBeLessThan(100);+ root?.querySelector<HTMLInputElement>('label input[type="checkbox"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:201");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected:201"))+ ?.click();+ await waitForBatch();+ expect(mocks.guard).toHaveBeenCalledOnce();+ const audit = (mocks.guard.mock.calls[0]![0] as { sql: string }).sql;+ expect(audit.split(";\n")).toHaveLength(201);+ expect(audit).toContain('"P_MATCH_200"');+ expect(audit).not.toContain('"P_OTHER"');+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ });++ it("preserves filters on refresh but resets them on a new scope", async () => {+ const schema = ref("APP");+ await mountDialog(ref(connection), ref("ORCL"), true, schema);+ await filterByName("P_OK");+ await setTypeOption("processList.oracleInvalidObjects.allTypes", false);+ await setTypeOption("PROCEDURE", true);+ await closeTypeMenu();+ listRow("P_OK")?.querySelector<HTMLInputElement>("input")?.click();+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileFiltered:1"))?.disabled).toBe(false));+ expect(root?.querySelector<HTMLInputElement>('input[type="search"]')?.value).toBe("P_OK");+ expect(root?.textContent).toContain("batchSelectedCount:0");+ mocks.batchObjects = mocks.batchObjects.map((row) => ["OTHER", ...row.slice(1)]);+ schema.value = "OTHER";+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll:3"))?.disabled).toBe(false));+ expect(root?.querySelector<HTMLInputElement>('input[type="search"]')?.value).toBe("");+ expect(root?.textContent).toContain("batchSelectedCount:0");+ });++ it("keeps filtered all disabled during incomplete reads while allowing the selected loaded target", async () => {+ let release!: () => void;+ mocks.batchPageGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountDialog(ref(connection), ref("ORCL"), true, ref("APP"), false);+ await filterByName("P_OK");+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compileFiltered")?.disabled).toBe(true);+ expect(root?.textContent).toContain("currentlyLoaded");+ listRow("P_OK")?.querySelector<HTMLInputElement>("input")?.click();+ await nextTick();+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileSelected:1"))?.disabled).toBe(false);+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected:1"))+ ?.click();+ await nextTick();+ expect(mocks.guard).not.toHaveBeenCalled();+ release();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]))).toEqual(['ALTER PROCEDURE "APP"."P_OK" COMPILE REUSE SETTINGS']);+ });++ it("retains the explicit selected type when its last matching object becomes valid", async () => {+ mocks.batchObjects = [+ ["APP", "P_ONLY", "PROCEDURE", "11", "time"],+ ["APP", "F_OTHER", "FUNCTION", "12", "time"],+ ];+ await mountDialog();+ await setTypeOption("processList.oracleInvalidObjects.allTypes", false);+ await setTypeOption("PROCEDURE", true);+ await closeTypeMenu();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileFiltered:1"))+ ?.click();+ await waitForBatch();+ expect(root?.textContent).toContain("noFilterMatches");+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileFiltered:0"))?.disabled).toBe(true);+ await setTypeOption("PROCEDURE", true);+ expect(+ Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]'))+ .find((element) => element.textContent?.trim() === "PROCEDURE")+ ?.getAttribute("aria-checked"),+ ).toBe("true");+ await closeTypeMenu();+ expect(listRow("F_OTHER", "FUNCTION")).toBeNull();+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.clearFilters")+ ?.click();+ await vi.waitFor(() => expect(listRow("F_OTHER", "FUNCTION")).not.toBeNull());+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ });++ it("returns from a deep detail to the same scroll position and original name focus", async () => {+ mocks.batchObjects = Array.from({ length: 601 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ await mountDialog();+ await scrollToRow(400, "P_400");+ const previousTop = root!.querySelector<HTMLElement>("[data-object-scroller]")!.scrollTop;+ listRow("P_400")!.querySelector<HTMLButtonElement>("button")!.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await vi.waitFor(() => expect((document.activeElement as HTMLElement)?.dataset.objectKey).toBe("APP:401"));+ expect(root!.querySelector<HTMLElement>("[data-object-scroller]")!.scrollTop).toBe(previousTop);+ expect(document.activeElement?.closest("[inert]")).toBeNull();+ });++ it("tabs across the recycled window edge to the next logical checkbox without selecting it", async () => {+ vi.spyOn(HTMLElement.prototype, "scrollTo").mockImplementation(function (this: HTMLElement, optionsOrX?: ScrollToOptions | number, y?: number) {+ this.scrollTop = typeof optionsOrX === "number" ? (y ?? 0) : (optionsOrX?.top ?? this.scrollTop);+ this.scrollLeft = typeof optionsOrX === "number" ? optionsOrX : (optionsOrX?.left ?? this.scrollLeft);+ // Simulate the browser scroll event, which happy-dom does not dispatch.+ this.dispatchEvent(new Event("scroll"));+ });+ mocks.batchObjects = Array.from({ length: 601 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ await mountDialog();+ const activeIndexes = Array.from(root!.querySelectorAll<HTMLButtonElement>("[data-row-key]:not([inert]) button")).map((button) => Number(button.textContent!.replace("P_", "")));+ const last = Math.max(...activeIndexes);+ expect(last).toBeLessThan(600);+ expect(listRow(`P_${last + 1}`)).toBeNull();+ const button = listRow(`P_${last}`)!.querySelector<HTMLButtonElement>("button")!;+ button.focus();+ button.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));+ await vi.waitFor(() => expect(document.activeElement?.getAttribute("aria-label")).toBe(`P_${last + 1} PROCEDURE`));+ expect(document.activeElement?.tagName).toBe("INPUT");+ expect(document.activeElement?.closest("[inert]")).toBeNull();+ expect((document.activeElement as HTMLInputElement).checked).toBe(false);+ expect(root?.textContent).toContain("batchSelectedCount:0");+ });++ it("separates opening object details from selection and exposes a zero-selection disabled action", async () => {+ await mountDialog();+ const checkboxes = Array.from(root?.querySelectorAll<HTMLInputElement>('input[type="checkbox"]') ?? []);+ expect(checkboxes.length).toBeGreaterThan(0);+ expect(checkboxes[0]?.checked).toBe(false);+ expect(dialogButtons().some((button) => button.textContent?.includes("batchCompileSelected") && button.disabled)).toBe(true);+ checkboxes[0]?.click();+ await nextTick();+ expect(root?.textContent).not.toContain("invalid identifier");+ expect(dialogButtons().some((button) => button.textContent?.includes("batchCompileSelected") && !button.disabled)).toBe(true);+ });++ it("preserves selected identities across virtual windows and compiles only checked objects", async () => {+ mocks.batchObjects = Array.from({ length: 101 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ await mountDialog();+ root?.querySelector<HTMLInputElement>('input[aria-label="P_0 PROCEDURE"]')?.click();+ await scrollToRow(100, "P_100");+ listRow("P_100")?.querySelector<HTMLInputElement>("input")?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:2");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await vi.waitFor(() => expect(mocks.guard).toHaveBeenCalled());+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ const submitted = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]));+ expect(submitted).toHaveLength(2);+ expect(submitted.join("\n")).toContain('"P_0"');+ expect(submitted.join("\n")).toContain('"P_100"');+ expect(submitted.join("\n")).not.toContain('"P_1"');+ });++ it("orders selected targets by the current full collection, not click order", async () => {+ mocks.batchObjects = [+ ["APP", "P_FIRST", "PROCEDURE", "11", "time"],+ ["APP", "P_SECOND", "PROCEDURE", "12", "time"],+ ];+ await mountDialog();+ root?.querySelector<HTMLInputElement>('input[aria-label="P_SECOND PROCEDURE"]')?.click();+ root?.querySelector<HTMLInputElement>('input[aria-label="P_FIRST PROCEDURE"]')?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ const submitted = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]));+ expect(submitted).toEqual(['ALTER PROCEDURE "APP"."P_FIRST" COMPILE REUSE SETTINGS', 'ALTER PROCEDURE "APP"."P_SECOND" COMPILE REUSE SETTINGS']);+ });++ it("orders all targets by the displayed collection rather than the dictionary ID cursor", async () => {+ mocks.batchObjects = [+ ["APP", "P_FIRST", "PROCEDURE", "12", "time"],+ ["APP", "P_SECOND", "PROCEDURE", "11", "time"],+ ];+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]))).toEqual(['ALTER PROCEDURE "APP"."P_FIRST" COMPILE REUSE SETTINGS', 'ALTER PROCEDURE "APP"."P_SECOND" COMPILE REUSE SETTINGS']);+ });++ it.each(["detail", "list"])("keeps a single compile's diagnostics with its frozen object after navigating to another %s", async (view) => {+ let release!: () => void;+ compileStatus = "INVALID";+ mocks.diagnosticTexts = { P_BAD: "A diagnostic", P_OK: "B diagnostic" };+ await mountDialog();+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(root?.textContent).toContain("A diagnostic"));+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ await openDetails("P_OK");+ if (view === "list") {+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ }+ mocks.compileGate = null;+ release();+ if (view === "detail") {+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(false));+ expect(root?.textContent).not.toContain("compileStillInvalid");+ expect(root?.textContent).not.toContain("A diagnostic");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ } else {+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ expect(root?.querySelector("section[aria-label]")).not.toBeNull();+ }+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(root?.textContent).toContain("compileStillInvalid"));+ expect(root?.textContent).toContain("A diagnostic");+ expect(root?.textContent).not.toContain("B diagnostic");+ });++ it("does not let the first diagnostic request overwrite the latest A result after A-B-A navigation", async () => {+ let release!: () => void;+ mocks.batchObjects = [+ ["APP", "P_A", "PROCEDURE", "11", "time"],+ ["APP", "P_B", "PROCEDURE", "12", "time"],+ ];+ mocks.diagnosticGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountDialog();+ root?.querySelector<HTMLButtonElement>('[data-object-key="APP:11"]')?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ root?.querySelector<HTMLButtonElement>('[data-object-key="APP:12"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ root?.querySelector<HTMLButtonElement>('[data-object-key="APP:11"]')?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ release();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(root?.textContent).not.toContain("late A diagnostics");+ });++ it("allows a resolved target again after an explicit refresh confirms it is still invalid", async () => {+ const { databaseState } = await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("compileValid"));+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(true);++ compileStatus = "INVALID";+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.title === "common.refresh")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("P_BAD"));+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(false));+ expect(databaseState.value).toBe("ORCL");+ });++ it("clears a resolved-target disable when the execution scope changes", async () => {+ const { databaseState } = await mountDialog();+ await openDetails("P_BAD");+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("compileValid"));++ compileStatus = "INVALID";+ databaseState.value = "ORCL2";+ await vi.waitFor(() => expect(root?.querySelector('button[aria-label="P_BAD PROCEDURE"]')).toBeTruthy());+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(false));+ });++ it("keeps detail navigation separate and restores selection and focus through the real scroller", async () => {+ await mountDialog();+ const checkbox = root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]');+ checkbox?.click();+ const nameButton = root?.querySelector<HTMLButtonElement>('[data-object-key="APP:8"]');+ nameButton?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ expect(root?.querySelector<HTMLInputElement>('input[type="checkbox"]')).toBeNull();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.checked).toBe(true);+ await vi.waitFor(() => expect((document.activeElement as HTMLElement | null)?.dataset.objectKey).toBe("APP:8"));+ });++ it("updates the original rows in place and keeps the frozen queue intact as VALID rows disappear", async () => {+ mocks.batchObjects.push(["APP", "P_LATER", "PROCEDURE", "11", "2026-10-20 09:00:00"]);+ const releases: Array<() => void> = [];+ mocks.compileGate = () => new Promise<void>((resolve) => releases.push(resolve));+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.click();+ root?.querySelector<HTMLInputElement>('input[aria-label="P_BAD PROCEDURE"]')?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await vi.waitFor(() => expect(releases).toHaveLength(1));+ expect(listRow("P_OK")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toContain("running");+ expect(listRow("P_BAD")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toContain("pending");+ expect(listRow("P_LATER")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toBe("INVALID");+ expect(root?.querySelectorAll("section[aria-label]")).toHaveLength(1);+ expect(root?.textContent).not.toContain("batchResults");+ releases[0]!();+ await vi.waitFor(() => expect(releases).toHaveLength(2));+ expect(listRow("P_OK")).toBeNull();+ expect(root?.textContent).toContain("batchProgress:1,2,APP.P_BAD");+ expect(listRow("P_OK")).toBeNull();+ expect(listRow("P_BAD")).not.toBeNull();+ expect(listRow("P_LATER")).not.toBeNull();+ expect(listRow("V_SKIP", "VIEW")).not.toBeNull();+ mocks.compileGate = null;+ releases[1]!();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(2);+ expect(mocks.compileFinished).toHaveBeenCalledOnce();+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.still-invalid");+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_BAD PROCEDURE"]')?.disabled).toBe(false);+ });++ it("keeps an unknown row absent from INVALID results until explicit read-only refresh confirms VALID", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ mocks.truncateBatchStatusAfter = true;+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await waitForBatch();+ expect(listRow("P_OK")).not.toBeNull();+ expect(listRow("P_OK")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toContain("unknown");+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.disabled).toBe(true);+ expect(root?.textContent).toContain("batchCompileAll:1");+ root?.querySelector<HTMLInputElement>('label input[type="checkbox"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:1");+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.checked).toBe(false);+ mocks.truncateBatchStatusAfter = false;+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(listRow("P_OK")).toBeNull());+ expect(listRow("P_BAD")).not.toBeNull();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(mocks.compileFinished).toHaveBeenCalledOnce();+ });++ it("retains a single unknown row when complete INVALID results omit it and does not retry its write", async () => {+ mocks.failStatusReadback = true;+ await mountDialog();+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("compileUnknown"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ expect(listRow("P_BAD")).not.toBeNull();+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_BAD PROCEDURE"]')?.disabled).toBe(true);+ mocks.failStatusReadback = false;+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(listRow("P_BAD")).toBeNull());+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ });++ it("keeps another unresolved row's diagnostic when a later selection starts a new batch", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ mocks.unknownBatchCompileName = "P_OK";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await waitForBatch();+ mocks.unknownBatchCompileName = "";+ root?.querySelector<HTMLInputElement>('input[aria-label="P_BAD PROCEDURE"]')?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await waitForBatch();+ expect(root?.textContent).toContain("batchSummary:0,1,0,0");+ expect(listRow("P_OK")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toContain("unknown");+ await openDetails("P_OK");+ expect(root?.textContent).toContain("connection lost during DDL");+ });++ it("keeps more than 501 objects during execution and restores the neighboring virtual row after removal", async () => {+ mocks.batchObjects = Array.from({ length: 601 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ let release!: () => void;+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountDialog();+ await scrollToRow(600, "P_600");+ listRow("P_600")?.querySelector<HTMLInputElement>("input")?.click();+ await nextTick();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(root?.textContent).toContain("listCount:601");+ expect(root?.querySelectorAll("[data-row-key]:not([inert])").length).toBeLessThan(50);+ const diagnosticsBefore = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM ALL_ERRORS")).length;+ await openDetails("P_600");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM ALL_ERRORS"))).toHaveLength(diagnosticsBefore);+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(true);+ release();+ await vi.waitFor(() => expect(mocks.compileFinished).toHaveBeenCalledOnce());+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(listRow("P_599")).not.toBeNull());+ expect(listRow("P_600")).toBeNull();+ await vi.waitFor(() => expect((document.activeElement as HTMLElement | null)?.dataset.objectKey).toBe("APP:600"));+ });++ it("shows the same ID as a new unselected INVALID observation if it becomes invalid again after a VALID read", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 1);+ await mountDialog();+ let release!: () => void;+ mocks.batchPageGate = () => new Promise<void>((resolve) => (release = resolve));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(listRow("P_OK")).toBeNull();+ mocks.batchStatuses.P_OK = "INVALID";+ release();+ await waitForBatch();+ expect(listRow("P_OK")).not.toBeNull();+ expect(listRow("P_OK")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toBe("INVALID");+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.checked).toBe(false);+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.disabled).toBe(false);+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ });++ it("distinguishes same-name package specification and body for accessible controls", async () => {+ mocks.batchObjects = [+ ["APP", "P_SHARED", "PACKAGE", "31", "time"],+ ["APP", "P_SHARED", "PACKAGE BODY", "32", "time"],+ ];+ await mountDialog();++ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_SHARED PACKAGE"]')).toBeTruthy();+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_SHARED PACKAGE BODY"]')).toBeTruthy();+ expect(root?.querySelector<HTMLButtonElement>('button[aria-label="P_SHARED PACKAGE"]')).toBeTruthy();+ expect(root?.querySelector<HTMLButtonElement>('button[aria-label="P_SHARED PACKAGE BODY"]')).toBeTruthy();+ });++ it("drains both the pending full-read page and diagnostic query before a single-object write", async () => {+ let releasePage!: () => void;+ let releaseErrors!: () => void;+ mocks.batchPageGate = () => new Promise<void>((resolve) => (releasePage = resolve));+ mocks.diagnosticGate = () => new Promise<void>((resolve) => (releaseErrors = resolve));+ await mountDialog(ref(connection), ref("ORCL"), true, ref("APP"), false);+ await vi.waitFor(() => expect(releasePage).toBeTypeOf("function"));+ root?.querySelector<HTMLButtonElement>('[data-object-key="APP:9"]')?.click();+ await vi.waitFor(() => expect(releaseErrors).toBeTypeOf("function"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(mocks.guard).not.toHaveBeenCalled();+ releasePage();+ await nextTick();+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ releaseErrors();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileValid"));+ expect(mocks.guard).toHaveBeenCalledOnce();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ });++ it("does not let a pending refresh start another diagnostic query after an action begins draining", async () => {+ let releaseList!: () => void;+ let releaseCompile!: () => void;+ await mountDialog();+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ mocks.listGate = () => new Promise<void>((resolve) => (releaseList = resolve));+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(releaseList).toBeTypeOf("function"));+ const diagnosticCount = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM ALL_ERRORS")).length;+ root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.click();+ await nextTick();+ mocks.compileGate = () => new Promise<void>((resolve) => (releaseCompile = resolve));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileSelected"))+ ?.click();+ await nextTick();+ expect(mocks.guard).not.toHaveBeenCalled();+ releaseList();+ await vi.waitFor(() => expect(releaseCompile).toBeTypeOf("function"));+ try {+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM ALL_ERRORS"))).toHaveLength(diagnosticCount);+ } finally {+ mocks.compileGate = null;+ releaseCompile();+ }+ await waitForBatch();+ });++ it("shows a dictionary read denial instead of treating it as an empty list", async () => {+ mocks.failInvalidObjectList = true;+ await mountDialog();+ expect(root?.textContent).toContain("ORA-01031: insufficient privileges");+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.empty");+ expect(dialogButtons().some((button) => button.title === "common.refresh")).toBe(true);+ });++ it("uses one managed client session, closes it, and rotates it when the dialog reopens", async () => {+ await mountDialog();+ const sessionIds = mocks.executeQuery.mock.calls.map((call) => (call[5] as { clientSessionId?: string } | undefined)?.clientSessionId);+ expect(new Set(sessionIds).size).toBe(1);+ const sessionId = sessionIds[0];+ expect(sessionId).toMatch(/^invalid-objects:/);+ root?.querySelector<HTMLButtonElement>("[data-test-close]")?.click();+ await nextTick();+ expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(connection.id, "ORCL", sessionId);+ const listCallsBeforeReopen = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length;+ root?.querySelector<HTMLButtonElement>("[data-test-open]")?.click();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length).toBeGreaterThan(listCallsBeforeReopen));+ const reopenedListCall = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).at(-1);+ expect((reopenedListCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId).not.toBe(sessionId);+ });++ it("does not create or close a client session when the hidden dialog context changes", async () => {+ const connectionState = ref({ ...connection });+ const databaseState = ref("ORCL");+ const { open } = await mountDialog(connectionState, databaseState, false);++ connectionState.value = { ...connection, host: "replacement-host" };+ databaseState.value = "ORCL2";+ await nextTick();++ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ open.value = true;+ await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalled());+ expect(mocks.executeQuery.mock.calls[0]).toEqual(expect.arrayContaining([connection.id, "ORCL2"]));+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ });++ it("reads the complete batch in the background and compiles all with one click", async () => {+ let release!: () => void;+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.truncatedErrors = true;+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ const compileAll = dialogButtons().find((button) => button.textContent?.includes("batchCompileAll"));+ expect(compileAll?.disabled).toBe(false);+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="V_SKIP VIEW"]')?.disabled).toBe(true);+ compileAll?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("OBJECT_ID >"))).toBe(true));+ expect(root?.textContent).toContain("V_SKIP");+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.running");+ mocks.compileGate = null;+ release();+ await waitForBatch();+ expect(mocks.guard).toHaveBeenCalledOnce();+ const sessionIds = mocks.executeQuery.mock.calls.map((call) => (call[5] as { clientSessionId?: string } | undefined)?.clientSessionId);+ expect(new Set(sessionIds).size).toBe(1);+ expect(sessionIds[0]).toMatch(/^invalid-objects:/);+ const options = mocks.guard.mock.calls[0]?.[0] as { sql: string };+ expect(options.sql).toContain('ALTER PROCEDURE "APP"."P_OK" COMPILE');+ expect(options.sql).toContain('ALTER PROCEDURE "APP"."P_BAD" COMPILE');+ expect(options.sql).not.toContain("V_SKIP");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(2);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.still-invalid");+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unsupported");+ expect(listRow("P_OK")).toBeNull();+ expect(listRow("P_BAD")).not.toBeNull();+ await openDetails("P_BAD");+ expect(root?.textContent).toContain("errorsTruncated");+ expect(root?.querySelectorAll("tbody tr")).toHaveLength(1000);+ });++ it("does not submit a partial plan when a middle batch page fails", async () => {+ mocks.batchObjects = Array.from({ length: 501 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ mocks.failBatchPage = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchReadFailed"));+ expect(root?.textContent).toContain("middle page failed");+ expect(root?.textContent).not.toContain("batchSummary");+ expect(mocks.guard).not.toHaveBeenCalled();+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ });++ it("does not compile an object when its preflight status result is truncated", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 1);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ mocks.truncateBatchStatusBefore = true;+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(0);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unknown");+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.disabled).toBe(true);+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll:0"))?.disabled).toBe(true);+ await openDetails("P_OK");+ expect(root?.textContent).toContain("batchIdentityUnknown");+ expect(root?.textContent).not.toContain("compileUnknown");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ mocks.truncateBatchStatusBefore = false;+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll:1"))?.disabled).toBe(false));+ expect(root?.querySelector<HTMLInputElement>('input[aria-label="P_OK PROCEDURE"]')?.disabled).toBe(false);+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(0);+ });++ it("does not compile a single object when its identity preflight is truncated", async () => {+ mocks.truncateSingleIdentity = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.batchIdentityUnknown"));+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileUnknown");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(0);+ });++ it("stops the batch with unknown status when post-compile readback is truncated", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ mocks.truncateBatchStatusAfter = true;+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unknown");+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ await openDetails("P_OK");+ expect(root?.textContent).toContain("compileUnknown");+ expect(root?.textContent).not.toContain("batchIdentityUnknown");+ });++ it("cancels batch confirmation without compiling or refreshing the remaining list", async () => {+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ mocks.executeAllowed = false;+ await vi.waitFor(() => expect(root?.textContent).toContain("batchGuardDeclined"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(mocks.compileFinished).not.toHaveBeenCalled();+ });++ it("stops before the next object when the user requests it during a submitted compile", async () => {+ let release!: () => void;+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(root?.querySelector('[role="status"]')?.textContent).not.toContain("batchStopping");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchStop"))+ ?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchStopping");+ const stopButton = dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.batchStop");+ expect(stopButton?.disabled).toBe(true);+ expect(root?.textContent?.split("batchStopping")).toHaveLength(2);+ release();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ });++ it("stops before the first DDL when requested while production confirmation is pending", async () => {+ let release!: () => void;+ mocks.guardGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ expect(root?.querySelector('[role="status"]')?.textContent).not.toContain("batchStopping");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchStop"))+ ?.click();+ release();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ });++ it("stops before DDL when requested while the first object's identity preflight is pending", async () => {+ let release!: () => void;+ mocks.batchStatusGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ dialogButtons()+ .find((button) => button.textContent?.includes("batchStop"))+ ?.click();+ release();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ });++ it("does not send a confirmed batch to a replacement connection configuration", async () => {+ let release!: () => void;+ mocks.guardGate = () => new Promise<void>((resolve) => (release = resolve));+ const connectionState = ref(connection);+ await mountDialog(connectionState);+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));++ connectionState.value = { ...connection, host: "replacement-host" };+ await nextTick();+ release();+ await nextTick();++ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(mocks.compileFinished).not.toHaveBeenCalled();+ });++ it("does not send a confirmed batch after the selected schema changes", async () => {+ let release!: () => void;+ mocks.guardGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ const schemaState = ref("APP");+ await mountDialog(ref(connection), ref("ORCL"), true, schemaState);+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ schemaState.value = "OTHER_SCHEMA";+ await nextTick();+ release();+ await nextTick();++ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(mocks.compileFinished).not.toHaveBeenCalled();+ });++ it("drains a submitted batch on its original session and reports completion only for its frozen scope", async () => {+ let release!: () => void;+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 1);+ const databaseState = ref("ORCL");+ await mountDialog(ref(connection), databaseState);+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ const ddlCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).startsWith("ALTER "));+ const sessionId = (ddlCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(sessionId).toBeTruthy();++ databaseState.value = "ORCL2";+ await nextTick();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ release();+ await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(connection.id, "ORCL", sessionId));+ expect(mocks.compileFinished).toHaveBeenCalledWith({ connectionId: connection.id, database: "ORCL", schema: "APP" });+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).every((call) => call[1] === "ORCL")).toBe(true);+ });++ it("removes confirmed VALID rows but preserves unresolved rows and diagnostics when remaining refresh fails", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ mocks.failRemainingAfterWrite = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("remaining list denied"));+ expect(listRow("P_OK")).toBeNull();+ expect(listRow("P_BAD")).not.toBeNull();+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.still-invalid");+ expect(root?.textContent).toContain("batchRemainingUnknown");+ await openDetails("P_BAD");+ expect(root?.textContent).toContain("invalid identifier");+ });++ it("stops after an unknown write outcome and leaves later items unsubmitted", async () => {+ mocks.unknownBatchCompileName = "P_OK";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ await openDetails("P_OK");+ expect(root?.textContent).toContain("connection lost during DDL");+ });++ it("stops after an unknown execution_error result object", async () => {+ mocks.unknownBatchCompileResultName = "P_OK";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await waitForBatch();+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unknown");+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ await openDetails("P_OK");+ expect(root?.textContent).toContain("result unavailable");+ });++ it("allows a later object when an earlier DDL is explicitly rejected before start", async () => {+ mocks.failBatchCompileName = "P_OK";+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(2);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.failed");+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.still-invalid");+ await openDetails("P_OK");+ expect(root?.textContent).toContain("ORA-01031: insufficient privileges");+ });++ it.each(["result", "throw"] as const)("continues the batch after a structured not_started rejection (%s)", async (mode) => {+ mocks.definiteBatchFailureName = "P_OK";+ mocks.definiteBatchFailureMode = mode;+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(2);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.failed");+ expect(statusLabels()).not.toContain("processList.oracleInvalidObjects.batchStatus.not-run");+ });++ it("skips an already-valid object and blocks an object whose identity changed", async () => {+ await mountDialog();+ mocks.batchStatuses.P_OK = "VALID";+ mocks.batchTimes.P_OK = "2026-10-20 09:01:00";+ mocks.batchObjectIds.P_BAD = "999";+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ const ddlNames = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER ")).map((call) => String(call[2]));+ expect(ddlNames).not.toContainEqual(expect.stringContaining('"P_OK"'));+ expect(ddlNames).not.toContainEqual(expect.stringContaining('"P_BAD"'));+ expect(listRow("P_OK")).toBeNull();+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.target-changed");+ });++ it("classifies missing and unexpected preflight states without submitting DDL", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(0, 2);+ await mountDialog();+ mocks.missingBatchStatusName = "P_OK";+ mocks.batchStatuses.P_BAD = "UNKNOWN_STATUS";+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.deleted");+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unknown");+ });++ it("blocks an object whose DDL time changed after the plan was read", async () => {+ mocks.batchObjects = mocks.batchObjects.slice(1, 2);+ await mountDialog();+ mocks.batchTimes.P_BAD = "2026-10-20 09:01:00";+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("batchSummary"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.target-changed");+ });++ it("browses the first middle and last of 5001 objects with a real bounded virtual pool", async () => {+ mocks.batchObjects = Array.from({ length: 5001 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ await mountDialog();+ expect(listRow("P_0")).not.toBeNull();+ expect(listRow("P_5000")).toBeNull();+ await scrollToRow(2500, "P_2500");+ await scrollToRow(5000, "P_5000");+ expect(root?.querySelectorAll("[data-row-key]").length).toBeLessThan(100);+ expect(root?.textContent).toContain("listCount:5001");+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll:5001"))?.disabled).toBe(false);+ });++ it("disables compile all when the engine has no supported compile type", async () => {+ mocks.batchObjects = [["APP", "V_ONLY", "VIEW", "201", "time"]];+ await mountDialog(ref({ ...connection, db_type: "oceanbase-oracle" }));+ const compileAll = dialogButtons().find((button) => button.textContent?.includes("batchCompileAll"));+ expect(compileAll?.disabled).toBe(true);+ expect(statusLabels()).toContain("processList.oracleInvalidObjects.batchStatus.unsupported");+ await openDetails("V_ONLY", "VIEW");+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.unsupportedOnEngine");+ expect(mocks.guard).not.toHaveBeenCalled();+ });++ it("loads diagnostics and compiles a single object with one guarded click", async () => {+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileValid"));+ expect(root?.textContent).not.toContain("singleConfirmTitle");+ expect(root?.querySelector("details")?.open).toBe(false);+ expect(root?.querySelector("details pre")?.textContent).toContain('ALTER PROCEDURE "APP"."P_BAD" COMPILE REUSE SETTINGS');+ expect(mocks.guard).toHaveBeenCalledOnce();+ expect(compiled).toBe(true);+ expect(mocks.compileFinished).toHaveBeenCalledWith({ connectionId: connection.id, database: "ORCL", schema: "APP" });+ expect(mocks.guard).toHaveBeenCalledWith(expect.objectContaining({ database: "APP", sql: 'ALTER PROCEDURE "APP"."P_BAD" COMPILE REUSE SETTINGS' }));+ const compileCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("ALTER PROCEDURE"));+ const clientSessionId = (compileCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(clientSessionId).toBeTruthy();+ expect(mocks.executeQuery.mock.calls.every((call) => (call[5] as { clientSessionId?: string } | undefined)?.clientSessionId === clientSessionId)).toBe(true);+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(true);+ });++ it("keeps compile unexecuted when production confirmation is declined", async () => {+ mocks.executeAllowed = false;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.guard).toHaveBeenCalled());+ expect(compiled).toBe(false);+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("ALTER PROCEDURE"))).toBe(false);+ });++ it("keeps the object selected and reloads diagnostics when compilation changes LAST_DDL_TIME but remains invalid", async () => {+ compileStatus = "INVALID";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();++ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileStillInvalid"));+ expect(root?.textContent).toContain("still invalid after compile");+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.targetChanged");+ expect(errorsReloadedAfterCompile).toBe(true);+ });++ it("keeps a confirmed INVALID status separate from a diagnostic read failure", async () => {+ compileStatus = "INVALID";+ await mountDialog();+ await openDetails("P_BAD");+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ const original = mocks.executeQuery.getMockImplementation()!;+ mocks.executeQuery.mockImplementation(async (...args) => {+ if (compiled && String(args[2]).includes("FROM ALL_ERRORS")) throw new Error("diagnostics denied");+ return original(...args);+ });+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("compileStillInvalid"));+ expect(root?.textContent).toContain("diagnostics denied");+ expect(root?.textContent).not.toContain("compileUnknown");+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCurrentList"))+ ?.click();+ await nextTick();+ expect(listRow("P_BAD")?.querySelector('[role="img"]')?.getAttribute("aria-label")).toContain("still-invalid");+ await openDetails("P_BAD");+ expect(root?.textContent).toContain("diagnostics denied");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(1);+ });++ it("does not report a replacement object as the compiled target", async () => {+ objectIdAfterCompile = "10";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();++ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.targetChanged"));+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileValid");+ });++ it("refreshes when the user clicks the refresh control", async () => {+ await mountDialog();+ const count = () => mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length;+ const before = count();+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(count()).toBeGreaterThan(before));+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ });++ it("replaces an in-flight background page on refresh and publishes only the fresh complete list", async () => {+ let release!: () => void;+ mocks.batchPageGate = () => new Promise<void>((resolve) => (release = resolve));+ await mountDialog(ref(connection), ref("ORCL"), true, ref("APP"), false);+ const listCount = () => mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length;+ const before = listCount();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(listCount()).toBeGreaterThan(before));+ release();+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ expect(root?.textContent).not.toContain("batchReading");+ expect(root?.textContent).not.toContain("batchConfirmTitle");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).startsWith("ALTER "))).toHaveLength(0);+ });++ it("manual refresh clears selection and rereads the full list without compiling", async () => {+ await mountDialog();+ const checkbox = root?.querySelector<HTMLInputElement>('input[type="checkbox"][aria-label="P_OK PROCEDURE"]');+ expect(checkbox).toBeTruthy();+ checkbox?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:1");+ const beforeRefresh = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length;+ root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.click();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length).toBeGreaterThan(beforeRefresh));+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ expect(root?.textContent).toContain("batchSelectedCount:0");+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER "))).toBe(false);+ });++ it("keeps actions scoped to the entire collection without pagination controls", async () => {+ mocks.batchObjects = Array.from({ length: 101 }, (_, index) => ["APP", `P_${index}`, "PROCEDURE", String(index + 1), "time"]);+ await mountDialog();+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.title · Oracle · APP");+ expect(dialogButtons().find((button) => button.textContent?.includes("batchCompileAll:101"))?.disabled).toBe(false);+ expect(dialogButtons().some((button) => /batchPreviousPage|batchNextPage/.test(button.textContent ?? ""))).toBe(false);+ root?.querySelector<HTMLInputElement>('label input[type="checkbox"]')?.click();+ await nextTick();+ expect(root?.textContent).toContain("batchSelectedCount:101");+ expect(listRow("P_0")).not.toBeNull();+ });++ it("shows the diagnostics truncation warning alongside the fetched error rows", async () => {+ mocks.truncatedErrors = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.errorsTruncated"));+ expect(root?.querySelectorAll("tbody tr").length).toBe(1000);+ });++ it("reports a removed object separately after compile", async () => {+ mocks.statusMissingAfterCompile = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileGone"));+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileGone");+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(true);+ });++ it("preserves status readback diagnostics when compile outcome is unknown", async () => {+ mocks.failStatusReadback = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: insufficient privileges while reading status"));+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileUnknown");+ });++ it.each(["throw", "result"] as const)("keeps submitted single compile unknown when status readback is denied (%s)", async (mode) => {+ mocks.failStatusReadback = true;+ mocks.statusReadbackErrorMode = mode;+ compileStatus = "INVALID";+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileUnknown"));+ expect(root?.textContent).toContain("ORA-01031: insufficient privileges");+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("ALTER PROCEDURE"))).toHaveLength(1);+ expect(mocks.compileFinished).toHaveBeenCalledWith({ connectionId: connection.id, database: "ORCL", schema: "APP" });+ expect(root?.querySelector("button")?.textContent).not.toContain("confirmCompile");+ });++ it("keeps single compile status unknown when the readback is truncated", async () => {+ mocks.truncateSingleStatusAfter = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileUnknown"));+ expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("ALTER PROCEDURE"))).toHaveLength(1);+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileValid");+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.batchIdentityUnknown");+ });++ it("preserves a definite compile permission denial", async () => {+ mocks.failCompile = true;+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("ORA-01031: insufficient privileges"));+ expect(root?.textContent).toContain("processList.oracleInvalidObjects.compileFailed");+ });++ it("rechecks identity after production confirmation", async () => {+ let release!: () => void;+ mocks.guardGate = () =>+ new Promise<void>((resolve) => {+ release = resolve;+ });+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.guard).toHaveBeenCalled());+ mocks.identityChangedAfterGuard = true;+ release();+ await vi.waitFor(() => expect(root?.textContent).toContain("processList.oracleInvalidObjects.targetChanged"));+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("ALTER PROCEDURE"))).toBe(false);+ });++ it("does not submit compile after the connection configuration changes behind the confirmation", async () => {+ let release!: () => void;+ mocks.guardGate = () => new Promise<void>((resolve) => (release = resolve));+ const connectionState = ref(connection);+ await mountDialog(connectionState);+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.guard).toHaveBeenCalled());++ connectionState.value = { ...connection, host: "replacement-host" };+ await nextTick();+ release();+ await nextTick();+ expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).startsWith("ALTER PROCEDURE"))).toBe(false);+ });++ it("uses a fresh session after close while a submitted compile drains, without leaving the reopened dialog stuck", async () => {+ let release!: () => void;+ mocks.compileGate = () =>+ new Promise<void>((resolve) => {+ release = resolve;+ });+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.some((call) => String(call[2]).includes("ALTER PROCEDURE"))).toBe(true));+ const compileCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).includes("ALTER PROCEDURE"));+ const compileSessionId = (compileCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ dialogButtons()+ .find((button) => button.hasAttribute("data-test-close"))+ ?.click();+ await nextTick();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ dialogButtons()+ .find((button) => button.hasAttribute("data-test-open"))+ ?.click();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length).toBeGreaterThan(1));+ const reopenedListCall = mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).at(-1);+ const reopenedSessionId = (reopenedListCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(reopenedSessionId).not.toBe(compileSessionId);+ release();+ await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(connection.id, "ORCL", compileSessionId));+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ // The old physical DDL can make P_BAD VALID. Check the unaffected current target.+ dialogButtons()+ .find((button) => button.textContent?.includes("P_OK"))+ ?.click();+ await vi.waitFor(() => expect(root?.querySelector<HTMLButtonElement>('button[title="common.refresh"]')?.disabled).toBe(false));+ expect(dialogButtons().find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")?.disabled).toBe(false);+ });++ it("does not write a late compile outcome into the reopened dialog after readback refresh", async () => {+ let release!: () => void;+ mocks.postCompileListGate = () => new Promise<void>((resolve) => (release = resolve));+ const { open } = await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("P_BAD"))+ ?.click();+ await vi.waitFor(() => expect(root?.textContent).toContain("invalid identifier"));+ dialogButtons()+ .find((button) => button.textContent?.trim() === "processList.oracleInvalidObjects.compile")+ ?.click();+ await nextTick();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length).toBeGreaterThan(1));+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));++ open.value = false;+ await nextTick();+ open.value = true;+ await nextTick();+ await vi.waitFor(() => expect(mocks.executeQuery.mock.calls.filter((call) => String(call[2]).includes("FROM (SELECT OWNER")).length).toBeGreaterThan(2));+ release();+ await nextTick();+ await vi.waitFor(() => expect(root?.textContent).toContain("P_OK"));+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileValid");+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileGone");+ expect(root?.textContent).not.toContain("processList.oracleInvalidObjects.compileUnknown");+ });++ it("drains a submitted batch session after the dialog unmounts", async () => {+ let release!: () => void;+ mocks.compileGate = () => new Promise<void>((resolve) => (release = resolve));+ mocks.batchObjects = mocks.batchObjects.slice(0, 1);+ await mountDialog();+ dialogButtons()+ .find((button) => button.textContent?.includes("batchCompileAll"))+ ?.click();+ await vi.waitFor(() => expect(release).toBeTypeOf("function"));+ const ddlCall = mocks.executeQuery.mock.calls.find((call) => String(call[2]).startsWith("ALTER "));+ const sessionId = (ddlCall?.[5] as { clientSessionId?: string } | undefined)?.clientSessionId;+ expect(sessionId).toBeTruthy();++ app?.unmount();+ app = null;+ release();+ await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith(connection.id, "ORCL", sessionId));+ expect(mocks.closeClientConnectionSession).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/i18n/__tests__/oracleInvalidObjectsMessages.spec.ts b/apps/desktop/src/i18n/__tests__/oracleInvalidObjectsMessages.spec.tsnew file mode 100644index 0000000000..73bec329b3--- /dev/null+++ b/apps/desktop/src/i18n/__tests__/oracleInvalidObjectsMessages.spec.ts@@ -0,0 +1,62 @@+import { readFileSync } from "node:fs";+import { createI18n } from "vue-i18n";+import { describe, expect, it } from "vitest";+import en from "../locales/en";+import es from "../locales/es";+import itLocale from "../locales/it";+import ja from "../locales/ja";+import ko from "../locales/ko";+import ptBR from "../locales/pt-BR";+import ru from "../locales/ru";+import th from "../locales/th";+import zhCN from "../locales/zh-CN";+import zhTW from "../locales/zh-TW";++const locales = [+ ["en", en, "Compile all"],+ ["es", es, "Compilar todos"],+ ["it", itLocale, "Compila tutto"],+ ["ja", ja, "すべてコンパイル"],+ ["ko", ko, "모두 컴파일"],+ ["pt-BR", ptBR, "Compilar tudo"],+ ["ru", ru, "Компилировать все"],+ ["th", th, "คอมไพล์ทั้งหมด"],+ ["zh-CN", zhCN, "编译全部"],+ ["zh-TW", zhTW, "全部編譯"],+] as const;++const componentSource = readFileSync(new URL("../../components/objects/OracleInvalidObjectsDialog.vue", import.meta.url), "utf8");+const literalKeys = [...componentSource.matchAll(/t\(["'](processList\.oracleInvalidObjects\.[A-Za-z]+)["']/g)].map((match) => match[1]!);+const batchStatuses = ["pending", "running", "unsupported", "valid", "still-invalid", "already-valid", "target-changed", "deleted", "failed", "unknown", "not-run"];++describe("invalid object dialog locale messages", () => {+ it.each(locales)("resolves all dialog messages in %s", (locale, messages, expectedCompileAll) => {+ const i18n = createI18n({ legacy: false, locale, fallbackLocale: false, messages: { [locale]: messages } });+ const rawMessages = messages as { processList: { oracleInvalidObjects: Record<string, string> } };++ for (const key of literalKeys) {+ expect(i18n.global.t(key), `${locale}: ${key}`).not.toBe(key);+ }+ for (const status of batchStatuses) {+ const key = `processList.oracleInvalidObjects.batchStatus.${status}`;+ expect(i18n.global.t(key), `${locale}: ${key}`).not.toBe(key);+ }+ expect(i18n.global.t("processList.oracleInvalidObjects.compileAll")).toBe(expectedCompileAll);+ const message = (key: string, values?: Record<string, number>) => i18n.global.t(`processList.oracleInvalidObjects.${key}`, values);+ const expectedPlaceholders: Record<string, string[]> = {+ selectedTypeCount: ["{count}"],+ filterCount: ["{matched}", "{total}"],+ batchCompileFiltered: ["{count}"],+ };+ for (const key of ["nameFilterLabel", "filterName", "filterTypes", "allTypes", "selectedTypeCount", "clearFilters", "filterCount", "currentlyLoaded", "batchSelectFiltered", "batchCompileFiltered", "compileFiltered", "noFilterMatches"]) {+ expect(message(key), `${locale}: ${key}`).not.toBe(`processList.oracleInvalidObjects.${key}`);+ const actualPlaceholders = [...rawMessages.processList.oracleInvalidObjects[key]!.matchAll(/\{[^{}]+\}/g)].map(([placeholder]) => placeholder).sort();+ expect(actualPlaceholders, `${locale}: ${key} placeholders`).toEqual((expectedPlaceholders[key] ?? []).sort());+ }+ expect(message("filterCount", { matched: 3, total: 5 })).toContain("3");+ expect(message("filterCount", { matched: 3, total: 5 })).toContain("5");+ expect(message("selectedTypeCount", { count: 2 })).toContain("2");+ expect(message("batchCompileFiltered", { count: 2 })).toContain("2");+ expect(message("noFilterMatches")).not.toBe("");+ });+});diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 1137e90fde..e0245f64a2 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -5112,6 +5112,100 @@ export default {noInstalled: "No extensions installed.",},processList: {+ oracleSerial: "Serial number",+ oracleAuditSession: "Audit session ID",+ oracleLogonTime: "Logon time",+ oracleInstance: "Instance",+ oracleContainer: "Container ID",+ oracleProgram: "Program",+ oracleSqlId: "SQL ID",+ oracleBlocker: "Blocking session",+ oracleTenant: "Tenant",+ oracleNode: "Node",+ oracleProxySession: "Proxy session ID",+ oracleProxyUnsupported: "Proxy sessions cannot be terminated here.",+ oracleIdentityUnavailable: "Session identity is incomplete or changed; termination is disabled. Refresh the list.",+ oracleVersionUnknown: "The Oracle major version could not be verified; using the session query scoped by CON_ID.",+ oracleConnectionChanged: "The connection configuration changed; this operation was not sent to the new connection.",+ oracleTerminateUnknown: "The termination result is unknown. Refresh the session list before deciding what to do next; do not resubmit yet.",+ oracleTerminatePending: "The termination request was accepted; the session may still be rolling back or disconnecting. Refresh to check its state.",+ oracleLockDetails: "Lock details",+ oracleLockDetailsTruncated: "Lock rows were truncated; the displayed details may be incomplete.",+ oracleLockTarget: "Target session: {user} · {identity}",+ oracleLockDetailsEmpty: "No visible lock rows for this session.",+ oracleInvalidObjects: {+ title: "Invalid objects",+ listLabel: "Invalid object list",+ listCount: "{count} objects",+ nameFilterLabel: "Name",+ filterName: "Filter object names",+ filterTypes: "Type",+ allTypes: "All",+ selectedTypeCount: "{count} types",+ clearFilters: "Clear filters",+ filterCount: "Matching {matched} / List {total}",+ currentlyLoaded: "Currently loaded",+ batchSelectFiltered: "Select filtered results",+ batchCompileFiltered: "Compile filtered results ({count})",+ compileFiltered: "Compile filtered results",+ noFilterMatches: "No matching objects",+ batchSelectedCount: "{count} selected",+ batchCompileSelected: "Compile selected ({count})",+ batchCompileAll: "Compile all ({count})",+ batchCurrentList: "Current list",+ empty: "No visible invalid objects in this schema.",+ truncated: "The list is truncated. Narrow the scope or check your privileges.",+ objectId: "Object ID {id}",+ openSource: "Open source",+ errorsTitle: "Compile diagnostics",+ errorsTruncated: "The error list is truncated; the displayed diagnostics may be incomplete.",+ noErrors: "No visible compile errors.",+ line: "Line",+ position: "Position",+ message: "Error",+ unsupportedOnEngine: "This object type cannot be compiled automatically on this OceanBase version. Open its source in a query tab to repair it.",+ unsupportedType: "This object type cannot be compiled automatically. You can still inspect and repair it in a query tab.",+ ddlWarning: "Compilation is DDL. It may invalidate dependent objects and cannot be undone with ROLLBACK.",+ targetChanged: "The object changed or was replaced. The list was refreshed; select it again and confirm compilation again.",+ compileValid: "Read-back status after compilation: VALID.",+ compileStillInvalid: "The object is still INVALID. Review its diagnostics or repair the source before retrying.",+ compileUnknown: "Compilation may have been submitted, but its result could not be confirmed. The list was refreshed; check the object state before proceeding.",+ compileGone: "The object no longer exists. The list was refreshed.",+ compileFailed: "Compilation did not complete: {message}",+ compile: "Compile",+ compileAll: "Compile all",+ batchSqlDetails: "View execution SQL",+ batchReadProgress: "Read {count} objects",+ batchReadFailed: "Could not read the complete object list",+ batchRunning: "Compiling objects in sequence…",+ batchProgress: "Handled {handled}/{total} · Current object: {current}",+ batchStopping: "Waiting for the current object to finish; later objects will not be submitted.",+ batchSummary: "Valid {valid} · Still invalid {stillInvalid} · Failed/unknown {failed} · Skipped {skipped}",+ batchRemaining: "{count} invalid objects remain after refresh",+ batchRemainingUnknown: "Could not confirm the remaining list: {message}",+ batchStop: "Stop before the next compile",+ batchRetryRead: "Read the list again",+ batchDeleted: "The object no longer exists; no compilation was submitted.",+ batchIdentityUnknown: "Could not confirm the object's identity or status; no compilation was submitted.",+ batchTargetChanged: "The object's identity or modification time changed; no compilation was submitted.",+ batchAlreadyValid: "The object is already VALID; compilation was skipped.",+ batchGuardDeclined: "The write was not confirmed; no objects were compiled.",+ batchStatus: {+ running: "Running",+ pending: "Pending",+ unsupported: "Unsupported",+ valid: "Valid",+ "still-invalid": "Still invalid",+ "already-valid": "Already valid; skipped",+ "target-changed": "Target changed",+ deleted: "Deleted",+ failed: "Failed",+ unknown: "Outcome unknown",+ "not-run": "Not run",+ },+ sourceUnavailable: "The database did not return editable source for this object.",+ sourceLoadFailed: "Could not load object source: {message}",+ },transactionTitle: "Active Transactions",transactionScope: "SYSDBA only. Reads active transactions from SYSTEM; idle sessions are not listed.",transactionRequiresSysdba: "Xugu transaction management requires a SYSDBA connection to query SYSTEM. A business-database DBA grant is not equivalent to SYSDBA.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 7e0550580e..ae2e6273f7 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -11184,6 +11184,100 @@ export default withEnglishFallback({sourceDataEditor: "Editor de datos",},processList: {+ oracleSerial: "Número de serie",+ oracleAuditSession: "ID de sesión de auditoría",+ oracleLogonTime: "Hora de inicio de sesión",+ oracleInstance: "Instancia",+ oracleContainer: "ID del contenedor",+ oracleProgram: "Programa",+ oracleSqlId: "ID de SQL",+ oracleBlocker: "Sesión bloqueadora",+ oracleTenant: "Inquilino",+ oracleNode: "Nodo",+ oracleProxySession: "ID de sesión proxy",+ oracleProxyUnsupported: "No se pueden terminar sesiones proxy aquí.",+ oracleIdentityUnavailable: "La identidad de la sesión está incompleta o cambió; se deshabilitó la terminación. Actualice la lista.",+ oracleVersionUnknown: "No se pudo verificar la versión principal de Oracle; se usará la consulta de sesiones limitada por CON_ID.",+ oracleConnectionChanged: "Cambió la configuración de conexión; esta operación no se envió a la nueva conexión.",+ oracleTerminateUnknown: "Se desconoce el resultado de la terminación. Actualice la lista antes de decidir el siguiente paso; no vuelva a enviarla todavía.",+ oracleTerminatePending: "Se aceptó la solicitud de terminación; la sesión aún podría estar revirtiendo o desconectándose. Actualice para comprobarlo.",+ oracleLockDetails: "Detalles de bloqueos",+ oracleLockDetailsTruncated: "Se truncaron filas de bloqueo; los detalles mostrados pueden estar incompletos.",+ oracleLockTarget: "Sesión objetivo: {user} · {identity}",+ oracleLockDetailsEmpty: "No hay filas de bloqueo visibles para esta sesión.",+ oracleInvalidObjects: {+ title: "Objetos no válidos",+ listLabel: "Lista de objetos no válidos",+ listCount: "{count} objetos",+ nameFilterLabel: "Nombre",+ filterName: "Filtrar nombres de objetos",+ filterTypes: "Tipo",+ allTypes: "Todos",+ selectedTypeCount: "{count} tipos",+ clearFilters: "Borrar filtros",+ filterCount: "Coincidencias {matched} / Lista {total}",+ currentlyLoaded: "Cargados actualmente",+ batchSelectFiltered: "Seleccionar resultados filtrados",+ batchCompileFiltered: "Compilar resultados filtrados ({count})",+ compileFiltered: "Compilar resultados filtrados",+ noFilterMatches: "No hay objetos que coincidan",+ batchSelectedCount: "{count} seleccionados",+ batchCompileSelected: "Compilar seleccionados ({count})",+ batchCompileAll: "Compilar todos ({count})",+ batchCurrentList: "Lista actual",+ empty: "No hay objetos no válidos visibles en este esquema.",+ truncated: "La lista está truncada. Reduzca el alcance o compruebe sus permisos.",+ objectId: "ID del objeto {id}",+ openSource: "Abrir código fuente",+ errorsTitle: "Diagnóstico de compilación",+ errorsTruncated: "La lista de errores está truncada; los diagnósticos mostrados pueden estar incompletos.",+ noErrors: "No hay errores de compilación visibles.",+ line: "Línea",+ position: "Posición",+ message: "Error",+ unsupportedOnEngine: "Esta versión de OceanBase no permite compilar automáticamente este tipo de objeto. Abra el código fuente en una pestaña de consultas para corregirlo.",+ unsupportedType: "Este tipo de objeto no permite la compilación automática. Puede inspeccionarlo y corregirlo en una pestaña de consultas.",+ ddlWarning: "La compilación es DDL. Puede invalidar objetos dependientes y no se puede deshacer con ROLLBACK.",+ targetChanged: "El objeto cambió o fue reemplazado. Se actualizó la lista; selecciónelo de nuevo y confirme la compilación otra vez.",+ compileValid: "Estado leído después de compilar: VALID.",+ compileStillInvalid: "El objeto sigue INVALID. Revise el diagnóstico o corrija el código fuente antes de volver a intentarlo.",+ compileUnknown: "Es posible que se enviara la compilación, pero no se pudo confirmar el resultado. Se actualizó la lista; compruebe el estado antes de continuar.",+ compileGone: "El objeto ya no existe. Se actualizó la lista.",+ compileFailed: "No se completó la compilación: {message}",+ compile: "Compilar",+ compileAll: "Compilar todos",+ sourceUnavailable: "La base de datos no devolvió código fuente editable para este objeto.",+ sourceLoadFailed: "No se pudo cargar el código fuente del objeto: {message}",+ batchSqlDetails: "Ver SQL de ejecución",+ batchReadProgress: "Leídos {count} objetos",+ batchReadFailed: "No se pudo leer la lista completa de objetos",+ batchRunning: "Compilando objetos en orden…",+ batchProgress: "Procesados {handled}/{total} · Objeto actual: {current}",+ batchStopping: "Esperando a que termine el objeto actual; no se enviarán los siguientes.",+ batchSummary: "Válidos {valid} · Siguen no válidos {stillInvalid} · Error/desconocido {failed} · Omitidos {skipped}",+ batchRemaining: "Quedan {count} objetos no válidos tras actualizar",+ batchRemainingUnknown: "No se pudo confirmar la lista restante: {message}",+ batchStop: "Detener antes de la siguiente compilación",+ batchRetryRead: "Volver a leer la lista",+ batchDeleted: "El objeto ya no existe; no se envió la compilación.",+ batchIdentityUnknown: "No se pudo confirmar la identidad o el estado; no se envió la compilación.",+ batchTargetChanged: "Cambió la identidad o la fecha de modificación; no se envió la compilación.",+ batchAlreadyValid: "El objeto ya es VALID; se omitió la compilación.",+ batchGuardDeclined: "No se confirmó la escritura; no se compiló ningún objeto.",+ batchStatus: {+ running: "En ejecución",+ pending: "Pendiente",+ unsupported: "No compatible",+ valid: "Válido",+ "still-invalid": "Sigue no válido",+ "already-valid": "Ya válido; omitido",+ "target-changed": "Objetivo cambiado",+ deleted: "Eliminado",+ failed: "Error",+ unknown: "Resultado desconocido",+ "not-run": "No ejecutado",+ },+ },transactionTitle: "Transacciones activas",transactionScope: "Solo SYSDBA. Lee las transacciones activas de SYSTEM; las sesiones inactivas no se listan.",transactionRequiresSysdba: "La gestión de transacciones de Xugu requiere una conexión SYSDBA para consultar SYSTEM. Un permiso DBA en una base de datos de negocio no equivale a SYSDBA.",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 7c1a2af660..430056df20 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -10928,6 +10928,100 @@ export default withEnglishFallback({sourceDataEditor: "Editor dati",},processList: {+ oracleSerial: "Numero di serie",+ oracleAuditSession: "ID sessione di audit",+ oracleLogonTime: "Ora di accesso",+ oracleInstance: "Istanza",+ oracleContainer: "ID contenitore",+ oracleProgram: "Programma",+ oracleSqlId: "ID SQL",+ oracleBlocker: "Sessione bloccante",+ oracleTenant: "Tenant",+ oracleNode: "Nodo",+ oracleProxySession: "ID sessione proxy",+ oracleProxyUnsupported: "Le sessioni proxy non possono essere terminate qui.",+ oracleIdentityUnavailable: "L'identità della sessione è incompleta o cambiata; terminazione disabilitata. Aggiornare l'elenco.",+ oracleVersionUnknown: "Impossibile verificare la versione principale di Oracle; verrà usata la query di sessione limitata da CON_ID.",+ oracleConnectionChanged: "La configurazione della connessione è cambiata; l'operazione non è stata inviata alla nuova connessione.",+ oracleTerminateUnknown: "Esito della terminazione sconosciuto. Aggiornare l'elenco prima di decidere il passaggio successivo; non inviare di nuovo l'operazione.",+ oracleTerminatePending: "Richiesta di terminazione accettata; la sessione potrebbe essere ancora in rollback o in disconnessione. Aggiornare per verificarne lo stato.",+ oracleLockDetails: "Dettagli blocchi",+ oracleLockDetailsTruncated: "Le righe dei blocchi sono state troncate; i dettagli visualizzati potrebbero essere incompleti.",+ oracleLockTarget: "Sessione obiettivo: {user} · {identity}",+ oracleLockDetailsEmpty: "Nessuna riga di blocco visibile per questa sessione.",+ oracleInvalidObjects: {+ title: "Oggetti non validi",+ listLabel: "Elenco oggetti non validi",+ listCount: "{count} oggetti",+ nameFilterLabel: "Nome",+ filterName: "Filtra i nomi degli oggetti",+ filterTypes: "Tipo",+ allTypes: "Tutti",+ selectedTypeCount: "{count} tipi",+ clearFilters: "Cancella filtri",+ filterCount: "Corrispondenze {matched} / Elenco {total}",+ currentlyLoaded: "Caricati attualmente",+ batchSelectFiltered: "Seleziona i risultati filtrati",+ batchCompileFiltered: "Compila i risultati filtrati ({count})",+ compileFiltered: "Compila i risultati filtrati",+ noFilterMatches: "Nessun oggetto corrispondente",+ batchSelectedCount: "{count} selezionati",+ batchCompileSelected: "Compila selezionati ({count})",+ batchCompileAll: "Compila tutto ({count})",+ batchCurrentList: "Elenco corrente",+ empty: "Nessun oggetto non valido visibile in questo schema.",+ truncated: "L'elenco è troncato. Restringere l'ambito o verificare i privilegi.",+ objectId: "ID oggetto {id}",+ openSource: "Apri sorgente",+ errorsTitle: "Diagnostica compilazione",+ errorsTruncated: "L'elenco degli errori è troncato; la diagnostica visualizzata potrebbe essere incompleta.",+ noErrors: "Nessun errore di compilazione visibile.",+ line: "Riga",+ position: "Posizione",+ message: "Errore",+ unsupportedOnEngine: "Questa versione di OceanBase non supporta la compilazione automatica di questo tipo di oggetto. Aprire la sorgente in una scheda di query per correggerla.",+ unsupportedType: "Questo tipo di oggetto non supporta la compilazione automatica. È comunque possibile esaminarlo e correggerlo in una scheda di query.",+ ddlWarning: "La compilazione è DDL: può invalidare oggetti dipendenti e non può essere annullata con ROLLBACK.",+ targetChanged: "L'oggetto è cambiato o è stato sostituito. Elenco aggiornato; selezionarlo di nuovo e confermare nuovamente la compilazione.",+ compileValid: "Stato letto dopo la compilazione: VALID.",+ compileStillInvalid: "L'oggetto è ancora INVALID. Esaminare la diagnostica o correggere la sorgente prima di riprovare.",+ compileUnknown: "La compilazione potrebbe essere stata inviata, ma non è stato possibile verificarne l'esito. Elenco aggiornato; controllare lo stato prima di procedere.",+ compileGone: "L'oggetto non esiste più. Elenco aggiornato.",+ compileFailed: "Compilazione non completata: {message}",+ compile: "Compila",+ compileAll: "Compila tutto",+ sourceUnavailable: "Il database non ha restituito una sorgente modificabile per questo oggetto.",+ sourceLoadFailed: "Impossibile caricare la sorgente dell'oggetto: {message}",+ batchSqlDetails: "Visualizza SQL di esecuzione",+ batchReadProgress: "Letti {count} oggetti",+ batchReadFailed: "Impossibile leggere l'elenco completo degli oggetti",+ batchRunning: "Compilazione degli oggetti in sequenza…",+ batchProgress: "Gestiti {handled}/{total} · Oggetto corrente: {current}",+ batchStopping: "In attesa del completamento dell'oggetto corrente; gli oggetti successivi non verranno inviati.",+ batchSummary: "Validi {valid} · Ancora non validi {stillInvalid} · Falliti/sconosciuti {failed} · Ignorati {skipped}",+ batchRemaining: "Dopo l'aggiornamento restano {count} oggetti non validi",+ batchRemainingUnknown: "Impossibile confermare l'elenco restante: {message}",+ batchStop: "Interrompi prima della prossima compilazione",+ batchRetryRead: "Rileggi l'elenco",+ batchDeleted: "L'oggetto non esiste più; compilazione non inviata.",+ batchIdentityUnknown: "Impossibile confermare identità o stato; compilazione non inviata.",+ batchTargetChanged: "L'identità o la data di modifica è cambiata; compilazione non inviata.",+ batchAlreadyValid: "L'oggetto è già VALID; compilazione ignorata.",+ batchGuardDeclined: "Scrittura non confermata; nessun oggetto compilato.",+ batchStatus: {+ running: "In esecuzione",+ pending: "In attesa",+ unsupported: "Non supportato",+ valid: "Valido",+ "still-invalid": "Ancora non valido",+ "already-valid": "Già valido; ignorato",+ "target-changed": "Obiettivo cambiato",+ deleted: "Eliminato",+ failed: "Non riuscito",+ unknown: "Esito sconosciuto",+ "not-run": "Non eseguito",+ },+ },batchCancel: "Annulla query selezionate ({count})",batchNeedsSession: "Sessione corrente sconosciuta. Aggiorna e riprova.",selectAll: "Seleziona le sessioni disponibili caricate nel filtro corrente",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 771438509d..06cfd2b443 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -10964,6 +10964,88 @@ export default withEnglishFallback({sourceDataEditor: "データエディター",},processList: {+ oracleSerial: "シリアル番号",+ oracleAuditSession: "監査セッション ID",+ oracleLogonTime: "ログイン時刻",+ oracleInstance: "インスタンス",+ oracleContainer: "コンテナ ID",+ oracleProgram: "プログラム",+ oracleSqlId: "SQL ID",+ oracleBlocker: "ブロック元セッション",+ oracleTenant: "テナント",+ oracleNode: "ノード",+ oracleProxySession: "プロキシセッション ID",+ oracleProxyUnsupported: "プロキシセッションはここから終了できません。",+ oracleIdentityUnavailable: "セッション識別情報が不完全または変更されたため、終了は無効です。一覧を更新してください。",+ oracleVersionUnknown: "Oracle のメジャーバージョンを確認できません。CON_ID で範囲を限定したセッション検索を使用します。",+ oracleConnectionChanged: "接続設定が変更されたため、この操作は新しい接続には送信されませんでした。",+ oracleTerminateUnknown: "終了結果を確認できません。次の操作を決める前に一覧を更新してください。まだ再送信しないでください。",+ oracleTerminatePending: "終了要求は受理されました。セッションはロールバック中または切断処理中の可能性があります。更新して状態を確認してください。",+ oracleLockDetails: "ロック詳細",+ oracleLockDetailsTruncated: "ロック行は切り詰められています。表示内容は不完全な可能性があります。",+ oracleLockTarget: "対象セッション: {user} · {identity}",+ oracleLockDetailsEmpty: "このセッションの表示可能なロック行はありません。",+ oracleInvalidObjects: {+ title: "無効なオブジェクト",+ listLabel: "無効なオブジェクト一覧",+ listCount: "{count} 件のオブジェクト",+ nameFilterLabel: "名前",+ filterName: "オブジェクト名を絞り込む",+ filterTypes: "種別",+ allTypes: "すべて",+ selectedTypeCount: "{count} 種別",+ clearFilters: "フィルターをクリア",+ filterCount: "一致 {matched} / 一覧 {total}",+ currentlyLoaded: "現在読み込み済み",+ batchSelectFiltered: "絞り込み結果をすべて選択",+ batchCompileFiltered: "絞り込み結果をコンパイル ({count})",+ compileFiltered: "絞り込み結果をコンパイル",+ noFilterMatches: "一致するオブジェクトはありません",+ batchSelectedCount: "{count} 件選択中",+ batchCompileSelected: "選択した項目をコンパイル ({count})",+ batchCompileAll: "すべてコンパイル ({count})",+ batchCurrentList: "現在の一覧",+ empty: "このスキーマに表示可能な無効オブジェクトはありません。",+ truncated: "一覧は切り詰められています。範囲を絞るか、権限を確認してください。",+ objectId: "オブジェクト ID {id}",+ openSource: "ソースを開く",+ errorsTitle: "コンパイル診断",+ errorsTruncated: "エラー一覧は切り詰められているため、表示内容は不完全な可能性があります。",+ noErrors: "表示可能なコンパイルエラーはありません。",+ line: "行",+ position: "位置",+ message: "エラー",+ unsupportedOnEngine: "この OceanBase バージョンでは、このオブジェクト種別を自動コンパイルできません。クエリタブでソースを開いて修正してください。",+ unsupportedType: "このオブジェクト種別は自動コンパイルできません。クエリタブで内容を確認して手動修正できます。",+ ddlWarning: "コンパイルは DDL です。依存オブジェクトが無効化される場合があり、ROLLBACK では取り消せません。",+ targetChanged: "オブジェクトが変更または置換されました。一覧を更新しました。再選択してコンパイルを再確認してください。",+ compileValid: "コンパイル後に読み取った状態: VALID。",+ compileStillInvalid: "オブジェクトはまだ INVALID です。診断を確認するか、ソースを修正してから再試行してください。",+ compileUnknown: "コンパイルが送信された可能性がありますが、結果を確認できませんでした。一覧を更新しました。状態を確認してから次へ進んでください。",+ compileGone: "オブジェクトは存在しなくなりました。一覧を更新しました。",+ compileFailed: "コンパイルを完了できませんでした: {message}",+ compile: "コンパイル",+ compileAll: "すべてコンパイル",+ sourceUnavailable: "データベースから編集可能なオブジェクトソースが返されませんでした。",+ sourceLoadFailed: "オブジェクトソースを読み込めませんでした: {message}",+ batchSqlDetails: "実行 SQL を表示",+ batchReadProgress: "{count} 件のオブジェクトを読み込み済み",+ batchReadFailed: "オブジェクト一覧を完全に読み込めませんでした",+ batchRunning: "オブジェクトを順番にコンパイル中…",+ batchProgress: "処理済み {handled}/{total} · 現在のオブジェクト: {current}",+ batchStopping: "現在のオブジェクトの完了を待機中です。以降のオブジェクトは送信しません。",+ batchSummary: "有効 {valid} · 無効のまま {stillInvalid} · 失敗/不明 {failed} · スキップ {skipped}",+ batchRemaining: "更新後も無効なオブジェクトが {count} 件あります",+ batchRemainingUnknown: "残りの一覧を確認できませんでした: {message}",+ batchStop: "次のコンパイル前に停止",+ batchRetryRead: "一覧を再読み込み",+ batchDeleted: "オブジェクトが存在しません。コンパイルは送信されませんでした。",+ batchIdentityUnknown: "オブジェクトの識別情報または状態を確認できないため、コンパイルは送信されませんでした。",+ batchTargetChanged: "識別情報または更新時刻が変わったため、コンパイルは送信されませんでした。",+ batchAlreadyValid: "オブジェクトはすでに VALID のため、コンパイルをスキップしました。",+ batchGuardDeclined: "書き込みが確認されなかったため、オブジェクトはコンパイルされていません。",+ batchStatus: { running: "実行中", pending: "保留中", unsupported: "未対応", valid: "有効", "still-invalid": "無効のまま", "already-valid": "有効のためスキップ", "target-changed": "対象が変更", deleted: "削除済み", failed: "失敗", unknown: "結果不明", "not-run": "未実行" },+ },batchCancel: "選択したクエリをキャンセル({count})",batchNeedsSession: "現在のセッションを識別できません。更新して再試行してください。",selectAll: "現在の絞り込み結果で読み込み済みの選択可能なセッションをすべて選択",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 4b940a0828..ac01c579fb 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -4627,6 +4627,100 @@ export default withEnglishFallback({actionSuccess: '"{name}"에 대한 {action}이(가) 완료되었습니다.',},processList: {+ oracleSerial: "일련번호",+ oracleAuditSession: "감사 세션 ID",+ oracleLogonTime: "로그인 시간",+ oracleInstance: "인스턴스",+ oracleContainer: "컨테이너 ID",+ oracleProgram: "프로그램",+ oracleSqlId: "SQL ID",+ oracleBlocker: "차단 세션",+ oracleTenant: "테넌트",+ oracleNode: "노드",+ oracleProxySession: "프록시 세션 ID",+ oracleProxyUnsupported: "프록시 세션은 여기서 종료할 수 없습니다.",+ oracleIdentityUnavailable: "세션 식별 정보가 불완전하거나 변경되어 종료할 수 없습니다. 목록을 새로 고치세요.",+ oracleVersionUnknown: "Oracle 주 버전을 확인할 수 없습니다. CON_ID로 범위를 제한한 세션 조회를 사용합니다.",+ oracleConnectionChanged: "연결 구성이 변경되어 이 작업을 새 연결로 보내지 않았습니다.",+ oracleTerminateUnknown: "종료 결과를 확인할 수 없습니다. 다음 작업을 결정하기 전에 목록을 새로 고치세요. 아직 다시 보내지 마세요.",+ oracleTerminatePending: "종료 요청이 수락되었습니다. 세션이 롤백 중이거나 연결을 끊는 중일 수 있습니다. 새로 고쳐 상태를 확인하세요.",+ oracleLockDetails: "잠금 세부 정보",+ oracleLockDetailsTruncated: "잠금 행이 잘려 표시된 정보가 불완전할 수 있습니다.",+ oracleLockTarget: "대상 세션: {user} · {identity}",+ oracleLockDetailsEmpty: "이 세션에 표시할 수 있는 잠금 행이 없습니다.",+ oracleInvalidObjects: {+ title: "잘못된 객체",+ listLabel: "잘못된 객체 목록",+ listCount: "객체 {count}개",+ nameFilterLabel: "이름",+ filterName: "객체 이름 필터",+ filterTypes: "유형",+ allTypes: "전체",+ selectedTypeCount: "{count}개 유형",+ clearFilters: "필터 지우기",+ filterCount: "일치 {matched} / 목록 {total}",+ currentlyLoaded: "현재 로드됨",+ batchSelectFiltered: "필터 결과 모두 선택",+ batchCompileFiltered: "필터 결과 컴파일 ({count})",+ compileFiltered: "필터 결과 컴파일",+ noFilterMatches: "일치하는 객체가 없습니다",+ batchSelectedCount: "{count}개 선택",+ batchCompileSelected: "선택 항목 컴파일 ({count})",+ batchCompileAll: "모두 컴파일 ({count})",+ batchCurrentList: "현재 목록",+ empty: "이 스키마에 표시할 수 있는 잘못된 객체가 없습니다.",+ truncated: "목록이 잘렸습니다. 범위를 좁히거나 권한을 확인하세요.",+ objectId: "객체 ID {id}",+ openSource: "소스 열기",+ errorsTitle: "컴파일 진단",+ errorsTruncated: "오류 목록이 잘려 표시된 진단이 불완전할 수 있습니다.",+ noErrors: "표시할 수 있는 컴파일 오류가 없습니다.",+ line: "줄",+ position: "위치",+ message: "오류",+ unsupportedOnEngine: "현재 OceanBase 버전에서는 이 객체 유형을 자동으로 컴파일할 수 없습니다. 쿼리 탭에서 소스를 열어 수정하세요.",+ unsupportedType: "이 객체 유형은 자동 컴파일을 지원하지 않습니다. 쿼리 탭에서 확인하고 수동으로 수정할 수 있습니다.",+ ddlWarning: "컴파일은 DDL입니다. 종속 객체가 무효화될 수 있으며 ROLLBACK으로 되돌릴 수 없습니다.",+ targetChanged: "객체가 변경되거나 교체되었습니다. 목록을 새로 고쳤습니다. 다시 선택하고 컴파일을 확인하세요.",+ compileValid: "컴파일 후 읽은 상태: VALID.",+ compileStillInvalid: "객체가 여전히 INVALID입니다. 진단을 확인하거나 소스를 수정한 뒤 다시 시도하세요.",+ compileUnknown: "컴파일이 제출되었을 수 있지만 결과를 확인할 수 없습니다. 목록을 새로 고쳤습니다. 계속하기 전에 객체 상태를 확인하세요.",+ compileGone: "객체가 더 이상 존재하지 않습니다. 목록을 새로 고쳤습니다.",+ compileFailed: "컴파일을 완료하지 못했습니다: {message}",+ compile: "컴파일",+ compileAll: "모두 컴파일",+ sourceUnavailable: "데이터베이스가 편집 가능한 객체 소스를 반환하지 않았습니다.",+ sourceLoadFailed: "객체 소스를 불러오지 못했습니다: {message}",+ batchSqlDetails: "실행 SQL 보기",+ batchReadProgress: "객체 {count}개 읽음",+ batchReadFailed: "전체 객체 목록을 읽지 못했습니다",+ batchRunning: "객체를 순서대로 컴파일하는 중…",+ batchProgress: "처리 {handled}/{total} · 현재 객체: {current}",+ batchStopping: "현재 객체가 완료될 때까지 기다립니다. 이후 객체는 제출하지 않습니다.",+ batchSummary: "유효 {valid} · 여전히 잘못됨 {stillInvalid} · 실패/알 수 없음 {failed} · 건너뜀 {skipped}",+ batchRemaining: "새로 고친 후 잘못된 객체 {count}개가 남아 있습니다",+ batchRemainingUnknown: "남은 목록을 확인하지 못했습니다: {message}",+ batchStop: "다음 컴파일 전에 중지",+ batchRetryRead: "목록 다시 읽기",+ batchDeleted: "객체가 더 이상 없습니다. 컴파일을 제출하지 않았습니다.",+ batchIdentityUnknown: "객체 ID 또는 상태를 확인할 수 없어 컴파일을 제출하지 않았습니다.",+ batchTargetChanged: "객체 ID 또는 수정 시간이 변경되어 컴파일을 제출하지 않았습니다.",+ batchAlreadyValid: "객체가 이미 VALID이므로 컴파일을 건너뛰었습니다.",+ batchGuardDeclined: "쓰기 확인이 취소되어 객체를 컴파일하지 않았습니다.",+ batchStatus: {+ running: "실행 중",+ pending: "대기 중",+ unsupported: "지원되지 않음",+ valid: "유효",+ "still-invalid": "여전히 잘못됨",+ "already-valid": "이미 유효함; 건너뜀",+ "target-changed": "대상 변경됨",+ deleted: "삭제됨",+ failed: "실패",+ unknown: "결과 알 수 없음",+ "not-run": "실행 안 됨",+ },+ },batchCancel: "선택한 쿼리 취소 ({count})",batchNeedsSession: "현재 세션을 확인할 수 없습니다. 새로 고침 후 다시 시도하세요.",selectAll: "현재 필터에서 로드된 선택 가능한 세션 모두 선택",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 66614f5c64..47228b672a 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -10924,6 +10924,100 @@ export default withEnglishFallback({sourceDataEditor: "Editor de dados",},processList: {+ oracleSerial: "Número de série",+ oracleAuditSession: "ID da sessão de auditoria",+ oracleLogonTime: "Horário de login",+ oracleInstance: "Instância",+ oracleContainer: "ID do contêiner",+ oracleProgram: "Programa",+ oracleSqlId: "ID SQL",+ oracleBlocker: "Sessão bloqueadora",+ oracleTenant: "Tenant",+ oracleNode: "Nó",+ oracleProxySession: "ID da sessão proxy",+ oracleProxyUnsupported: "Sessões proxy não podem ser encerradas aqui.",+ oracleIdentityUnavailable: "A identidade da sessão está incompleta ou mudou; o encerramento foi desativado. Atualize a lista.",+ oracleVersionUnknown: "Não foi possível verificar a versão principal do Oracle; será usada a consulta de sessões limitada por CON_ID.",+ oracleConnectionChanged: "A configuração da conexão mudou; esta operação não foi enviada à nova conexão.",+ oracleTerminateUnknown: "O resultado do encerramento é desconhecido. Atualize a lista antes de decidir o próximo passo; não reenvie ainda.",+ oracleTerminatePending: "A solicitação de encerramento foi aceita; a sessão ainda pode estar revertendo ou desconectando. Atualize para verificar o estado.",+ oracleLockDetails: "Detalhes de bloqueio",+ oracleLockDetailsTruncated: "As linhas de bloqueio foram truncadas; os detalhes exibidos podem estar incompletos.",+ oracleLockTarget: "Sessão de destino: {user} · {identity}",+ oracleLockDetailsEmpty: "Não há linhas de bloqueio visíveis para esta sessão.",+ oracleInvalidObjects: {+ title: "Objetos inválidos",+ listLabel: "Lista de objetos inválidos",+ listCount: "{count} objetos",+ nameFilterLabel: "Nome",+ filterName: "Filtrar nomes de objetos",+ filterTypes: "Tipo",+ allTypes: "Todos",+ selectedTypeCount: "{count} tipos",+ clearFilters: "Limpar filtros",+ filterCount: "Correspondentes {matched} / Lista {total}",+ currentlyLoaded: "Carregados no momento",+ batchSelectFiltered: "Selecionar resultados filtrados",+ batchCompileFiltered: "Compilar resultados filtrados ({count})",+ compileFiltered: "Compilar resultados filtrados",+ noFilterMatches: "Nenhum objeto correspondente",+ batchSelectedCount: "{count} selecionados",+ batchCompileSelected: "Compilar selecionados ({count})",+ batchCompileAll: "Compilar tudo ({count})",+ batchCurrentList: "Lista atual",+ empty: "Não há objetos inválidos visíveis neste esquema.",+ truncated: "A lista foi truncada. Restrinja o escopo ou verifique suas permissões.",+ objectId: "ID do objeto {id}",+ openSource: "Abrir código-fonte",+ errorsTitle: "Diagnóstico de compilação",+ errorsTruncated: "A lista de erros foi truncada; os diagnósticos exibidos podem estar incompletos.",+ noErrors: "Não há erros de compilação visíveis.",+ line: "Linha",+ position: "Posição",+ message: "Erro",+ unsupportedOnEngine: "Esta versão do OceanBase não compila automaticamente este tipo de objeto. Abra o código-fonte em uma aba de consulta para corrigi-lo.",+ unsupportedType: "Este tipo de objeto não pode ser compilado automaticamente. Ainda é possível inspecioná-lo e corrigi-lo em uma aba de consulta.",+ ddlWarning: "A compilação é DDL. Ela pode invalidar objetos dependentes e não pode ser desfeita com ROLLBACK.",+ targetChanged: "O objeto mudou ou foi substituído. A lista foi atualizada; selecione-o novamente e confirme a compilação.",+ compileValid: "Status lido após a compilação: VALID.",+ compileStillInvalid: "O objeto continua INVALID. Revise o diagnóstico ou corrija o código-fonte antes de tentar novamente.",+ compileUnknown: "A compilação pode ter sido enviada, mas não foi possível confirmar o resultado. A lista foi atualizada; verifique o estado antes de prosseguir.",+ compileGone: "O objeto não existe mais. A lista foi atualizada.",+ compileFailed: "A compilação não foi concluída: {message}",+ compile: "Compilar",+ compileAll: "Compilar tudo",+ sourceUnavailable: "O banco de dados não retornou código-fonte editável para este objeto.",+ sourceLoadFailed: "Não foi possível carregar o código-fonte do objeto: {message}",+ batchSqlDetails: "Ver SQL de execução",+ batchReadProgress: "{count} objetos lidos",+ batchReadFailed: "Não foi possível ler a lista completa de objetos",+ batchRunning: "Compilando objetos em sequência…",+ batchProgress: "Processados {handled}/{total} · Objeto atual: {current}",+ batchStopping: "Aguardando a conclusão do objeto atual; os próximos não serão enviados.",+ batchSummary: "Válidos {valid} · Ainda inválidos {stillInvalid} · Falhos/desconhecidos {failed} · Ignorados {skipped}",+ batchRemaining: "Restam {count} objetos inválidos após atualizar",+ batchRemainingUnknown: "Não foi possível confirmar a lista restante: {message}",+ batchStop: "Parar antes da próxima compilação",+ batchRetryRead: "Ler a lista novamente",+ batchDeleted: "O objeto não existe mais; a compilação não foi enviada.",+ batchIdentityUnknown: "Não foi possível confirmar a identidade ou o status; a compilação não foi enviada.",+ batchTargetChanged: "A identidade ou a data de alteração mudou; a compilação não foi enviada.",+ batchAlreadyValid: "O objeto já está VALID; a compilação foi ignorada.",+ batchGuardDeclined: "A gravação não foi confirmada; nenhum objeto foi compilado.",+ batchStatus: {+ running: "Em execução",+ pending: "Pendente",+ unsupported: "Não compatível",+ valid: "Válido",+ "still-invalid": "Ainda inválido",+ "already-valid": "Já válido; ignorado",+ "target-changed": "Alvo alterado",+ deleted: "Excluído",+ failed: "Falhou",+ unknown: "Resultado desconhecido",+ "not-run": "Não executado",+ },+ },batchCancel: "Cancelar consultas selecionadas ({count})",batchNeedsSession: "Sessão atual desconhecida. Atualize e tente novamente.",selectAll: "Selecionar sessões disponíveis carregadas no filtro atual",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex d43bff9249..f2d3236821 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -4810,6 +4810,100 @@ export default withEnglishFallback({noInstalled: "Расширения не установлены.",},processList: {+ oracleSerial: "Серийный номер",+ oracleAuditSession: "ID сеанса аудита",+ oracleLogonTime: "Время входа",+ oracleInstance: "Экземпляр",+ oracleContainer: "ID контейнера",+ oracleProgram: "Программа",+ oracleSqlId: "ID SQL",+ oracleBlocker: "Блокирующий сеанс",+ oracleTenant: "Тенант",+ oracleNode: "Узел",+ oracleProxySession: "ID прокси-сеанса",+ oracleProxyUnsupported: "Прокси-сеанс нельзя завершить здесь.",+ oracleIdentityUnavailable: "Идентификатор сеанса неполон или изменился; завершение отключено. Обновите список.",+ oracleVersionUnknown: "Не удалось определить основную версию Oracle; используется запрос сеансов с ограничением по CON_ID.",+ oracleConnectionChanged: "Параметры подключения изменились; операция не отправлена в новое подключение.",+ oracleTerminateUnknown: "Результат завершения неизвестен. Обновите список перед следующим действием; пока не отправляйте запрос повторно.",+ oracleTerminatePending: "Запрос на завершение принят; сеанс может ещё выполнять откат или отключаться. Обновите список, чтобы проверить состояние.",+ oracleLockDetails: "Сведения о блокировках",+ oracleLockDetailsTruncated: "Строки блокировок обрезаны; сведения могут быть неполными.",+ oracleLockTarget: "Целевой сеанс: {user} · {identity}",+ oracleLockDetailsEmpty: "Видимые строки блокировок для этого сеанса отсутствуют.",+ oracleInvalidObjects: {+ title: "Недействительные объекты",+ listLabel: "Список недействительных объектов",+ listCount: "Объектов: {count}",+ nameFilterLabel: "Имя",+ filterName: "Фильтр по имени объекта",+ filterTypes: "Тип",+ allTypes: "Все",+ selectedTypeCount: "Типов: {count}",+ clearFilters: "Сбросить фильтры",+ filterCount: "Совпадений: {matched} / Список: {total}",+ currentlyLoaded: "Загружено сейчас",+ batchSelectFiltered: "Выбрать отфильтрованные результаты",+ batchCompileFiltered: "Компилировать отфильтрованные результаты ({count})",+ compileFiltered: "Компилировать отфильтрованные результаты",+ noFilterMatches: "Подходящих объектов нет",+ batchSelectedCount: "Выбрано: {count}",+ batchCompileSelected: "Компилировать выбранные ({count})",+ batchCompileAll: "Компилировать все ({count})",+ batchCurrentList: "Текущий список",+ empty: "В этой схеме нет видимых недействительных объектов.",+ truncated: "Список обрезан. Сузьте область или проверьте права доступа.",+ objectId: "ID объекта {id}",+ openSource: "Открыть исходный код",+ errorsTitle: "Диагностика компиляции",+ errorsTruncated: "Список ошибок обрезан; отображаемая диагностика может быть неполной.",+ noErrors: "Видимых ошибок компиляции нет.",+ line: "Строка",+ position: "Позиция",+ message: "Ошибка",+ unsupportedOnEngine: "Эта версия OceanBase не поддерживает автоматическую компиляцию данного типа. Откройте исходный код во вкладке запроса для исправления.",+ unsupportedType: "Автоматическая компиляция этого типа не поддерживается. Объект можно просмотреть и исправить во вкладке запроса.",+ ddlWarning: "Компиляция — это DDL. Она может сделать зависимые объекты недействительными и не отменяется командой ROLLBACK.",+ targetChanged: "Объект изменён или заменён. Список обновлён; выберите его снова и подтвердите компиляцию.",+ compileValid: "Состояние после компиляции: VALID.",+ compileStillInvalid: "Объект по-прежнему INVALID. Проверьте диагностику или исправьте исходный код перед повторной попыткой.",+ compileUnknown: "Команда компиляции могла быть отправлена, но результат подтвердить не удалось. Список обновлён; проверьте состояние перед продолжением.",+ compileGone: "Объект больше не существует. Список обновлён.",+ compileFailed: "Не удалось завершить компиляцию: {message}",+ compile: "Компилировать",+ compileAll: "Компилировать все",+ sourceUnavailable: "База данных не вернула редактируемый исходный код этого объекта.",+ sourceLoadFailed: "Не удалось загрузить исходный код объекта: {message}",+ batchSqlDetails: "Показать SQL выполнения",+ batchReadProgress: "Прочитано объектов: {count}",+ batchReadFailed: "Не удалось прочитать полный список объектов",+ batchRunning: "Последовательная компиляция объектов…",+ batchProgress: "Обработано {handled}/{total} · Текущий объект: {current}",+ batchStopping: "Ожидание завершения текущего объекта; последующие объекты отправлены не будут.",+ batchSummary: "Действительны {valid} · Всё ещё недействительны {stillInvalid} · Ошибки/неизвестно {failed} · Пропущено {skipped}",+ batchRemaining: "После обновления осталось недействительных объектов: {count}",+ batchRemainingUnknown: "Не удалось подтвердить оставшийся список: {message}",+ batchStop: "Остановить перед следующей компиляцией",+ batchRetryRead: "Прочитать список снова",+ batchDeleted: "Объект больше не существует; команда компиляции не отправлялась.",+ batchIdentityUnknown: "Не удалось подтвердить идентификатор или состояние; команда не отправлялась.",+ batchTargetChanged: "Идентификатор или время изменения объекта поменялись; команда не отправлялась.",+ batchAlreadyValid: "Объект уже VALID; компиляция пропущена.",+ batchGuardDeclined: "Запись не подтверждена; объекты не компилировались.",+ batchStatus: {+ running: "Выполняется",+ pending: "Ожидает",+ unsupported: "Не поддерживается",+ valid: "Действителен",+ "still-invalid": "Всё ещё недействителен",+ "already-valid": "Уже действителен; пропущен",+ "target-changed": "Цель изменилась",+ deleted: "Удалён",+ failed: "Ошибка",+ unknown: "Результат неизвестен",+ "not-run": "Не выполнен",+ },+ },batchCancel: "Отменить выбранные запросы ({count})",batchNeedsSession: "Текущая сессия неизвестна. Обновите и повторите попытку.",selectAll: "Выбрать подходящие загруженные сессии в текущем фильтре",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex c5e9f34fcc..fc36b65afe 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -5032,6 +5032,89 @@ export default withEnglishFallback({noInstalled: "ยังไม่มี Extension ติดตั้ง",},processList: {+ oracleSerial: "หมายเลขซีเรียล",+ oracleAuditSession: "ID เซสชันตรวจสอบ",+ oracleLogonTime: "เวลาเข้าสู่ระบบ",+ oracleInstance: "อินสแตนซ์",+ oracleContainer: "ID คอนเทนเนอร์",+ oracleProgram: "โปรแกรม",+ oracleSqlId: "SQL ID",+ oracleBlocker: "เซสชันที่บล็อก",+ oracleTenant: "Tenant",+ oracleNode: "โหนด",+ oracleProxySession: "ID เซสชันพร็อกซี",+ oracleProxyUnsupported: "ไม่สามารถยุติเซสชันพร็อกซีจากที่นี่ได้",+ oracleIdentityUnavailable: "ข้อมูลระบุตัวเซสชันไม่ครบถ้วนหรือเปลี่ยนไป จึงปิดใช้การยุติ โปรดรีเฟรชรายการ",++ oracleVersionUnknown: "ยืนยัน Oracle major version ไม่ได้ โดยยังใช้คำสั่งรายการเซสชันที่จำกัดด้วย CON_ID",+ oracleConnectionChanged: "การตั้งค่าการเชื่อมต่อเปลี่ยนไป จึงไม่ได้ส่งการดำเนินการนี้ไปยังการเชื่อมต่อใหม่",+ oracleTerminateUnknown: "ไม่ทราบผลการยุติเซสชัน โปรดรีเฟรชรายการก่อนตัดสินใจขั้นต่อไป และอย่าส่งคำขอซ้ำในตอนนี้",+ oracleTerminatePending: "ยอมรับคำขอยุติแล้ว เซสชันอาจกำลัง rollback หรือกำลังตัดการเชื่อมต่อ รีเฟรชเพื่อตรวจสอบสถานะ",+ oracleLockDetails: "รายละเอียดล็อก",+ oracleLockDetailsTruncated: "แถวล็อกถูกตัดทอน รายละเอียดที่แสดงอาจไม่ครบถ้วน",+ oracleLockTarget: "เซสชันเป้าหมาย: {user} · {identity}",+ oracleLockDetailsEmpty: "ไม่มีแถวล็อกที่มองเห็นได้สำหรับเซสชันนี้",+ oracleInvalidObjects: {+ title: "ออบเจ็กต์ไม่ถูกต้อง",+ listLabel: "รายการออบเจ็กต์ไม่ถูกต้อง",+ listCount: "{count} ออบเจ็กต์",+ nameFilterLabel: "ชื่อ",+ filterName: "กรองชื่อออบเจ็กต์",+ filterTypes: "ประเภท",+ allTypes: "ทั้งหมด",+ selectedTypeCount: "{count} ประเภท",+ clearFilters: "ล้างตัวกรอง",+ filterCount: "ตรงกัน {matched} / รายการ {total}",+ currentlyLoaded: "โหลดแล้วในขณะนี้",+ batchSelectFiltered: "เลือกผลลัพธ์ที่กรองแล้วทั้งหมด",+ batchCompileFiltered: "คอมไพล์ผลลัพธ์ที่กรองแล้ว ({count})",+ compileFiltered: "คอมไพล์ผลลัพธ์ที่กรองแล้ว",+ noFilterMatches: "ไม่มีออบเจ็กต์ที่ตรงกัน",+ batchSelectedCount: "เลือกแล้ว {count} รายการ",+ batchCompileSelected: "คอมไพล์รายการที่เลือก ({count})",+ batchCompileAll: "คอมไพล์ทั้งหมด ({count})",+ batchCurrentList: "รายการปัจจุบัน",+ empty: "ไม่มีออบเจ็กต์ไม่ถูกต้องที่มองเห็นได้ใน schema นี้",+ truncated: "รายการถูกตัดทอน โปรดจำกัดขอบเขตหรือตรวจสอบสิทธิ์",+ objectId: "ออบเจ็กต์ ID {id}",+ openSource: "เปิดซอร์ส",+ errorsTitle: "การวินิจฉัยการคอมไพล์",+ errorsTruncated: "รายการข้อผิดพลาดถูกตัดทอน การวินิจฉัยที่แสดงอาจไม่ครบถ้วน",+ noErrors: "ไม่มีข้อผิดพลาดการคอมไพล์ที่มองเห็นได้",+ line: "บรรทัด",+ position: "ตำแหน่ง",+ message: "ข้อผิดพลาด",+ unsupportedOnEngine: "OceanBase เวอร์ชันนี้ไม่รองรับการคอมไพล์ออบเจ็กต์ชนิดนี้โดยอัตโนมัติ เปิดซอร์สในแท็บ Query เพื่อแก้ไข",+ unsupportedType: "ไม่รองรับการคอมไพล์ออบเจ็กต์ชนิดนี้โดยอัตโนมัติ แต่ยังตรวจสอบและแก้ไขในแท็บ Query ได้",+ ddlWarning: "การคอมไพล์เป็น DDL อาจทำให้ออบเจ็กต์ที่ขึ้นต่อกันไม่ถูกต้อง และย้อนกลับด้วย ROLLBACK ไม่ได้",+ targetChanged: "ออบเจ็กต์เปลี่ยนแปลงหรือถูกแทนที่แล้ว รีเฟรชรายการแล้ว โปรดเลือกและยืนยันการคอมไพล์อีกครั้ง",+ compileValid: "สถานะที่อ่านกลับหลังคอมไพล์: VALID",+ compileStillInvalid: "ออบเจ็กต์ยังเป็น INVALID ตรวจสอบการวินิจฉัยหรือแก้ซอร์สก่อนลองอีกครั้ง",+ compileUnknown: "อาจส่งคำสั่งคอมไพล์แล้ว แต่ยืนยันผลไม่ได้ รีเฟรชรายการแล้ว โปรดตรวจสอบสถานะก่อนดำเนินการต่อ",+ compileGone: "ออบเจ็กต์นี้ไม่มีอยู่แล้ว รีเฟรชรายการแล้ว",+ compileFailed: "คอมไพล์ไม่สำเร็จ: {message}",+ compile: "คอมไพล์",+ compileAll: "คอมไพล์ทั้งหมด",+ sourceUnavailable: "ฐานข้อมูลไม่ได้ส่งคืนซอร์สออบเจ็กต์ที่แก้ไขได้",+ sourceLoadFailed: "โหลดซอร์สออบเจ็กต์ไม่ได้: {message}",+ batchSqlDetails: "ดู SQL ที่จะดำเนินการ",+ batchReadProgress: "อ่านแล้ว {count} ออบเจ็กต์",+ batchReadFailed: "อ่านรายการออบเจ็กต์ทั้งหมดไม่ได้",+ batchRunning: "กำลังคอมไพล์ออบเจ็กต์ตามลำดับ…",+ batchProgress: "จัดการแล้ว {handled}/{total} · ออบเจ็กต์ปัจจุบัน: {current}",+ batchStopping: "กำลังรอให้ออบเจ็กต์ปัจจุบันเสร็จสิ้น โดยจะไม่ส่งออบเจ็กต์ถัดไป",+ batchSummary: "ถูกต้อง {valid} · ยังไม่ถูกต้อง {stillInvalid} · ล้มเหลว/ไม่ทราบผล {failed} · ข้าม {skipped}",+ batchRemaining: "หลังรีเฟรชยังมีออบเจ็กต์ไม่ถูกต้อง {count} รายการ",+ batchRemainingUnknown: "ยืนยันรายการที่เหลือไม่ได้: {message}",+ batchStop: "หยุดก่อนคอมไพล์รายการถัดไป",+ batchRetryRead: "อ่านรายการอีกครั้ง",+ batchDeleted: "ไม่มีออบเจ็กต์นี้แล้ว ไม่ได้ส่งคำสั่งคอมไพล์",+ batchIdentityUnknown: "ยืนยันตัวตนหรือสถานะออบเจ็กต์ไม่ได้ ไม่ได้ส่งคำสั่งคอมไพล์",+ batchTargetChanged: "ตัวตนหรือเวลาแก้ไขออบเจ็กต์เปลี่ยนไป ไม่ได้ส่งคำสั่งคอมไพล์",+ batchAlreadyValid: "ออบเจ็กต์เป็น VALID อยู่แล้ว จึงข้ามการคอมไพล์",+ batchGuardDeclined: "ไม่ได้ยืนยันการเขียน จึงไม่มีการคอมไพล์ออบเจ็กต์",+ batchStatus: { running: "กำลังดำเนินการ", pending: "รอดำเนินการ", unsupported: "ไม่รองรับ", valid: "ถูกต้อง", "still-invalid": "ยังไม่ถูกต้อง", "already-valid": "ถูกต้องแล้ว ข้ามแล้ว", "target-changed": "เป้าหมายเปลี่ยน", deleted: "ลบแล้ว", failed: "ล้มเหลว", unknown: "ไม่ทราบผล", "not-run": "ไม่ได้ดำเนินการ" },+ },transactionTitle: "Transaction ที่กำลังทำงาน",transactionScope: "เฉพาะ SYSDBA อ่าน Transaction ที่กำลังทำงานจาก SYSTEM ไม่แสดง Session ที่ Idle",transactionRequiresSysdba: "การจัดการ Transaction ของ Xugu ต้องใช้การเชื่อมต่อ SYSDBA เพื่อ Query SYSTEM การ Grant DBA ของฐานข้อมูลธุรกิจไม่เทียบเท่า SYSDBA",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex dd89785be5..d61c1f3ef3 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -5040,6 +5040,88 @@ export default withEnglishFallback({noInstalled: "暂无已安装的扩展。",},processList: {+ oracleSerial: "序列号",+ oracleAuditSession: "审计会话 ID",+ oracleLogonTime: "登录时间",+ oracleInstance: "实例",+ oracleContainer: "容器 ID",+ oracleProgram: "程序",+ oracleSqlId: "SQL ID",+ oracleBlocker: "阻塞会话",+ oracleTenant: "租户",+ oracleNode: "节点",+ oracleProxySession: "代理会话 ID",+ oracleProxyUnsupported: "代理会话暂不支持终止",+ oracleIdentityUnavailable: "会话身份信息不完整或已变化,已禁用终止;请刷新列表。",+ oracleVersionUnknown: "无法确认 Oracle 主版本;仍使用限定当前容器的会话查询。",+ oracleConnectionChanged: "连接配置已更改;未向新连接发送此操作。",+ oracleTerminateUnknown: "终止请求结果不明。请刷新会话列表确认状态,不要重复提交。",+ oracleTerminatePending: "终止请求已接受,会话仍在回滚或尚未退出。刷新以查看状态。",+ oracleLockDetails: "锁详情",+ oracleLockDetailsTruncated: "锁记录已截断;显示结果可能不完整。",+ oracleLockTarget: "目标会话:{user} · {identity}",+ oracleLockDetailsEmpty: "此会话没有可见的锁记录。",+ oracleInvalidObjects: {+ title: "无效对象",+ listLabel: "无效对象列表",+ listCount: "{count} 个对象",+ nameFilterLabel: "名称",+ filterName: "过滤对象名称",+ filterTypes: "类型",+ allTypes: "全部",+ selectedTypeCount: "{count} 类",+ clearFilters: "清空筛选",+ filterCount: "匹配 {matched} / 清单 {total}",+ currentlyLoaded: "当前已加载",+ batchSelectFiltered: "全选筛选结果",+ batchCompileFiltered: "编译筛选结果({count})",+ compileFiltered: "编译筛选结果",+ noFilterMatches: "没有匹配的对象",+ batchSelectedCount: "已选 {count} 个",+ batchCompileSelected: "编译所选({count})",+ batchCompileAll: "编译全部({count})",+ batchCurrentList: "当前清单",+ empty: "当前模式没有可见的无效对象。",+ truncated: "列表已截断;请缩小范围或确认权限。",+ objectId: "对象 ID {id}",+ openSource: "打开源码",+ errorsTitle: "编译诊断",+ errorsTruncated: "错误列表已截断;显示内容可能不完整。",+ noErrors: "没有可见的编译错误。",+ line: "行",+ position: "列",+ message: "错误",+ unsupportedOnEngine: "此对象类型在当前 OceanBase 版本不支持自动编译。可打开源码,在查询编辑器中修复。",+ unsupportedType: "此对象类型不支持自动编译。仍可查看并在查询编辑器中人工处理。",+ ddlWarning: "编译是数据库 DDL,可能使依赖对象失效,且不能通过回滚撤销。",+ targetChanged: "对象已更改或被替换。已刷新列表,请重新选择并重新确认编译。",+ compileValid: "编译后读回状态为 VALID。",+ compileStillInvalid: "对象仍为 INVALID;请检查诊断或修正源码后重试。",+ compileUnknown: "编译可能已提交,但无法确认结果。已刷新列表;请检查对象状态后再决定下一步。",+ compileGone: "对象已不存在。已刷新列表。",+ compileFailed: "编译未能完成:{message}",+ compile: "编译",+ compileAll: "编译全部",+ batchSqlDetails: "查看执行语句",+ batchReadProgress: "已读取 {count} 个对象",+ batchReadFailed: "无法读取完整对象清单",+ batchRunning: "正在串行编译…",+ batchProgress: "已处理 {handled}/{total};当前对象:{current}",+ batchStopping: "正在等待当前对象完成;后续对象将不会提交。",+ batchSummary: "有效 {valid} · 仍无效 {stillInvalid} · 失败/待确认 {failed} · 跳过 {skipped}",+ batchRemaining: "刷新后仍有 {count} 个无效对象",+ batchRemainingUnknown: "无法确认剩余清单:{message}",+ batchStop: "停止后续编译",+ batchRetryRead: "重新读取清单",+ batchDeleted: "执行前对象已不存在。",+ batchIdentityUnknown: "无法确认对象身份或状态,未提交编译。",+ batchTargetChanged: "对象身份或修改时间已变化,未提交编译。",+ batchAlreadyValid: "对象已是 VALID,未重复编译。",+ batchGuardDeclined: "未确认写入;没有对象被编译。",+ batchStatus: { running: "执行中", pending: "待处理", unsupported: "不支持", valid: "已有效", "still-invalid": "仍无效", "already-valid": "已有效,跳过", "target-changed": "目标已变化", deleted: "已删除", failed: "明确失败", unknown: "结果待确认", "not-run": "未执行" },+ sourceUnavailable: "数据库没有返回可编辑的对象源码。",+ sourceLoadFailed: "无法载入对象源码:{message}",+ },transactionTitle: "活跃事务",transactionScope: "仅 SYSDBA 可用;在 SYSTEM 库查询实例的活跃事务,不包含空闲会话。",transactionRequiresSysdba: "虚谷事务管理需要使用 SYSDBA 连接,并在 SYSTEM 库查询。业务库的 DBA 权限不等同于 SYSDBA。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 56cce15983..31f1c1f12d 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -10934,6 +10934,88 @@ export default withEnglishFallback({sourceDataEditor: "資料編輯器",},processList: {+ oracleSerial: "序號",+ oracleAuditSession: "稽核工作階段 ID",+ oracleLogonTime: "登入時間",+ oracleInstance: "執行個體",+ oracleContainer: "容器 ID",+ oracleProgram: "程式",+ oracleSqlId: "SQL ID",+ oracleBlocker: "阻塞工作階段",+ oracleTenant: "租戶",+ oracleNode: "節點",+ oracleProxySession: "代理工作階段 ID",+ oracleProxyUnsupported: "目前不支援終止代理工作階段。",+ oracleIdentityUnavailable: "工作階段識別資訊不完整或已變更,已停用終止操作。請重新整理清單。",+ oracleVersionUnknown: "無法確認 Oracle 主版本;仍使用限定目前容器的工作階段查詢。",+ oracleConnectionChanged: "連線設定已變更;此操作不會送往新連線。",+ oracleTerminateUnknown: "無法確認終止結果。請先重新整理工作階段清單,再決定下一步;請勿立即重送。",+ oracleTerminatePending: "已接受終止要求;工作階段可能仍在復原交易或中斷連線。請重新整理確認狀態。",+ oracleLockDetails: "鎖定詳細資料",+ oracleLockDetailsTruncated: "鎖定資料列已截斷,顯示內容可能不完整。",+ oracleLockTarget: "目標工作階段:{user} · {identity}",+ oracleLockDetailsEmpty: "此工作階段沒有可見的鎖定資料列。",+ oracleInvalidObjects: {+ title: "無效物件",+ listLabel: "無效物件清單",+ listCount: "{count} 個物件",+ nameFilterLabel: "名稱",+ filterName: "篩選物件名稱",+ filterTypes: "類型",+ allTypes: "全部",+ selectedTypeCount: "{count} 類",+ clearFilters: "清除篩選",+ filterCount: "符合 {matched} / 清單 {total}",+ currentlyLoaded: "目前已載入",+ batchSelectFiltered: "全選篩選結果",+ batchCompileFiltered: "編譯篩選結果({count})",+ compileFiltered: "編譯篩選結果",+ noFilterMatches: "沒有符合的物件",+ batchSelectedCount: "已選取 {count} 個",+ batchCompileSelected: "編譯所選({count})",+ batchCompileAll: "全部編譯({count})",+ batchCurrentList: "目前清單",+ empty: "此結構描述沒有可見的無效物件。",+ truncated: "清單已截斷。請縮小範圍或確認權限。",+ objectId: "物件 ID {id}",+ openSource: "開啟原始碼",+ errorsTitle: "編譯診斷",+ errorsTruncated: "錯誤清單已截斷,顯示的診斷可能不完整。",+ noErrors: "沒有可見的編譯錯誤。",+ line: "行",+ position: "位置",+ message: "錯誤",+ unsupportedOnEngine: "此 OceanBase 版本不支援自動編譯此物件類型。請在查詢分頁開啟原始碼並修正。",+ unsupportedType: "此物件類型不支援自動編譯。仍可在查詢分頁檢視並手動修正。",+ ddlWarning: "編譯屬於 DDL,可能使相依物件失效,且無法使用 ROLLBACK 還原。",+ targetChanged: "物件已變更或遭到取代。清單已重新整理;請重新選取並再次確認編譯。",+ compileValid: "編譯後讀取的狀態:VALID。",+ compileStillInvalid: "物件仍為 INVALID。請檢視診斷或修正原始碼後再試一次。",+ compileUnknown: "編譯可能已送出,但無法確認結果。清單已重新整理;請先確認物件狀態再繼續。",+ compileGone: "物件已不存在。清單已重新整理。",+ compileFailed: "編譯未完成:{message}",+ compile: "編譯",+ compileAll: "全部編譯",+ sourceUnavailable: "資料庫未傳回此物件的可編輯原始碼。",+ sourceLoadFailed: "無法載入物件原始碼:{message}",+ batchSqlDetails: "檢視執行 SQL",+ batchReadProgress: "已讀取 {count} 個物件",+ batchReadFailed: "無法讀取完整物件清單",+ batchRunning: "正在依序編譯物件…",+ batchProgress: "已處理 {handled}/{total} · 目前物件:{current}",+ batchStopping: "正在等待目前物件完成;後續物件將不會送出。",+ batchSummary: "有效 {valid} · 仍無效 {stillInvalid} · 失敗/未知 {failed} · 略過 {skipped}",+ batchRemaining: "重新整理後仍有 {count} 個無效物件",+ batchRemainingUnknown: "無法確認剩餘清單:{message}",+ batchStop: "停止後續編譯",+ batchRetryRead: "重新讀取清單",+ batchDeleted: "物件已不存在,未送出編譯。",+ batchIdentityUnknown: "無法確認物件識別或狀態,未送出編譯。",+ batchTargetChanged: "物件識別或修改時間已變更,未送出編譯。",+ batchAlreadyValid: "物件已是 VALID,略過編譯。",+ batchGuardDeclined: "未確認寫入,因此沒有編譯任何物件。",+ batchStatus: { running: "執行中", pending: "待處理", unsupported: "不支援", valid: "有效", "still-invalid": "仍無效", "already-valid": "已有效,略過", "target-changed": "目標已變更", deleted: "已刪除", failed: "失敗", unknown: "結果待確認", "not-run": "未執行" },+ },batchCancel: "批次取消查詢({count})",batchNeedsSession: "尚未識別目前工作階段,請重新整理後重試",selectAll: "選取目前篩選結果中已載入的可選工作階段",diff --git a/apps/desktop/src/lib/database/__tests__/oracleInvalidObjectCacheRefresh.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjectCacheRefresh.spec.tsnew file mode 100644index 0000000000..97dd7658df--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjectCacheRefresh.spec.ts@@ -0,0 +1,42 @@+import { describe, expect, it, vi } from "vitest";+import { completeOracleInvalidObjectCompile, type OracleInvalidObjectCompileScope } from "../oracleInvalidObjectCacheRefresh";++const scopeA: OracleInvalidObjectCompileScope = { connectionId: "conn-a", database: "ORCL", schema: "APP_A" };++describe("invalid-object compile cache refresh routing", () => {+ it.each([+ ["another schema in the same connection", { ...scopeA, schema: "APP_B" }],+ ["another connection", { connectionId: "conn-b", database: "ORCL", schema: "APP_A" }],+ ])("invalidates the completed scope but does not refresh %s", async (_label, current) => {+ const invalidate = vi.fn<(_: OracleInvalidObjectCompileScope) => Promise<void>>().mockResolvedValue(undefined);+ const refresh = vi.fn<(_: OracleInvalidObjectCompileScope) => Promise<void>>().mockResolvedValue(undefined);++ await completeOracleInvalidObjectCompile(scopeA, () => current, invalidate, refresh);++ expect(invalidate).toHaveBeenCalledWith(scopeA);+ expect(refresh).not.toHaveBeenCalled();+ });++ it("invalidates and refreshes the same completed scope", async () => {+ const invalidate = vi.fn<(_: OracleInvalidObjectCompileScope) => Promise<void>>().mockResolvedValue(undefined);+ const refresh = vi.fn<(_: OracleInvalidObjectCompileScope) => Promise<void>>().mockResolvedValue(undefined);++ await completeOracleInvalidObjectCompile(scopeA, () => scopeA, invalidate, refresh);++ expect(invalidate).toHaveBeenCalledWith(scopeA);+ expect(refresh).toHaveBeenCalledWith(scopeA);+ });++ it("checks current scope after invalidation completes", async () => {+ let current = scopeA;+ const invalidate = vi.fn(async () => {+ current = { ...scopeA, schema: "APP_B" };+ });+ const refresh = vi.fn<(_: OracleInvalidObjectCompileScope) => Promise<void>>().mockResolvedValue(undefined);++ await completeOracleInvalidObjectCompile(scopeA, () => current, invalidate, refresh);++ expect(invalidate).toHaveBeenCalledWith(scopeA);+ expect(refresh).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.tsnew file mode 100644index 0000000000..fa37d5dd8a--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/oracleInvalidObjects.spec.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from "vitest";+import {+ buildOracleCompileSql,+ buildOracleInvalidObjectsPageSql,+ buildOracleInvalidObjectsSql,+ buildOracleObjectErrorsSql,+ buildOracleObjectIdentitySql,+ mapOracleInvalidObjects,+ mapOracleObjectErrors,+ oracleCompileUnsupportedReason,+ oracleInvalidObjectSourceKind,+ readAllOracleInvalidObjects,+ ORACLE_INVALID_OBJECTS_PAGE_SIZE,+} from "../oracleInvalidObjects";++describe("Oracle invalid-object SQL and mapping", () => {+ const pageColumns = ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "LAST_DDL_TIME"];+ it.each(["VIEW", "MATERIALIZED VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "SYNONYM", "PACKAGE", "PACKAGE BODY", "TYPE", "TYPE BODY"])("maps source-readable %s to its API kind", (type) => {+ expect(oracleInvalidObjectSourceKind(type)).toBe(type.replaceAll(" ", "_"));+ });++ it.each(["INDEX", "JAVA CLASS", "JAVA SOURCE", "TABLE", "", "__proto__"])("rejects unsupported source kind %s", (type) => {+ expect(oracleInvalidObjectSourceKind(type)).toBeNull();+ });++ it("builds an owner-quoted numeric keyset page with a string cursor", () => {+ const sql = buildOracleInvalidObjectsPageSql("Owner'X", "90071992547409931234");+ expect(sql).toContain("OWNER = 'Owner''X'");+ expect(sql).toContain("OBJECT_ID > 90071992547409931234");+ expect(sql).toContain("TO_CHAR(OBJECT_ID) AS OBJECT_ID");+ expect(sql).toContain("ORDER BY OBJECT_ID");+ expect(sql).toContain(`ROWNUM <= ${ORACLE_INVALID_OBJECTS_PAGE_SIZE}`);+ expect(() => buildOracleInvalidObjectsPageSql("APP", "1 OR 1=1")).toThrow("Invalid Oracle object ID cursor");+ });++ it.each([0, 500, 501, 5001])("reads every visible invalid object across keyset pages (%i rows)", async (count) => {+ const queries: Array<[string, number]> = [];+ const objects = Array.from({ length: count }, (_, index) => {+ const objectId = index === 0 ? "90071992547409931234" : String(90071992547409931234n + BigInt(index));+ return ["APP", `P_${index}`, "PROCEDURE", objectId, "2026-10-20 09:00:00"];+ });+ const rowsByCursor = (sql: string) => {+ const cursor = BigInt(sql.match(/OBJECT_ID > (\d+)/)?.[1] ?? "0");+ return objects.filter((row) => BigInt(row[3] as string) > cursor).slice(0, ORACLE_INVALID_OBJECTS_PAGE_SIZE);+ };+ const result = await readAllOracleInvalidObjects(async (sql, maxRows) => {+ queries.push([sql, maxRows]);+ return { columns: pageColumns, rows: rowsByCursor(sql) };+ }, "APP");+ expect(result).toHaveLength(count);+ expect(new Set(result.map((object) => object.objectId)).size).toBe(count);+ expect(queries.every(([, maxRows]) => maxRows === 501)).toBe(true);+ expect(queries.length).toBe(count === 0 ? 1 : Math.floor(count / ORACLE_INVALID_OBJECTS_PAGE_SIZE) + 1);+ });++ it.each([+ [+ "duplicate/non-advancing IDs",+ [+ ["APP", "A", "PROCEDURE", "2", "time"],+ ["APP", "B", "PROCEDURE", "2", "time"],+ ],+ ],+ ["missing fields", [["APP", "A", "PROCEDURE", "2"]]],+ ["wrong owner", [["OTHER", "A", "PROCEDURE", "2", "time"]]],+ ["numeric object IDs", [["APP", "A", "PROCEDURE", 2, "time"]]],+ ])("rejects %s instead of producing a partial plan", async (_label, rows) => {+ await expect(readAllOracleInvalidObjects(async () => ({ columns: pageColumns, rows }), "APP")).rejects.toThrow();+ });++ it("rejects truncated, overfull, execution-error, and middle-page failures", async () => {+ await expect(readAllOracleInvalidObjects(async () => ({ columns: pageColumns, rows: [], truncated: true }), "APP")).rejects.toThrow("truncated");+ await expect(readAllOracleInvalidObjects(async () => ({ columns: pageColumns, rows: Array.from({ length: 501 }, (_, index) => ["APP", `P${index}`, "PROCEDURE", String(index + 1), "time"]) }), "APP")).rejects.toThrow("truncated");+ await expect(readAllOracleInvalidObjects(async () => ({ columns: pageColumns, rows: [["ORA-01031"]], execution_error: true, error: { detail: "ORA-01031: denied" } }), "APP")).rejects.toThrow("ORA-01031: denied");++ let page = 0;+ await expect(+ readAllOracleInvalidObjects(async () => {+ page++;+ if (page === 2) throw new Error("middle page failed");+ return { columns: pageColumns, rows: Array.from({ length: 500 }, (_, index) => ["APP", `P${index}`, "PROCEDURE", String(index + 1), "time"]) };+ }, "APP"),+ ).rejects.toThrow("middle page failed");+ });++ it("rejects a page that omits required dictionary columns", async () => {+ await expect(readAllOracleInvalidObjects(async () => ({ columns: ["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID"], rows: [] }), "APP")).rejects.toThrow("omitted required columns");+ });++ it("quotes schema and names as SQL literals and limits the complete ordered listing", () => {+ const sql = buildOracleInvalidObjectsSql("Owner'X", 501);+ expect(sql).toContain("OWNER = 'Owner''X'");+ expect(sql).toContain("STATUS = 'INVALID'");+ expect(sql).toContain("ORDER BY OBJECT_NAME, OBJECT_TYPE");+ expect(sql).toContain("ROWNUM <= 501");+ });++ it("preserves distinct object/body types and creates exact identity/error queries", () => {+ const object = { owner: "A", name: 'p"name', type: "PACKAGE BODY", objectId: "52", lastDdlTime: "now" };+ const rows = mapOracleInvalidObjects(+ [+ ["A", object.name, "PACKAGE", 51, "now"],+ ["A", object.name, "PACKAGE BODY", 52, "now"],+ ],+ "A",+ );+ expect(rows.map((row) => row.type)).toEqual(["PACKAGE", "PACKAGE BODY"]);+ expect(buildOracleObjectErrorsSql("A", object)).toContain("TYPE = 'PACKAGE BODY'");+ expect(buildOracleObjectErrorsSql("A", object)).toContain(`NAME = 'p"name'`);+ expect(buildOracleObjectIdentitySql("A", object)).toContain("OBJECT_ID");+ expect(buildOracleObjectIdentitySql("A", object)).toContain("STATUS = 'INVALID'");+ });++ it.each([+ ["oracle", "PROCEDURE", 'ALTER PROCEDURE "APP"."P" COMPILE REUSE SETTINGS'],+ ["oracle", "FUNCTION", 'ALTER FUNCTION "APP"."P" COMPILE REUSE SETTINGS'],+ ["oracle", "TRIGGER", 'ALTER TRIGGER "APP"."P" COMPILE REUSE SETTINGS'],+ ["oracle", "PACKAGE", 'ALTER PACKAGE "APP"."P" COMPILE SPECIFICATION REUSE SETTINGS'],+ ["oracle", "PACKAGE BODY", 'ALTER PACKAGE "APP"."P" COMPILE BODY REUSE SETTINGS'],+ ["oracle", "TYPE", 'ALTER TYPE "APP"."T" COMPILE SPECIFICATION REUSE SETTINGS'],+ ["oracle", "TYPE BODY", 'ALTER TYPE "APP"."P" COMPILE BODY REUSE SETTINGS'],+ ["oracle", "VIEW", 'ALTER VIEW "APP"."P" COMPILE'],+ ["oracle", "MATERIALIZED VIEW", 'ALTER MATERIALIZED VIEW "APP"."P" COMPILE'],+ ["oracle", "SYNONYM", 'ALTER SYNONYM "APP"."P" COMPILE'],+ ["oceanbase-oracle", "PROCEDURE", 'ALTER PROCEDURE "APP"."P" COMPILE'],+ ["oceanbase-oracle", "FUNCTION", 'ALTER FUNCTION "APP"."P" COMPILE'],+ ["oceanbase-oracle", "PACKAGE", 'ALTER PACKAGE "APP"."P" COMPILE'],+ ["oceanbase-oracle", "PACKAGE BODY", 'ALTER PACKAGE "APP"."P" COMPILE BODY'],+ ] as const)("builds the engine-specific compile command for %s %s", (dbType, type, expected) => {+ expect(buildOracleCompileSql(dbType, "APP", { name: type === "TYPE" ? "T" : "P", type })).toBe(expected);+ });++ it("treats only the exact PUBLIC dictionary owner as a public synonym", () => {+ expect(buildOracleCompileSql("oracle", "PUBLIC", { name: "EMP", type: "SYNONYM" })).toBe('ALTER PUBLIC SYNONYM "EMP" COMPILE');+ expect(buildOracleCompileSql("oracle", "Public", { name: "EMP", type: "SYNONYM" })).toBe('ALTER SYNONYM "Public"."EMP" COMPILE');+ });++ it("keeps unsupported OceanBase types visible without generating a write", () => {+ expect(oracleCompileUnsupportedReason("oceanbase-oracle", "VIEW")).toBe("unsupported-on-engine");+ expect(oracleCompileUnsupportedReason("oceanbase-oracle", "JAVA CLASS")).toBe("unsupported-type");+ expect(() => buildOracleCompileSql("oceanbase-oracle", "APP", { name: "V", type: "VIEW" })).toThrow();+ });++ it("maps numeric error locations and keeps the database sequence", () => {+ expect(+ mapOracleObjectErrors([+ [2, 18, 7, "second"],+ [1, 4, 3, "first"],+ ]),+ ).toEqual([+ { sequence: 1, line: 4, position: 3, text: "first" },+ { sequence: 2, line: 18, position: 7, text: "second" },+ ]);+ });+});diff --git a/apps/desktop/src/lib/database/__tests__/oracleSessionManagement.spec.ts b/apps/desktop/src/lib/database/__tests__/oracleSessionManagement.spec.tsnew file mode 100644index 0000000000..5caf23d0f4--- /dev/null+++ b/apps/desktop/src/lib/database/__tests__/oracleSessionManagement.spec.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from "vitest";+import {+ buildOceanbaseKillConnectionBlock,+ buildOceanbaseLockDetailsSql,+ buildOceanbaseSessionListSql,+ buildOracleKillSessionBlock,+ buildOracleLockDetailsSql,+ buildOracleSessionListSql,+ mapOceanbaseSessions,+ mapOracleSessions,+ oracleMajorVersion,+ OCEANBASE_OWN_SESSION_SQL,+} from "../oracleSessionManagement";++describe("Oracle session identity and SQL", () => {+ it("parses the reported Oracle major version and rejects unknown formats", () => {+ expect(oracleMajorVersion("19.0.0.0.0")).toBe(19);+ expect(oracleMajorVersion(" 11.2.0.4.0 ")).toBe(11);+ expect(oracleMajorVersion("Oracle Database 19c")).toBeNull();+ });++ it("scopes modern sessions to the current container and keeps legacy SQL separate", () => {+ expect(buildOracleSessionListSql(false)).toContain("s.CON_ID = TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID'))");+ expect(buildOracleSessionListSql(true)).not.toContain("CON_ID");+ });++ it("preserves complete Oracle target identity and permits non-CDB CON_ID zero", () => {+ const [target] = mapOracleSessions({ rows: [["17", "8", "2", "0", "APP", "INACTIVE", "host", "client", null, null, null, null, "99", "2026-10-20 10:00:00"]] });+ expect(buildOracleKillSessionBlock(target!, false)).toContain("CON_ID = 0");+ expect(buildOracleKillSessionBlock(target!, false)).toContain("SID = 17 AND SERIAL# = 8 AND INST_ID = 2 AND CON_ID = 0");+ expect(buildOracleKillSessionBlock(target!, false)).toContain("ALTER SYSTEM KILL SESSION ''17,8,@2'' IMMEDIATE");+ const lockSql = buildOracleLockDetailsSql(target!, false);+ expect(lockSql).toContain("l.CON_ID = 0");+ expect(lockSql).toContain("target.SID = 17 AND target.SERIAL# = 8 AND target.INST_ID = 2 AND target.CON_ID = 0");+ expect(lockSql).toContain("target.AUDSID = 99");+ expect(lockSql).toContain("TO_CHAR(target.LOGON_TIME,'YYYY-MM-DD HH24:MI:SS') = '2026-10-20 10:00:00'");+ });++ it("rejects unsafe Oracle target identities", () => {+ const [target] = mapOracleSessions({ rows: [["9007199254740993", "8", "2", "1", "APP", "INACTIVE", "", "", null, null, null, null, "99", "2026-10-20 10:00:00"]] });+ expect(() => buildOracleKillSessionBlock(target!, false)).toThrow("Invalid SID");+ });+});++describe("OceanBase session identity and SQL", () => {+ const row = {+ id: "9007199254740993",+ user: "APP'X",+ tenant: "tenant_a",+ proxySessionId: null,+ serverIp: "127.0.0.1",+ serverPort: "2882",+ };++ it("maps large IDs losslessly, scopes the list to the active tenant, and reads own identity", () => {+ expect(mapOceanbaseSessions({ rows: [[row.id, row.user, row.tenant, "host", "db", "Query", "2", "active", "SELECT 1", null, row.serverIp, row.serverPort]] })[0]?.id).toBe(row.id);+ expect(buildOceanbaseSessionListSql()).toContain("TENANT = (SELECT TENANT FROM GV$OB_SESSION");+ });++ it("reads the dictionary USER column rather than the login USER function", () => {+ expect(buildOceanbaseSessionListSql()).toContain('"USER" AS SESSION_USER');+ expect(buildOceanbaseSessionListSql()).toContain('AND "USER" = SYS_CONTEXT');+ expect(OCEANBASE_OWN_SESSION_SQL).toContain('SELECT TO_CHAR(ID), "USER", TENANT');+ expect(OCEANBASE_OWN_SESSION_SQL).toContain('AND "USER" = SYS_CONTEXT');+ });++ it("uses one guarded KILL CONNECTION block with exact user, tenant, node and decimal ID", () => {+ const sql = buildOceanbaseKillConnectionBlock(row);+ expect(sql).toContain(`ID = ${row.id} AND "USER" = 'APP''X' AND TENANT = 'tenant_a'`);+ expect(sql).toContain(`IF TO_NUMBER(SYS_CONTEXT('USERENV','SID')) = ${row.id} AND USER = 'APP''X' THEN`);+ expect(sql).toContain("SVR_IP = '127.0.0.1' AND SVR_PORT = 2882");+ expect(sql).toContain(`EXECUTE IMMEDIATE 'KILL CONNECTION ${row.id}'`);+ expect(sql).toContain("Cannot terminate the executing management session");+ });++ it("rejects proxy sessions and includes same-resource lock rows within the target tenant", () => {+ expect(() => buildOceanbaseKillConnectionBlock({ ...row, proxySessionId: "88" })).toThrow("Unsupported");+ const sql = buildOceanbaseLockDetailsSql({ ...row, tenantId: 7 });+ expect(sql).toContain("tl.ID3 = l.ID3");+ expect(sql).toContain('p."USER" AS SESSION_USER');+ expect(sql).toContain(`tp."USER" = 'APP''X'`);+ expect(sql).toContain("tl.SESSION_ID = 9007199254740993 AND tl.SVR_IP = '127.0.0.1' AND tl.SVR_PORT = 2882");+ expect(sql).toContain("p.SVR_IP = l.SVR_IP AND p.SVR_PORT = l.SVR_PORT");+ expect(sql).not.toContain("TENANT_ID FROM GV$OB_SESSION");+ });+});diff --git a/apps/desktop/src/lib/database/__tests__/productionExecutionGuard.spec.ts b/apps/desktop/src/lib/database/__tests__/productionExecutionGuard.spec.tsindex a81293b1f1..26c2c24668 100644--- a/apps/desktop/src/lib/database/__tests__/productionExecutionGuard.spec.ts+++ b/apps/desktop/src/lib/database/__tests__/productionExecutionGuard.spec.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createPinia, setActivePinia } from "pinia";import { executeWithProductionContextGuard, executeWithProductionSqlGuard } from "../productionExecutionGuard";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { useReadOnlyUnlockStore } from "@/stores/readOnlyUnlockStore";import type { ConnectionConfig } from "@/types/database";function connection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {@@ -48,6 +49,42 @@ describe("production SQL execution guard", () => {expect(execute).toHaveBeenCalledTimes(1);});+ it("reviews the entire batch mutation once and executes its callback once", async () => {+ const batchSql = ['ALTER PROCEDURE "APP"."P1" COMPILE REUSE SETTINGS', 'ALTER PACKAGE "APP"."PKG" COMPILE SPECIFICATION REUSE SETTINGS', 'ALTER PACKAGE "APP"."PKG" COMPILE BODY REUSE SETTINGS'].join(";\n");+ const execute = vi.fn().mockResolvedValue("completed");+ const pending = executeWithProductionSqlGuard({+ connection: connection({ db_type: "oracle", production_databases: ["app"] }),+ database: "APP",+ sql: batchSql,+ source: "Invalid objects batch",+ execute,+ });++ await Promise.resolve();+ expect(useProductionSafetyStore().pending).toMatchObject({ sql: batchSql, database: "APP", source: "Invalid objects batch" });+ expect(execute).not.toHaveBeenCalled();+ useProductionSafetyStore().confirm();+ await expect(pending).resolves.toBe("completed");+ expect(execute).toHaveBeenCalledOnce();+ });++ it("blocks a batch on a read-only connection until write access is explicitly unlocked", async () => {+ const execute = vi.fn().mockResolvedValue("completed");+ const pending = executeWithProductionSqlGuard({+ connection: connection({ db_type: "oracle", read_only: true }),+ database: "APP",+ sql: 'ALTER PROCEDURE "APP"."P1" COMPILE;\nALTER PROCEDURE "APP"."P2" COMPILE',+ source: "Invalid objects batch",+ execute,+ });++ await vi.waitFor(() => expect(useReadOnlyUnlockStore().pending?.connectionId).toBe("conn-1"));+ expect(execute).not.toHaveBeenCalled();+ useReadOnlyUnlockStore().cancel();+ await expect(pending).resolves.toBeUndefined();+ expect(execute).not.toHaveBeenCalled();+ });+it("cancels production SQL without executing the callback", async () => {const execute = vi.fn().mockResolvedValue("done");const pendingExecution = executeWithProductionSqlGuard({@@ -180,4 +217,27 @@ describe("production context execution guard (non-SQL)", () => {expect(useProductionSafetyStore().pending).toBeUndefined();expect(execute).toHaveBeenCalledTimes(1);});++ it("connection scope confirms any marked database even when the current schema is unmarked", async () => {+ const execute = vi.fn().mockResolvedValue("killed");+ const pending = executeWithProductionContextGuard({+ connection: connection({ db_type: "oracle", production_databases: ["PROD_A", "PROD_B"] }),+ database: "scratch",+ reviewText: "terminate session 42",+ scope: "connection",+ execute,+ });+ await Promise.resolve();+ expect(useProductionSafetyStore().pending).toMatchObject({ productionDatabases: ["prod_a", "prod_b"] });+ useProductionSafetyStore().confirm();+ await expect(pending).resolves.toBe("killed");+ expect(execute).toHaveBeenCalledOnce();+ });++ it("connection scope leaves unmarked connections immediate and preserves the default database scope", async () => {+ const execute = vi.fn().mockResolvedValue("done");+ await expect(executeWithProductionContextGuard({ connection: connection({ db_type: "oracle", production_databases: [] }), database: "scratch", reviewText: "terminate session", scope: "connection", execute })).resolves.toBe("done");+ await expect(executeWithProductionContextGuard({ connection: connection({ db_type: "oracle", production_databases: ["prod_a"] }), database: "scratch", reviewText: "legacy action", execute })).resolves.toBe("done");+ expect(useProductionSafetyStore().pending).toBeUndefined();+ });});diff --git a/apps/desktop/src/lib/database/oracleInvalidObjectCacheRefresh.ts b/apps/desktop/src/lib/database/oracleInvalidObjectCacheRefresh.tsnew file mode 100644index 0000000000..d7a9dce7c7--- /dev/null+++ b/apps/desktop/src/lib/database/oracleInvalidObjectCacheRefresh.ts@@ -0,0 +1,20 @@+export type OracleInvalidObjectCompileScope = {+ connectionId: string;+ database: string;+ schema: string;+};++function sameScope(left: OracleInvalidObjectCompileScope, right: OracleInvalidObjectCompileScope): boolean {+ return left.connectionId === right.connectionId && left.database === right.database && left.schema === right.schema;+}++export async function completeOracleInvalidObjectCompile(+ completed: OracleInvalidObjectCompileScope,+ getCurrent: () => OracleInvalidObjectCompileScope,+ invalidate: (scope: OracleInvalidObjectCompileScope) => Promise<void>,+ refresh: (scope: OracleInvalidObjectCompileScope) => Promise<void>,+): Promise<void> {+ await invalidate(completed);+ const current = getCurrent();+ if (sameScope(completed, current)) await refresh(current);+}diff --git a/apps/desktop/src/lib/database/oracleInvalidObjects.ts b/apps/desktop/src/lib/database/oracleInvalidObjects.tsnew file mode 100644index 0000000000..815a866766--- /dev/null+++ b/apps/desktop/src/lib/database/oracleInvalidObjects.ts@@ -0,0 +1,161 @@+import type { DatabaseType, ObjectSourceKind, QueryResult } from "@/types/database";++export type OracleInvalidObject = {+ owner: string;+ name: string;+ type: string;+ objectId: string;+ lastDdlTime: string;+};++export type OracleObjectError = {+ sequence: number;+ line: number;+ position: number;+ text: string;+};++export const ORACLE_INVALID_OBJECTS_PAGE_SIZE = 500;++export type OracleInvalidObjectsPageQuery = (sql: string, maxRows: number) => Promise<QueryResult>;++const ORACLE_COMPILE_TYPES = new Set(["VIEW", "MATERIALIZED VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "PACKAGE", "PACKAGE BODY", "TYPE", "TYPE BODY", "SYNONYM"]);++const OCEANBASE_COMPILE_TYPES = new Set(["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY"]);++export function oracleInvalidObjectSourceKind(objectType: string): ObjectSourceKind | null {+ const kind = objectType.trim().toUpperCase().replaceAll(" ", "_");+ switch (kind) {+ case "VIEW":+ case "MATERIALIZED_VIEW":+ case "PROCEDURE":+ case "FUNCTION":+ case "TRIGGER":+ case "SEQUENCE":+ case "SYNONYM":+ case "PACKAGE":+ case "PACKAGE_BODY":+ case "TYPE":+ case "TYPE_BODY":+ return kind;+ default:+ return null;+ }+}++export function quoteOracleLiteral(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++export function quoteOracleIdentifier(value: string): string {+ if (!value || value.includes("\0")) throw new Error("Invalid Oracle identifier");+ return `"${value.replaceAll('"', '""')}"`;+}++export function buildOracleInvalidObjectsSql(owner: string, limit: number): string {+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 5000) throw new Error("Invalid row limit");+ const escapedOwner = quoteOracleLiteral(owner);+ return `SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME\nFROM (SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, LAST_DDL_TIME FROM ALL_OBJECTS WHERE OWNER = ${escapedOwner} AND STATUS = 'INVALID' ORDER BY OBJECT_NAME, OBJECT_TYPE)\nWHERE ROWNUM <= ${limit}`;+}++export function buildOracleInvalidObjectsPageSql(owner: string, afterObjectId = "0"): string {+ if (!/^(0|[1-9]\d*)$/.test(afterObjectId)) throw new Error("Invalid Oracle object ID cursor");+ return `SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, TO_CHAR(OBJECT_ID) AS OBJECT_ID, TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME\nFROM (SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, LAST_DDL_TIME FROM ALL_OBJECTS WHERE OWNER = ${quoteOracleLiteral(owner)} AND STATUS = 'INVALID' AND OBJECT_ID > ${afterObjectId} ORDER BY OBJECT_ID)\nWHERE ROWNUM <= ${ORACLE_INVALID_OBJECTS_PAGE_SIZE}`;+}++function strictInvalidObjectRows(rows: unknown[][], owner: string, previousId: bigint): OracleInvalidObject[] {+ let lastId = previousId;+ const result: OracleInvalidObject[] = [];+ for (const row of rows) {+ const [rowOwner, name, type, objectId, lastDdlTime] = row;+ if (typeof rowOwner !== "string" || rowOwner !== owner || typeof name !== "string" || !name || typeof type !== "string" || !type || typeof objectId !== "string" || !/^[1-9]\d*$/.test(objectId) || typeof lastDdlTime !== "string" || !lastDdlTime) {+ throw new Error("Incomplete Oracle invalid-object row");+ }+ const numericId = BigInt(objectId);+ if (numericId <= lastId) throw new Error("Oracle invalid-object cursor did not advance");+ lastId = numericId;+ result.push({ owner: rowOwner, name, type, objectId, lastDdlTime });+ }+ return result;+}++export async function readAllOracleInvalidObjects(query: OracleInvalidObjectsPageQuery, owner: string, options: { onProgress?: (count: number) => void; isCurrent?: () => boolean } = {}): Promise<OracleInvalidObject[]> {+ const objects: OracleInvalidObject[] = [];+ let cursor = "0";+ let previousId = 0n;+ const seen = new Set<string>();+ while (true) {+ if (options.isCurrent && !options.isCurrent()) throw new Error("Oracle invalid-object read is no longer current");+ const page = await query(buildOracleInvalidObjectsPageSql(owner, cursor), ORACLE_INVALID_OBJECTS_PAGE_SIZE + 1);+ if (options.isCurrent && !options.isCurrent()) throw new Error("Oracle invalid-object read is no longer current");+ if (page.execution_error) throw new Error(page.error?.detail ?? String(page.rows[0]?.[0] ?? "Oracle invalid-object page query failed"));+ if (page.truncated === true || page.rows.length > ORACLE_INVALID_OBJECTS_PAGE_SIZE) throw new Error("Oracle invalid-object page was truncated");+ const columns = new Set(page.columns.map((column) => column.trim().toUpperCase()));+ if (["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "LAST_DDL_TIME"].some((column) => !columns.has(column))) throw new Error("Oracle invalid-object page omitted required columns");+ const mapped = strictInvalidObjectRows(page.rows, owner, previousId);+ for (const object of mapped) {+ if (seen.has(object.objectId)) throw new Error("Duplicate Oracle invalid-object ID");+ seen.add(object.objectId);+ previousId = BigInt(object.objectId);+ }+ objects.push(...mapped);+ options.onProgress?.(objects.length);+ if (page.rows.length < ORACLE_INVALID_OBJECTS_PAGE_SIZE) return objects;+ cursor = mapped[mapped.length - 1]?.objectId ?? cursor;+ if (!mapped.length) throw new Error("Oracle invalid-object cursor did not advance");+ }+}++export function buildOracleObjectErrorsSql(owner: string, object: Pick<OracleInvalidObject, "name" | "type">): string {+ return `SELECT SEQUENCE, LINE, POSITION, TEXT FROM ALL_ERRORS WHERE OWNER = ${quoteOracleLiteral(owner)} AND NAME = ${quoteOracleLiteral(object.name)} AND TYPE = ${quoteOracleLiteral(object.type)} ORDER BY SEQUENCE`;+}++export function buildOracleObjectIdentitySql(owner: string, object: OracleInvalidObject): string {+ return `SELECT TO_CHAR(OBJECT_ID) AS OBJECT_ID, TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME FROM ALL_OBJECTS WHERE OWNER = ${quoteOracleLiteral(owner)} AND OBJECT_NAME = ${quoteOracleLiteral(object.name)} AND OBJECT_TYPE = ${quoteOracleLiteral(object.type)} AND STATUS = 'INVALID'`;+}++export function buildOracleObjectStatusSql(owner: string, object: OracleInvalidObject): string {+ return `SELECT TO_CHAR(OBJECT_ID) AS OBJECT_ID, TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD HH24:MI:SS') AS LAST_DDL_TIME, STATUS FROM ALL_OBJECTS WHERE OWNER = ${quoteOracleLiteral(owner)} AND OBJECT_NAME = ${quoteOracleLiteral(object.name)} AND OBJECT_TYPE = ${quoteOracleLiteral(object.type)}`;+}++export function oracleCompileUnsupportedReason(dbType: DatabaseType, objectType: string): "unsupported-type" | "unsupported-on-engine" | null {+ const type = objectType.toUpperCase();+ if (!ORACLE_COMPILE_TYPES.has(type)) return "unsupported-type";+ if (dbType === "oceanbase-oracle" && !OCEANBASE_COMPILE_TYPES.has(type)) return "unsupported-on-engine";+ return null;+}++export function buildOracleCompileSql(dbType: DatabaseType, owner: string, object: Pick<OracleInvalidObject, "name" | "type">): string {+ const type = object.type.toUpperCase();+ if (oracleCompileUnsupportedReason(dbType, type)) throw new Error("Unsupported Oracle object compile type");+ const qualified = `${quoteOracleIdentifier(owner)}.${quoteOracleIdentifier(object.name)}`;+ if (type === "SYNONYM") return `ALTER ${owner === "PUBLIC" ? "PUBLIC " : ""}SYNONYM ${owner === "PUBLIC" ? quoteOracleIdentifier(object.name) : qualified} COMPILE`;+ if (type === "MATERIALIZED VIEW") return `ALTER MATERIALIZED VIEW ${qualified} COMPILE`;+ if (type === "PACKAGE BODY") return `ALTER PACKAGE ${qualified} COMPILE BODY${dbType === "oracle" ? " REUSE SETTINGS" : ""}`;+ if (type === "PACKAGE" && dbType === "oracle") return `ALTER PACKAGE ${qualified} COMPILE SPECIFICATION REUSE SETTINGS`;+ if (type === "TYPE") return `ALTER TYPE ${qualified} COMPILE SPECIFICATION${dbType === "oracle" ? " REUSE SETTINGS" : ""}`;+ if (type === "TYPE BODY") return `ALTER TYPE ${qualified} COMPILE BODY${dbType === "oracle" ? " REUSE SETTINGS" : ""}`;+ const reuseSettings = dbType === "oracle" && ["PROCEDURE", "FUNCTION", "TRIGGER"].includes(type) ? " REUSE SETTINGS" : "";+ return `ALTER ${type} ${qualified} COMPILE${reuseSettings}`;+}++export function mapOracleInvalidObjects(rows: unknown[][], owner: string): OracleInvalidObject[] {+ return rows.flatMap((row) => {+ const name = row[1];+ const type = row[2];+ if (typeof name !== "string" || typeof type !== "string") return [];+ return [{ owner: String(row[0] ?? owner), name, type, objectId: String(row[3] ?? ""), lastDdlTime: String(row[4] ?? "") }];+ });+}++export function mapOracleObjectErrors(rows: unknown[][]): OracleObjectError[] {+ return rows+ .flatMap((row) => {+ const sequence = Number(row[0]);+ const line = Number(row[1]);+ const position = Number(row[2]);+ if (![sequence, line, position].every(Number.isSafeInteger)) return [];+ return [{ sequence, line, position, text: String(row[3] ?? "") }];+ })+ .sort((a, b) => a.sequence - b.sequence);+}diff --git a/apps/desktop/src/lib/database/oracleSessionManagement.ts b/apps/desktop/src/lib/database/oracleSessionManagement.tsnew file mode 100644index 0000000000..b18722e030--- /dev/null+++ b/apps/desktop/src/lib/database/oracleSessionManagement.ts@@ -0,0 +1,219 @@+import type { QueryResult } from "@/types/database";+import type { ProcessColumn, ProcessRow } from "@/lib/database/processListDrivers";++const ORACLE_COLUMNS: ProcessColumn[] = [+ { key: "id", labelKey: "processList.colId", mono: true },+ { key: "serial", labelKey: "processList.oracleSerial", mono: true },+ { key: "instance", labelKey: "processList.oracleInstance", mono: true },+ { key: "container", labelKey: "processList.oracleContainer", mono: true },+ { key: "user", labelKey: "processList.colUser" },+ { key: "status", labelKey: "processList.colState" },+ { key: "machine", labelKey: "processList.colClient" },+ { key: "program", labelKey: "processList.oracleProgram", wide: true },+ { key: "sqlId", labelKey: "processList.oracleSqlId", mono: true },+ { key: "wait", labelKey: "processList.colWait", wide: true },+ { key: "blocker", labelKey: "processList.oracleBlocker", mono: true },+];++const OCEANBASE_COLUMNS: ProcessColumn[] = [+ { key: "id", labelKey: "processList.colId", mono: true },+ { key: "user", labelKey: "processList.colUser" },+ { key: "tenant", labelKey: "processList.oracleTenant" },+ { key: "host", labelKey: "processList.colHost" },+ { key: "db", labelKey: "processList.colDb" },+ { key: "command", labelKey: "processList.colCommand" },+ { key: "time", labelKey: "processList.colTime" },+ { key: "state", labelKey: "processList.colState" },+ { key: "info", labelKey: "processList.colInfo", wide: true, mono: true },+ { key: "server", labelKey: "processList.oracleNode", mono: true },+];++const ORACLE_VERSION_SQL = "SELECT VERSION FROM PRODUCT_COMPONENT_VERSION WHERE PRODUCT LIKE 'Oracle Database%' AND ROWNUM = 1";+const ORACLE_OWN_SQL = `SELECT TO_CHAR(SYS_CONTEXT('USERENV','SID')), TO_CHAR(SYS_CONTEXT('USERENV','INSTANCE')), TO_CHAR(SYS_CONTEXT('USERENV','CON_ID')) FROM DUAL`;+const ORACLE_LEGACY_OWN_SQL = `SELECT TO_CHAR(SYS_CONTEXT('USERENV','SID')), TO_CHAR(SYS_CONTEXT('USERENV','INSTANCE')), '0' FROM DUAL`;++export type OracleSessionTarget = ProcessRow & {+ id: string;+ serial: string;+ instance: string;+ container: string;+ user: string;+ auditSession: string;+ logonTime: string;+};++function sqlLiteral(value: string): string {+ return `'${value.replaceAll("'", "''")}'`;+}++function positiveInteger(value: string, label: string): string {+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) <= 0) throw new Error(`Invalid ${label}`);+ return String(Number(value));+}++function nonNegativeInteger(value: string, label: string): string {+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 0) throw new Error(`Invalid ${label}`);+ return String(Number(value));+}++function positiveDecimalString(value: string, label: string): string {+ if (!/^\d+$/.test(value) || !/[1-9]/.test(value)) throw new Error(`Invalid ${label}`);+ return value.replace(/^0+(?=\d)/, "");+}++export function oracleMajorVersion(version: string): number | null {+ const match = version.match(/^\s*(\d+)(?:\.|\s|$)/);+ const major = match ? Number(match[1]) : NaN;+ return Number.isSafeInteger(major) && major > 0 ? major : null;+}++export function buildOracleSessionListSql(legacy: boolean): string {+ const container = legacy ? "'0'" : "TO_CHAR(s.CON_ID)";+ const predicate = legacy ? "" : " AND s.CON_ID = TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID'))";+ return `SELECT TO_CHAR(s.SID) AS SESSION_ID, TO_CHAR(s.SERIAL#) AS SERIAL_NUMBER, TO_CHAR(s.INST_ID) AS INSTANCE_ID, ${container} AS CONTAINER_ID, s.USERNAME AS SESSION_USER, s.STATUS AS SESSION_STATUS, s.MACHINE AS MACHINE, s.PROGRAM AS PROGRAM, s.SQL_ID AS SQL_ID, s.EVENT || CASE WHEN s.WAIT_CLASS IS NULL THEN '' ELSE ' (' || s.WAIT_CLASS || ')' END AS WAIT_INFO, TO_CHAR(s.BLOCKING_INSTANCE) AS BLOCKING_INSTANCE, TO_CHAR(s.BLOCKING_SESSION) AS BLOCKING_SESSION, TO_CHAR(s.AUDSID) AS AUDIT_SESSION, TO_CHAR(s.LOGON_TIME,'YYYY-MM-DD HH24:MI:SS') AS LOGON_TIME\nFROM GV$SESSION s\nWHERE s.USERNAME IS NOT NULL${predicate}\nORDER BY s.INST_ID, s.SID`;+}++export function buildOracleOwnSessionSql(legacy: boolean): string {+ return legacy ? ORACLE_LEGACY_OWN_SQL : ORACLE_OWN_SQL;+}++export function mapOracleSessions(result: QueryResult | null | undefined): OracleSessionTarget[] {+ return (result?.rows ?? []).flatMap((row) => {+ const [id, serial, instance, container, user, status, machine, program, sqlId, wait, blockingInstance, blockingSession, auditSession, logonTime] = row;+ if ([id, serial, instance, container, user].some((value) => value === null || value === undefined || String(value) === "")) return [];+ return [+ {+ id: String(id),+ serial: String(serial),+ instance: String(instance),+ container: String(container),+ user: String(user),+ status: String(status ?? ""),+ machine: String(machine ?? ""),+ program: String(program ?? ""),+ sqlId: String(sqlId ?? ""),+ wait: String(wait ?? ""),+ blockingInstance: String(blockingInstance ?? ""),+ blockingSession: String(blockingSession ?? ""),+ blocker: blockingSession === null || blockingSession === undefined ? "" : `${String(blockingInstance ?? "")}:${String(blockingSession)}`,+ auditSession: String(auditSession ?? ""),+ logonTime: String(logonTime ?? ""),+ } as OracleSessionTarget,+ ];+ });+}++export function buildOracleKillSessionBlock(target: OracleSessionTarget, legacy: boolean): string {+ const sid = positiveInteger(target.id, "SID");+ const serial = positiveInteger(target.serial, "serial number");+ const instance = positiveInteger(target.instance, "instance id");+ const containerId = legacy ? "0" : nonNegativeInteger(target.container, "container id");+ const conIdProjection = legacy ? "0" : "CON_ID";+ const conIdPredicate = legacy ? "" : ` AND CON_ID = ${containerId}`;+ const selfIdentity = legacy+ ? `TO_NUMBER(SYS_CONTEXT('USERENV','SID')) = ${sid} AND TO_NUMBER(SYS_CONTEXT('USERENV','INSTANCE')) = ${instance}`+ : `TO_NUMBER(SYS_CONTEXT('USERENV','SID')) = ${sid} AND TO_NUMBER(SYS_CONTEXT('USERENV','INSTANCE')) = ${instance} AND TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID')) = ${containerId}`;+ const identity = `SID = ${sid} AND SERIAL# = ${serial} AND INST_ID = ${instance}${conIdPredicate} AND USERNAME = ${sqlLiteral(target.user)} AND AUDSID = ${positiveInteger(target.auditSession, "audit session id")} AND TO_CHAR(LOGON_TIME,'YYYY-MM-DD HH24:MI:SS') = ${sqlLiteral(target.logonTime)}`;+ const currentContainerCheck = legacy ? "" : ` OR TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID')) <> ${containerId}`;+ return `DECLARE\n v_self_serial NUMBER;\n v_self_container NUMBER := ${legacy ? "0" : "TO_NUMBER(SYS_CONTEXT('USERENV','CON_ID'))"};\n v_target_count NUMBER;\nBEGIN\n IF ${selfIdentity} THEN\n SELECT SERIAL# INTO v_self_serial FROM GV$SESSION WHERE SID = ${sid} AND INST_ID = ${instance} AND ${conIdProjection} = v_self_container;\n IF v_self_serial = ${serial} THEN RAISE_APPLICATION_ERROR(-20001, 'Cannot terminate the executing management session'); END IF;\n END IF;\n SELECT COUNT(*) INTO v_target_count FROM GV$SESSION WHERE ${identity};\n IF v_target_count <> 1${currentContainerCheck} THEN RAISE_APPLICATION_ERROR(-20002, 'Session identity changed; refresh the list'); END IF;\n EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION ''${sid},${serial},@${instance}'' IMMEDIATE';\nEND;`;+}++export function oracleSessionRowKey(row: ProcessRow): string {+ return JSON.stringify([row.container, row.instance, row.id, row.serial, row.auditSession, row.logonTime]);+}++export function oracleTargetIsSelf(row: ProcessRow, ownRow: unknown[] | null): boolean {+ return !!ownRow && String(row.id) === String(ownRow[0] ?? "") && String(row.instance) === String(ownRow[1] ?? "") && String(row.container) === String(ownRow[2] ?? "");+}++export function canTerminateOracleSession(row: ProcessRow): boolean {+ const positive = (value: unknown) => /^\d+$/.test(String(value ?? "")) && Number.isSafeInteger(Number(value)) && Number(value) > 0;+ const container = (value: unknown) => /^\d+$/.test(String(value ?? "")) && Number.isSafeInteger(Number(value)) && Number(value) >= 0;+ return positive(row.id) && positive(row.serial) && positive(row.instance) && container(row.container) && positive(row.auditSession) && !!row.user && !!row.logonTime;+}++export function buildOracleLockDetailsSql(target: OracleSessionTarget, legacy: boolean): string {+ const sid = positiveInteger(target.id, "SID");+ const serial = positiveInteger(target.serial, "serial number");+ const instance = positiveInteger(target.instance, "instance id");+ const container = legacy ? "0" : nonNegativeInteger(target.container, "container id");+ const conIdColumn = legacy ? "0" : "l.CON_ID";+ const sessionConId = legacy ? "0" : "s.CON_ID";+ const containerJoin = legacy ? "" : " AND s.CON_ID = l.CON_ID";+ const containerFilter = legacy ? "" : ` AND l.CON_ID = ${container}`;+ const targetConId = legacy ? "" : ` AND target.CON_ID = ${container}`;+ const related = `s.SID = ${sid} AND s.INST_ID = ${instance}${legacy ? "" : ` AND s.CON_ID = ${container}`}`;+ const blockerMatch =+ /^\d+$/.test(String(target.blockingSession ?? "")) && Number(target.blockingSession) > 0 && /^\d+$/.test(String(target.blockingInstance ?? "")) && Number(target.blockingInstance) > 0+ ? `s.SID = ${positiveInteger(String(target.blockingSession), "blocking SID")} AND s.INST_ID = ${positiveInteger(String(target.blockingInstance), "blocking instance")}${legacy ? "" : ` AND s.CON_ID = ${container}`}`+ : "1 = 0";+ const targetIdentity = `target.SID = ${sid} AND target.SERIAL# = ${serial} AND target.INST_ID = ${instance}${targetConId} AND target.USERNAME = ${sqlLiteral(target.user)} AND target.AUDSID = ${positiveInteger(target.auditSession, "audit session id")} AND TO_CHAR(target.LOGON_TIME,'YYYY-MM-DD HH24:MI:SS') = ${sqlLiteral(target.logonTime)}`;+ return `SELECT ${conIdColumn} AS CONTAINER_ID, l.INST_ID AS INSTANCE_ID, l.SID AS SESSION_ID, l.TYPE AS LOCK_TYPE, TO_CHAR(l.ID1) AS ID1, TO_CHAR(l.ID2) AS ID2, l.LMODE AS HELD_MODE, l.REQUEST AS REQUESTED_MODE, l.BLOCK AS BLOCKING, s.USERNAME AS SESSION_USER, s.STATUS AS SESSION_STATUS, TO_CHAR(s.BLOCKING_INSTANCE) || ':' || TO_CHAR(s.BLOCKING_SESSION) AS BLOCKER\nFROM GV$LOCK l JOIN GV$SESSION s ON s.SID = l.SID AND s.INST_ID = l.INST_ID${containerJoin}\nWHERE EXISTS (SELECT 1 FROM GV$SESSION target WHERE ${targetIdentity}) AND (${related} OR ${blockerMatch} OR s.BLOCKING_INSTANCE = ${instance} AND s.BLOCKING_SESSION = ${sid}${legacy ? "" : ` AND ${sessionConId} = ${container}`})${containerFilter}\nORDER BY l.TYPE, l.ID1, l.ID2, l.REQUEST`;+}++export 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`;+}++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;+ if (id === null || id === undefined || !/^\d+$/.test(String(id)) || user === null || tenant === null) return [];+ return [+ {+ id: String(id),+ user: String(user),+ tenant: String(tenant),+ host: String(host ?? ""),+ db: String(db ?? ""),+ command: String(command ?? ""),+ time: String(time ?? ""),+ state: String(state ?? ""),+ info: String(info ?? ""),+ proxySessionId: proxySessionId === null || proxySessionId === undefined ? null : String(proxySessionId),+ serverIp: String(serverIp ?? ""),+ serverPort: String(serverPort ?? ""),+ server: `${String(serverIp ?? "")}:${String(serverPort ?? "")}`,+ },+ ];+ });+}++export function buildOceanbaseKillConnectionBlock(row: ProcessRow): string {+ const user = String(row.user ?? "");+ const tenant = String(row.tenant ?? "");+ const serverIp = String(row.serverIp ?? "");+ const serverPort = positiveInteger(String(row.serverPort ?? ""), "server port");+ if (!user || !tenant || !serverIp || (row.proxySessionId !== null && row.proxySessionId !== undefined && String(row.proxySessionId) !== "")) throw new Error("Unsupported or incomplete OceanBase session identity");+ const id = positiveDecimalString(String(row.id), "session id");+ return `DECLARE n NUMBER; BEGIN SELECT COUNT(*) INTO n FROM GV$OB_SESSION WHERE ID = ${id} AND "USER" = ${sqlLiteral(user)} AND TENANT = ${sqlLiteral(tenant)} AND SVR_IP = ${sqlLiteral(serverIp)} AND SVR_PORT = ${serverPort} AND PROXY_SESSID IS NULL; IF TO_NUMBER(SYS_CONTEXT('USERENV','SID')) = ${id} AND USER = ${sqlLiteral(user)} THEN RAISE_APPLICATION_ERROR(-20002, 'Cannot terminate the executing management session'); END IF; IF n = 1 THEN EXECUTE IMMEDIATE 'KILL CONNECTION ${id}'; ELSE RAISE_APPLICATION_ERROR(-20001, 'Session identity changed or is not directly addressable'); END IF; END;`;+}++export function oceanbaseSessionRowKey(row: ProcessRow): string {+ return JSON.stringify([row.tenant, row.serverIp, row.serverPort, row.id, row.user, row.proxySessionId]);+}++export function canTerminateOceanbaseSession(row: ProcessRow): boolean {+ return /^\d+$/.test(String(row.id)) && /[1-9]/.test(String(row.id)) && !!row.user && !!row.tenant && !!row.serverIp && /^\d+$/.test(String(row.serverPort)) && String(row.serverPort) !== "0" && (row.proxySessionId === null || row.proxySessionId === undefined || String(row.proxySessionId) === "");+}++export function buildOceanbaseLockDetailsSql(row: ProcessRow): string {+ const id = positiveDecimalString(String(row.id), "session id");+ const user = String(row.user ?? "");+ const tenant = String(row.tenant ?? "");+ const serverIp = String(row.serverIp ?? "");+ const serverPort = positiveInteger(String(row.serverPort ?? ""), "server port");+ if (!user || !tenant || !serverIp) throw new Error("Incomplete OceanBase session identity");+ const proxySessionPredicate = row.proxySessionId === null || row.proxySessionId === undefined || String(row.proxySessionId) === "" ? "IS NULL" : `= ${sqlLiteral(String(row.proxySessionId))}`;+ const targetSessionIdentity = `tp.ID = ${id} AND tp."USER" = ${sqlLiteral(user)} AND tp.TENANT = ${sqlLiteral(tenant)} AND tp.SVR_IP = ${sqlLiteral(serverIp)} AND tp.SVR_PORT = ${serverPort} AND tp.PROXY_SESSID ${proxySessionPredicate}`;+ const targetLockIdentity = `tl.SESSION_ID = ${id} AND tl.SVR_IP = ${sqlLiteral(serverIp)} AND tl.SVR_PORT = ${serverPort}`;+ const tenantIds = `SELECT DISTINCT tl.TENANT_ID FROM GV$OB_LOCKS tl WHERE ${targetLockIdentity} AND EXISTS (SELECT 1 FROM GV$OB_PROCESSLIST tp WHERE ${targetSessionIdentity})`;+ return `SELECT l.SVR_IP, l.SVR_PORT, l.TENANT_ID, l.TRANS_ID, l.SESSION_ID, l.TYPE, TO_CHAR(l.ID1), TO_CHAR(l.ID2), TO_CHAR(l.ID3), l.LMODE, l.REQUEST, l.CTIME, l.BLOCK, p."USER" AS SESSION_USER, p.STATE AS SESSION_STATE FROM GV$OB_LOCKS l LEFT JOIN GV$OB_PROCESSLIST p ON p.ID = l.SESSION_ID AND p.TENANT = ${sqlLiteral(tenant)} AND p.SVR_IP = l.SVR_IP AND p.SVR_PORT = l.SVR_PORT WHERE l.TENANT_ID IN (${tenantIds}) AND ((l.SESSION_ID = ${id} AND l.SVR_IP = ${sqlLiteral(serverIp)} AND l.SVR_PORT = ${serverPort}) OR EXISTS (SELECT 1 FROM GV$OB_LOCKS tl WHERE ${targetLockIdentity} AND tl.TYPE = l.TYPE AND tl.ID1 = l.ID1 AND tl.ID2 = l.ID2 AND tl.ID3 = l.ID3)) ORDER BY l.TYPE, l.ID1, l.ID2, l.SESSION_ID, l.TRANS_ID`;+}++export const ORACLE_SESSION_DRIVER_COLUMNS = ORACLE_COLUMNS;+export const OCEANBASE_SESSION_DRIVER_COLUMNS = OCEANBASE_COLUMNS;+export const ORACLE_SESSION_VERSION_SQL = ORACLE_VERSION_SQL;diff --git a/apps/desktop/src/lib/database/processListDrivers.ts b/apps/desktop/src/lib/database/processListDrivers.tsindex e92533f63b..6717e89e2c 100644--- a/apps/desktop/src/lib/database/processListDrivers.ts+++ b/apps/desktop/src/lib/database/processListDrivers.ts@@ -31,6 +31,27 @@ import {PG_PROCESS_LIST_LEGACY_SQL,PG_PROCESS_LIST_SQL,} from "./postgresProcessList";+import {+ buildOceanbaseKillConnectionBlock,+ canTerminateOceanbaseSession,+ buildOceanbaseLockDetailsSql,+ buildOceanbaseSessionListSql,+ buildOracleKillSessionBlock,+ buildOracleLockDetailsSql,+ buildOracleOwnSessionSql,+ buildOracleSessionListSql,+ canTerminateOracleSession,+ mapOceanbaseSessions,+ oceanbaseSessionRowKey,+ mapOracleSessions,+ oracleSessionRowKey,+ oracleTargetIsSelf,+ ORACLE_SESSION_DRIVER_COLUMNS,+ OCEANBASE_SESSION_DRIVER_COLUMNS,+ ORACLE_SESSION_VERSION_SQL,+ OCEANBASE_OWN_SESSION_SQL,+ type OracleSessionTarget,+} from "./oracleSessionManagement";/*** Engine-agnostic operations model. Each supported engine contributes a driver@@ -39,7 +60,7 @@ import {*//** A displayable row. `id` is the session/process id; transaction drivers use a separate composite target. */-export type ProcessRow = { id: number } & Record<string, string | number | null>;+export type ProcessRow = { id: number | string } & Record<string, string | number | null>;export interface ProcessColumn {/** Key into the mapped row. */@@ -59,7 +80,17 @@ export interface ProcessListDriver {mode?: "transaction";/** Execution database for a system-wide administrative view. */database?: string;- /** Stable row key when a server-local session id is not globally unique. */+ /** Probe a verified engine version before choosing version-dependent SQL. */+ versionSql?: string;+ listSqlForVersion?(major: number): string;+ ownSessionSqlForVersion?(major: number): string;+ /** Keep session-manager reads and writes off the editor's client transaction. */+ useClientSession?: boolean;+ /** Prevent a manager-wide termination from inheriting schema-scoped confirmation. */+ productionGuardScope?: "connection";+ /** Some session identities are strings or composite and must be matched by the driver. */+ ownSessionMatches?(row: ProcessRow, ownSessionRow: unknown[] | null): boolean;+ /** Stable identity for selections and post-action readback. */rowKey?(row: ProcessRow): string;/** Whether the panel offers multi-selection and batch query cancellation. */supportsBatchCancel?: boolean;@@ -100,6 +131,15 @@ export interface ProcessListDriver {* only offer query cancellation, because they cannot close a session over the wire.*/buildTerminateSessionSql?(id: number): string;+ /** Build a safe action from the full selected-row snapshot. */+ buildTerminateSessionSqlForRow?(row: ProcessRow, versionMajor?: number): string;+ /** Disable unsafe/unsupported per-row termination targets before confirmation. */+ canTerminateSessionRow?(row: ProcessRow): boolean;+ terminateRowUnavailableReason?(row: ProcessRow): string | undefined;+ /** Build a lock/holder detail query for the selected row. */+ buildLockDetailsSql?(row: ProcessRow, versionMajor?: number): string;+ /** These drivers expose only per-row management, not multi-selection. */+ supportsBatchTerminate?: boolean;/** Build the compatibility statement used when the primary terminate function is unavailable. */buildFallbackTerminateSessionSql?(id: number): string;/** Restrict terminate fallback attempts to known compatibility failures. */@@ -220,6 +260,48 @@ const XUGU_DRIVER: ProcessListDriver = {buildKillTransactionSql: (row) => buildXuguKillTransactionSql(row as unknown as ReturnType<typeof mapXuguTransactionRows>[number]),};+const ORACLE_DRIVER: ProcessListDriver = {+ versionSql: ORACLE_SESSION_VERSION_SQL,+ listSql: buildOracleSessionListSql(false),+ listSqlForVersion: (major) => buildOracleSessionListSql(major < 12),+ ownSessionSql: buildOracleOwnSessionSql(false),+ ownSessionSqlForVersion: (major) => buildOracleOwnSessionSql(major < 12),+ useClientSession: true,+ productionGuardScope: "connection",+ ownSessionMatches: oracleTargetIsSelf,+ rowKey: oracleSessionRowKey,+ columns: ORACLE_SESSION_DRIVER_COLUMNS,+ defaultSortKey: "id",+ maxRows: 5001,+ mapRows: mapOracleSessions,+ buildTerminateSessionSqlForRow: (row, major) => buildOracleKillSessionBlock(row as OracleSessionTarget, (major ?? 12) < 12),+ canTerminateSessionRow: canTerminateOracleSession,+ terminateRowUnavailableReason: (row) => (canTerminateOracleSession(row) ? undefined : "processList.oracleIdentityUnavailable"),+ buildLockDetailsSql: (row, major) => buildOracleLockDetailsSql(row as OracleSessionTarget, (major ?? 12) < 12),+ supportsBatchTerminate: false,+};++const OCEANBASE_ORACLE_DRIVER: ProcessListDriver = {+ listSql: buildOceanbaseSessionListSql(),+ ownSessionSql: OCEANBASE_OWN_SESSION_SQL,+ useClientSession: true,+ productionGuardScope: "connection",+ ownSessionMatches: (row, own) => !!own && String(row.id) === String(own[0] ?? "") && String(row.user) === String(own[1] ?? "") && String(row.tenant) === String(own[2] ?? ""),+ rowKey: oceanbaseSessionRowKey,+ columns: OCEANBASE_SESSION_DRIVER_COLUMNS,+ defaultSortKey: "time",+ maxRows: 5001,+ mapRows: mapOceanbaseSessions,+ buildTerminateSessionSqlForRow: buildOceanbaseKillConnectionBlock,+ canTerminateSessionRow: canTerminateOceanbaseSession,+ terminateRowUnavailableReason: (row) => {+ if (row.proxySessionId !== null && row.proxySessionId !== undefined && String(row.proxySessionId) !== "") return "processList.oracleProxyUnsupported";+ return canTerminateOceanbaseSession(row) ? undefined : "processList.oracleIdentityUnavailable";+ },+ buildLockDetailsSql: buildOceanbaseLockDetailsSql,+ supportsBatchTerminate: false,+};+/** Resolve the process-list driver for a connection, or null if unsupported. */export function resolveProcessListDriver(dbType: DatabaseType | undefined): ProcessListDriver | null {if (supportsMysqlProcessList(dbType)) return MYSQL_DRIVER;@@ -227,6 +309,8 @@ export function resolveProcessListDriver(dbType: DatabaseType | undefined): Procif (dbType === "opengauss") return OPENGAUSS_DRIVER;if (dbType === "kingbase") return KINGBASE_DRIVER;if (dbType === "xugu") return XUGU_DRIVER;+ if (dbType === "oracle") return ORACLE_DRIVER;+ if (dbType === "oceanbase-oracle") return OCEANBASE_ORACLE_DRIVER;return null;}diff --git a/apps/desktop/src/lib/database/processListSelection.ts b/apps/desktop/src/lib/database/processListSelection.tsindex 8639fae3c4..5a4486e56f 100644--- a/apps/desktop/src/lib/database/processListSelection.ts+++ b/apps/desktop/src/lib/database/processListSelection.ts@@ -2,12 +2,12 @@ import { orderedListRangeIndices, orderedListSelectionIntent } from "../selectio/** Rows are identified by the server session id, matching the process list grid. */export interface ProcessListSelectionRow {- id: number;+ id: string | number;}export interface ProcessListSelectionState {- selected: Set<number>;- anchorId: number | null;+ selected: Set<string | number>;+ anchorId: string | number | null;}/**@@ -22,7 +22,7 @@ export interface ProcessListSelectionState {* The next state is derived from the current selection because the grid binds* `:checked` without cancelling the native checkbox activation.*/-export function processListSelectionAfterClick(rows: ProcessListSelectionRow[], state: ProcessListSelectionState, id: number, event: Pick<MouseEvent, "shiftKey" | "metaKey" | "ctrlKey">): ProcessListSelectionState {+export function processListSelectionAfterClick(rows: ProcessListSelectionRow[], state: ProcessListSelectionState, id: string | number, event: Pick<MouseEvent, "shiftKey" | "metaKey" | "ctrlKey">): ProcessListSelectionState {const targetIndex = rows.findIndex((row) => row.id === id);if (targetIndex < 0) return state;const checked = !state.selected.has(id);diff --git a/apps/desktop/src/lib/database/productionExecutionGuard.ts b/apps/desktop/src/lib/database/productionExecutionGuard.tsindex 303b8115bd..dfd31282ea 100644--- a/apps/desktop/src/lib/database/productionExecutionGuard.ts+++ b/apps/desktop/src/lib/database/productionExecutionGuard.ts@@ -1,5 +1,5 @@import { useProductionSafetyStore } from "@/stores/productionSafetyStore";-import { assessProductionSql, productionContextForDatabase } from "@/lib/database/productionSafety";+import { assessProductionSql, productionContextForDatabase, productionDatabases } from "@/lib/database/productionSafety";import { ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess";import type { ConnectionConfig } from "@/types/database";@@ -37,6 +37,8 @@ export interface ProductionContextExecutionGuardOptions<T> {/** Review text shown in the production confirmation dialog (SQL or shell preview). */reviewText: string;source?: string;+ /** Use every production marker for connection-wide mutations; omitted keeps the existing database scope. */+ scope?: "database" | "connection";execute: () => Promise<T>;}@@ -48,12 +50,19 @@ export async function executeWithProductionContextGuard<T>(options: ProductionCoif (!(await ensureReadOnlyWriteAccess({ connection: options.connection, sql: options.reviewText, source: options.source, treatAsMutation: true }))) {return undefined;}- const productionContext = productionContextForDatabase(options.connection, options.database);+ const productionContext =+ options.scope === "connection"+ ? (() => {+ const databases = productionDatabases(options.connection);+ const active = Boolean(options.connection?.is_production || databases.length > 0);+ return { active, reason: active ? ("connection" as const) : undefined, databases };+ })()+ : productionContextForDatabase(options.connection, options.database);if (productionContext.active) {const confirmed = await useProductionSafetyStore().requestConfirmation({sql: options.reviewText,connectionName: options.connection?.name,- database: options.database ?? undefined,+ database: options.scope === "connection" ? undefined : (options.database ?? undefined),productionDatabases: productionContext.databases,source: options.source,});