feat(extractor): configure INSERT quoting and portable temporal output
Closes #10559
This commit is contained in:
1 parent
a95762a536
commit
d4b4cf8279
13 files changed
+725
-20
No files matched your search
@@ -106,6 +106,7 @@ function warningText(code: DataGridExtractWarningCode, omittedColumns: string[]
|
||||
}
|
||||
|
||||
function schedulePreview() {
|
||||
previewSequence += 1;
|
||||
if (previewTimer) clearTimeout(previewTimer);
|
||||
previewTimer = setTimeout(() => void refreshPreview(), 180);
|
||||
}
|
||||
@@ -124,6 +125,7 @@ watch(
|
||||
draftOptions.value = normalizeDataGridExtractorOptions(props.options);
|
||||
schedulePreview();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
@@ -212,6 +214,18 @@ function save() {
|
||||
<label v-if="draftExtractor === 'sql-inserts'" class="flex items-center gap-2 text-sm"
|
||||
><input type="checkbox" :checked="draftOptions.sql.includeDatabaseName" @change="updateSql('includeDatabaseName', ($event.target as HTMLInputElement).checked)" />{{ t("grid.copyExtractorIncludeDatabaseName") }}</label
|
||||
>
|
||||
<div v-if="draftExtractor === 'sql-inserts'" class="space-y-1.5">
|
||||
<label class="flex items-center gap-2 text-sm"><input type="checkbox" :checked="draftOptions.sql.quoteIdentifiers" @change="updateSql('quoteIdentifiers', ($event.target as HTMLInputElement).checked)" />{{ t("grid.copyExtractorQuoteIdentifiers") }}</label>
|
||||
<Label>{{ t("grid.copyExtractorTemporalFormat") }}</Label>
|
||||
<Select :model-value="draftOptions.sql.temporalFormat" @update:model-value="updateSql('temporalFormat', $event as DataGridExtractorOptions['sql']['temporalFormat'])">
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="native">{{ t("grid.copyExtractorTemporalNative") }}</SelectItem>
|
||||
<SelectItem value="string">{{ t("grid.copyExtractorTemporalString") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p v-if="draftOptions.sql.temporalFormat === 'string'" class="text-xs text-muted-foreground">{{ t("grid.copyExtractorTemporalStringHint") }}</p>
|
||||
</div>
|
||||
<div v-if="draftExtractor === 'sql-inserts'" class="space-y-1.5">
|
||||
<Label>{{ t("grid.copyExtractorInsertMode") }}</Label>
|
||||
<Select :model-value="draftOptions.sql.insertMode" @update:model-value="updateSql('insertMode', $event as DataGridExtractorOptions['sql']['insertMode'])">
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { normalizeDataGridExtractorOptions, type DataGridExtractPreview } from "@/lib/dataGrid/dataGridCopyExtractor";
|
||||
|
||||
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("@/components/ui/dialog", () => {
|
||||
const passthrough = defineComponent({
|
||||
setup:
|
||||
(_, { slots }) =>
|
||||
() =>
|
||||
h("div", slots.default?.()),
|
||||
});
|
||||
return { Dialog: passthrough, DialogContent: passthrough, DialogFooter: passthrough, DialogHeader: passthrough, DialogTitle: passthrough };
|
||||
});
|
||||
vi.mock("@/components/ui/select", () => {
|
||||
const passthrough = defineComponent({
|
||||
setup:
|
||||
(_, { slots }) =>
|
||||
() =>
|
||||
h("div", slots.default?.()),
|
||||
});
|
||||
return {
|
||||
Select: defineComponent({
|
||||
props: ["modelValue"],
|
||||
emits: ["update:modelValue"],
|
||||
setup:
|
||||
(props, { emit, slots }) =>
|
||||
() =>
|
||||
h("select", { value: props.modelValue, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value) }, slots.default?.()),
|
||||
}),
|
||||
SelectItem: defineComponent({
|
||||
props: ["value"],
|
||||
setup:
|
||||
(props, { slots }) =>
|
||||
() =>
|
||||
h("option", { value: props.value }, slots.default?.()),
|
||||
}),
|
||||
SelectContent: passthrough,
|
||||
SelectTrigger: passthrough,
|
||||
SelectValue: passthrough,
|
||||
};
|
||||
});
|
||||
|
||||
import DataGridExtractorDialog from "../DataGridExtractorDialog.vue";
|
||||
|
||||
const mounted: Array<{ app: App; host: HTMLElement }> = [];
|
||||
const result = (text: string): DataGridExtractPreview => ({ text, mimeType: "text/plain", fileExtension: "sql", rowCount: 1, columnCount: 1, sourceRowCount: 1, truncated: false });
|
||||
|
||||
function deferred() {
|
||||
let resolve!: (value: DataGridExtractPreview) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<DataGridExtractPreview>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function mountDialog(preview = vi.fn(async () => result("initial")), open = false) {
|
||||
const props = reactive({ open, preference: "sql-inserts" as const, options: normalizeDataGridExtractorOptions({}), items: [{ value: "sql-inserts" as const, label: "INSERT" }], preview });
|
||||
const save = vi.fn();
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp({ render: () => h(DataGridExtractorDialog, { ...props, onSave: save }) });
|
||||
app.mount(host);
|
||||
mounted.push({ app, host });
|
||||
return { props, host, save, preview };
|
||||
}
|
||||
|
||||
async function advancePreview() {
|
||||
await nextTick();
|
||||
await vi.advanceTimersByTimeAsync(180);
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
async function toggle(host: HTMLElement, key: string) {
|
||||
const label = Array.from(host.querySelectorAll("label")).find((item) => item.textContent?.includes(key));
|
||||
const input = label?.querySelector("input");
|
||||
expect(input).toBeTruthy();
|
||||
input!.checked = !input!.checked;
|
||||
input!.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const { app, host } of mounted.splice(0)) {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
}
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("extractor draft preview", () => {
|
||||
it("previews an initially open dialog", async () => {
|
||||
const { preview, host } = mountDialog(undefined, true);
|
||||
await advancePreview();
|
||||
expect(preview).toHaveBeenCalledOnce();
|
||||
expect(host.querySelector("pre")?.textContent).toBe("initial");
|
||||
});
|
||||
|
||||
it("previews unsaved quote and temporal options without mutating saved settings", async () => {
|
||||
const { props, host, preview, save } = mountDialog();
|
||||
props.open = true;
|
||||
await advancePreview();
|
||||
await toggle(host, "copyExtractorQuoteIdentifiers");
|
||||
const select = Array.from(host.querySelectorAll("select")).find((item) => item.querySelector('option[value="string"]'))!;
|
||||
expect(select).toBeTruthy();
|
||||
select.value = "string";
|
||||
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
await advancePreview();
|
||||
expect(preview).toHaveBeenLastCalledWith("sql-inserts", expect.objectContaining({ sql: expect.objectContaining({ quoteIdentifiers: false, temporalFormat: "string" }) }));
|
||||
expect(props.options.sql).toMatchObject({ quoteIdentifiers: true, temporalFormat: "native" });
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
const button = Array.from(host.querySelectorAll("button")).find((item) => item.textContent?.includes("common.save"))!;
|
||||
button.click();
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ options: expect.objectContaining({ sql: expect.objectContaining({ quoteIdentifiers: false, temporalFormat: "string" }) }) }));
|
||||
});
|
||||
|
||||
it.each(["resolve", "reject"] as const)("ignores an old %s during the debounce window and after a newer preview", async (settle) => {
|
||||
const old = deferred();
|
||||
const newer = deferred();
|
||||
const preview = vi
|
||||
.fn(async () => result("latest"))
|
||||
.mockReturnValueOnce(old.promise)
|
||||
.mockReturnValueOnce(newer.promise);
|
||||
const { props, host } = mountDialog(preview);
|
||||
props.open = true;
|
||||
await advancePreview();
|
||||
await toggle(host, "copyExtractorSkipComputed");
|
||||
if (settle === "resolve") old.resolve(result("stale"));
|
||||
else old.reject(new Error("stale error"));
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(host.querySelector("pre")?.textContent).not.toContain("stale");
|
||||
await advancePreview();
|
||||
await toggle(host, "copyExtractorSkipGenerated");
|
||||
await advancePreview();
|
||||
expect(host.querySelector("pre")?.textContent).toBe("latest");
|
||||
newer.resolve(result("also stale"));
|
||||
await nextTick();
|
||||
expect(host.querySelector("pre")?.textContent).toBe("latest");
|
||||
});
|
||||
|
||||
it("shows current errors and resets draft options when reopened", async () => {
|
||||
const preview = vi.fn(async () => result("reopened")).mockRejectedValueOnce(new Error("preview failed"));
|
||||
const { props, host } = mountDialog(preview);
|
||||
props.open = true;
|
||||
await advancePreview();
|
||||
expect(host.querySelector("pre")?.textContent).toBe("preview failed");
|
||||
await toggle(host, "copyExtractorSkipComputed");
|
||||
props.open = false;
|
||||
await advancePreview();
|
||||
expect(preview).toHaveBeenCalledOnce();
|
||||
props.open = true;
|
||||
await advancePreview();
|
||||
expect(preview).toHaveBeenLastCalledWith("sql-inserts", props.options);
|
||||
expect(host.querySelector("pre")?.textContent).toBe("reopened");
|
||||
});
|
||||
|
||||
it("ignores pending results after the dialog closes", async () => {
|
||||
const pending = deferred();
|
||||
const { props, host } = mountDialog(vi.fn(() => pending.promise));
|
||||
props.open = true;
|
||||
await advancePreview();
|
||||
props.open = false;
|
||||
await nextTick();
|
||||
pending.resolve(result("closed result"));
|
||||
await nextTick();
|
||||
expect(host.querySelector("pre")?.textContent).not.toContain("closed result");
|
||||
});
|
||||
});
|
||||
@@ -1227,6 +1227,19 @@ describe("useDataGridExport prepared row statements", () => {
|
||||
expect(vi.mocked(extractDataGridSelection).mock.calls.map(([request]) => request.options)).toEqual([extractorOptions, extractorOptions, extractorOptions]);
|
||||
});
|
||||
|
||||
it("sends unsaved INSERT policies to preview without changing the saved copy options", async () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0, 1], columns: ["id", "name"], rows: [[1, "Ada"]] };
|
||||
const saved = structuredClone(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS);
|
||||
const draft = { ...saved, sql: { ...saved.sql, quoteIdentifiers: false, temporalFormat: "string" as const } };
|
||||
const state = createExportState(editableTable, ["id", "name"], matrix, [1, "Ada"], undefined, matrix.rows, [], saved);
|
||||
|
||||
await state.previewWithPreference("sql-inserts", draft);
|
||||
expect(vi.mocked(extractDataGridSelection).mock.lastCall?.[0].options.sql).toEqual(draft.sql);
|
||||
expect(copyToClipboard).not.toHaveBeenCalled();
|
||||
await state.copyWithExtractor("sql-inserts");
|
||||
expect(vi.mocked(extractDataGridSelection).mock.lastCall?.[0].options.sql).toEqual(saved.sql);
|
||||
});
|
||||
|
||||
it("does not report success when an extractor export save is cancelled", async () => {
|
||||
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [1], columns: ["name"], rows: [["Ada"]] };
|
||||
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text: '[{"name":"Ada"}]', mimeType: "application/json", fileExtension: "json", rowCount: 1, columnCount: 1 });
|
||||
|
||||
@@ -2250,6 +2250,11 @@ export default {
|
||||
copyExtractorSkipGenerated: "Skip generated columns",
|
||||
copyExtractorExcludePrimaryKeys: "Exclude primary keys",
|
||||
copyExtractorIncludeDatabaseName: "Include database name",
|
||||
copyExtractorQuoteIdentifiers: "Quote table and column names",
|
||||
copyExtractorTemporalFormat: "Date and time values",
|
||||
copyExtractorTemporalNative: "Native database format",
|
||||
copyExtractorTemporalString: "Quoted string (YYYY-MM-DD HH:mm:ss)",
|
||||
copyExtractorTemporalStringHint: "Keeps the source date and time to seconds, without fractional seconds or a time zone.",
|
||||
copyExtractorInsertMode: "INSERT statements",
|
||||
copyExtractorInsertMerged: "Merge rows",
|
||||
copyExtractorInsertRowByRow: "One statement per row",
|
||||
|
||||
@@ -2162,6 +2162,11 @@ export default withEnglishFallback({
|
||||
copyExtractorSkipGenerated: "跳过生成列",
|
||||
copyExtractorExcludePrimaryKeys: "排除主键",
|
||||
copyExtractorIncludeDatabaseName: "包含数据库名称",
|
||||
copyExtractorQuoteIdentifiers: "表名和字段名加引号",
|
||||
copyExtractorTemporalFormat: "日期和时间值",
|
||||
copyExtractorTemporalNative: "数据库原生格式",
|
||||
copyExtractorTemporalString: "带引号字符串(YYYY-MM-DD HH:mm:ss)",
|
||||
copyExtractorTemporalStringHint: "保留原日期和时间到秒,不包含小数秒和时区。",
|
||||
copyExtractorInsertMode: "INSERT 语句模式",
|
||||
copyExtractorInsertMerged: "合并多行",
|
||||
copyExtractorInsertRowByRow: "每行一条语句",
|
||||
|
||||
@@ -2688,6 +2688,11 @@ export default withEnglishFallback({
|
||||
copyExtractorSkipGenerated: "跳過生成列",
|
||||
copyExtractorExcludePrimaryKeys: "排除主鍵",
|
||||
copyExtractorIncludeDatabaseName: "包含資料庫名稱",
|
||||
copyExtractorQuoteIdentifiers: "資料表名稱和欄位名稱加引號",
|
||||
copyExtractorTemporalFormat: "日期和時間值",
|
||||
copyExtractorTemporalNative: "資料庫原生格式",
|
||||
copyExtractorTemporalString: "帶引號字串(YYYY-MM-DD HH:mm:ss)",
|
||||
copyExtractorTemporalStringHint: "保留原日期和時間到秒,不包含小數秒和時區。",
|
||||
copyExtractorInsertMode: "INSERT 語句模式",
|
||||
copyExtractorInsertMerged: "合併多行",
|
||||
copyExtractorInsertRowByRow: "每行一條語句",
|
||||
|
||||
@@ -2,6 +2,16 @@ import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, normalizeDataGridCopyPreference, normalizeDataGridExtractorOptions, resolveDataGridCopyPreference, validateDataGridExtractorOptions } from "@/lib/dataGrid/dataGridCopyExtractor";
|
||||
|
||||
describe("data-grid extractor options", () => {
|
||||
it("preserves native SQL defaults and normalizes portable INSERT options", () => {
|
||||
for (const legacy of [undefined, {}, { sql: {} }, { sql: { insertMode: "row-by-row" } }]) {
|
||||
expect(normalizeDataGridExtractorOptions(legacy).sql).toMatchObject({ quoteIdentifiers: true, temporalFormat: "native" });
|
||||
}
|
||||
const configured = normalizeDataGridExtractorOptions({ sql: { quoteIdentifiers: false, temporalFormat: "string" } });
|
||||
expect(configured.sql).toMatchObject({ quoteIdentifiers: false, temporalFormat: "string" });
|
||||
expect(normalizeDataGridExtractorOptions(JSON.parse(JSON.stringify(configured)))).toEqual(configured);
|
||||
expect(normalizeDataGridExtractorOptions({ sql: { quoteIdentifiers: "false", temporalFormat: "custom" } }).sql).toMatchObject({ quoteIdentifiers: true, temporalFormat: "native" });
|
||||
});
|
||||
|
||||
it("keeps database qualification for legacy options and persists explicit opt-out", () => {
|
||||
expect(normalizeDataGridExtractorOptions({ sql: {} }).sql.includeDatabaseName).toBe(true);
|
||||
const configured = normalizeDataGridExtractorOptions({ sql: { includeDatabaseName: false } });
|
||||
|
||||
@@ -89,6 +89,8 @@ export interface DataGridExtractorOptions {
|
||||
insertMode: DataGridCopyInsertMode;
|
||||
excludePrimaryKeysFromInsert: boolean;
|
||||
includeDatabaseName: boolean;
|
||||
quoteIdentifiers: boolean;
|
||||
temporalFormat: "native" | "string";
|
||||
};
|
||||
json: {
|
||||
pretty: boolean;
|
||||
@@ -150,6 +152,8 @@ export const DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS: DataGridExtractorOptions = {
|
||||
insertMode: "merged",
|
||||
excludePrimaryKeysFromInsert: false,
|
||||
includeDatabaseName: true,
|
||||
quoteIdentifiers: true,
|
||||
temporalFormat: "native",
|
||||
},
|
||||
json: { pretty: true, camelCaseFieldNames: false },
|
||||
};
|
||||
@@ -181,6 +185,8 @@ export function normalizeDataGridExtractorOptions(value: unknown): DataGridExtra
|
||||
insertMode: sql.insertMode === "row-by-row" ? "row-by-row" : "merged",
|
||||
excludePrimaryKeysFromInsert: sql.excludePrimaryKeysFromInsert === true,
|
||||
includeDatabaseName: sql.includeDatabaseName !== false,
|
||||
quoteIdentifiers: sql.quoteIdentifiers !== false,
|
||||
temporalFormat: sql.temporalFormat === "string" ? "string" : "native",
|
||||
},
|
||||
json: {
|
||||
pretty: json.pretty !== false,
|
||||
|
||||
Reference in new issue
Block a user