feat(grid): navigate foreign key cells to referenced records
This commit is contained in:
1 parent
8f3fd0ebfb
commit
ac6b53365b
14 files changed
+436
-11
No files matched your search
+159
@@ -0,0 +1,159 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildColumnForeignKeyMap, combineForeignKeyConditions, foreignKeyAssociationCells, foreignKeyCellNavigable, foreignKeyMetadataRequestCurrent, foreignKeyNavigationTarget, foreignKeySourceColumnName, foreignKeyTableIdentity } from "@/lib/dataGrid/dataGridForeignKeyNavigation";
|
||||
import type { ForeignKeyInfo } from "@/types/database";
|
||||
|
||||
function fk(overrides: Partial<ForeignKeyInfo> = {}): ForeignKeyInfo {
|
||||
return {
|
||||
name: "fk_orders_customer",
|
||||
column: "customer_id",
|
||||
ref_schema: "public",
|
||||
ref_table: "customers",
|
||||
ref_column: "id",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildColumnForeignKeyMap", () => {
|
||||
it("indexa por nombre de columna en minúsculas", () => {
|
||||
const map = buildColumnForeignKeyMap([fk({ column: "Customer_ID" })]);
|
||||
expect(map.get("customer_id")?.foreignKey.ref_table).toBe("customers");
|
||||
expect(map.has("Customer_ID")).toBe(false);
|
||||
});
|
||||
|
||||
it("ante columnas duplicadas gana la primera entrada", () => {
|
||||
const map = buildColumnForeignKeyMap([fk({ name: "fk_a", ref_table: "customers" }), fk({ name: "fk_b", ref_table: "accounts" })]);
|
||||
expect(map.get("customer_id")?.foreignKey.name).toBe("fk_a");
|
||||
});
|
||||
|
||||
it("agrupa todas las parejas de columnas de una FK compuesta", () => {
|
||||
const map = buildColumnForeignKeyMap([fk({ name: "fk_comp", column: "order_id", ref_table: "order_items", ref_column: "order_id" }), fk({ name: "fk_comp", column: "line_no", ref_table: "order_items", ref_column: "line_no" })]);
|
||||
expect(map.size).toBe(2);
|
||||
expect(map.get("order_id")).toBe(map.get("line_no"));
|
||||
expect(map.get("order_id")?.columnPairs.map((pair) => [pair.column, pair.ref_column])).toEqual([
|
||||
["order_id", "order_id"],
|
||||
["line_no", "line_no"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignora entradas incompletas", () => {
|
||||
const map = buildColumnForeignKeyMap([fk({ column: "" }), fk({ column: "a", ref_table: "" }), fk({ column: "b", ref_column: "" })]);
|
||||
expect(map.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreignKeySourceColumnName", () => {
|
||||
it("en resultados SQL solo usa el binding de columna física", () => {
|
||||
expect(foreignKeySourceColumnName({ context: "results", resultColumns: ["customer"], sourceColumns: ["customer_id"], columnIndex: 0 })).toBe("customer_id");
|
||||
expect(foreignKeySourceColumnName({ context: "results", resultColumns: ["customer_id"], columnIndex: 0 })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("en datos de tabla usa el nombre visible si no hay binding separado", () => {
|
||||
expect(foreignKeySourceColumnName({ context: "table-data", resultColumns: ["customer_id"], columnIndex: 0 })).toBe("customer_id");
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreignKeyAssociationCells", () => {
|
||||
const association = buildColumnForeignKeyMap([fk({ name: "fk_comp", column: "order_id", ref_table: "order_items", ref_column: "order_id" }), fk({ name: "fk_comp", column: "line_no", ref_table: "order_items", ref_column: "line_no" })]).get("order_id")!;
|
||||
|
||||
it("resuelve todas las columnas físicas de una FK compuesta en resultados con alias", () => {
|
||||
const cells = foreignKeyAssociationCells({
|
||||
association,
|
||||
context: "results",
|
||||
resultColumns: ["order", "line"],
|
||||
sourceColumns: ["order_id", "line_no"],
|
||||
row: [42, 7],
|
||||
});
|
||||
expect(cells?.map((cell) => [cell.foreignKey.ref_column, cell.columnIndex, cell.value])).toEqual([
|
||||
["order_id", 0, 42],
|
||||
["line_no", 1, 7],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rechaza la navegación si falta un binding físico", () => {
|
||||
expect(
|
||||
foreignKeyAssociationCells({
|
||||
association,
|
||||
context: "results",
|
||||
resultColumns: ["order", "line_no"],
|
||||
sourceColumns: ["order_id", undefined],
|
||||
row: [42, 7],
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rechaza la navegación si cualquier valor compuesto es nulo", () => {
|
||||
expect(
|
||||
foreignKeyAssociationCells({
|
||||
association,
|
||||
context: "table-data",
|
||||
resultColumns: ["order_id", "line_no"],
|
||||
row: [42, null],
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("combineForeignKeyConditions", () => {
|
||||
it("combina todas las parejas de una FK compuesta con AND", () => {
|
||||
expect(combineForeignKeyConditions(['"order_id" = 42', '"line_no" = 7'])).toBe('("order_id" = 42) AND ("line_no" = 7)');
|
||||
});
|
||||
|
||||
it("no construye un filtro parcial", () => {
|
||||
expect(combineForeignKeyConditions(['"order_id" = 42', undefined])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreign key metadata request guard", () => {
|
||||
it("incluye toda la identidad de tabla", () => {
|
||||
const first = foreignKeyTableIdentity({ connectionId: "c1", database: "db", catalog: "cat", schema: "sales", tableName: "orders" });
|
||||
const reusedTab = foreignKeyTableIdentity({ connectionId: "c1", database: "db", catalog: "cat", schema: "sales", tableName: "invoices" });
|
||||
expect(first).not.toBe(reusedTab);
|
||||
});
|
||||
|
||||
it("ignora respuestas de otra tabla o generación", () => {
|
||||
const orders = foreignKeyTableIdentity({ connectionId: "c1", database: "db", schema: "sales", tableName: "orders" })!;
|
||||
const invoices = foreignKeyTableIdentity({ connectionId: "c1", database: "db", schema: "sales", tableName: "invoices" })!;
|
||||
expect(foreignKeyMetadataRequestCurrent({ requestGeneration: 3, currentGeneration: 3, requestIdentity: orders, currentIdentity: orders })).toBe(true);
|
||||
expect(foreignKeyMetadataRequestCurrent({ requestGeneration: 3, currentGeneration: 4, requestIdentity: orders, currentIdentity: orders })).toBe(false);
|
||||
expect(foreignKeyMetadataRequestCurrent({ requestGeneration: 3, currentGeneration: 3, requestIdentity: orders, currentIdentity: invoices })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreignKeyCellNavigable", () => {
|
||||
it("null y undefined no son navegables", () => {
|
||||
expect(foreignKeyCellNavigable(null)).toBe(false);
|
||||
expect(foreignKeyCellNavigable(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("0, cadena vacía y false son valores FK legítimos", () => {
|
||||
expect(foreignKeyCellNavigable(0)).toBe(true);
|
||||
expect(foreignKeyCellNavigable("")).toBe(true);
|
||||
expect(foreignKeyCellNavigable(false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("foreignKeyNavigationTarget", () => {
|
||||
it("usa ref_schema cuando está presente", () => {
|
||||
const target = foreignKeyNavigationTarget({ connectionId: "c1", database: "db", currentSchema: "app", fk: fk({ ref_schema: "sales" }) });
|
||||
expect(target.schema).toBe("sales");
|
||||
expect(target.tableName).toBe("customers");
|
||||
expect(target.columnName).toBe("id");
|
||||
expect(target.connectionId).toBe("c1");
|
||||
expect(target.database).toBe("db");
|
||||
});
|
||||
|
||||
it("sin ref_schema cae al schema actual", () => {
|
||||
const target = foreignKeyNavigationTarget({ connectionId: "c1", database: "db", currentSchema: "app", fk: fk({ ref_schema: null }) });
|
||||
expect(target.schema).toBe("app");
|
||||
});
|
||||
|
||||
it("sin ref_schema ni schema actual queda undefined", () => {
|
||||
const target = foreignKeyNavigationTarget({ connectionId: "c1", database: "db", fk: fk({ ref_schema: undefined }) });
|
||||
expect(target.schema).toBeUndefined();
|
||||
});
|
||||
|
||||
it("propaga whereInput", () => {
|
||||
const target = foreignKeyNavigationTarget({ connectionId: "c1", database: "db", fk: fk(), whereInput: '"id" = 7' });
|
||||
expect(target.whereInput).toBe('"id" = 7');
|
||||
});
|
||||
});
|
||||
@@ -143,8 +143,13 @@ export function fitCanvasText(ctx: CanvasRenderingContext2D, text: string, maxWi
|
||||
return result;
|
||||
}
|
||||
|
||||
export function canvasDataGridActionReservedWidth(canQuickDownload: boolean): number {
|
||||
return (canQuickDownload ? 44 : 22) + 6;
|
||||
export function canvasDataGridActionReservedWidth(canQuickDownload: boolean, canNavigateForeignKey = false): number {
|
||||
return canvasDataGridActionOverlayWidth(canQuickDownload, canNavigateForeignKey) + 6;
|
||||
}
|
||||
|
||||
/** 悬浮按钮组宽度:每个按钮 20px + 2px 间距(detail 按钮始终存在) */
|
||||
export function canvasDataGridActionOverlayWidth(canQuickDownload: boolean, canNavigateForeignKey = false): number {
|
||||
return 22 + (canQuickDownload ? 22 : 0) + (canNavigateForeignKey ? 22 : 0);
|
||||
}
|
||||
|
||||
export function resolveCanvasCellTextLayout(options: { drawX: number; colWidth: number; dpr: number; isRightAlign: boolean; reservedWidth?: number }): { textAnchorX: number; maxWidth: number } {
|
||||
|
||||
@@ -129,6 +129,7 @@ export function createDataGridCellContextMenuItems(options: {
|
||||
icons: Pick<DataGridContextMenuIcons, "cellDetails" | "columnDetails" | "rowDetails" | "setNull" | "bulkEdit" | "transpose">;
|
||||
actions: Record<"cellDetails" | "columnDetails" | "rowDetails" | "setNull" | "bulkEdit" | "transpose", () => void>;
|
||||
downloadItem?: DataGridContextMenuItem | null;
|
||||
foreignKeyItem?: DataGridContextMenuItem | null;
|
||||
copySubmenu: DataGridContextMenuItem;
|
||||
clearSelectionItem?: DataGridContextMenuItem;
|
||||
generateSubmenu?: DataGridContextMenuItem;
|
||||
@@ -138,6 +139,7 @@ export function createDataGridCellContextMenuItems(options: {
|
||||
if (options.hasColumn) {
|
||||
items.push({ label: options.labels.cellDetails, action: options.actions.cellDetails, icon: options.icons.cellDetails });
|
||||
if (options.downloadItem) items.push(options.downloadItem);
|
||||
if (options.foreignKeyItem) items.push(options.foreignKeyItem);
|
||||
items.push({ label: options.labels.columnDetails, action: options.actions.columnDetails, icon: options.icons.columnDetails });
|
||||
}
|
||||
items.push({ label: options.labels.rowDetails, action: options.actions.rowDetails, icon: options.icons.rowDetails }, { label: "", separator: true });
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { NavigationTarget } from "@/composables/useNavigationTargets";
|
||||
import type { CellValue } from "@/lib/dataGrid/cellValue";
|
||||
import type { ForeignKeyInfo } from "@/types/database";
|
||||
|
||||
export interface ForeignKeyAssociation {
|
||||
foreignKey: ForeignKeyInfo;
|
||||
columnPairs: ForeignKeyInfo[];
|
||||
}
|
||||
|
||||
export interface ForeignKeyAssociationCell {
|
||||
foreignKey: ForeignKeyInfo;
|
||||
columnIndex: number;
|
||||
value: CellValue;
|
||||
}
|
||||
|
||||
function foreignKeyAssociationKey(foreignKey: ForeignKeyInfo): string {
|
||||
return JSON.stringify([foreignKey.name, foreignKey.ref_schema ?? "", foreignKey.ref_table, foreignKey.on_update ?? "", foreignKey.on_delete ?? ""]);
|
||||
}
|
||||
|
||||
/** 列名(小写)→ 外键 association。同列出现在多个 association 时保留第一条。 */
|
||||
export function buildColumnForeignKeyMap(foreignKeys: ForeignKeyInfo[]): Map<string, ForeignKeyAssociation> {
|
||||
const associations = new Map<string, ForeignKeyAssociation>();
|
||||
for (const fk of foreignKeys) {
|
||||
if (!fk.column || !fk.ref_table || !fk.ref_column) continue;
|
||||
const associationKey = foreignKeyAssociationKey(fk);
|
||||
const association = associations.get(associationKey);
|
||||
if (association) association.columnPairs.push(fk);
|
||||
else associations.set(associationKey, { foreignKey: fk, columnPairs: [fk] });
|
||||
}
|
||||
|
||||
const map = new Map<string, ForeignKeyAssociation>();
|
||||
for (const association of associations.values()) {
|
||||
for (const foreignKey of association.columnPairs) {
|
||||
const columnKey = foreignKey.column.toLowerCase();
|
||||
if (!map.has(columnKey)) map.set(columnKey, association);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/** NULL/undefined 没有可跳转的目标记录;0、空串、false 都是合法外键值 */
|
||||
export function foreignKeyCellNavigable(value: CellValue | undefined): value is Exclude<CellValue, null> {
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
export function foreignKeySourceColumnName(options: { context?: "results" | "table-data"; resultColumns: readonly string[]; sourceColumns?: readonly (string | undefined)[]; columnIndex: number }): string | undefined {
|
||||
const sourceColumn = options.sourceColumns?.[options.columnIndex] || undefined;
|
||||
if (sourceColumn || options.context === "results") return sourceColumn;
|
||||
return options.resultColumns[options.columnIndex] || undefined;
|
||||
}
|
||||
|
||||
export function foreignKeyAssociationCells(options: { association: ForeignKeyAssociation; context?: "results" | "table-data"; resultColumns: readonly string[]; sourceColumns?: readonly (string | undefined)[]; row: readonly (CellValue | undefined)[] }): ForeignKeyAssociationCell[] | undefined {
|
||||
const sourceColumnIndexes = new Map<string, number>();
|
||||
for (let columnIndex = 0; columnIndex < options.resultColumns.length; columnIndex += 1) {
|
||||
const sourceColumn = foreignKeySourceColumnName({
|
||||
context: options.context,
|
||||
resultColumns: options.resultColumns,
|
||||
sourceColumns: options.sourceColumns,
|
||||
columnIndex,
|
||||
});
|
||||
if (sourceColumn && !sourceColumnIndexes.has(sourceColumn.toLowerCase())) sourceColumnIndexes.set(sourceColumn.toLowerCase(), columnIndex);
|
||||
}
|
||||
|
||||
const cells: ForeignKeyAssociationCell[] = [];
|
||||
for (const foreignKey of options.association.columnPairs) {
|
||||
const columnIndex = sourceColumnIndexes.get(foreignKey.column.toLowerCase());
|
||||
if (columnIndex === undefined) return undefined;
|
||||
const value = options.row[columnIndex];
|
||||
if (!foreignKeyCellNavigable(value)) return undefined;
|
||||
cells.push({ foreignKey, columnIndex, value });
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
export function combineForeignKeyConditions(conditions: readonly (string | undefined)[]): string | undefined {
|
||||
if (conditions.length === 0 || conditions.some((condition) => !condition)) return undefined;
|
||||
if (conditions.length === 1) return conditions[0];
|
||||
return conditions.map((condition) => `(${condition})`).join(" AND ");
|
||||
}
|
||||
|
||||
export function foreignKeyTableIdentity(options: { connectionId?: string; database?: string; catalog?: string; schema?: string; tableName?: string }): string | undefined {
|
||||
if (!options.connectionId || !options.tableName) return undefined;
|
||||
return JSON.stringify([options.connectionId, options.database ?? "", options.catalog ?? "", options.schema ?? "", options.tableName]);
|
||||
}
|
||||
|
||||
export function foreignKeyMetadataRequestCurrent(options: { requestGeneration: number; currentGeneration: number; requestIdentity: string; currentIdentity?: string }): boolean {
|
||||
return options.requestGeneration === options.currentGeneration && options.requestIdentity === options.currentIdentity;
|
||||
}
|
||||
|
||||
/** 构建跳转到被引用表的导航目标:ref_schema 缺失时回退当前 schema(同 ER 图) */
|
||||
export function foreignKeyNavigationTarget(options: { connectionId: string; database: string; currentSchema?: string; fk: ForeignKeyInfo; whereInput?: string }): NavigationTarget {
|
||||
const schema = options.fk.ref_schema || options.currentSchema || undefined;
|
||||
return {
|
||||
connectionId: options.connectionId,
|
||||
database: options.database,
|
||||
schema,
|
||||
tableName: options.fk.ref_table,
|
||||
columnName: options.fk.ref_column,
|
||||
whereInput: options.whereInput,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user