feat(pg,kingbase): partition table operations and detail queries

This commit is contained in:
amwps290 authored and GitHub committed 2026-09-21 15:36:49 +08:00
1 parent 882bd130ab
commit 1000aa07b6
62 files changed
+6180 -133

No files matched your search

@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { flattenPgPartitionNodes, pgPartitionBoundText, pgPartitionKindLabelKey, pgPartitionNodeBoundText, pgPartitionRowHint, splitPgPartitionBoundValues, visiblePgPartitionRows } from "@/lib/table/pgPartitionPresentation";
import type { PgPartitionNode } from "@/types/database";
function node(name: string, children: PgPartitionNode[] = []): PgPartitionNode {
return { schema: "public", name, isLeaf: children.length === 0, children };
}
describe("pgPartitionPresentation", () => {
it("flattens a multi-level tree depth-first with nesting depth", () => {
const tree = [node("logs", [node("logs_2024", [node("logs_2024_us")])]), node("logs_default")];
expect(flattenPgPartitionNodes(tree).map(({ depth, node: rowNode }) => `${depth}:${rowNode.name}`)).toEqual(["0:logs", "1:logs_2024", "2:logs_2024_us", "0:logs_default"]);
});
it("carries the direct parent identity for nested partition operations", () => {
const rows = flattenPgPartitionNodes([node("logs_2024", [node("logs_2024_cn")])], { schema: "public", name: "logs" });
expect(rows.map((row) => ({ name: row.node.name, parentSchema: row.parentSchema, parentName: row.parentName }))).toEqual([
{ name: "logs_2024", parentSchema: "public", parentName: "logs" },
{ name: "logs_2024_cn", parentSchema: "public", parentName: "logs_2024" },
]);
});
it("gives every row a unique key", () => {
const rows = flattenPgPartitionNodes([node("a"), node("b", [node("b1")])]);
expect(new Set(rows.map((row) => row.key)).size).toBe(rows.length);
});
it("tracks depth and the ancestor key chain used to fold and indent a parent", () => {
const rows = flattenPgPartitionNodes([node("p1", [node("p1a", [node("p1a1")])]), node("p2")]);
expect(rows.map((row) => [row.node.name, row.depth, row.ancestorKeys])).toEqual([
["p1", 0, []],
["p1a", 1, ["public.p1"]],
["p1a1", 2, ["public.p1", "public.p1/public.p1a"]],
["p2", 0, []],
]);
});
it("hides every descendant of a collapsed parent", () => {
const rows = flattenPgPartitionNodes([node("p1", [node("p1a"), node("p1b")]), node("p2")]);
expect(visiblePgPartitionRows(rows, new Set()).map((row) => row.node.name)).toEqual(["p1", "p1a", "p1b", "p2"]);
expect(visiblePgPartitionRows(rows, new Set(["public.p1"])).map((row) => row.node.name)).toEqual(["p1", "p2"]);
});
it("builds a row hover hint from the size and count estimates", () => {
const t = (key: string, params?: Record<string, unknown>) => `${key}(${JSON.stringify(params)})`;
const bytes = (value: number) => `${value}B`;
expect(pgPartitionRowHint({ ...node("p"), rowEstimate: 366, totalBytes: 1048576 }, t, bytes)).toBe('structureEditor.partitionsRowEstimate({"count":366}) · structureEditor.partitionsSize({"size":"1048576B"})');
expect(pgPartitionRowHint({ ...node("p"), rowEstimate: 5 }, t, bytes)).toBe('structureEditor.partitionsRowEstimate({"count":5})');
expect(pgPartitionRowHint({ ...node("p"), totalBytes: 10 }, t, bytes)).toBe('structureEditor.partitionsSize({"size":"10B"})');
// No estimates -> no tooltip at all.
expect(pgPartitionRowHint(node("p"), t, bytes)).toBeUndefined();
});
it("renders each bound kind as its SQL fragment", () => {
expect(pgPartitionBoundText({ kind: "range", from: ["'2024-01-01'"], to: ["'2025-01-01'"] })).toBe("FROM ('2024-01-01') TO ('2025-01-01')");
expect(pgPartitionBoundText({ kind: "range", from: ["MINVALUE", "'a'"], to: ["MAXVALUE", "'b'"] })).toBe("FROM (MINVALUE, 'a') TO (MAXVALUE, 'b')");
expect(pgPartitionBoundText({ kind: "list", values: ["'a'", "'b'"] })).toBe("IN ('a', 'b')");
expect(pgPartitionBoundText({ kind: "hash", modulus: 2, remainder: 1 })).toBe("MODULUS 2 REMAINDER 1");
expect(pgPartitionBoundText({ kind: "default" })).toBe("DEFAULT");
expect(pgPartitionBoundText(undefined)).toBe("");
});
it("falls back to the raw catalog definition when the bound was not parsed", () => {
expect(pgPartitionNodeBoundText({ ...node("p"), boundDefinition: "FOR VALUES IN (1)" })).toBe("FOR VALUES IN (1)");
expect(pgPartitionNodeBoundText({ ...node("p"), bound: { kind: "default" }, boundDefinition: "DEFAULT" })).toBe("DEFAULT");
expect(pgPartitionNodeBoundText(node("p"))).toBe("");
});
it("splits bound values on top-level commas only", () => {
expect(splitPgPartitionBoundValues("1, 2, 3")).toEqual(["1", "2", "3"]);
expect(splitPgPartitionBoundValues("'a,b', 'c'")).toEqual(["'a,b'", "'c'"]);
expect(splitPgPartitionBoundValues("lower('A''B'), lower('C')")).toEqual(["lower('A''B')", "lower('C')"]);
expect(splitPgPartitionBoundValues(" '2024-01-01' ")).toEqual(["'2024-01-01'"]);
expect(splitPgPartitionBoundValues("")).toEqual([]);
expect(splitPgPartitionBoundValues(" , ")).toEqual([]);
});
it("maps strategies to translation keys", () => {
expect(pgPartitionKindLabelKey("range")).toBe("structureEditor.partitionKindRange");
expect(pgPartitionKindLabelKey("list")).toBe("structureEditor.partitionKindList");
expect(pgPartitionKindLabelKey("hash")).toBe("structureEditor.partitionKindHash");
expect(pgPartitionKindLabelKey(undefined)).toBeUndefined();
});
});
@@ -3,12 +3,13 @@ import { hasTableStructureRefreshWork, unloadedTableStructureRefreshScope, visib
describe("table structure metadata loading", () => {
it.each([
["columns", { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, tableComment: true }],
["indexes", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, tableComment: true }],
["foreignKeys", { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, tableComment: true }],
["constraints", { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, tableComment: true }],
["triggers", { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, tableComment: true }],
["ddl", { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, tableComment: true }],
["columns", { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
["indexes", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
["foreignKeys", { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, partitions: false, tableComment: true }],
["constraints", { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, partitions: false, tableComment: true }],
["triggers", { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, partitions: false, tableComment: true }],
["partitions", { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: true, tableComment: false }],
["ddl", { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
] as const)("requests only the metadata required by the %s tab", (tab, expected) => {
expect(visibleTableStructureRefreshScope(tab)).toEqual(expected);
});
@@ -16,18 +17,24 @@ describe("table structure metadata loading", () => {
it("requests only index metadata after columns and comments are already loaded", () => {
const scope = unloadedTableStructureRefreshScope("indexes", new Set(["columns", "comment"]));
expect(scope).toEqual({ columns: false, indexes: true, foreignKeys: false, constraints: false, triggers: false, tableComment: false });
expect(scope).toEqual({ columns: false, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: false });
expect(hasTableStructureRefreshWork(scope)).toBe(true);
expect(hasTableStructureRefreshWork(unloadedTableStructureRefreshScope("indexes", new Set(["columns", "indexes", "comment"])))).toBe(false);
});
it("requests trigger metadata only until that facet is loaded", () => {
expect(unloadedTableStructureRefreshScope("triggers", new Set(["comment"]))).toEqual({ columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, tableComment: false });
expect(unloadedTableStructureRefreshScope("triggers", new Set(["comment"]))).toEqual({ columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, partitions: false, tableComment: false });
expect(hasTableStructureRefreshWork(unloadedTableStructureRefreshScope("triggers", new Set(["triggers", "comment"])))).toBe(false);
});
it("requests constraint metadata only until that facet is loaded", () => {
expect(unloadedTableStructureRefreshScope("constraints", new Set(["comment"]))).toEqual({ columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, tableComment: false });
expect(unloadedTableStructureRefreshScope("constraints", new Set(["comment"]))).toEqual({ columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, partitions: false, tableComment: false });
expect(hasTableStructureRefreshWork(unloadedTableStructureRefreshScope("constraints", new Set(["constraints", "comment"])))).toBe(false);
});
it("tracks the partitions facet through the loaded set so re-activating the tab does not refetch", () => {
expect(unloadedTableStructureRefreshScope("partitions", new Set())).toEqual({ columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: true, tableComment: false });
expect(hasTableStructureRefreshWork(unloadedTableStructureRefreshScope("partitions", new Set()))).toBe(true);
expect(hasTableStructureRefreshWork(unloadedTableStructureRefreshScope("partitions", new Set(["partitions"])))).toBe(false);
});
});
+22
View File
@@ -518,4 +518,26 @@ describe("TDengine table hierarchy", () => {
expect(nodes[0].children?.[0]).toMatchObject({ label: "tree.partitions", isExpanded: false });
});
it("nests second-level partitions under Kingbase-style lowercase parent names", () => {
// KingbaseES returns lowercase relation names and a direct `parent_name`;
// a partition that is itself a partitioned parent must nest recursively.
const nodes = buildTableTreeNodes({
...context,
schema: "partition_demo",
tables: [
{ name: "catalog_nested", table_type: "BASE TABLE", comment: null },
{ name: "catalog_nested_2024", table_type: "BASE TABLE", comment: null, parent_schema: "partition_demo", parent_name: "catalog_nested" },
{ name: "catalog_nested_2024_asia", table_type: "BASE TABLE", comment: null, parent_schema: "partition_demo", parent_name: "catalog_nested_2024" },
{ name: "catalog_nested_2024_eu", table_type: "BASE TABLE", comment: null, parent_schema: "partition_demo", parent_name: "catalog_nested_2024" },
{ name: "catalog_nested_2025", table_type: "BASE TABLE", comment: null, parent_schema: "partition_demo", parent_name: "catalog_nested" },
],
});
expect(nodes.map((node) => node.label)).toEqual(["catalog_nested"]);
const level1 = tablePartitionGroups(nodes[0])[0].children ?? [];
expect(level1.map((node) => node.label)).toEqual(["catalog_nested_2024", "catalog_nested_2025"]);
const yearPartition = level1.find((node) => node.label === "catalog_nested_2024");
expect(tablePartitionGroups(yearPartition!)[0].children?.map((node) => node.label)).toEqual(["catalog_nested_2024_asia", "catalog_nested_2024_eu"]);
});
});
@@ -0,0 +1,85 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildCreatePartitionedTableSql, buildTablePartitionOperationSql, getTablePartitioning } from "@/lib/backend/http";
describe("PostgreSQL table partitioning web API", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("loads the structured partitioning view from the schema endpoint", async () => {
const payload = {
isPartitioned: true,
isPartition: false,
strategy: "range",
keyDefinition: "RANGE (sold_on)",
keyColumns: ["sold_on"],
partitions: [{ schema: "public", name: "sales_2024", isLeaf: true, children: [] }],
};
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: vi.fn().mockResolvedValue(payload),
});
vi.stubGlobal("fetch", fetchMock);
await expect(getTablePartitioning("connection 1", "sales/db", "public", "order items")).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith("/api/schema/table-partitioning?connection_id=connection+1&database=sales%2Fdb&schema=public&table=order+items");
});
it("builds partition maintenance SQL through the query endpoint", async () => {
const options = {
databaseType: "postgres" as const,
schema: "public",
tableName: "sales",
operations: [
{
id: "op:1",
kind: "create" as const,
parentSchema: "",
parentTable: "",
schema: "",
name: "sales_2025",
bound: { kind: "default" as const },
concurrently: false,
},
],
};
const payload = {
statements: ['CREATE TABLE "public"."sales_2025" PARTITION OF "public"."sales" DEFAULT;'],
warnings: [],
};
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: vi.fn().mockResolvedValue(payload),
});
vi.stubGlobal("fetch", fetchMock);
await expect(buildTablePartitionOperationSql(options)).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith("/api/query/build-table-partition-operation-sql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ options }),
});
});
it("builds a partitioned CREATE TABLE through the query endpoint", async () => {
const options = { databaseType: "postgres" as const, schema: "public", tableName: "sales", columns: [] } as never;
const partitioning = { kind: "range" as const, columns: ["sold_on"], expression: "" };
const payload = { statements: ['CREATE TABLE "public"."sales" (\n "sold_on" date\n) PARTITION BY RANGE ("sold_on");'], warnings: [] };
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: vi.fn().mockResolvedValue(payload),
});
vi.stubGlobal("fetch", fetchMock);
await expect(buildCreatePartitionedTableSql({ options, partitioning })).resolves.toEqual(payload);
expect(fetchMock).toHaveBeenCalledWith("/api/query/build-create-partitioned-table-sql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ options, partitioning }),
});
});
});
+3
View File
@@ -220,6 +220,7 @@ export const listTriggers = forward("listTriggers");
export const listConstraints = forward("listConstraints");
export const listPartitions = forward("listPartitions");
export const getTablePartitionStatus = forward("getTablePartitionStatus");
export const getTablePartitioning = forward("getTablePartitioning");
export const listInvalidIndexes = forward("listInvalidIndexes");
export const listSubpartitions = forward("listSubpartitions");
export const getTableDdl = forward("getTableDdl");
@@ -299,6 +300,8 @@ export const buildRoutineRenameObjectSourceStatements = forward("buildRoutineRen
export const buildViewDdlSql = forward("buildViewDdlSql");
export const buildTableStructureChangeSql = forward("buildTableStructureChangeSql");
export const buildTableOwnerChangeSql = forward("buildTableOwnerChangeSql");
export const buildTablePartitionOperationSql = forward("buildTablePartitionOperationSql");
export const buildCreatePartitionedTableSql = forward("buildCreatePartitionedTableSql");
export const previewSqliteTableStructureChange = forward("previewSqliteTableStructureChange");
export const applySqliteTableStructureChange = forward("applySqliteTableStructureChange");
export const buildCreateTableSql = forward("buildCreateTableSql");
+15 -2
View File
@@ -189,7 +189,7 @@ import type {
} from "@/lib/dataGrid/dataGridSql";
import type { DmlChangePreviewSqlOptions, DmlChangePreviewSqlResult } from "@/lib/sql/dmlChangePreview";
import type { DataGridExtractRequest, DataGridExtractResult } from "@/lib/dataGrid/dataGridCopyExtractor";
import type { BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
import type { BuildCreatePartitionedTableSqlOptions, BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TablePartitionSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
@@ -1179,6 +1179,10 @@ export async function getTablePartitionStatus(connectionId: string, database: st
return get(`/api/schema/table-partition-status?${qs({ connection_id: connectionId, database, schema, table })}`);
}
export async function getTablePartitioning(connectionId: string, database: string, schema: string, table: string): Promise<import("@/types/database").PgTablePartitioning> {
return get(`/api/schema/table-partitioning?${qs({ connection_id: connectionId, database, schema, table })}`);
}
export async function listInvalidIndexes(connectionId: string, database: string, schema: string, table: string): Promise<string[]> {
return get(`/api/schema/invalid-indexes?${qs({ connection_id: connectionId, database, schema, table })}`);
}
@@ -1458,13 +1462,14 @@ export async function closeClientConnectionSession(connectionId: string, databas
});
}
export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number): Promise<QueryResult> {
export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean): Promise<QueryResult> {
return post("/api/query/execute-batch", {
connectionId,
database,
statements,
schema,
timeoutSecs,
useTransaction,
});
}
@@ -1712,6 +1717,14 @@ export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSql
return post("/api/query/build-table-owner-change-sql", { options });
}
export async function buildTablePartitionOperationSql(options: TablePartitionSqlOptions): Promise<TableStructureChangeSql> {
return post("/api/query/build-table-partition-operation-sql", { options });
}
export async function buildCreatePartitionedTableSql(options: BuildCreatePartitionedTableSqlOptions): Promise<TableStructureChangeSql> {
return post("/api/query/build-create-partitioned-table-sql", { options: options.options, partitioning: options.partitioning });
}
export async function previewSqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions): Promise<SqliteTableStructureChangePreview> {
return post("/api/query/preview-sqlite-table-structure-change", {
connectionId,
+20 -2
View File
@@ -122,7 +122,7 @@ import type { DmlChangePreviewSqlOptions, DmlChangePreviewSqlResult } from "@/li
import type { DataGridExtractRequest, DataGridExtractResult } from "@/lib/dataGrid/dataGridCopyExtractor";
import type { DataCompareFromTablesOptions, DataCompareFromTablesPreparation, DataCompareSyncPlan, DataCompareSyncPlanOptions, DataComparePreparation, DataComparePreparationOptions } from "@/lib/dataGrid/dataCompare";
import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, SchemaSyncSqlPlan, SelectedSchemaDiffInput, GenerateSchemaSyncPlanOptions, TableDiff, FunctionDiff, SequenceDiff, RuleDiff, OwnerDiff } from "@/lib/schema/schemaDiff";
import type { BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
import type { BuildCreatePartitionedTableSqlOptions, BuildTableOwnerChangeSqlOptions, BuildTableStructureChangeSqlOptions, BuildSingleColumnAlterSqlOptions, SqliteTableStructureChangePreview, TablePartitionSqlOptions, TableStructureChangeSql } from "@/lib/table/tableStructureEditorSql";
import type { BuildTableSelectSqlOptions } from "@/lib/table/tableSelectSql";
import type { DatabaseSearchSql, DatabaseSearchSqlOptions, SearchResultWhereOptions } from "@/lib/database/databaseSearch";
import type { BuildEditableObjectSourceSqlInput, BuildRoutineRenameObjectSourceInput } from "@/lib/table/objectSourceEditor";
@@ -1718,13 +1718,14 @@ export async function closeClientConnectionSession(connectionId: string, databas
});
}
export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number): Promise<QueryResult> {
export async function executeBatch(connectionId: string, database: string, statements: string[], schema?: string, timeoutSecs?: number, useTransaction?: boolean): Promise<QueryResult> {
return invoke("execute_batch", {
connectionId,
database,
statements,
schema,
timeoutSecs,
useTransaction,
});
}
@@ -1961,6 +1962,14 @@ export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSql
return invoke("build_table_owner_change_sql", { options });
}
export async function buildTablePartitionOperationSql(options: TablePartitionSqlOptions): Promise<TableStructureChangeSql> {
return invoke("build_table_partition_operation_sql", { options });
}
export async function buildCreatePartitionedTableSql(options: BuildCreatePartitionedTableSqlOptions): Promise<TableStructureChangeSql> {
return invoke("build_create_partitioned_table_sql", { options: options.options, partitioning: options.partitioning });
}
export async function previewSqliteTableStructureChange(connectionId: string, database: string, options: BuildTableStructureChangeSqlOptions): Promise<SqliteTableStructureChangePreview> {
return invoke("preview_sqlite_table_structure_change", {
connectionId,
@@ -2174,6 +2183,15 @@ export async function getTablePartitionStatus(connectionId: string, database: st
});
}
export async function getTablePartitioning(connectionId: string, database: string, schema: string, table: string): Promise<import("@/types/database").PgTablePartitioning> {
return invoke("get_table_partitioning", {
connectionId,
database,
schema,
table,
});
}
export async function listInvalidIndexes(connectionId: string, database: string, schema: string, table: string): Promise<string[]> {
return invoke("list_invalid_indexes", {
connectionId,
@@ -42,7 +42,7 @@ async function saveSchemaCacheSafe(cacheKey: string, payload: unknown): Promise<
}
}
export type ObjectMetadataFacet = "columns" | "indexes" | "foreign-keys" | "constraints" | "triggers" | "comment" | "owner";
export type ObjectMetadataFacet = "columns" | "indexes" | "foreign-keys" | "constraints" | "triggers" | "partitions" | "comment" | "owner";
function cacheSegment(value: string | undefined): string {
return encodeURIComponent(value ?? "");
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getTableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";
import { getTableMetadataCapabilities, isStructureMetadataTabSupported } from "@/lib/table/tableMetadataCapabilities";
describe("tableMetadataCapabilities", () => {
it("exposes only collection indexes for MongoDB table information", () => {
@@ -9,6 +9,7 @@ describe("tableMetadataCapabilities", () => {
foreignKeys: false,
constraints: false,
triggers: false,
partitions: false,
ddl: false,
});
});
@@ -23,4 +24,28 @@ describe("tableMetadataCapabilities", () => {
expect(getTableMetadataCapabilities("mysql").constraints).toBe(false);
expect(getTableMetadataCapabilities(undefined).constraints).toBe(false);
});
it("exposes partitions only for dialects with declarative partitioning metadata", () => {
expect(getTableMetadataCapabilities("postgres").partitions).toBe(true);
expect(getTableMetadataCapabilities("kingbase").partitions).toBe(true);
expect(getTableMetadataCapabilities("mysql").partitions).toBe(false);
expect(getTableMetadataCapabilities("oracle").partitions).toBe(false);
// openGauss-based engines use a different partition catalog and stay off.
expect(getTableMetadataCapabilities("opengauss").partitions).toBe(false);
expect(getTableMetadataCapabilities("vastbase").partitions).toBe(false);
expect(getTableMetadataCapabilities("gaussdb").partitions).toBe(false);
expect(getTableMetadataCapabilities(undefined).partitions).toBe(false);
});
it("shows the Partitions tab for PostgreSQL in both edit and create mode only", () => {
const postgres = getTableMetadataCapabilities("postgres");
expect(isStructureMetadataTabSupported("partitions", postgres, false)).toBe(true);
// Create mode declares `PARTITION BY` instead of reading the catalog.
expect(isStructureMetadataTabSupported("partitions", postgres, true)).toBe(true);
const mysql = getTableMetadataCapabilities("mysql");
expect(isStructureMetadataTabSupported("partitions", mysql, false)).toBe(false);
// The DDL tab has no create-mode baseline; the partitions tab does.
expect(isStructureMetadataTabSupported("ddl", postgres, true)).toBe(false);
});
});
@@ -244,6 +244,78 @@ function markPartitionRows(rows: ObjectBrowserRow[], fallbackSchema: string) {
}
}
export type ObjectBrowserRowSorter = (rows: ObjectBrowserRow[]) => ObjectBrowserRow[];
/**
* Flattens the object rows into render order: roots first, each followed by its
* partition children — recursively, because a PostgreSQL partition can itself be
* a partitioned parent (a second-level sub-partitioned table).
*
* `depths` carries each partition row's nesting level so the caller can indent
* it; roots are 0.
*
* `rows`/`matchingRows` are expected to be pre-filtered by the caller's type
* filter. When `query` is non-empty the tree is force-expanded so a deep match
* and the ancestors leading to it stay visible even while collapsed.
*/
export function groupObjectBrowserRows(options: { rows: readonly ObjectBrowserRow[]; matchingRows: readonly ObjectBrowserRow[]; query: string; expandedPartitionParentIds: ReadonlySet<string>; sortRows: ObjectBrowserRowSorter }): { rows: ObjectBrowserRow[]; depths: Map<string, number> } {
const { rows, matchingRows, query, expandedPartitionParentIds, sortRows } = options;
const candidateIds = new Set(rows.map((row) => row.id));
const matchingIds = new Set(matchingRows.map((row) => row.id));
const rowById = new Map(rows.map((row) => [row.id, row]));
const partitionRowsByParentId = new Map<string, ObjectBrowserRow[]>();
for (const row of rows) {
if (!row.partitionParentId) continue;
const group = partitionRowsByParentId.get(row.partitionParentId) ?? [];
group.push(row);
partitionRowsByParentId.set(row.partitionParentId, group);
}
// A deep match must be reachable: pull in every ancestor that leads to it, or
// the match would be filtered out as an orphaned sub-partition.
const ancestorIdsWithMatchingPartitions = new Set<string>();
if (query) {
for (const row of matchingRows) {
let ancestorId = row.partitionParentId;
while (ancestorId && !ancestorIdsWithMatchingPartitions.has(ancestorId)) {
ancestorIdsWithMatchingPartitions.add(ancestorId);
ancestorId = rowById.get(ancestorId)?.partitionParentId;
}
}
}
const rootRows = rows.filter((row) => {
if (row.partitionParentId) return false;
if (!query) return true;
return matchingIds.has(row.id) || ancestorIdsWithMatchingPartitions.has(row.id);
});
const result: ObjectBrowserRow[] = [];
const depths = new Map<string, number>();
const appendPartitions = (parent: ObjectBrowserRow, depth: number) => {
const partitions = partitionRowsByParentId.get(parent.id)?.filter((partition) => candidateIds.has(partition.id));
if (!partitions?.length) return;
// Search force-expands the tree so every match (and its ancestor chain) is visible.
if (!query && !expandedPartitionParentIds.has(parent.id)) return;
const parentMatches = matchingIds.has(parent.id);
const visiblePartitions = query && !parentMatches ? partitions.filter((partition) => matchingIds.has(partition.id) || ancestorIdsWithMatchingPartitions.has(partition.id)) : partitions;
for (const partition of sortRows(visiblePartitions)) {
result.push(partition);
depths.set(partition.id, depth);
appendPartitions(partition, depth + 1);
}
};
for (const row of sortRows(rootRows)) {
result.push(row);
depths.set(row.id, 0);
appendPartitions(row, 1);
}
return { rows: result, depths };
}
function objectKey(row: Pick<ObjectBrowserRow, "schema" | "name" | "type">, fallbackSchema: string) {
return `${row.type}\0${(row.schema || fallbackSchema).toLowerCase()}\0${row.name.toLowerCase()}`;
}
@@ -0,0 +1,131 @@
import type { PgPartitionBound, PgPartitionKind, PgPartitionNode } from "@/types/database";
/** One flattened row of a partition tree, carrying what a renderer needs. */
export interface PgPartitionTreeRow {
key: string;
/** 0 for a top-level partition of the table; +1 per nesting level. */
depth: number;
node: PgPartitionNode;
/** Direct parent identity, used by detach operations on nested partitions. */
parentSchema?: string;
parentName?: string;
/** Keys of every ancestor above this row, outermost first (for collapse). */
ancestorKeys: string[];
}
export interface PgPartitionParentIdentity {
schema?: string;
name?: string;
}
/**
* Depth-first flatten of a partition tree so a renderer can show multi-level
* hierarchies without recursive components. Nesting is conveyed by indentation
* and the fold control; no tree guide lines are drawn.
*/
export function flattenPgPartitionNodes(nodes: PgPartitionNode[], rootParent: PgPartitionParentIdentity = {}): PgPartitionTreeRow[] {
return flattenPgPartitionNodesAtDepth(nodes, rootParent, 0, "", []);
}
function flattenPgPartitionNodesAtDepth(nodes: PgPartitionNode[], parent: PgPartitionParentIdentity, depth: number, keyPrefix: string, ancestorKeys: string[]): PgPartitionTreeRow[] {
const rows: PgPartitionTreeRow[] = [];
for (const node of nodes) {
const key = `${keyPrefix}${node.schema}.${node.name}`;
rows.push({ key, depth, node, parentSchema: parent.schema, parentName: parent.name, ancestorKeys: [...ancestorKeys] });
if (node.children.length > 0) {
rows.push(...flattenPgPartitionNodesAtDepth(node.children, { schema: node.schema, name: node.name }, depth + 1, `${key}/`, [...ancestorKeys, key]));
}
}
return rows;
}
/** Pixels of indentation added per nesting level. */
export const PARTITION_TREE_INDENT_PX = 16;
/**
* Drops rows hidden behind a collapsed ancestor, so a renderer can show a
* folded tree without re-walking it.
*/
export function visiblePgPartitionRows(rows: PgPartitionTreeRow[], collapsedKeys: ReadonlySet<string>): PgPartitionTreeRow[] {
if (collapsedKeys.size === 0) return rows;
return rows.filter((row) => !row.ancestorKeys.some((key) => collapsedKeys.has(key)));
}
export type PartitionTranslate = (key: string, params?: Record<string, unknown>) => string;
/**
* Hover hint for a partition row. The estimated row count and size are kept out
* of the row body (they doubled every row's height) and surfaced here instead.
*/
export function pgPartitionRowHint(node: PgPartitionNode, t: PartitionTranslate, formatBytes: (value: number) => string): string | undefined {
const parts: string[] = [];
if (node.rowEstimate != null) parts.push(t("structureEditor.partitionsRowEstimate", { count: node.rowEstimate }));
if (node.totalBytes != null) parts.push(t("structureEditor.partitionsSize", { size: formatBytes(node.totalBytes) }));
return parts.length > 0 ? parts.join(" · ") : undefined;
}
/** Renders a parsed bound as the SQL fragment PostgreSQL uses in `CREATE TABLE ... PARTITION OF`. */
export function pgPartitionBoundText(bound?: PgPartitionBound): string {
if (!bound) return "";
if (bound.kind === "default") return "DEFAULT";
if (bound.kind === "range") return `FROM (${bound.from.join(", ")}) TO (${bound.to.join(", ")})`;
if (bound.kind === "list") return `IN (${bound.values.join(", ")})`;
return `MODULUS ${bound.modulus} REMAINDER ${bound.remainder}`;
}
/**
* Bound text for a tree node, falling back to the raw catalog definition when
* the bound shape was not recognized by the backend parser.
*/
export function pgPartitionNodeBoundText(node: PgPartitionNode): string {
return node.bound ? pgPartitionBoundText(node.bound) : node.boundDefinition || "";
}
/**
* Splits user-entered partition bound values on top-level commas only. Commas
* inside single quotes (with `''` escapes) or nested parentheses stay in the
* value, so `lower('a,b'), 2` yields two values.
*/
export function splitPgPartitionBoundValues(input: string): string[] {
const values: string[] = [];
let current = "";
let depth = 0;
let inSingle = false;
let inDouble = false;
for (let index = 0; index < input.length; index += 1) {
const ch = input[index];
if (ch === "'" && !inDouble) {
if (inSingle && input[index + 1] === "'") {
current += "''";
index += 1;
continue;
}
inSingle = !inSingle;
current += ch;
continue;
}
if (ch === '"' && !inSingle) {
inDouble = !inDouble;
current += ch;
continue;
}
if (!inSingle && !inDouble && ch === "(") depth += 1;
if (!inSingle && !inDouble && ch === ")") depth -= 1;
if (ch === "," && !inSingle && !inDouble && depth === 0) {
values.push(current.trim());
current = "";
continue;
}
current += ch;
}
values.push(current.trim());
return values.filter((value) => value.length > 0);
}
/** Translation key for a partition strategy label. */
export function pgPartitionKindLabelKey(kind?: PgPartitionKind): string | undefined {
if (kind === "range") return "structureEditor.partitionKindRange";
if (kind === "list") return "structureEditor.partitionKindList";
if (kind === "hash") return "structureEditor.partitionKindHash";
return undefined;
}
@@ -6,6 +6,7 @@ export interface TableMetadataCapabilities {
foreignKeys: boolean;
constraints: boolean;
triggers: boolean;
partitions: boolean;
ddl: boolean;
}
@@ -19,6 +20,9 @@ const defaultCapabilities: TableMetadataCapabilities = {
// empty tab.
constraints: false,
triggers: true,
// Declarative partitioning metadata (pg_partitioned_table / pg_get_partkeydef)
// is PostgreSQL-only for now; other dialects leave the tab hidden.
partitions: false,
ddl: true,
};
@@ -26,8 +30,10 @@ const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabi
oracle: {
constraints: true,
},
// KingbaseES V9 shares PostgreSQL's declarative partition catalog and DDL.
kingbase: {
constraints: true,
partitions: true,
},
vastbase: {
constraints: true,
@@ -39,6 +45,7 @@ const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabi
// EXCLUDE/NOT NULL) through list_constraints.
postgres: {
constraints: true,
partitions: true,
},
// SQL Server reports PK/UNIQUE/FOREIGN KEY/CHECK/DEFAULT constraints from the
// sys.* catalog views through list_constraints.
@@ -155,6 +162,7 @@ export function isStructureMetadataTabSupported(tab: TableInfoTab, capabilities:
(tab === "foreignKeys" && capabilities.foreignKeys) ||
(tab === "constraints" && capabilities.constraints) ||
(tab === "triggers" && capabilities.triggers) ||
(tab === "partitions" && capabilities.partitions) ||
(tab === "ddl" && capabilities.ddl && !isCreateMode)
);
}
@@ -108,6 +108,48 @@ export interface TableStructureChangeSql {
warnings: string[];
}
/** Explicit partition maintenance operations (PostgreSQL only). */
export type TablePartitionOperationKind = "create" | "attach" | "detach" | "drop";
/** Partition bound as entered in the UI; values are SQL literal text. */
export type TablePartitionBoundDraft = { kind: "range"; from: string[]; to: string[] } | { kind: "list"; values: string[] } | { kind: "hash"; modulus: number; remainder: number } | { kind: "default" };
export interface TablePartitionOperation {
id: string;
kind: TablePartitionOperationKind;
/** Partitioned parent's schema; empty falls back to the edited table's schema. */
parentSchema: string;
/** Partitioned parent; empty falls back to the edited table. */
parentTable: string;
/** Schema of the partition relation; empty falls back to the parent's schema. */
schema: string;
name: string;
/** Required for `create`/`attach`; must be absent for `detach`/`drop`. */
bound?: TablePartitionBoundDraft;
/** Emit `DETACH PARTITION ... CONCURRENTLY` (PostgreSQL 14+). */
concurrently: boolean;
}
export interface TablePartitionSqlOptions {
databaseType?: DatabaseType;
driverProfile?: string | null;
schema?: string;
tableName: string;
operations: TablePartitionOperation[];
}
/** Declarative partitioning for a table being created. */
export interface TablePartitionDefinition {
kind: "range" | "list" | "hash";
columns: string[];
expression: string;
}
export interface BuildCreatePartitionedTableSqlOptions {
options: BuildTableStructureChangeSqlOptions;
partitioning: TablePartitionDefinition;
}
export interface BuildTableOwnerChangeSqlOptions {
databaseType?: DatabaseType;
schema?: string;
@@ -7,23 +7,26 @@ export interface TableStructureRefreshScope {
foreignKeys: boolean;
constraints: boolean;
triggers: boolean;
partitions: boolean;
tableComment: boolean;
}
export function visibleTableStructureRefreshScope(activeTab: TableInfoTab): TableStructureRefreshScope {
switch (activeTab) {
case "columns":
return { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, tableComment: true };
return { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
case "indexes":
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, tableComment: true };
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
case "foreignKeys":
return { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, tableComment: true };
return { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, partitions: false, tableComment: true };
case "constraints":
return { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, tableComment: true };
return { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, partitions: false, tableComment: true };
case "triggers":
return { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, tableComment: true };
return { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: true, partitions: false, tableComment: true };
case "partitions":
return { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: true, tableComment: false };
case "ddl":
return { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, tableComment: true };
return { columns: false, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
}
}
@@ -35,10 +38,14 @@ export function unloadedTableStructureRefreshScope(activeTab: TableInfoTab, load
foreignKeys: visibleScope.foreignKeys && !loadedFacets.has("foreign-keys"),
constraints: visibleScope.constraints && !loadedFacets.has("constraints"),
triggers: visibleScope.triggers && !loadedFacets.has("triggers"),
// Partition metadata has no persisted cache facet; "partitions" is only
// tracked in the loaded-facet set so re-activating the tab does not
// re-fetch in a loop.
partitions: visibleScope.partitions && !loadedFacets.has("partitions"),
tableComment: visibleScope.tableComment && !loadedFacets.has("comment"),
};
}
export function hasTableStructureRefreshWork(scope: TableStructureRefreshScope): boolean {
return scope.columns || scope.indexes || scope.foreignKeys || scope.constraints || scope.triggers || scope.tableComment;
return scope.columns || scope.indexes || scope.foreignKeys || scope.constraints || scope.triggers || scope.partitions || scope.tableComment;
}