feat(pg,kingbase): partition table operations and detail queries
This commit is contained in:
1 parent
882bd130ab
commit
1000aa07b6
62 files changed
+6180
-133
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user