fix(query): enable editing multi-table JOIN result sets

This commit is contained in:
zipg authored and GitHub committed 2026-09-07 00:54:59 +08:00
1 parent 93a4b5803a
commit 14e1d4f25b
16 files changed
+345 -22

No files matched your search

@@ -0,0 +1,8 @@
import { expect, it } from "vitest";
import { analyzeEditableQueryEditability } from "../../sql/sqlAnalysis";
it("allows parentheses in JOIN predicates but not derived or function sources", () => {
expect(analyzeEditableQueryEditability("SELECT u.id,u.name,p.id,p.title FROM users u JOIN papers p ON (u.id=p.user_id)").editable).toBe(true);
for (const sql of ["SELECT u.id,p.id FROM users u JOIN (SELECT id FROM papers) p ON u.id=p.id", "SELECT u.id,p.id FROM users u JOIN generate_series(1,2) p ON u.id=p.id"]) {
expect(analyzeEditableQueryEditability(sql).editable).toBe(false);
}
});
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { joinedRowChanges, type JoinedWriteSource } from "../../dataGrid/joinedRowChanges";
const sources: JoinedWriteSource[] = [
{ tableKey: "users", primaryKeys: ["id"], sourceColumns: ["id", "name", undefined, undefined] },
{ tableKey: "papers", primaryKeys: ["id"], sourceColumns: [undefined, undefined, "id", "title"] },
];
describe("joined row updates", () => {
it("routes edits on both tables to their own primary key row", () => {
const updates = joinedRowChanges(
sources,
[[1, "user", 20, "paper"]],
new Map([
[
0,
new Map([
[1, "renamed"],
[3, "retitled"],
]),
],
]),
);
expect(updates).toEqual([
{ sourceIndex: 0, rowIndex: 0, changes: new Map([[1, "renamed"]]) },
{ sourceIndex: 1, rowIndex: 0, changes: new Map([[3, "retitled"]]) },
]);
});
it("coalesces the same user repeated by a one-to-many join", () => {
const rows = [
[1, "user", 20, "one"],
[1, "user", 21, "two"],
];
const updates = joinedRowChanges(
sources,
rows,
new Map([
[0, new Map([[1, "same"]])],
[1, new Map([[1, "same"]])],
]),
);
expect(updates).toHaveLength(1);
expect(() =>
joinedRowChanges(
sources,
rows,
new Map([
[0, new Map([[1, "first"]])],
[1, new Map([[1, "second"]])],
]),
),
).toThrow("Conflicting edits");
});
it("rejects an outer join row without an existing target record", () => {
expect(() => joinedRowChanges(sources, [[1, "user", null, null]], new Map([[0, new Map([[3, "new"]])]]))).toThrow("unmatched outer-join");
});
it("never treats an unbound expression or incomplete key as writable", () => {
expect(() => joinedRowChanges(sources, [[1, "user", 20, "paper", 5]], new Map([[0, new Map([[4, "value"]])]]))).toThrow("unique source");
expect(() => joinedRowChanges([{ ...sources[0]!, primaryKeys: ["missing"] }], [[1, "user"]], new Map([[0, new Map([[1, "new"]])]]))).toThrow("complete primary key");
});
it("distinguishes composite keys and physical tables", () => {
const composite = [{ tableKey: "users", primaryKeys: ["tenant", "id"], sourceColumns: ["tenant", "id", "name"] }];
expect(
joinedRowChanges(
composite,
[
[1, 2, "a"],
[2, 2, "b"],
],
new Map([
[0, new Map([[2, "x"]])],
[1, new Map([[2, "y"]])],
]),
),
).toHaveLength(2);
});
});
@@ -0,0 +1,89 @@
import type { CellValue } from "./cellValue";
import type { DataGridSaveStatementOptions, DataGridTableMeta } from "./dataGridSql";
export interface JoinedSaveTarget {
tableMeta: DataGridTableMeta;
sourceColumns: Array<string | undefined>;
}
/** Feed per-source changes through the existing SQL builder, including undo SQL. */
export function joinedSaveOptions(
targets: JoinedSaveTarget[],
options: Pick<DataGridSaveStatementOptions, "databaseType" | "identifierQuote" | "columns"> & {
rows: CellValue[][];
dirtyRows: Map<number, Map<number, CellValue>>;
newRows: CellValue[][];
deletedRows: Set<number>;
},
): DataGridSaveStatementOptions[] {
if (options.newRows.length || options.deletedRows.size) throw new Error("Joined results support updates only.");
const sources = targets.map(({ tableMeta, sourceColumns }) => ({
tableKey: JSON.stringify([tableMeta.catalog, tableMeta.database, tableMeta.schema, tableMeta.tableName]),
primaryKeys: tableMeta.primaryKeys,
sourceColumns,
}));
return joinedRowChanges(sources, options.rows, options.dirtyRows).map((update) => ({
databaseType: options.databaseType,
identifierQuote: options.identifierQuote,
columns: options.columns,
tableMeta: targets[update.sourceIndex]!.tableMeta,
sourceColumns: targets[update.sourceIndex]!.sourceColumns,
rows: options.rows,
dirtyRows: [[update.rowIndex, [...update.changes]]],
newRows: [],
deletedRows: [],
}));
}
export interface JoinedWriteSource {
/** Physical table identity; aliases of the same table must share this key. */
tableKey: string;
primaryKeys: string[];
sourceColumns: Array<string | undefined>;
}
export interface JoinedRowChange {
sourceIndex: number;
rowIndex: number;
changes: Map<number, CellValue>;
}
/** Route each edited cell to its physical row, coalescing repeated JOIN rows. */
export function joinedRowChanges(sources: JoinedWriteSource[], rows: CellValue[][], dirtyRows: Map<number, Map<number, CellValue>>): JoinedRowChange[] {
const updates = new Map<string, JoinedRowChange>();
for (const [rowIndex, changes] of dirtyRows) {
const row = rows[rowIndex];
if (!row) throw new Error("The edited query row is no longer available.");
for (const [columnIndex, value] of changes) {
const owners = sources.flatMap((source, index) => (source.sourceColumns[columnIndex] === undefined ? [] : [index]));
if (owners.length !== 1) throw new Error("The edited column does not have a unique source table.");
const sourceIndex = owners[0]!;
const source = sources[sourceIndex]!;
if (!source.primaryKeys.length) throw new Error("A joined row requires a complete primary key.");
const keys = source.primaryKeys.map((key) => {
const positions = source.sourceColumns.flatMap((name, index) => (name === key ? [index] : []));
if (!positions.length) throw new Error("A joined row requires a complete primary key.");
const original = row[positions[0]!];
if (original === null || original === undefined) throw new Error("Cannot update an unmatched outer-join row.");
if (positions.some((position) => JSON.stringify(row[position]) !== JSON.stringify(original))) throw new Error("Conflicting primary key projections in the query result.");
return original;
});
const identity = JSON.stringify([source.tableKey, keys]);
let update = updates.get(identity);
if (!update) {
update = { sourceIndex, rowIndex, changes: new Map() };
updates.set(identity, update);
}
// A self-join can project the same record through different aliases.
const target = sources[update.sourceIndex]!;
const columnName = source.sourceColumns[columnIndex]!;
const targetIndex = target.sourceColumns.indexOf(columnName);
if (targetIndex < 0) throw new Error("Repeated source rows have incompatible column projections.");
if (update.changes.has(targetIndex) && JSON.stringify(update.changes.get(targetIndex)) !== JSON.stringify(value)) {
throw new Error("Conflicting edits refer to the same source row and column.");
}
update.changes.set(targetIndex, value);
}
}
return [...updates.values()];
}
+1 -1
View File
@@ -613,7 +613,7 @@ function isSelectStar(body: string, alias: string | undefined): boolean {
}
function parseFromSources(body: string): EditableQuerySource[] {
if (!body || /[()]/.test(body)) return [];
if (!body) return [];
const sources: EditableQuerySource[] = [];
let pos = 0;
const first = parseTableSourceAt(body, pos, sources.length);
@@ -34,6 +34,7 @@ export interface TabResultSnapshot {
activeResultRunId?: string;
queryAnalysis?: QueryTab["queryAnalysis"];
querySourceColumns?: QueryTab["querySourceColumns"];
queryWriteTargets?: QueryTab["queryWriteTargets"];
resultColumnComments?: QueryTab["resultColumnComments"];
queryDisplaySourceColumns?: QueryTab["queryDisplaySourceColumns"];
queryEditabilityReason?: QueryTab["queryEditabilityReason"];
@@ -748,6 +749,7 @@ export function buildTabResultSnapshot(tab: QueryTab): TabResultSnapshot | undef
activeResultRunId: tab.activeResultRunId,
queryAnalysis: tab.queryAnalysis ? clonePlain(tab.queryAnalysis) : undefined,
querySourceColumns: tab.querySourceColumns ? [...tab.querySourceColumns] : undefined,
queryWriteTargets: tab.queryWriteTargets?.map((target) => ({ ...target, sourceColumns: [...target.sourceColumns] })),
resultColumnComments: tab.resultColumnComments ? clonePlain(tab.resultColumnComments) : undefined,
queryDisplaySourceColumns: tab.queryDisplaySourceColumns ? [...tab.queryDisplaySourceColumns] : undefined,
queryEditabilityReason: tab.queryEditabilityReason,