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(postgres): support creating foreign tables
Acd-kk479424055419
diff --git a/apps/desktop/src/components/structure/PostgresForeignTableOptionsEditor.vue b/apps/desktop/src/components/structure/PostgresForeignTableOptionsEditor.vuenew file mode 100644index 0000000000..111628f784--- /dev/null+++ b/apps/desktop/src/components/structure/PostgresForeignTableOptionsEditor.vue@@ -0,0 +1,78 @@+<script setup lang="ts">+import { onBeforeUnmount, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Plus, RefreshCw, X } from "@lucide/vue";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { SearchableSelect } from "@/components/ui/searchable-select";+import * as api from "@/lib/backend/api";+import { translateBackendError } from "@/i18n/backend-errors";+import { POSTGRES_FOREIGN_SERVERS_SQL, type PostgresForeignTableDraft } from "@/lib/table/postgresForeignTable";++const draft = defineModel<PostgresForeignTableDraft>({ required: true });+const props = defineProps<{ connectionId: string; database: string; catalog?: string; disabled?: boolean }>();+const { t } = useI18n();+const servers = ref<string[]>([]);+const loading = ref(false);+const error = ref("");+let request = 0;++async function loadServers() {+ const current = ++request;+ loading.value = true;+ error.value = "";+ servers.value = [];+ try {+ const result = await api.executeQuery(props.connectionId, props.database, POSTGRES_FOREIGN_SERVERS_SQL, undefined, undefined, { catalog: props.catalog, maxRows: 10000 });+ if (current !== request) return;+ servers.value = result.rows.map((row) => String(row[0] ?? "")).filter(Boolean);+ } catch (reason) {+ if (current === request) error.value = translateBackendError(t, String(reason));+ } finally {+ if (current === request) loading.value = false;+ }+}++function setOption(index: number, key: "name" | "value", value: string) {+ draft.value = { ...draft.value, options: draft.value.options.map((option, position) => (position === index ? { ...option, [key]: value } : option)) };+}++watch(+ () => [props.connectionId, props.database, props.catalog],+ () => void loadServers(),+ { immediate: true },+);+onBeforeUnmount(() => {+ request += 1;+});+</script>++<template>+ <fieldset data-postgres-foreign-table-options class="max-h-64 shrink-0 space-y-2 overflow-y-auto rounded-md border p-3" :disabled="disabled">+ <div class="flex flex-wrap items-center gap-2">+ <label class="text-muted-foreground">{{ t("postgresForeignTable.server") }}</label>+ <SearchableSelect+ v-model="draft.server"+ :options="servers"+ :placeholder="t('postgresForeignTable.serverPlaceholder')"+ :search-placeholder="t('postgresForeignTable.serverPlaceholder')"+ :empty-text="t('postgresForeignTable.noServers')"+ :allow-custom="true"+ :loading="loading"+ :disabled="disabled"+ trigger-class="w-64 max-w-full"+ />+ <Button variant="ghost" size="icon-xs" :disabled="disabled || loading" :title="t('common.refresh')" @click="loadServers"><RefreshCw class="h-4 w-4" :class="{ 'animate-spin': loading }" /></Button>+ </div>+ <p v-if="error" role="alert" class="text-xs text-destructive">{{ error }}</p>+ <p v-else-if="!loading && !servers.length" class="text-xs text-muted-foreground">{{ t("postgresForeignTable.noServers") }}</p>+ <p class="text-xs text-muted-foreground">{{ t("postgresForeignTable.optionsHelp") }}</p>+ <div v-for="(option, index) in draft.options" :key="index" class="flex items-center gap-2" data-foreign-table-option>+ <Input :model-value="option.name" :aria-label="t('postgresForeignTable.optionName')" :placeholder="t('postgresForeignTable.optionName')" class="max-w-56 font-mono" :disabled="disabled" @update:model-value="setOption(index, 'name', String($event))" />+ <Input :model-value="option.value" :aria-label="t('postgresForeignTable.optionValue')" :placeholder="t('postgresForeignTable.optionValue')" class="max-w-md font-mono" :disabled="disabled" @update:model-value="setOption(index, 'value', String($event))" />+ <Button variant="ghost" size="icon-xs" :title="t('common.delete')" :disabled="disabled" @click="draft = { ...draft, options: draft.options.filter((_, position) => position !== index) }"><X class="h-4 w-4" /></Button>+ </div>+ <Button variant="outline" size="sm" :disabled="disabled" @click="draft = { ...draft, options: [...draft.options, { name: '', value: '' }] }"><Plus class="h-4 w-4" />{{ t("postgresForeignTable.addOption") }}</Button>+ <p class="text-xs text-muted-foreground">{{ t("postgresForeignTable.constraintsHelp") }}</p>+ </fieldset>+</template>diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex 39016fdc4b..74f8c2906e 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import PostgresForeignTableOptionsEditor from "@/components/structure/PostgresForeignTableOptionsEditor.vue";+import { buildPostgresForeignTableOptions, emptyPostgresForeignTableDraft, restorePostgresForeignTableDraft, supportsPostgresForeignTableCreation } from "@/lib/table/postgresForeignTable";import { Compartment } from "@codemirror/state";import { keymap as codeMirrorKeymap } from "@codemirror/view";import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";@@ -1677,6 +1679,18 @@ function onIndexColResize(e: MouseEvent, col: number) {const connection = computed(() => (props.connectionId ? store.getConfig(props.connectionId) : undefined));const databaseType = computed(() => tableStructureDatabaseTypeForConnection(connection.value));+const postgresForeignTable = ref(emptyPostgresForeignTableDraft());+const canCreateForeignTable = computed(() => !props.tableName && supportsPostgresForeignTableCreation(connection.value));+const isCreatingForeignTable = computed(() => canCreateForeignTable.value && postgresForeignTable.value.enabled);++function setCreateTableKind(kind: string) {+ const foreign = kind === "foreign";+ if (foreign && (columns.value.some((column) => !column.markedForDrop && (column.isPrimaryKey || column.extra.autoIncrement || column.extra.identity)) || indexes.value.some((index) => !index.markedForDrop) || foreignKeys.value.some((key) => !key.markedForDrop) || createPartitioningEnabled.value)) {+ toast(t("postgresForeignTable.removeUnsupported"));+ return;+ }+ postgresForeignTable.value.enabled = foreign;+}const usesNativeMysqlIndexNames = computed(() => {const profile = connection.value?.driver_profile?.trim().toLowerCase();return databaseType.value === "mysql" && connection.value?.db_type === "mysql" && (!profile || profile === "mysql");@@ -1684,7 +1698,10 @@ const usesNativeMysqlIndexNames = computed(() => {const supportsCharacterLengthUnits = computed(() => databaseType.value === "dameng" || databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");const usesMysql8SafeDefaults = computed(() => databaseType.value === "mysql" && connection.value?.db_type === "mysql" && connection.value.driver_profile === "mysql");const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type, connection.value?.database_info?.productVersion, starrocksAlterContext.value?.model));-const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value, { connectionType: connection.value?.db_type, exactIdentity: props.exactIdentity }));+const tableMetadataCapabilities = computed(() => {+ const capabilities = getTableMetadataCapabilities(databaseType.value, { connectionType: connection.value?.db_type, exactIdentity: props.exactIdentity });+ return isCreatingForeignTable.value ? { ...capabilities, indexes: false, foreignKeys: false, constraints: false, partitions: false } : capabilities;+});const structureDialect = computed(() => structureCapabilities.value.dialect);const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment || (!isCreateMode.value && databaseType.value === "starrocks" && !getStarRocksCapabilities(connection.value?.database_info?.productVersion).tableComment));const dynamicDataTypeOptions = ref<string[]>([]);@@ -2964,6 +2981,7 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {originalMysqlTableCollation: originalMysqlTableCollation.value,physicalOptions: cloneDraftValue(physicalOptions.value),starrocksPhysicalOptions: cloneDraftValue(starrocksPhysicalOptions.value),+ postgresForeignTable: canCreateForeignTable.value ? cloneDraftValue(postgresForeignTable.value) : undefined,starrocksSortColumns: starrocksSortColumns.value ? [...starrocksSortColumns.value] : undefined,tableOwner: tableOwner.value,originalTableOwner: originalTableOwner.value,@@ -3047,6 +3065,7 @@ function restoreDraft(draft: TableStructureEditorDraft) {}ddlDraft.value = draft.ddlDraft ?? null;newTableName.value = draft.newTableName || "";+ postgresForeignTable.value = restorePostgresForeignTableDraft(draft.postgresForeignTable);tableComment.value = draft.tableComment || "";originalTableComment.value = draft.originalTableComment || "";mysqlAutoIncrementValue.value = draft.mysqlAutoIncrementValue;@@ -3225,6 +3244,7 @@ function hasPendingStructureChanges(includeExistingPrimaryKey = true, includeOraif (isCreateMode.value) {return (!!newTableName.value.trim() ||+ isCreatingForeignTable.value ||!!tableComment.value.trim() ||mysqlTableEngine.value !== originalMysqlTableEngine.value ||hasTablePhysicalOptions(physicalOptions.value) ||@@ -3739,7 +3759,11 @@ async function refreshSqlPreview() {isCreateMode.value? createPartitioningEnabled.value? api.buildCreatePartitionedTableSql({ options, partitioning: { kind: createPartitioningKind.value, columns: createPartitioningColumns.value, expression: createPartitioningExpression.value } })- : api.buildCreateTableSql(options, connection.value?.database_info?.productVersion, databaseType.value === "starrocks" ? buildStarRocksDialectOptions(starrocksPhysicalOptions.value) : undefined)+ : api.buildCreateTableSql(+ options,+ connection.value?.database_info?.productVersion,+ isCreatingForeignTable.value ? { postgresForeignTable: buildPostgresForeignTableOptions(postgresForeignTable.value) } : databaseType.value === "starrocks" ? buildStarRocksDialectOptions(starrocksPhysicalOptions.value) : undefined,+ ): hasSqliteTypeChange.value? api.previewSqliteTableStructureChange(props.connectionId, props.database, options): databaseType.value === "starrocks"@@ -3905,6 +3929,7 @@ function resetState() {ddlFetched.value = false;loadedMetadataFacets.clear();newTableName.value = "";+ postgresForeignTable.value = emptyPostgresForeignTableDraft();tableComment.value = "";originalTableComment.value = "";mysqlAutoIncrementValue.value = undefined;@@ -5003,6 +5028,13 @@ function applyColumnTemplate(templateId: string) {createId: uuid,});if (!templateColumns.length) return;+ if (isCreatingForeignTable.value) {+ for (const column of templateColumns) {+ column.isPrimaryKey = false;+ column.extra.autoIncrement = false;+ column.extra.identity = undefined;+ }+ }const insertAt = resolveInsertColumnIndex(columns.value, selectedColumnId.value);columns.value.splice(insertAt, 0, ...templateColumns);const lastTemplateColumn = templateColumns[templateColumns.length - 1];@@ -5881,6 +5913,7 @@ function isColumnCharsetDisabled(column: EditableStructureColumn): boolean {}function isPrimaryKeyDisabled(column: EditableStructureColumn): boolean {+ if (isCreatingForeignTable.value) return true;if (column.markedForDrop) return true;if (isCreateMode.value || structureCapabilities.value.alterPrimaryKey) return false;if (!structureCapabilities.value.addPrimaryKey) return true;@@ -8041,6 +8074,7 @@ watch(originalMysqlTableEngine,physicalOptions,starrocksPhysicalOptions,+ postgresForeignTable,starrocksSortColumns,mysqlTableEngineLoading,mysqlTableEngineLoadError,@@ -8255,10 +8289,22 @@ watch(/><div v-if="isCreateMode" class="flex shrink-0 items-center gap-2">+ <template v-if="canCreateForeignTable">+ <label class="shrink-0 font-medium text-muted-foreground">{{ t("postgresForeignTable.tableKind") }}</label>+ <Select :model-value="isCreatingForeignTable ? 'foreign' : 'table'" :disabled="saving" @update:model-value="setCreateTableKind(String($event))">+ <SelectTrigger data-create-table-kind class="w-36"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="table">{{ t("postgresForeignTable.regularTable") }}</SelectItem>+ <SelectItem value="foreign">{{ t("postgresForeignTable.foreignTable") }}</SelectItem>+ </SelectContent>+ </Select>+ </template><label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.tableName") }}</label><Input v-model="newTableName" :placeholder="t('contextMenu.duplicateNamePlaceholder')" :class="[structureControlClass, 'max-w-[220px]']" /></div>+ <PostgresForeignTableOptionsEditor v-if="isCreatingForeignTable" v-model="postgresForeignTable" :connection-id="props.connectionId" :database="props.database" :catalog="props.catalog" :disabled="saving" />+<div class="flex shrink-0 items-center gap-2"><label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.comment") }}</label><Input v-model="tableComment" :placeholder="t('structureEditor.tableCommentPlaceholder')" :class="[structureControlClass, 'max-w-[320px]']" :disabled="isTableCommentDisabled" data-table-comment-input />@@ -9066,6 +9112,7 @@ watch(<template v-else-if="structureDialect === 'postgres'"><Select:model-value="column.extra.identity?.generation ?? 'none'"+ :disabled="isCreatingForeignTable"@update:model-value="(value: any) => {const generation = String(value ?? '');diff --git a/apps/desktop/src/components/structure/__tests__/PostgresForeignTableOptionsEditor.spec.ts b/apps/desktop/src/components/structure/__tests__/PostgresForeignTableOptionsEditor.spec.tsnew file mode 100644index 0000000000..4d2224a7c3--- /dev/null+++ b/apps/desktop/src/components/structure/__tests__/PostgresForeignTableOptionsEditor.spec.ts@@ -0,0 +1,115 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, reactive, ref, type App } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { PostgresForeignTableDraft } from "@/lib/table/postgresForeignTable";++const mocks = vi.hoisted(() => ({ executeQuery: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery }));+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("@/components/ui/searchable-select", () => ({+ SearchableSelect: defineComponent({+ props: { modelValue: String, options: Array, disabled: Boolean },+ emits: ["update:modelValue"],+ setup:+ (props, { emit }) =>+ () =>+ h("div", [+ h("input", { "data-server-picker": "", value: props.modelValue, disabled: props.disabled, onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) }),+ h(+ "datalist",+ (props.options ?? []).map((option) => h("option", { value: String(option) })),+ ),+ ]),+ }),+}));+import PostgresForeignTableOptionsEditor from "@/components/structure/PostgresForeignTableOptionsEditor.vue";++const apps: App[] = [];+const result = (names: string[]) => ({ columns: ["name", "wrapper"], rows: names.map((name) => [name, "postgres_fdw"]) });+beforeEach(() => {+ mocks.executeQuery.mockReset();+ mocks.executeQuery.mockResolvedValue(result(["remote server"]));+});+afterEach(() => {+ apps.splice(0).forEach((app) => app.unmount());+ document.body.innerHTML = "";+});++async function mountEditor(initial: PostgresForeignTableDraft = { enabled: true, server: "", options: [] }) {+ const scope = reactive({ connectionId: "conn-a", database: "db-a", catalog: "catalog-a", disabled: false });+ const draft = ref(initial);+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ setup: () => () =>+ h(PostgresForeignTableOptionsEditor, {+ ...scope,+ modelValue: draft.value,+ "onUpdate:modelValue": (value) => {+ draft.value = value;+ },+ }),+ });+ apps.push(app);+ app.mount(host);+ await nextTick();+ return { host, scope, draft };+}++function button(host: HTMLElement, key: string) {+ return [...host.querySelectorAll("button")].find((item) => item.textContent?.trim() === key || item.title === key)!;+}++function inputValue(input: HTMLInputElement, value: string) {+ input.value = value;+ input.dispatchEvent(new Event("input", { bubbles: true }));+}++describe("PostgreSQL foreign table options editor", () => {+ it("loads server choices in the selected database and updates the draft", async () => {+ const { host, draft } = await mountEditor();+ await vi.waitFor(() => expect(host.querySelector("option")?.getAttribute("value")).toBe("remote server"));+ expect(mocks.executeQuery).toHaveBeenCalledWith("conn-a", "db-a", expect.any(String), undefined, undefined, { catalog: "catalog-a", maxRows: 10000 });+ inputValue(host.querySelector("[data-server-picker]")!, 'server"name');+ await nextTick();+ button(host, "postgresForeignTable.addOption").click();+ await nextTick();+ const inputs = host.querySelectorAll<HTMLInputElement>("[data-foreign-table-option] input");+ inputValue(inputs[0]!, "schema_name");+ inputValue(inputs[1]!, "remote's schema");+ await nextTick();+ expect(draft.value.server).toBe('server"name');+ expect(draft.value.options).toEqual([{ name: "schema_name", value: "remote's schema" }]);+ button(host, "common.delete").click();+ await nextTick();+ expect(draft.value.options).toEqual([]);+ });++ it("keeps a restored server and options when metadata loading fails", async () => {+ mocks.executeQuery.mockRejectedValue(new Error("permission denied"));+ const initial = { enabled: true, server: "saved server", options: [{ name: "filename", value: "/data/input.csv" }] };+ const { host, draft } = await mountEditor(initial);+ await vi.waitFor(() => expect(host.querySelector('[role="alert"]')).toBeTruthy());+ expect(draft.value).toEqual(initial);+ expect(host.querySelector<HTMLInputElement>("[data-server-picker]")!.value).toBe("saved server");+ });++ it("discards stale choices when the target database changes", async () => {+ let old!: (value: ReturnType<typeof result>) => void;+ mocks.executeQuery.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ old = resolve;+ }),+ );+ const { host, scope } = await mountEditor();+ mocks.executeQuery.mockResolvedValue(result(["new server"]));+ scope.database = "db-b";+ await nextTick();+ await vi.waitFor(() => expect(host.querySelector("option")?.value).toBe("new server"));+ old(result(["old server"]));+ await nextTick();+ await nextTick();+ expect([...host.querySelectorAll("option")].map((option) => option.value)).toEqual(["new server"]);+ });+});diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.tsindex 96b35e7772..da90aa586d 100644--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts@@ -336,7 +336,7 @@ type SavedPayload = { commentChanged: boolean; createdTableName?: string };* completion, and return what the `saved` event carried — the exact string* the converted edit tab would be assigned as its table name.*/-async function createTableAndCaptureSaved(dbType: string, newTableName: string): Promise<SavedPayload> {+async function createTableAndCaptureSaved(dbType: string, newTableName: string, postgresForeignTable?: TableStructureEditorDraft["postgresForeignTable"]): Promise<SavedPayload> {const previousDbType = mocks.connection.db_type;mocks.connection.db_type = dbType;let saved: SavedPayload | undefined;@@ -351,6 +351,7 @@ async function createTableAndCaptureSaved(dbType: string, newTableName: string):dirty: true,activeTab: "columns",newTableName,+ postgresForeignTable,tableComment: "",originalTableComment: "",columns: [{ id: "new:id", name: "id", dataType: "number", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false }],@@ -413,6 +414,22 @@ afterEach(() => {});describe("TableStructureEditor created-table name write-back", () => {+ it("restores a PostgreSQL foreign table draft and saves its generated SQL", async () => {+ const foreign = {+ enabled: true,+ server: "remote server",+ options: [+ { name: "schema_name", value: "source" },+ { name: "table_name", value: "remote_table" },+ ],+ };+ mocks.buildCreateTableSql.mockResolvedValue({ statements: ['CREATE FOREIGN TABLE "external_data" (id integer) SERVER "remote server"'], warnings: [] });+ const saved = await createTableAndCaptureSaved("postgres", "external_data", foreign);+ expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ databaseType: "postgres", tableName: "external_data" }), expect.anything(), { postgresForeignTable: { server: foreign.server, options: foreign.options } });+ expect(mocks.executeBatch.mock.calls.some((call) => JSON.stringify(call).includes("CREATE FOREIGN TABLE"))).toBe(true);+ expect(saved.createdTableName).toBe("external_data");+ });+it("emits the upper-folded storage name for a plain Oracle table", async () => {const saved = await createTableAndCaptureSaved("oracle", "MyTable");expect(saved.createdTableName).toBe("MYTABLE");diff --git a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts b/apps/desktop/src/i18n/__tests__/featureMessages.spec.tsindex a5437b2ea6..15de3ecdaa 100644--- a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts+++ b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts@@ -87,6 +87,7 @@ const FEATURE_MESSAGES: FeatureMessages[] = [{ feature: "offline Agent import", keys: ["driverStore.offlineImport*", "driverStore.offlineJreImport*"] },{ feature: "driver runtime connection-owned message (#10412)", keys: ["driverStore.runtimeControlConnectionOwned"], translated: true },{ feature: "multi-database execution and export progress", keys: ["multiDbExecute.*", "exportProgress.*"], locales: ["en", "zh-CN"] },+ { feature: "PostgreSQL foreign table creation", keys: ["postgresForeignTable.*"], locales: ["en", "es", "it", "ja", "ko", "pt-BR", "ru", "th", "zh-CN", "zh-TW"], translated: true },{ feature: "process list batch terminate", keys: under("processList", ["batchTerminate", "batchTerminateTitle", "batchTerminateConfirm", "batchTerminateRunning", "batchTerminateSummary"]) },{ feature: "cached result fallback", keys: ["grid.cachedResultUnavailable", "grid.reexecuteQuery"] },{ feature: "Nacos global replace", keys: ["nacos.contentReplace*", "nacos.replaceHistory.*"], locales: EXCEPT_AZ_TR, translated: true },diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex ac17cc2816..6de3162710 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -6938,6 +6938,20 @@ export default {sortDesc: "Descending",sortBy: "Sort by",},+ postgresForeignTable: {+ tableKind: "Table type",+ regularTable: "Regular table",+ foreignTable: "Foreign table",+ server: "Foreign server",+ serverPlaceholder: "Select or enter an existing server",+ noServers: "No accessible foreign servers found. Create a foreign server and grant USAGE before creating a foreign table.",+ optionsHelp: "Options depend on the foreign data wrapper. For postgres_fdw, use schema_name and table_name to map the remote table.",+ optionName: "Option name",+ optionValue: "Option value",+ addOption: "Add option",+ constraintsHelp: "Foreign tables use an existing foreign server. Primary keys, indexes, foreign keys and identity columns are unavailable in this editor.",+ removeUnsupported: "Remove primary keys, indexes, foreign keys, identity settings and partitioning before selecting a foreign table.",+ },structureEditor: {unsetDefault: "No default value",title: "Edit Table Structure",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex c26a5cf9e7..7696bfd86e 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -5965,6 +5965,20 @@ export default withEnglishFallback({compactCardWidth: "Ancho mínimo de tarjeta compacta",configureColumns: "Configurar columnas de visualización",},+ postgresForeignTable: {+ tableKind: "Tipo de tabla",+ regularTable: "Tabla normal",+ foreignTable: "Tabla externa",+ server: "Servidor externo",+ serverPlaceholder: "Seleccione o introduzca un servidor externo existente",+ noServers: "No hay servidores externos disponibles. Cree primero un servidor externo y conceda el permiso USAGE antes de crear una tabla externa.",+ optionsHelp: "Las opciones dependen del contenedor de datos externos. Con postgres_fdw, schema_name y table_name permiten vincular la tabla remota.",+ optionName: "Nombre de la opción",+ optionValue: "Valor de la opción",+ addOption: "Añadir opción",+ constraintsHelp: "Las tablas externas utilizan un servidor externo existente. Este editor no crea claves primarias, índices, claves foráneas ni columnas de identidad para tablas externas.",+ removeUnsupported: "Elimine las claves primarias, los índices, las claves foráneas, las columnas de identidad y la configuración de particiones antes de seleccionar una tabla externa.",+ },structureEditor: {mysqlDataTypeHelp: {tinyint: "Entero de 1 byte: con signo -128 a 127; sin signo 0 a 255.",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 579835e651..f9619b295b 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -5785,6 +5785,20 @@ export default withEnglishFallback({compactCardWidth: "Larghezza minima scheda compatta",configureColumns: "Configura colonne visualizzate",},+ postgresForeignTable: {+ tableKind: "Tipo di tabella",+ regularTable: "Tabella normale",+ foreignTable: "Tabella esterna",+ server: "Server esterno",+ serverPlaceholder: "Seleziona o inserisci un server esterno esistente",+ noServers: "Nessun server esterno disponibile. Crea prima un server esterno e concedi il privilegio USAGE prima di creare una tabella esterna.",+ optionsHelp: "Le opzioni dipendono dal wrapper di dati esterni. Con postgres_fdw, schema_name e table_name consentono di mappare la tabella remota.",+ optionName: "Nome opzione",+ optionValue: "Valore opzione",+ addOption: "Aggiungi opzione",+ constraintsHelp: "Le tabelle esterne utilizzano un server esterno esistente. Questo editor non crea chiavi primarie, indici, chiavi esterne o colonne di identità per le tabelle esterne.",+ removeUnsupported: "Rimuovi chiavi primarie, indici, chiavi esterne, colonne di identità e configurazione delle partizioni prima di selezionare una tabella esterna.",+ },structureEditor: {mysqlDataTypeHelp: {tinyint: "Intero da 1 byte: con segno da -128 a 127, senza segno da 0 a 255.",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 15da052281..93c71f9370 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -5837,6 +5837,20 @@ export default withEnglishFallback({compactCardWidth: "コンパクトカードの最小幅",configureColumns: "表示列を設定",},+ postgresForeignTable: {+ tableKind: "テーブルの種類",+ regularTable: "通常のテーブル",+ foreignTable: "外部テーブル",+ server: "外部サーバー",+ serverPlaceholder: "既存の外部サーバーを選択または入力",+ noServers: "利用可能な外部サーバーがありません。外部テーブルを作成する前に、外部サーバーを作成して USAGE 権限を付与してください。",+ optionsHelp: "オプションは外部データラッパーによって異なります。postgres_fdw では schema_name と table_name でリモートテーブルを指定できます。",+ optionName: "オプション名",+ optionValue: "オプション値",+ addOption: "オプションを追加",+ constraintsHelp: "外部テーブルは既存の外部サーバーを使用します。このエディターでは、外部テーブルに主キー、インデックス、外部キー、IDENTITY 列を作成しません。",+ removeUnsupported: "外部テーブルを選択する前に、主キー、インデックス、外部キー、IDENTITY 列、パーティション設定を削除してください。",+ },structureEditor: {mysqlDataTypeHelp: {tinyint: "1 バイト整数。符号付きは -128~127、符号なしは 0~255 です。",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex cc47c4f653..41b2233bda 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -6056,6 +6056,20 @@ export default withEnglishFallback({compactCardWidth: "컴팩트 카드 최소 너비",configureColumns: "표시 열 구성",},+ postgresForeignTable: {+ tableKind: "테이블 유형",+ regularTable: "일반 테이블",+ foreignTable: "외부 테이블",+ server: "외부 서버",+ serverPlaceholder: "기존 외부 서버를 선택하거나 입력하세요",+ noServers: "사용 가능한 외부 서버가 없습니다. 외부 테이블을 만들기 전에 외부 서버를 생성하고 USAGE 권한을 부여하세요.",+ optionsHelp: "옵션은 외부 데이터 래퍼에 따라 다릅니다. postgres_fdw에서는 schema_name과 table_name으로 원격 테이블을 매핑할 수 있습니다.",+ optionName: "옵션 이름",+ optionValue: "옵션 값",+ addOption: "옵션 추가",+ constraintsHelp: "외부 테이블은 기존 외부 서버를 사용합니다. 이 편집기에서는 외부 테이블의 기본 키, 인덱스, 외래 키 또는 IDENTITY 열을 생성하지 않습니다.",+ removeUnsupported: "외부 테이블을 선택하기 전에 기본 키, 인덱스, 외래 키, IDENTITY 열 및 파티션 설정을 제거하세요.",+ },structureEditor: {createTitle: "테이블 만들기",editTabTitle: "편집: {tableName}",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 9d738d0b30..a4674bb2c1 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -5783,6 +5783,20 @@ export default withEnglishFallback({compactCardWidth: "Largura mínima do cartão compacto",configureColumns: "Configurar colunas de exibição",},+ postgresForeignTable: {+ tableKind: "Tipo de tabela",+ regularTable: "Tabela normal",+ foreignTable: "Tabela externa",+ server: "Servidor externo",+ serverPlaceholder: "Selecione ou informe um servidor externo existente",+ noServers: "Nenhum servidor externo disponível. Crie um servidor externo e conceda o privilégio USAGE antes de criar uma tabela externa.",+ optionsHelp: "As opções dependem do wrapper de dados externos. Com postgres_fdw, schema_name e table_name permitem mapear a tabela remota.",+ optionName: "Nome da opção",+ optionValue: "Valor da opção",+ addOption: "Adicionar opção",+ constraintsHelp: "As tabelas externas usam um servidor externo existente. Este editor não cria chaves primárias, índices, chaves estrangeiras ou colunas de identidade para tabelas externas.",+ removeUnsupported: "Remova as chaves primárias, os índices, as chaves estrangeiras, as colunas de identidade e a configuração de particionamento antes de selecionar uma tabela externa.",+ },structureEditor: {mysqlDataTypeHelp: {tinyint: "Inteiro de 1 byte: com sinal, de -128 a 127; sem sinal, de 0 a 255.",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 34f41489b4..544f15e8a8 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -6539,6 +6539,20 @@ export default withEnglishFallback({compactCardWidth: "Минимальная ширина компактной карточки",configureColumns: "Настроить отображаемые столбцы",},+ postgresForeignTable: {+ tableKind: "Тип таблицы",+ regularTable: "Обычная таблица",+ foreignTable: "Внешняя таблица",+ server: "Внешний сервер",+ serverPlaceholder: "Выберите или введите существующий внешний сервер",+ noServers: "Нет доступных внешних серверов. Перед созданием внешней таблицы создайте внешний сервер и предоставьте право USAGE.",+ optionsHelp: "Параметры зависят от обёртки сторонних данных. В postgres_fdw параметры schema_name и table_name задают соответствующую удалённую таблицу.",+ optionName: "Имя параметра",+ optionValue: "Значение параметра",+ addOption: "Добавить параметр",+ constraintsHelp: "Внешние таблицы используют существующий внешний сервер. Этот редактор не создаёт для внешних таблиц первичные ключи, индексы, внешние ключи или столбцы IDENTITY.",+ removeUnsupported: "Перед выбором внешней таблицы удалите первичные ключи, индексы, внешние ключи, столбцы IDENTITY и настройки секционирования.",+ },structureEditor: {createTitle: "Создание таблицы",editTabTitle: "Редактирование: {tableName}",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 10551932f3..e005c38aa4 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -6806,6 +6806,20 @@ export default withEnglishFallback({compactCardWidth: "ความกว้างขั้นต่ำของการ์ดแบบกะทัดรัด",configureColumns: "กำหนดค่าคอลัมน์ที่แสดง",},+ postgresForeignTable: {+ tableKind: "ประเภทตาราง",+ regularTable: "ตารางปกติ",+ foreignTable: "ตารางภายนอก",+ server: "เซิร์ฟเวอร์ภายนอก",+ serverPlaceholder: "เลือกหรือป้อนเซิร์ฟเวอร์ภายนอกที่มีอยู่",+ noServers: "ไม่มีเซิร์ฟเวอร์ภายนอกที่พร้อมใช้งาน โปรดสร้างเซิร์ฟเวอร์ภายนอกและให้สิทธิ์ USAGE ก่อนสร้างตารางภายนอก",+ optionsHelp: "ตัวเลือกขึ้นอยู่กับตัวห่อหุ้มข้อมูลภายนอก สำหรับ postgres_fdw ให้ใช้ schema_name และ table_name เพื่อเชื่อมโยงกับตารางระยะไกล",+ optionName: "ชื่อตัวเลือก",+ optionValue: "ค่าตัวเลือก",+ addOption: "เพิ่มตัวเลือก",+ constraintsHelp: "ตารางภายนอกใช้เซิร์ฟเวอร์ภายนอกที่มีอยู่ ตัวแก้ไขนี้จะไม่สร้างคีย์หลัก ดัชนี คีย์นอก หรือคอลัมน์ IDENTITY สำหรับตารางภายนอก",+ removeUnsupported: "โปรดลบคีย์หลัก ดัชนี คีย์นอก คอลัมน์ IDENTITY และการตั้งค่าพาร์ทิชันก่อนเลือกตารางภายนอก",+ },structureEditor: {createTitle: "สร้าง Table",editTabTitle: "แก้ไข: {tableName}",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 6ba17a8824..e9f7f5fd03 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -6912,6 +6912,20 @@ export default withEnglishFallback({sortDesc: "降序",sortBy: "排序方式",},+ postgresForeignTable: {+ tableKind: "表类型",+ regularTable: "普通表",+ foreignTable: "外部表",+ server: "外部服务器",+ serverPlaceholder: "选择或输入已有的外部服务器",+ noServers: "没有可用的外部服务器。请先创建外部服务器并授予 USAGE 权限,再创建外部表。",+ optionsHelp: "选项由外部数据包装器决定。postgres_fdw 可通过 schema_name 和 table_name 映射远程表。",+ optionName: "选项名称",+ optionValue: "选项值",+ addOption: "添加选项",+ constraintsHelp: "外部表使用已有的外部服务器。本编辑器不为外部表创建主键、索引、外键或标识列。",+ removeUnsupported: "请先移除主键、索引、外键、标识列和分区配置,再选择外部表。",+ },structureEditor: {unsetDefault: "不设置默认值",title: "编辑表结构",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 33f074923f..10b4f21e77 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -5307,6 +5307,20 @@ export default withEnglishFallback({compactCardWidth: "緊湊卡片最小寬度",configureColumns: "設定顯示欄",},+ postgresForeignTable: {+ tableKind: "資料表類型",+ regularTable: "一般資料表",+ foreignTable: "外部資料表",+ server: "外部伺服器",+ serverPlaceholder: "選擇或輸入現有的外部伺服器",+ noServers: "沒有可用的外部伺服器。請先建立外部伺服器並授予 USAGE 權限,再建立外部資料表。",+ optionsHelp: "選項由外部資料包裝器決定。postgres_fdw 可透過 schema_name 和 table_name 對應遠端資料表。",+ optionName: "選項名稱",+ optionValue: "選項值",+ addOption: "新增選項",+ constraintsHelp: "外部資料表使用現有的外部伺服器。本編輯器不為外部資料表建立主鍵、索引、外鍵或識別欄位。",+ removeUnsupported: "請先移除主鍵、索引、外鍵、識別欄位及分割設定,再選擇外部資料表。",+ },structureEditor: {mysqlDataTypeHelp: {tinyint: "1 位元組整數:有號範圍 -128 至 127;無號範圍 0 至 255。",diff --git a/apps/desktop/src/lib/table/__tests__/postgresForeignTable.spec.ts b/apps/desktop/src/lib/table/__tests__/postgresForeignTable.spec.tsnew file mode 100644index 0000000000..b7a1f6673c--- /dev/null+++ b/apps/desktop/src/lib/table/__tests__/postgresForeignTable.spec.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { buildPostgresForeignTableOptions, restorePostgresForeignTableDraft, supportsPostgresForeignTableCreation } from "../postgresForeignTable";++describe("PostgreSQL foreign table creation", () => {+ it("limits the creation form to native PostgreSQL profiles", () => {+ expect(supportsPostgresForeignTableCreation({ db_type: "postgres" })).toBe(true);+ expect(supportsPostgresForeignTableCreation({ db_type: "postgres", driver_profile: " POSTGRES " })).toBe(true);+ expect(supportsPostgresForeignTableCreation({ db_type: "postgres", driver_profile: "redshift" })).toBe(false);+ expect(supportsPostgresForeignTableCreation({ db_type: "mysql" })).toBe(false);+ expect(supportsPostgresForeignTableCreation()).toBe(false);+ });++ it("preserves exact server names and option values for backend quoting", () => {+ expect(+ buildPostgresForeignTableOptions({+ enabled: true,+ server: 'server" name',+ options: [+ { name: " schema_name ", value: "remote's schema" },+ { name: "", value: "" },+ { name: "filename", value: " path with spaces " },+ ],+ }),+ ).toEqual({+ server: 'server" name',+ options: [+ { name: "schema_name", value: "remote's schema" },+ { name: "filename", value: " path with spaces " },+ ],+ });+ });++ it("keeps invalid partial options for authoritative validation and clones restored drafts", () => {+ const saved = { enabled: true, server: "remote", options: [{ name: "", value: "orphan value" }] };+ const draft = restorePostgresForeignTableDraft(saved);+ expect(buildPostgresForeignTableOptions(draft).options).toEqual(saved.options);+ draft.options[0]!.value = "changed";+ expect(saved.options[0]!.value).toBe("orphan value");+ expect(restorePostgresForeignTableDraft()).toEqual({ enabled: false, server: "", options: [] });+ });+});diff --git a/apps/desktop/src/lib/table/postgresForeignTable.ts b/apps/desktop/src/lib/table/postgresForeignTable.tsnew file mode 100644index 0000000000..c1caf87b1f--- /dev/null+++ b/apps/desktop/src/lib/table/postgresForeignTable.ts@@ -0,0 +1,33 @@+import type { ConnectionConfig } from "@/types/database";++export interface PostgresForeignTableCreateOptions {+ server: string;+ options: Array<{ name: string; value: string }>;+}++export interface PostgresForeignTableDraft extends PostgresForeignTableCreateOptions {+ enabled: boolean;+}++export function supportsPostgresForeignTableCreation(connection?: Pick<ConnectionConfig, "db_type" | "driver_profile">): boolean {+ const profile = connection?.driver_profile?.trim().toLowerCase();+ return connection?.db_type === "postgres" && (!profile || profile === "postgres");+}++export function emptyPostgresForeignTableDraft(): PostgresForeignTableDraft {+ return { enabled: false, server: "", options: [] };+}++export function restorePostgresForeignTableDraft(saved?: PostgresForeignTableDraft): PostgresForeignTableDraft {+ return { ...emptyPostgresForeignTableDraft(), ...saved, options: (saved?.options ?? []).map((option) => ({ ...option })) };+}++export function buildPostgresForeignTableOptions(draft: PostgresForeignTableDraft): PostgresForeignTableCreateOptions {+ return { server: draft.server, options: draft.options.filter((option) => option.name.trim() || option.value).map((option) => ({ name: option.name.trim(), value: option.value })) };+}++export const POSTGRES_FOREIGN_SERVERS_SQL = `SELECT s.srvname AS name, w.fdwname AS wrapper+FROM pg_catalog.pg_foreign_server s+JOIN pg_catalog.pg_foreign_data_wrapper w ON w.oid = s.srvfdw+WHERE pg_catalog.has_server_privilege(s.oid, 'USAGE')+ORDER BY s.srvname`;diff --git a/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts b/apps/desktop/src/lib/table/starrocksPhysicalOptions.tsindex cced9d5d62..717ee574d0 100644--- a/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts+++ b/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts@@ -29,6 +29,7 @@ export interface StarRocksPhysicalOptionsDraft {bucketCount: string;}export interface CreateTableDialectOptions {+ postgresForeignTable?: import("@/lib/table/postgresForeignTable").PostgresForeignTableCreateOptions;starrocks?: {timePartition?: { columnId: string; granularity: StarRocksTimeGranularity; interval?: number; additionalColumnIds: string[] };partition?: { kind: "values"; columnIds: string[] } | { kind: "range"; columnIds: string[]; partitions: Array<{ name: string; lower: string[]; upper: string[] }> } | { kind: "list"; columnIds: string[]; partitions: Array<{ name: string; values: string[][] }> };diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 83fb59a256..2fcabc6739 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -2408,6 +2408,7 @@ export interface TableStructureEditorDraft {starrocksLayoutDraft?: import("@/lib/table/starrocksAlterOptions").StarRocksLayoutDraft;starrocksSortColumns?: string[];starrocksPhysicalOptions?: import("@/lib/table/starrocksPhysicalOptions").StarRocksPhysicalOptionsDraft;+ postgresForeignTable?: import("@/lib/table/postgresForeignTable").PostgresForeignTableDraft;tableOwner?: string;originalTableOwner?: string;columns: import("@/lib/table/tableStructureEditorSql").EditableStructureColumn[];diff --git a/crates/dbx-driver-agent/src/pl_debug_runtime_tests.rs b/crates/dbx-driver-agent/src/pl_debug_runtime_tests.rsindex 766b31d8da..9957256057 100644--- a/crates/dbx-driver-agent/src/pl_debug_runtime_tests.rs+++ b/crates/dbx-driver-agent/src/pl_debug_runtime_tests.rs@@ -9,13 +9,12 @@ struct Fixture {channel: PlDebugAgentChannel,}-impl Fixture {- async fn spawn(mode: &str) -> Self {- let directory = tempfile::tempdir().unwrap();- let script = directory.path().join("debug-agent.py");- std::fs::write(- &script,- r#"import json, os, pathlib, sys, time+fn debug_agent_launch(mode: &str) -> (tempfile::TempDir, AgentLaunchSpec) {+ let directory = tempfile::tempdir().unwrap();+ let script = directory.path().join("debug-agent.py");+ std::fs::write(+ &script,+ r#"import json, os, pathlib, sys, timeroot = pathlib.Path(sys.argv[1]); mode = sys.argv[2]pending = []; methods = []; cancel_count = 0; opens = 0def reply(req, result):@@ -58,19 +57,38 @@ for line in sys.stdin:reply(req, {'running':bool(pending),'pending':len(pending),'genericCancels':cancel_count,'opens':opens,'agentSessionId':params.get('agentSessionId'),'methods':methods,'pid':os.getpid()})"#,- )- .unwrap();- let python = if cfg!(windows) { "python" } else { "python3" };- let runtime = AgentRuntimeClient::spawn(- AgentLaunchSpec::new(python).with_args([- script.to_string_lossy().to_string(),- directory.path().to_string_lossy().to_string(),- mode.to_string(),- ]),- "test",- )- .await- .unwrap();+ )+ .unwrap();+ let python = if cfg!(windows) { "python" } else { "python3" };+ let launch = AgentLaunchSpec::new(python).with_args([+ script.to_string_lossy().to_string(),+ directory.path().to_string_lossy().to_string(),+ mode.to_string(),+ ]);+ (directory, launch)+}++impl Fixture {+ async fn spawn(mode: &str) -> Self {+ let (directory, launch) = debug_agent_launch(mode);+ let runtime = AgentRuntimeClient::spawn(launch, "test").await.unwrap();+ Self::assemble(directory, runtime)+ }++ /// The plain `AgentRuntimeClient::spawn` path leaves `startup_exit` unset,+ /// so exit confirmation only exists on the startup-observed production+ /// path; exit-confirmation tests must spawn through it.+ async fn spawn_observed(mode: &str) -> Self {+ let (directory, launch) = debug_agent_launch(mode);+ let (startup, _cleanup) = crate::startup_cleanup::StartupCleanup::new_pair();+ let runtime =+ AgentRuntimeClient::spawn_before_observed(launch, "test", Instant::now() + TEST_TIMEOUT, &startup)+ .await+ .unwrap();+ Self::assemble(directory, runtime)+ }++ fn assemble(directory: tempfile::TempDir, runtime: Arc<AgentRuntimeClient>) -> Self {runtime.increment_session_count();let channel = PlDebugAgentChannel::from_reserved(runtime.clone(),@@ -366,6 +384,19 @@ async fn pl_debug_process_exit_requires_the_child_status_not_only_a_reaper_flag(fixture.runtime.child_reaped.store(false, Ordering::Release);}+#[tokio::test]+async fn pl_debug_confirmed_process_exit_survives_child_lock_contention() {+ use futures::FutureExt;++ let fixture = Fixture::spawn_observed("normal").await;+ fixture.channel.fail_stop();+ assert!(fixture.channel.wait_for_exit(TEST_TIMEOUT).await);++ // Another exit observer/reaper can own the lock after exit was confirmed.+ let _child = fixture.runtime.child.lock().unwrap();+ assert_eq!(fixture.channel.wait_for_exit(Duration::ZERO).now_or_never(), Some(true));+}+#[tokio::test]async fn pl_debug_runtime_retirement_requires_exit_and_releases_the_original_reservation_once() {let fixture = Fixture::spawn("normal").await;diff --git a/crates/dbx-sql-schema/src/table_structure_sql.rs b/crates/dbx-sql-schema/src/table_structure_sql.rsindex 629da963b7..c6491985ad 100644--- a/crates/dbx-sql-schema/src/table_structure_sql.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql.rs@@ -17,6 +17,7 @@ mod oracle_constraints;mod oracle_foreign_keys;mod owner;mod partitions;+mod postgres_foreign_table;mod starrocks_layout;mod starrocks_partition;mod transwarp;diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_options.rsindex f46a60b11c..f484a2c888 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs@@ -5,6 +5,22 @@ use serde::{Deserialize, Serialize};#[serde(rename_all = "camelCase")]pub struct CreateTableDialectOptions {pub starrocks: Option<StarRocksCreateOptions>,+ pub postgres_foreign_table: Option<PostgresForeignTableCreateOptions>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PostgresForeignTableCreateOptions {+ pub server: String,+ #[serde(default)]+ pub options: Vec<PostgresForeignTableOption>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PostgresForeignTableOption {+ pub name: String,+ pub value: String,}#[derive(Debug, Clone, Default, Serialize, Deserialize)]diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rsindex 23407f2974..f8d3f3ab42 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs@@ -75,6 +75,13 @@ fn build_create_table_sql_impl(server_version: Option<&str>,dialect_options: CreateTableDialectOptions,) -> TableStructureSqlPlan {+ let foreign_clause = match dialect_options.postgres_foreign_table.as_ref() {+ Some(foreign) => match super::postgres_foreign_table::create_clause(&options, foreign) {+ Ok(clause) => Some(clause),+ Err(warnings) => return TableStructureSqlResult { statements: Vec::new(), warnings }.into(),+ },+ None => None,+ };let create_dialect = create_table_dialect(&options, server_version, dialect_options);let capabilities;let dialect;@@ -338,7 +345,9 @@ fn build_create_table_sql_impl(column_definitions.push(definition.clone());}- let mut create_table = format!("CREATE TABLE {table} (\n {}\n)", column_definitions.join(",\n "));+ let is_foreign_table = foreign_clause.is_some();+ let kind = if is_foreign_table { "FOREIGN TABLE" } else { "TABLE" };+ let mut create_table = format!("CREATE {kind} {table} (\n {}\n)", column_definitions.join(",\n "));create_table.push_str(&create_dialect.after_columns(&options, &pk_list));create_table.push_str(&transwarp::create_table_suffix(&options, &active_columns, dialect));let mut create_table = match partition_clause {@@ -348,6 +357,9 @@ fn build_create_table_sql_impl(create_table.push_str(&create_dialect.partition_clause(&active_columns));create_table.push_str(&create_dialect.after_partition(&active_columns, &pk_list));create_table.push_str(&create_dialect.sort_clause(&active_columns));+ if let Some(clause) = foreign_clause {+ create_table.push_str(&clause);+ }statements.push(format!("{create_table};"));if let Some(engine) = options.mysql_engine.as_deref().map(str::trim).filter(|engine| !engine.is_empty()) {@@ -381,7 +393,9 @@ fn build_create_table_sql_impl(| StructureDialect::H2| StructureDialect::SapHana) {- statements.push(format!("COMMENT ON TABLE {table} IS {};", quote_string(&table_comment)));+ let comment_kind =+ if dialect == StructureDialect::Postgres && is_foreign_table { "FOREIGN TABLE" } else { "TABLE" };+ statements.push(format!("COMMENT ON {comment_kind} {table} IS {};", quote_string(&table_comment)));} else if dialect == StructureDialect::ClickHouse {statements.push(format!("ALTER TABLE {table} MODIFY COMMENT {};", quote_string(&table_comment)));} else if dialect == StructureDialect::SqlServer {diff --git a/crates/dbx-sql-schema/src/table_structure_sql/postgres_foreign_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/postgres_foreign_table.rsnew file mode 100644index 0000000000..9e521406c2--- /dev/null+++ b/crates/dbx-sql-schema/src/table_structure_sql/postgres_foreign_table.rs@@ -0,0 +1,62 @@+use std::collections::HashSet;++use super::create_options::PostgresForeignTableCreateOptions;+use super::dialect::StructureDialect;+use super::types::TableStructureSqlOptions;+use super::util::{quote_ident, quote_string};+use crate::models::connection::DatabaseType;++pub(super) fn create_clause(+ options: &TableStructureSqlOptions,+ foreign: &PostgresForeignTableCreateOptions,+) -> Result<String, Vec<String>> {+ let mut warnings = Vec::new();+ let native_profile = options+ .driver_profile+ .as_deref()+ .is_none_or(|profile| profile.trim().is_empty() || profile.trim().eq_ignore_ascii_case("postgres"));+ if options.database_type != Some(DatabaseType::Postgres) || !native_profile || options.is_gaussdb_m_mode {+ warnings.push("Foreign table creation is supported only for PostgreSQL.".into());+ }+ if foreign.server.trim().is_empty() || foreign.server.contains('\0') {+ warnings.push("A foreign server is required to create a PostgreSQL foreign table.".into());+ }+ if options.partitioned {+ warnings.push("Foreign table creation cannot be combined with partitioned table creation.".into());+ }+ if options.columns.iter().any(|column| !column.marked_for_drop && column.is_primary_key)+ || options.indexes.iter().any(|index| !index.marked_for_drop)+ || options.foreign_keys.iter().any(|key| !key.marked_for_drop)+ {+ warnings.push("PostgreSQL foreign tables do not support primary keys, indexes or foreign keys.".into());+ }+ if options.columns.iter().filter(|column| !column.marked_for_drop).any(|column| {+ column.extra.as_ref().is_some_and(|extra| extra.auto_increment == Some(true) || extra.identity.is_some())+ }) {+ warnings.push("PostgreSQL foreign tables do not support identity columns.".into());+ }+ let mut names = HashSet::new();+ for option in &foreign.options {+ if option.name.trim().is_empty() || option.name.contains('\0') || option.value.contains('\0') {+ warnings.push("Foreign table options require a valid name and cannot contain NUL characters.".into());+ } else if !names.insert(&option.name) {+ warnings.push(format!("Duplicate foreign table option: {}", option.name));+ }+ }+ if !warnings.is_empty() {+ return Err(warnings);+ }+ let mut clause = format!(" SERVER {}", quote_ident(StructureDialect::Postgres, &foreign.server));+ if !foreign.options.is_empty() {+ let values = foreign+ .options+ .iter()+ .map(|option| {+ format!("{} {}", quote_ident(StructureDialect::Postgres, &option.name), quote_string(&option.value))+ })+ .collect::<Vec<_>>()+ .join(", ");+ clause.push_str(&format!(" OPTIONS ({values})"));+ }+ Ok(clause)+}diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rsindex 58b0e67b72..494baab880 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs@@ -3,6 +3,133 @@ use crate::models::connection::DatabaseType;use crate::table_structure_sql::dialect::StructureDialect;use crate::types::PgPartitionKind;+fn foreign_create_options(server: &str) -> CreateTableDialectOptions {+ CreateTableDialectOptions {+ postgres_foreign_table: Some(PostgresForeignTableCreateOptions {+ server: server.into(),+ options: vec![+ PostgresForeignTableOption { name: "schema_name".into(), value: "remote's schema".into() },+ PostgresForeignTableOption { name: "table_name".into(), value: "source table".into() },+ ],+ }),+ ..Default::default()+ }+}++#[test]+fn postgres_foreign_table_create_quotes_server_options_and_comments() {+ let mut options = structure_change_options(+ DatabaseType::Postgres,+ Some("local\"schema"),+ "foreign table",+ vec![column("remote\"column")],+ );+ options.table_comment = Some("foreign's comment".into());+ options.columns[0].comment = "column's comment".into();+ options.columns[0].is_nullable = false;+ options.columns[0].default_value = "'fallback'".into();+ let result = build_create_table_sql_with_dialect_options(options, None, foreign_create_options("server\"name"));+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert_eq!(result.statements.len(), 3);+ assert!(result.statements[0].starts_with("CREATE FOREIGN TABLE \"local\"\"schema\".\"foreign table\" ("));+ assert!(result.statements[0].contains("\"remote\"\"column\""));+ assert!(result.statements[0].contains("NOT NULL"));+ assert!(result.statements[0].contains("DEFAULT 'fallback'"));+ assert!(result.statements[0].ends_with(+ "SERVER \"server\"\"name\" OPTIONS (\"schema_name\" 'remote''s schema', \"table_name\" 'source table');"+ ));+ assert_eq!(+ result.statements[1],+ "COMMENT ON FOREIGN TABLE \"local\"\"schema\".\"foreign table\" IS 'foreign''s comment';"+ );+ assert!(result.statements[2].contains("COMMENT ON COLUMN"));+}++#[test]+fn postgres_foreign_table_create_validates_required_server_and_options() {+ let options = structure_change_options(DatabaseType::Postgres, Some("public"), "foreign_table", vec![column("id")]);+ for server in ["", " ", "invalid\0server"] {+ let result = build_create_table_sql_with_dialect_options(options.clone(), None, foreign_create_options(server));+ assert!(result.statements.is_empty());+ assert!(!result.warnings.is_empty());+ }+ for option in [+ PostgresForeignTableOption { name: "schema_name".into(), value: "duplicate".into() },+ PostgresForeignTableOption { name: "".into(), value: "orphan".into() },+ PostgresForeignTableOption { name: "bad\0name".into(), value: "value".into() },+ PostgresForeignTableOption { name: "filename".into(), value: "bad\0value".into() },+ ] {+ let mut settings = foreign_create_options("server");+ settings.postgres_foreign_table.as_mut().unwrap().options.push(option);+ let result = build_create_table_sql_with_dialect_options(options.clone(), None, settings);+ assert!(result.statements.is_empty());+ assert!(!result.warnings.is_empty());+ }+}++#[test]+fn postgres_foreign_table_create_rejects_unsupported_dialects_and_constraints() {+ let options = structure_change_options(DatabaseType::Postgres, Some("public"), "foreign_table", vec![column("id")]);+ for database_type in [DatabaseType::Mysql, DatabaseType::Sqlite, DatabaseType::OpenGauss, DatabaseType::Gaussdb] {+ let mut request = options.clone();+ request.database_type = Some(database_type);+ assert!(build_create_table_sql_with_dialect_options(request, None, foreign_create_options("server"))+ .statements+ .is_empty());+ }+ let mut primary = options.clone();+ primary.columns[0].is_primary_key = true;+ let mut identity = options.clone();+ identity.columns[0].extra =+ Some(serde_json::from_value(serde_json::json!({"identity":{"generation":"ALWAYS"}})).unwrap());+ let mut partition = options.clone();+ partition.partitioned = true;+ let mut redshift = options;+ redshift.driver_profile = Some("redshift".into());+ for request in [primary, identity, partition, redshift] {+ let result = build_create_table_sql_with_dialect_options(request, None, foreign_create_options("server"));+ assert!(result.statements.is_empty());+ assert!(!result.warnings.is_empty());+ }+}++#[test]+fn postgres_foreign_table_options_are_optional_and_allow_empty_values() {+ let mut options =+ structure_change_options(DatabaseType::Postgres, Some("public"), "foreign_table", vec![column("id")]);+ options.foreign_table = true;+ options.table_comment = Some("table comment".into());+ let regular =+ build_create_table_sql_with_dialect_options(options.clone(), None, CreateTableDialectOptions::default());+ assert!(regular.statements[0].starts_with("CREATE TABLE "));+ assert!(regular.statements[1].starts_with("COMMENT ON TABLE "));+ let mut settings = foreign_create_options("server");+ settings.postgres_foreign_table.as_mut().unwrap().options.clear();+ let result = build_create_table_sql_with_dialect_options(options.clone(), None, settings.clone());+ assert!(result.warnings.is_empty());+ assert!(result.statements[0].ends_with("SERVER \"server\";"));+ settings+ .postgres_foreign_table+ .as_mut()+ .unwrap()+ .options+ .push(PostgresForeignTableOption { name: "custom_option".into(), value: "".into() });+ let result = build_create_table_sql_with_dialect_options(options, None, settings);+ assert!(result.warnings.is_empty());+ assert!(result.statements[0].ends_with("OPTIONS (\"custom_option\" '');"));+}++#[test]+fn postgres_foreign_table_create_allows_serial_types() {+ let mut options =+ structure_change_options(DatabaseType::Postgres, Some("public"), "foreign_table", vec![column("id")]);+ options.columns[0].data_type = "serial".into();+ let result = build_create_table_sql_with_dialect_options(options, None, foreign_create_options("server"));+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert!(result.statements[0].starts_with("CREATE FOREIGN TABLE"));+ assert!(result.statements[0].to_ascii_lowercase().contains("serial"));+}+fn column(name: &str) -> EditableStructureColumn {EditableStructureColumn {id: name.to_string(),@@ -12102,6 +12229,7 @@ fn starrocks_places_primary_keys_before_value_columns() {fn starrocks_layout_options(granularity: StarRocksTimeGranularity) -> CreateTableDialectOptions {CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: None,time_partition: Some(StarRocksTimePartition {@@ -12201,6 +12329,7 @@ fn starrocks_validates_hash_keys_and_bucket_count() {#[test]fn starrocks_random_distribution_requires_duplicate_table_and_supported_version() {let settings = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions { distribution: StarRocksDistribution::Random, ..Default::default() }),};let mut options = starrocks_partitioned_table_options();@@ -12236,6 +12365,7 @@ fn starrocks_builds_multicolumn_value_and_list_partitions() {let options =structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("city"), column("channel")]);let values = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: Some(StarRocksPartitionOptions::Values { column_ids: vec!["city".into(), "channel".into()] }),..Default::default()@@ -12245,6 +12375,7 @@ fn starrocks_builds_multicolumn_value_and_list_partitions() {assert!(result.warnings.is_empty(), "{:?}", result.warnings);assert!(result.statements[0].contains("PARTITION BY (`city`, `channel`) DISTRIBUTED BY RANDOM"));let list = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: Some(StarRocksPartitionOptions::List {column_ids: vec!["city".into(), "channel".into()],@@ -12267,6 +12398,7 @@ fn starrocks_builds_range_bounds_and_validates_arity() {// Intentionally interleaved primary and value columns: SQL reorders without changing membership.options.columns.insert(1, column("payload"));let settings = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: Some(StarRocksPartitionOptions::Range {column_ids: vec!["ts".into(), "id".into()],@@ -12318,6 +12450,7 @@ fn starrocks_time_slice_and_mixed_partitions_are_version_and_type_checked() {fn starrocks_rejects_duplicate_list_values_and_incompatible_partition_types() {let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("city")]);let list = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: Some(StarRocksPartitionOptions::List {column_ids: vec!["city".into()],@@ -12331,6 +12464,7 @@ fn starrocks_rejects_duplicate_list_values_and_incompatible_partition_types() {};assert!(build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), list).statements.is_empty());let range = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {partition: Some(StarRocksPartitionOptions::Range {column_ids: vec!["city".into()],@@ -12352,6 +12486,7 @@ fn starrocks_sort_columns_preserve_priority_and_allow_non_primary_columns() {options.columns[1].is_primary_key = false;options.columns[1].name = "event`time".into();let settings = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions {sort_column_ids: vec!["ts".into(), "id".into()],..Default::default()@@ -12383,6 +12518,7 @@ fn starrocks_sort_validates_version_identity_and_primary_table_types() {_ => {}}let settings = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions { sort_column_ids: ids, ..Default::default() }),};let result = build_create_table_sql_with_dialect_options(options, version, settings);@@ -12399,6 +12535,7 @@ fn starrocks_duplicate_sort_requires_33_and_allows_decimal() {}options.columns[1].data_type = "decimal(10,2)".into();let settings = CreateTableDialectOptions {+ postgres_foreign_table: None,starrocks: Some(StarRocksCreateOptions { sort_column_ids: vec!["ts".into()], ..Default::default() }),};let old = build_create_table_sql_with_dialect_options(options.clone(), Some("3.2.0"), settings.clone());diff --git a/crates/dbx-sql-schema/tests/live_postgres_foreign_table.rs b/crates/dbx-sql-schema/tests/live_postgres_foreign_table.rsnew file mode 100644index 0000000000..f817e57540--- /dev/null+++ b/crates/dbx-sql-schema/tests/live_postgres_foreign_table.rs@@ -0,0 +1,64 @@+//! Opt-in CREATE FOREIGN TABLE regression against a disposable PostgreSQL database.+use dbx_sql_schema::table_structure_sql::{+ build_create_table_sql_with_dialect_options, CreateTableDialectOptions, TableStructureSqlOptions,+};+use serde_json::json;+use std::process::Command;++#[test]+#[ignore = "requires DBX_TEST_POSTGRES_FOREIGN_TABLE_URL and psql; creates postgres_fdw objects"]+fn creates_and_queries_postgres_foreign_table_with_comments() {+ let url = std::env::var("DBX_TEST_POSTGRES_FOREIGN_TABLE_URL").expect("explicit disposable database URL");+ let psql = std::env::var_os("DBX_TEST_PSQL").unwrap_or_else(|| "psql".into());+ let run = |sql: &str| {+ let output = Command::new(&psql)+ .args(["-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "--dbname", &url, "-c", sql])+ .output()+ .expect("run psql");+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));+ String::from_utf8(output.stdout).unwrap().trim().to_string()+ };+ let id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let schema = format!("dbx_foreign_{id}");+ let server = format!("foreign server {id}");+ let db = run("SELECT current_database()");+ let port = run("SHOW port");+ let user = run("SELECT current_user");+ run(&format!(+ "CREATE EXTENSION IF NOT EXISTS postgres_fdw; CREATE SCHEMA \"{schema}\"; \+ CREATE TABLE \"{schema}\".source_table (id integer, label text); \+ INSERT INTO \"{schema}\".source_table VALUES (7, 'remote value'); \+ CREATE SERVER \"{server}\" FOREIGN DATA WRAPPER postgres_fdw \+ OPTIONS (host '127.0.0.1', port '{port}', dbname '{}'); \+ CREATE USER MAPPING FOR CURRENT_USER SERVER \"{server}\" OPTIONS (user '{}');",+ db.replace('\'', "''"),+ user.replace('\'', "''"),+ ));+ let result = std::panic::catch_unwind(|| {+ let options: TableStructureSqlOptions = serde_json::from_value(json!({+ "databaseType": "postgres", "schema": schema, "tableName": "foreign\"table",+ "tableComment": "foreign's comment",+ "columns": [+ {"id":"id", "name":"id", "dataType":"integer", "isNullable":false, "defaultValue":"7", "comment":"id's comment", "isPrimaryKey":false, "markedForDrop":false},+ {"id":"label", "name":"label", "dataType":"text", "isNullable":true, "defaultValue":"", "comment":"", "isPrimaryKey":false, "markedForDrop":false}+ ]+ })).unwrap();+ let settings: CreateTableDialectOptions = serde_json::from_value(json!({+ "postgresForeignTable": {"server": server, "options":[{"name":"schema_name", "value":schema}, {"name":"table_name", "value":"source_table"}]}+ })).unwrap();+ let generated = build_create_table_sql_with_dialect_options(options, Some("18"), settings);+ assert!(generated.warnings.is_empty(), "{:?}", generated.warnings);+ run(&generated.statements.join("\n"));+ assert_eq!(run(&format!("SELECT id, label FROM \"{schema}\".\"foreign\"\"table\"")), "7|remote value");+ let metadata = run(&format!(+ "SELECT c.relkind, obj_description(c.oid), col_description(c.oid, 1) \+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \+ WHERE n.nspname = '{schema}' AND c.relname = 'foreign\"table'"+ ));+ assert_eq!(metadata, "f|foreign's comment|id's comment");+ });+ run(&format!("DROP SCHEMA \"{schema}\" CASCADE; DROP SERVER \"{server}\" CASCADE;"));+ if let Err(error) = result {+ std::panic::resume_unwind(error);+ }+}