feat(grid): paste SQL INSERT statements into blank new rows

This commit is contained in:
yangzidemuou authored and GitHub committed 2026-09-30 15:28:07 +08:00
1 parent b32ef45da1
commit dc02e3bccf
18 files changed
+530 -9

No files matched your search

+18 -2
View File
@@ -307,6 +307,7 @@ import { useNavigationTargets } from "@/composables/useNavigationTargets";
import { useDataGridExport, type MongoCopyUpdateTarget } from "@/composables/useDataGridExport"; import { useDataGridExport, type MongoCopyUpdateTarget } from "@/composables/useDataGridExport";
import { eventTargetAllowsNativeClipboard, isPlainClipboardShortcut, readTextFromClipboard } from "@/lib/common/clipboard"; import { eventTargetAllowsNativeClipboard, isPlainClipboardShortcut, readTextFromClipboard } from "@/lib/common/clipboard";
import { claimDataGridPaste, claimDataGridSelectAll, clearDataGridClipboardCopy, parseDataGridClipboard, planDataGridPaste } from "@/lib/dataGrid/dataGridClipboard"; import { claimDataGridPaste, claimDataGridSelectAll, clearDataGridClipboardCopy, parseDataGridClipboard, planDataGridPaste } from "@/lib/dataGrid/dataGridClipboard";
import { parseInsertStatementPaste } from "@/lib/dataGrid/dataGridInsertPaste";
import { beginDataGridNativeSelectionBlock, finishDataGridNativeSelectionBlock } from "@/lib/dataGrid/dataGridNativeSelection"; import { beginDataGridNativeSelectionBlock, finishDataGridNativeSelectionBlock } from "@/lib/dataGrid/dataGridNativeSelection";
import { DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS, DATA_GRID_COPY_EXTRACTOR_IDS, DATA_GRID_DEFAULT_COPY_PREFERENCES, extractorUnavailableForDatabase, type DataGridCopyExtractorId, type DataGridCopyPreference } from "@/lib/dataGrid/dataGridCopyExtractor"; import { DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS, DATA_GRID_COPY_EXTRACTOR_IDS, DATA_GRID_DEFAULT_COPY_PREFERENCES, extractorUnavailableForDatabase, type DataGridCopyExtractorId, type DataGridCopyPreference } from "@/lib/dataGrid/dataGridCopyExtractor";
import { columnNamesForCopy } from "@/lib/dataGrid/dataGridColumnNameCopy"; import { columnNamesForCopy } from "@/lib/dataGrid/dataGridColumnNameCopy";
@@ -8481,6 +8482,7 @@ function batchAppendPasteError(reason: string): string {
"target-not-empty": "grid.batchAppendPasteTargetNotEmpty", "target-not-empty": "grid.batchAppendPasteTargetNotEmpty",
"empty-paste": "grid.batchAppendPasteEmpty", "empty-paste": "grid.batchAppendPasteEmpty",
"readonly-column": "grid.batchAppendPasteReadonlyColumn", "readonly-column": "grid.batchAppendPasteReadonlyColumn",
"no-matching-columns": "grid.batchAppendPasteNoMatchingColumns",
}; };
return t(messages[reason] ?? "grid.batchAppendPasteInvalidTarget"); return t(messages[reason] ?? "grid.batchAppendPasteInvalidTarget");
} }
@@ -8497,8 +8499,8 @@ function blankSelectionBatchAppendPasteTarget(pastedRows: readonly (readonly (st
return { rowId: item.id, columnIndexes: visibleColumnIndexes.value.slice(range.startCol) }; return { rowId: item.id, columnIndexes: visibleColumnIndexes.value.slice(range.startCol) };
} }
function appendParsedRowsToBlankTarget(targetRowId: number, rows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[]): boolean { function appendParsedRowsToBlankTarget(targetRowId: number, rows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[], columnNames?: readonly string[] | null): boolean {
const result = appendPastedRowsToNewRow(targetRowId, rows, columnIndexes); const result = appendPastedRowsToNewRow(targetRowId, rows, columnIndexes, columnNames);
if (!result.ok) { if (!result.ok) {
if (result.reason === "invalid-target" || result.reason === "target-not-empty") { if (result.reason === "invalid-target" || result.reason === "target-not-empty") {
batchAppendPasteRowId.value = null; batchAppendPasteRowId.value = null;
@@ -8512,6 +8514,20 @@ function appendParsedRowsToBlankTarget(targetRowId: number, rows: readonly (read
} }
function pasteTextIntoGrid(text: string): boolean { function pasteTextIntoGrid(text: string): boolean {
// SQL INSERT statements are only meaningful as new rows, so they are honored
// on the blank-new-row targets below; any other target pastes the parsed
// values through the regular cell path instead of treating the whole
// statement as literal text.
const insertPaste = parseInsertStatementPaste(text);
if (insertPaste) {
const insertTargetRowId = batchAppendPasteTargetRowId();
if (insertTargetRowId !== null) {
return appendParsedRowsToBlankTarget(insertTargetRowId, insertPaste.rows, visibleColumnIndexes.value, insertPaste.columnNames);
}
const insertCellTarget = blankSelectionBatchAppendPasteTarget(insertPaste.rows);
if (insertCellTarget) return appendParsedRowsToBlankTarget(insertCellTarget.rowId, insertPaste.rows, insertCellTarget.columnIndexes, insertPaste.columnNames);
return pasteRowsIntoSelection(insertPaste.rows);
}
const rows = parseDataGridClipboard(text); const rows = parseDataGridClipboard(text);
const targetRowId = batchAppendPasteTargetRowId(); const targetRowId = batchAppendPasteTargetRowId();
if (targetRowId !== null) { if (targetRowId !== null) {
@@ -516,3 +516,44 @@ describe("DataGrid multi-row paste from a blank cell", () => {
expect(updates).toEqual([{ $set: { status: "{plain text" } }, { $set: { status: "{plain text" } }]); expect(updates).toEqual([{ $set: { status: "{plain text" } }, { $set: { status: "{plain text" } }]);
}); });
}); });
describe("DataGrid INSERT statement paste into blank new rows", () => {
it("fills a blank new row from a pasted INSERT statement aligned by column names", async () => {
const { host } = mountGrid();
await settle();
await addBlankRow(host);
const blankRows = pendingRows(host);
expect(blankRows).toHaveLength(1);
// Row-number selection marks the blank new row as the append target, so
// the INSERT values are aligned by column names instead of positions.
await selectRowNumber(blankRows[0]!);
// Column names in a scrambled order: c0 is the first visible column but
// receives 42 through name alignment, not position.
await paste(host, "INSERT INTO paste_target (c2, c0, hidden) VALUES ('from-insert', 42, 'h-val')");
const rows = pendingRows(host);
expect(rows).toHaveLength(1);
const cells = visibleCellTexts(rows[0]!);
expect(cells[0]).toBe("42");
expect(cells[1]).toBe("h-val");
expect(cells[2]).toBe("from-insert");
});
it("appends one row per statement when pasting multiple INSERT statements", async () => {
const { host } = mountGrid();
await settle();
await addBlankRow(host);
const blankRows = pendingRows(host);
await selectCell(visibleCells(blankRows[0]!)[0]!);
await paste(host, "INSERT INTO paste_target (c0, c2) VALUES (1, 'a');\nINSERT INTO paste_target (c0, c2) VALUES (2, 'b');");
const rows = pendingRows(host);
expect(rows).toHaveLength(2);
expect(visibleCellTexts(rows[0]!)[0]).toBe("1");
expect(visibleCellTexts(rows[0]!)[2]).toBe("a");
expect(visibleCellTexts(rows[1]!)[0]).toBe("2");
expect(visibleCellTexts(rows[1]!)[2]).toBe("b");
});
});
@@ -713,6 +713,36 @@ describe("useDataGridEditor appendPastedRowsToNewRow", () => {
expect(editor.hasPendingChanges.value).toBe(true); expect(editor.hasPendingChanges.value).toBe(true);
}); });
it("aligns pasted INSERT values by column name regardless of visible order", () => {
const editor = createEditor(["first", "hidden", "last"]);
// Visible columns are [2, 0]: "last" first, "first" second. The INSERT
// column names must map values to the real grid columns, not positions.
const result = editor.appendPastedRowsToNewRow(-1, [["Lovelace", "Ada"]], [2, 0], ["last", "first"]);
expect(result).toEqual({ ok: true, rowCount: 1 });
expect(editor.newRows.value).toEqual([["Ada", null, "Lovelace"]]);
});
it("matches INSERT column names case-insensitively and ignores unknown names", () => {
const editor = createEditor(["first", "hidden", "last"]);
const result = editor.appendPastedRowsToNewRow(-1, [["Ada", "extra", "Lovelace"]], [0, 1, 2], ["FIRST", "not_here", "Last"]);
expect(result).toEqual({ ok: true, rowCount: 1 });
expect(editor.newRows.value).toEqual([["Ada", null, "Lovelace"]]);
});
it("rejects an INSERT paste when no column names match", () => {
const editor = createEditor(["first", "hidden", "last"]);
const result = editor.appendPastedRowsToNewRow(-1, [["x"]], [0, 1, 2], ["nope"]);
expect(result).toEqual({ ok: false, reason: "no-matching-columns" });
// The pre-seeded blank new row stays untouched.
expect(editor.newRows.value).toEqual([[null, null, null]]);
});
it("clears generated key columns instead of pasting the copied value", () => { it("clears generated key columns instead of pasting the copied value", () => {
const editor = createEditor(undefined, true, undefined, undefined, [], undefined, [ const editor = createEditor(undefined, true, undefined, undefined, [], undefined, [
{ name: "first", data_type: "integer", extra: "autoincrement" }, { name: "first", data_type: "integer", extra: "autoincrement" },
@@ -737,6 +737,27 @@ describe("useDataGridExport prepared row statements", () => {
]); ]);
}); });
it("copies a selected row as whole-row TSV across all visible columns on smart copy", async () => {
// Row selection only (no cell matrix): the Cmd+C smart path must copy the
// full row (#10573), not just a single cell.
vi.mocked(extractDataGridSelection).mockResolvedValueOnce({ text: "1\tAda", mimeType: "text/tab-separated-values", fileExtension: "tsv", rowCount: 1, columnCount: 2 });
const state = createExportState(editableTable, ["id", "name"], undefined, undefined, undefined, [[1, "Ada"]], [1]);
await expect(state.copyWithPreference("smart")).resolves.toBe(true);
expect(extractDataGridSelection).toHaveBeenCalledWith(
expect.objectContaining({
extractor: "tsv",
selectionKind: "rows",
rows: [[1, "Ada"]],
selectedColumnIndexes: [0, 1],
}),
);
expect(copyToClipboard).toHaveBeenCalledWith("1\tAda");
// The internal clipboard matrix keeps the row paste-able back into a new row.
expect(parseDataGridClipboard("1\tAda")).toEqual([["1", "Ada"]]);
});
it("uses TSV (quotes only for separator/newline) for a multi-cell smart copy without relying on clipboard metadata", async () => { it("uses TSV (quotes only for separator/newline) for a multi-cell smart copy without relying on clipboard metadata", async () => {
const rows = [ const rows = [
[1, '{"msg":"success"}'], [1, '{"msg":"success"}'],
@@ -51,7 +51,7 @@ interface ConditionalUpdateExecution {
outcome: ConditionalUpdateOutcome; outcome: ConditionalUpdateOutcome;
} }
export type DataGridAppendPastedRowsResult = { ok: true; rowCount: number } | { ok: false; reason: "not-editable" | "invalid-target" | "target-not-empty" | "empty-paste" | "readonly-column" }; export type DataGridAppendPastedRowsResult = { ok: true; rowCount: number } | { ok: false; reason: "not-editable" | "invalid-target" | "target-not-empty" | "empty-paste" | "readonly-column" | "no-matching-columns" };
type CommitEditResult = type CommitEditResult =
| { | {
@@ -1240,7 +1240,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return row.every((value) => value === null || (typeof value === "string" && value.trim() === "")); return row.every((value) => value === null || (typeof value === "string" && value.trim() === ""));
} }
function appendPastedRowsToNewRow(targetRowId: number, pastedRows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[]): DataGridAppendPastedRowsResult { function appendPastedRowsToNewRow(targetRowId: number, pastedRows: readonly (readonly (string | null)[])[], columnIndexes: readonly number[], columnNames?: readonly string[] | null): DataGridAppendPastedRowsResult {
if (!editable.value) return { ok: false, reason: "not-editable" }; if (!editable.value) return { ok: false, reason: "not-editable" };
if (pastedRows.every((row) => row.every((value) => value === ""))) { if (pastedRows.every((row) => row.every((value) => value === ""))) {
return { ok: false, reason: "empty-paste" }; return { ok: false, reason: "empty-paste" };
@@ -1260,8 +1260,26 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const pastedColumnCount = Math.max(...pastedRows.map((row) => row.length)); const pastedColumnCount = Math.max(...pastedRows.map((row) => row.length));
if (pastedColumnCount <= 0) return { ok: false, reason: "empty-paste" }; if (pastedColumnCount <= 0) return { ok: false, reason: "empty-paste" };
const targetColumns = columnIndexes.slice(0, pastedColumnCount); // With explicit column names (SQL INSERT), align pasted values by column
if (targetColumns.some((columnIndex) => !canEditColumn(columnIndex))) return { ok: false, reason: "readonly-column" }; // name instead of visible position. Unknown names are ignored together
// with their values; if none of the pasted names matches this result's
// columns, reject the paste.
const valueTargets: Array<{ columnIndex: number; valueIndex: number }> = [];
if (columnNames?.length) {
const nameToColumnIndex = new Map<string, number>();
columnIndexes.forEach((columnIndex) => {
const name = sourceColumns.value?.[columnIndex] ?? result.value.columns[columnIndex];
if (name !== undefined && !nameToColumnIndex.has(name.toLowerCase())) nameToColumnIndex.set(name.toLowerCase(), columnIndex);
});
columnNames.forEach((name, valueIndex) => {
const columnIndex = nameToColumnIndex.get(name.toLowerCase());
if (columnIndex !== undefined) valueTargets.push({ columnIndex, valueIndex });
});
if (valueTargets.length === 0) return { ok: false, reason: "no-matching-columns" };
} else {
columnIndexes.slice(0, pastedColumnCount).forEach((columnIndex, valueIndex) => valueTargets.push({ columnIndex, valueIndex }));
}
if (valueTargets.some(({ columnIndex }) => !canEditColumn(columnIndex))) return { ok: false, reason: "readonly-column" };
const nextRows = newRows.value.map((row) => [...row]); const nextRows = newRows.value.map((row) => [...row]);
const nextMeta = cloneNewRowMeta(newRowMeta.value); const nextMeta = cloneNewRowMeta(newRowMeta.value);
@@ -1275,14 +1293,14 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const shouldClearColumn = clonedColumnClearPredicate(); const shouldClearColumn = clonedColumnClearPredicate();
const mappedRows = pastedRows.map((pastedRow, rowIndex) => { const mappedRows = pastedRows.map((pastedRow, rowIndex) => {
const nextRow = rowIndex < reusableNewRowCount ? nextRows[targetNewIndex! + rowIndex]! : emptyDraftRow(); const nextRow = rowIndex < reusableNewRowCount ? nextRows[targetNewIndex! + rowIndex]! : emptyDraftRow();
for (let columnOffset = 0; columnOffset < Math.min(pastedRow.length, targetColumns.length); columnOffset++) { for (const { columnIndex, valueIndex } of valueTargets) {
const columnIndex = targetColumns[columnOffset]!; if (valueIndex >= pastedRow.length) continue;
// Pasting a copied row into a new row must not reuse its generated key. // Pasting a copied row into a new row must not reuse its generated key.
if (shouldClearColumn(columnIndex)) { if (shouldClearColumn(columnIndex)) {
nextRow[columnIndex] = null; nextRow[columnIndex] = null;
continue; continue;
} }
const value = pastedRow[columnOffset]; const value = pastedRow[valueIndex];
nextRow[columnIndex] = value === null ? null : coerceCellValue(value, nextRow[columnIndex], columnIndex); nextRow[columnIndex] = value === null ? null : coerceCellValue(value, nextRow[columnIndex], columnIndex);
} }
return nextRow; return nextRow;
+1
View File
@@ -2176,6 +2176,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "Seçilmiş yeni sətirdə artıq verilənlər var.", batchAppendPasteTargetNotEmpty: "Seçilmiş yeni sətirdə artıq verilənlər var.",
batchAppendPasteEmpty: "Mübadilə buferində əlavə ediləcək sətir yoxdur.", batchAppendPasteEmpty: "Mübadilə buferində əlavə ediləcək sətir yoxdur.",
batchAppendPasteReadonlyColumn: "Yerləşdirilən verilənlərdə redaktə edilə bilməyən sütun var.", batchAppendPasteReadonlyColumn: "Yerləşdirilən verilənlərdə redaktə edilə bilməyən sütun var.",
batchAppendPasteNoMatchingColumns: "INSERT ifadəsindəki sütun adlarının heç biri bu nəticənin sütunları ilə uyğun gəlmir.",
search: "Axtarış...", search: "Axtarış...",
searchTruncatedValuesHint: "Bəzi uzun mətn/JSON dəyərləri göstərilərkən qısaldılır; axtarış yalnız yüklənmiş xana mətnini əhatə edir və bəzi uyğunluqları tapmaya bilər.", searchTruncatedValuesHint: "Bəzi uzun mətn/JSON dəyərləri göstərilərkən qısaldılır; axtarış yalnız yüklənmiş xana mətnini əhatə edir və bəzi uyğunluqları tapmaya bilər.",
searchOrWhere: "Axtarın və ya WHERE ifadəsi daxil edin...", searchOrWhere: "Axtarın və ya WHERE ifadəsi daxil edin...",
+1
View File
@@ -2515,6 +2515,7 @@ export default {
batchAppendPasteTargetNotEmpty: "The selected new row already contains data.", batchAppendPasteTargetNotEmpty: "The selected new row already contains data.",
batchAppendPasteEmpty: "The clipboard does not contain rows to add.", batchAppendPasteEmpty: "The clipboard does not contain rows to add.",
batchAppendPasteReadonlyColumn: "The pasted data includes a column that cannot be edited.", batchAppendPasteReadonlyColumn: "The pasted data includes a column that cannot be edited.",
batchAppendPasteNoMatchingColumns: "None of the INSERT statement's column names match this result's columns.",
replaceText: "Replace with", replaceText: "Replace with",
replaceCurrentCell: "Replace all matching text in the current cell", replaceCurrentCell: "Replace all matching text in the current cell",
replaceScope: "Replacement scope", replaceScope: "Replacement scope",
+1
View File
@@ -2748,6 +2748,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "La nueva fila seleccionada ya contiene datos.", batchAppendPasteTargetNotEmpty: "La nueva fila seleccionada ya contiene datos.",
batchAppendPasteEmpty: "No hay filas nuevas en el portapapeles.", batchAppendPasteEmpty: "No hay filas nuevas en el portapapeles.",
batchAppendPasteReadonlyColumn: "Los datos pegados contienen columnas no editables.", batchAppendPasteReadonlyColumn: "Los datos pegados contienen columnas no editables.",
batchAppendPasteNoMatchingColumns: "Ninguno de los nombres de columna de la instrucción INSERT coincide con las columnas de este resultado.",
replaceText: "Reemplazar por", replaceText: "Reemplazar por",
replaceCurrentCell: "Reemplazar todo el texto coincidente en la celda actual", replaceCurrentCell: "Reemplazar todo el texto coincidente en la celda actual",
replaceScope: "Ámbito de reemplazo", replaceScope: "Ámbito de reemplazo",
+1
View File
@@ -2670,6 +2670,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "La riga nuova selezionata contiene già dati.", batchAppendPasteTargetNotEmpty: "La riga nuova selezionata contiene già dati.",
batchAppendPasteEmpty: "Negli appunti non ci sono righe da aggiungere.", batchAppendPasteEmpty: "Negli appunti non ci sono righe da aggiungere.",
batchAppendPasteReadonlyColumn: "I dati incollati contengono colonne non modificabili.", batchAppendPasteReadonlyColumn: "I dati incollati contengono colonne non modificabili.",
batchAppendPasteNoMatchingColumns: "Nessuno dei nomi di colonna dell'istruzione INSERT corrisponde alle colonne di questo risultato.",
replaceText: "Sostituisci con", replaceText: "Sostituisci con",
replaceCurrentCell: "Sostituisci tutto il testo corrispondente nella cella corrente", replaceCurrentCell: "Sostituisci tutto il testo corrispondente nella cella corrente",
replaceScope: "Ambito di sostituzione", replaceScope: "Ambito di sostituzione",
+1
View File
@@ -2687,6 +2687,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "選択した新規行には既にデータが含まれています。", batchAppendPasteTargetNotEmpty: "選択した新規行には既にデータが含まれています。",
batchAppendPasteEmpty: "クリップボードに追加可能な行がありません。", batchAppendPasteEmpty: "クリップボードに追加可能な行がありません。",
batchAppendPasteReadonlyColumn: "貼り付けたデータに編集不可能な列が含まれています。", batchAppendPasteReadonlyColumn: "貼り付けたデータに編集不可能な列が含まれています。",
batchAppendPasteNoMatchingColumns: "INSERT 文の列名がこの結果の列と一致しません。",
replaceText: "置換後の文字列", replaceText: "置換後の文字列",
replaceCurrentCell: "現在のセル内の一致するテキストをすべて置換", replaceCurrentCell: "現在のセル内の一致するテキストをすべて置換",
replaceScope: "置換範囲", replaceScope: "置換範囲",
+1
View File
@@ -2602,6 +2602,7 @@ export default withEnglishFallback({
xlsxExportTitle: "내보내기 옵션", xlsxExportTitle: "내보내기 옵션",
xlsxFilterPrompt: "내보낸 Excel에 필터를 포함할지 선택하십시오:", xlsxFilterPrompt: "내보낸 Excel에 필터를 포함할지 선택하십시오:",
xlsxIncludeAutoFilter: "필터 포함", xlsxIncludeAutoFilter: "필터 포함",
batchAppendPasteNoMatchingColumns: "INSERT 문의 열 이름이 현재 결과 집합의 어떤 열과도 일치하지 않습니다.",
}, },
exportProgress: { exportProgress: {
streamingUnsupported: "이 쿼리는 스트리밍 내보내기를 지원하지 않습니다. 쿼리를 단순화하거나 지원되는 드라이버를 사용하세요.", streamingUnsupported: "이 쿼리는 스트리밍 내보내기를 지원하지 않습니다. 쿼리를 단순화하거나 지원되는 드라이버를 사용하세요.",
+1
View File
@@ -2672,6 +2672,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "A nova linha selecionada já contém dados.", batchAppendPasteTargetNotEmpty: "A nova linha selecionada já contém dados.",
batchAppendPasteEmpty: "Não há linhas para adicionar na área de transferência.", batchAppendPasteEmpty: "Não há linhas para adicionar na área de transferência.",
batchAppendPasteReadonlyColumn: "Os dados colados contêm colunas não editáveis.", batchAppendPasteReadonlyColumn: "Os dados colados contêm colunas não editáveis.",
batchAppendPasteNoMatchingColumns: "Nenhum dos nomes de coluna da instrução INSERT corresponde às colunas deste resultado.",
replaceText: "Substituir por", replaceText: "Substituir por",
replaceCurrentCell: "Substituir todo o texto correspondente na célula atual", replaceCurrentCell: "Substituir todo o texto correspondente na célula atual",
replaceScope: "Escopo da substituição", replaceScope: "Escopo da substituição",
+1
View File
@@ -2389,6 +2389,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "Выбранная новая строка уже содержит данные.", batchAppendPasteTargetNotEmpty: "Выбранная новая строка уже содержит данные.",
batchAppendPasteEmpty: "В буфере обмена нет строк для добавления.", batchAppendPasteEmpty: "В буфере обмена нет строк для добавления.",
batchAppendPasteReadonlyColumn: "Вставленные данные содержат столбец, который нельзя редактировать.", batchAppendPasteReadonlyColumn: "Вставленные данные содержат столбец, который нельзя редактировать.",
batchAppendPasteNoMatchingColumns: "Ни одно имя столбца из инструкции INSERT не совпадает со столбцами этого результата.",
replaceText: "Заменить на", replaceText: "Заменить на",
replaceCurrentCell: "Заменить весь подходящий текст в текущей ячейке", replaceCurrentCell: "Заменить весь подходящий текст в текущей ячейке",
replaceScope: "Область замены", replaceScope: "Область замены",
+1
View File
@@ -2171,6 +2171,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "Seçili yeni satır zaten veri içeriyor.", batchAppendPasteTargetNotEmpty: "Seçili yeni satır zaten veri içeriyor.",
batchAppendPasteEmpty: "Pano, eklenecek satır içermiyor.", batchAppendPasteEmpty: "Pano, eklenecek satır içermiyor.",
batchAppendPasteReadonlyColumn: "Yapıştırılan veri, düzenlenemeyen bir sütun içeriyor.", batchAppendPasteReadonlyColumn: "Yapıştırılan veri, düzenlenemeyen bir sütun içeriyor.",
batchAppendPasteNoMatchingColumns: "INSERT ifadesindeki sütun adlarının hiçbiri bu sonucun sütunlarıyla eşleşmiyor.",
search: "Ara...", search: "Ara...",
searchTruncatedValuesHint: "Bazı uzun metin/JSON değerleri görüntülenirken kısaltılır; arama yalnızca yüklenmiş hücre metnini kapsar ve bazı eşleşmeleri kaçırabilir.", searchTruncatedValuesHint: "Bazı uzun metin/JSON değerleri görüntülenirken kısaltılır; arama yalnızca yüklenmiş hücre metnini kapsar ve bazı eşleşmeleri kaçırabilir.",
searchOrWhere: "Arayın veya bir WHERE yan tümcesi girin...", searchOrWhere: "Arayın veya bir WHERE yan tümcesi girin...",
+1
View File
@@ -2428,6 +2428,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "选中的新增行已包含数据。", batchAppendPasteTargetNotEmpty: "选中的新增行已包含数据。",
batchAppendPasteEmpty: "剪贴板中没有可新增的行。", batchAppendPasteEmpty: "剪贴板中没有可新增的行。",
batchAppendPasteReadonlyColumn: "粘贴的数据包含不可编辑的列。", batchAppendPasteReadonlyColumn: "粘贴的数据包含不可编辑的列。",
batchAppendPasteNoMatchingColumns: "INSERT 语句中的列名与当前结果集的列均不匹配。",
replaceText: "替换为", replaceText: "替换为",
replaceCurrentCell: "替换当前命中单元格中的全部匹配文字", replaceCurrentCell: "替换当前命中单元格中的全部匹配文字",
replaceScope: "替换范围", replaceScope: "替换范围",
+1
View File
@@ -2675,6 +2675,7 @@ export default withEnglishFallback({
batchAppendPasteTargetNotEmpty: "選取的新增行已包含資料。", batchAppendPasteTargetNotEmpty: "選取的新增行已包含資料。",
batchAppendPasteEmpty: "剪貼簿中沒有可新增的行。", batchAppendPasteEmpty: "剪貼簿中沒有可新增的行。",
batchAppendPasteReadonlyColumn: "貼上的資料包含不可編輯的列。", batchAppendPasteReadonlyColumn: "貼上的資料包含不可編輯的列。",
batchAppendPasteNoMatchingColumns: "INSERT 語句中的欄位名稱與目前結果集的欄位皆不符。",
replaceText: "取代為", replaceText: "取代為",
replaceCurrentCell: "取代目前符合儲存格中的所有相符文字", replaceCurrentCell: "取代目前符合儲存格中的所有相符文字",
replaceScope: "取代範圍", replaceScope: "取代範圍",
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import { parseInsertStatementPaste } from "@/lib/dataGrid/dataGridInsertPaste";
describe("parseInsertStatementPaste", () => {
it("returns null for non-INSERT text", () => {
expect(parseInsertStatementPaste("name\tage\nalice\t30")).toBeNull();
expect(parseInsertStatementPaste("SELECT * FROM users")).toBeNull();
expect(parseInsertStatementPaste("")).toBeNull();
});
it("parses a single statement with an explicit column list", () => {
const parsed = parseInsertStatementPaste("INSERT INTO users (name, age, bio) VALUES ('Alice', 30, NULL)");
expect(parsed).not.toBeNull();
expect(parsed?.columnNames).toEqual(["name", "age", "bio"]);
expect(parsed?.rows).toEqual([["Alice", "30", null]]);
});
it("parses a statement without a column list", () => {
const parsed = parseInsertStatementPaste("insert into users values (1, 'bob', NULL)");
expect(parsed?.columnNames).toBeNull();
expect(parsed?.rows).toEqual([["1", "bob", null]]);
});
it("parses multi-row VALUES tuples", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y'), (3, 'z')");
expect(parsed?.rows).toEqual([
["1", "x"],
["2", "y"],
["3", "z"],
]);
});
it("unescapes doubled single quotes inside string literals", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a) VALUES ('it''s ok')");
expect(parsed?.rows).toEqual([["it's ok"]]);
});
it("unescapes MySQL backslash escapes inside string literals", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b, c, d) VALUES ('It\\'s', 'line1\\nline2', 'back\\\\slash', 'tab\\there')");
expect(parsed?.rows).toEqual([["It's", "line1\nline2", "back\\slash", "tab\there"]]);
});
it("keeps an escaped quote from merging two values", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b) VALUES ('It\\'s', 'ok')");
expect(parsed?.rows).toEqual([["It's", "ok"]]);
});
it("reads double-quoted strings as string values", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a) VALUES (\"plain 'text'\")");
expect(parsed?.rows).toEqual([["plain 'text'"]]);
});
it("strips typed-literal keywords and national prefixes from quoted values", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b, c) VALUES (TIMESTAMP '2024-01-01 10:00:00', DATE '2024-01-01', N'nebula')");
expect(parsed?.rows).toEqual([["2024-01-01 10:00:00", "2024-01-01", "nebula"]]);
});
it("supports multiple statements separated by semicolons", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a) VALUES (1); INSERT INTO t (a) VALUES (2);");
expect(parsed?.rows).toEqual([["1"], ["2"]]);
expect(parsed?.columnNames).toEqual(["a"]);
});
it("drops column alignment when statements disagree on column lists", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a) VALUES (1); INSERT INTO t (b) VALUES (2);");
expect(parsed?.rows).toEqual([["1"], ["2"]]);
expect(parsed?.columnNames).toBeNull();
});
it("keeps embedded commas, parens, and newlines inside string literals", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b) VALUES ('hello, world', 'line1\nline2 (x)')");
expect(parsed?.rows).toEqual([["hello, world", "line1\nline2 (x)"]]);
});
it("keeps function calls and numeric tokens verbatim for cell coercion", () => {
const parsed = parseInsertStatementPaste("INSERT INTO t (a, b, c) VALUES (NOW(), -12.5, 0xFF)");
expect(parsed?.rows).toEqual([["NOW()", "-12.5", "0xFF"]]);
});
it("skips SQL comments", () => {
const parsed = parseInsertStatementPaste("-- lead comment\nINSERT INTO t (a) /* block */ VALUES (1) -- trailing");
expect(parsed?.rows).toEqual([["1"]]);
});
it("handles quoted identifiers for table and column names", () => {
const parsed = parseInsertStatementPaste('INSERT INTO "my table" ("select", `order`) VALUES (1, 2)');
expect(parsed?.columnNames).toEqual(["select", "order"]);
expect(parsed?.rows).toEqual([["1", "2"]]);
});
it("returns null for INSERT ... SELECT", () => {
expect(parseInsertStatementPaste("INSERT INTO t (a) SELECT a FROM other")).toBeNull();
});
it("returns null when VALUES tuples are missing", () => {
expect(parseInsertStatementPaste("INSERT INTO t (a) VALUES")).toBeNull();
});
});
@@ -0,0 +1,285 @@
// Parser for pasting SQL INSERT statements into blank new rows (#10573).
// Accepts single or multiple statements and converts each VALUES tuple into a
// grid row. String literals keep their unescaped text (doubled quotes and
// MySQL backslash escapes), NULL becomes null, and every other token (numbers,
// functions, hex literals) is kept verbatim so the regular cell coercion
// handles it.
export interface ParsedInsertStatementPaste {
rows: Array<Array<string | null>>;
columnNames: string[] | null;
}
interface InsertStatementPart {
columnNames: string[] | null;
tuples: Array<Array<string | null>>;
}
type CharClass = "code" | "single-quote" | "double-quote" | "backtick" | "bracket-ident";
interface ScanState {
class: CharClass;
text: string;
}
function appendRaw(state: ScanState, char: string): void {
state.text += char;
}
function splitTopLevelStatements(text: string): string[] {
const statements: string[] = [];
const state: ScanState = { class: "code", text: "" };
let depth = 0;
for (let index = 0; index < text.length; index++) {
const char = text[index]!;
if (state.class === "code") {
if (char === "'" || char === '"' || char === "`") {
state.class = char === "'" ? "single-quote" : char === '"' ? "double-quote" : "backtick";
appendRaw(state, char);
continue;
}
if (char === "[" && depth === 0) {
state.class = "bracket-ident";
appendRaw(state, char);
continue;
}
if (char === "-" && text[index + 1] === "-") {
while (index < text.length && text[index] !== "\n") index++;
if (index < text.length) index--;
continue;
}
if (char === "/" && text[index + 1] === "*") {
index = text.indexOf("*/", index + 2);
index = index === -1 ? text.length : index + 1;
continue;
}
if (char === "(") depth++;
if (char === ")") depth = Math.max(0, depth - 1);
if (char === ";" && depth === 0) {
if (state.text.trim()) statements.push(state.text);
state.text = "";
continue;
}
appendRaw(state, char);
continue;
}
if (char === "\\" && (state.class === "single-quote" || state.class === "double-quote")) {
// MySQL string escapes: \' must not end the literal (backticks keep
// backslashes literal).
appendRaw(state, char);
if (index + 1 < text.length) appendRaw(state, text[++index]!);
continue;
}
appendRaw(state, char);
const closing = state.class === "single-quote" ? "'" : state.class === "double-quote" ? '"' : state.class === "backtick" ? "`" : "]";
if (char === closing) {
// Doubled quotes ('' / "" / ``) stay inside the literal; a doubled ]
// inside a bracket identifier is not standard, so only quotes double.
if (closing !== "]" && text[index + 1] === closing) {
appendRaw(state, text[++index]!);
continue;
}
state.class = "code";
}
}
if (state.text.trim()) statements.push(state.text);
return statements;
}
function normalizeIdentifier(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length >= 2) {
const first = trimmed[0]!;
const last = trimmed[trimmed.length - 1]!;
if ((first === "'" && last === "'") || (first === '"' && last === '"') || (first === "`" && last === "`")) {
return trimmed.slice(1, -1).replaceAll(first + first, first);
}
if (first === "[" && last === "]") return trimmed.slice(1, -1).replaceAll("]]", "]");
}
return trimmed;
}
interface Lexer {
source: string;
pos: number;
}
function skipWhitespace(lexer: Lexer): void {
while (lexer.pos < lexer.source.length && /\s/.test(lexer.source[lexer.pos]!)) lexer.pos++;
}
function matchKeyword(lexer: Lexer, keyword: string): boolean {
skipWhitespace(lexer);
const slice = lexer.source.slice(lexer.pos, lexer.pos + keyword.length);
if (slice.toUpperCase() !== keyword) return false;
const next = lexer.source[lexer.pos + keyword.length];
if (next && !/[\s(]/.test(next)) return false;
lexer.pos += keyword.length;
return true;
}
function readBracketedGroup(lexer: Lexer): string[] | null {
skipWhitespace(lexer);
if (lexer.source[lexer.pos] !== "(") return null;
lexer.pos++;
const items: string[] = [];
let current = "";
let depth = 0;
let classState: CharClass = "code";
while (lexer.pos < lexer.source.length) {
const char = lexer.source[lexer.pos++]!;
if (classState === "code") {
if (char === "'" || char === '"' || char === "`") {
classState = char === "'" ? "single-quote" : char === '"' ? "double-quote" : "backtick";
} else if (char === "[" && depth === 0) {
classState = "bracket-ident";
} else if (char === "(") {
depth++;
} else if (char === ")") {
if (depth === 0) {
items.push(current);
return items;
}
depth--;
} else if (char === "," && depth === 0) {
items.push(current);
current = "";
continue;
}
} else if (char === "\\" && (classState === "single-quote" || classState === "double-quote")) {
current += char;
if (lexer.pos < lexer.source.length) current += lexer.source[lexer.pos++]!;
continue;
} else if (char === (classState === "bracket-ident" ? "]" : classState === "single-quote" ? "'" : classState === "double-quote" ? '"' : "`")) {
classState = "code";
}
current += char;
}
return null;
}
function readValueToken(lexer: Lexer): string | null {
skipWhitespace(lexer);
if (lexer.pos >= lexer.source.length) return null;
const start = lexer.pos;
const char = lexer.source[lexer.pos]!;
if (char === "'" || char === '"' || char === "`") {
const closing = char;
lexer.pos++;
while (lexer.pos < lexer.source.length) {
const inner = lexer.source[lexer.pos++]!;
if (inner === closing) {
if (lexer.source[lexer.pos] === closing) lexer.pos++;
else break;
} else if (inner === "\\" && closing !== "`") {
if (lexer.pos < lexer.source.length) lexer.pos++;
}
}
return lexer.source.slice(start, lexer.pos);
}
while (lexer.pos < lexer.source.length) {
const inner = lexer.source[lexer.pos]!;
// A table reference never contains commas, brackets, or whitespace, so the
// first one of those ends the token (and leaves "(" for the column list).
if (inner === "," || inner === "(" || inner === ")" || /\s/.test(inner)) break;
lexer.pos++;
}
return lexer.source.slice(start, lexer.pos).trim() || null;
}
function unescapeSqlString(text: string): string {
return text.replace(/\\(.)/gs, (_match, char: string) => {
switch (char) {
case "n":
return "\n";
case "r":
return "\r";
case "t":
return "\t";
case "0":
return "\0";
default:
// \\ \' \" and unrecognized escapes keep the escaped character itself,
// matching MySQL string-literal semantics.
return char;
}
});
}
function convertValue(raw: string | null): string | null {
if (raw === null) return null;
let trimmed = raw.trim();
if (trimmed.toUpperCase() === "NULL") return null;
// Typed literals keep only the quoted payload: TIMESTAMP '...', DATE '...',
// or a national-character prefix N'...'.
const typed = trimmed.match(/^(?:N|DATE|TIME|TIMESTAMP|DATETIME)(?=\s*['"])/i);
if (typed) trimmed = trimmed.slice(typed[0].length).trimStart();
if (trimmed.length >= 2 && trimmed[0] === "'" && trimmed[trimmed.length - 1] === "'") {
return unescapeSqlString(trimmed.slice(1, -1).replaceAll("''", "'"));
}
if (trimmed.length >= 2 && trimmed[0] === '"' && trimmed[trimmed.length - 1] === '"') {
return unescapeSqlString(trimmed.slice(1, -1).replaceAll('""', '"'));
}
return trimmed;
}
function parseSingleInsertStatement(statement: string): InsertStatementPart | null {
const lexer: Lexer = { source: statement, pos: 0 };
if (!matchKeyword(lexer, "INSERT")) return null;
if (!matchKeyword(lexer, "INTO")) return null;
// Skip the table reference (possibly db.schema."table" or `db`.`table`).
if (!readValueToken(lexer)) return null;
// Optional column-name list: the next bracketed group before VALUES/VALUE.
const save = lexer.pos;
let columnNames: string[] | null = null;
const group = readBracketedGroup(lexer);
if (group) {
columnNames = group.map(normalizeIdentifier);
} else {
lexer.pos = save;
}
if (!matchKeyword(lexer, "VALUES") && !matchKeyword(lexer, "VALUE")) return null;
const tuples: Array<Array<string | null>> = [];
for (;;) {
skipWhitespace(lexer);
if (lexer.source[lexer.pos] !== "(") break;
const rawValues = readBracketedGroup(lexer);
if (rawValues === null) return null;
// Values inside a tuple: split on top-level commas again (readBracketedGroup
// already did that) and convert each token.
tuples.push(rawValues.map(convertValue));
skipWhitespace(lexer);
if (lexer.source[lexer.pos] === ",") {
lexer.pos++;
continue;
}
break;
}
if (tuples.length === 0) return null;
return { columnNames, tuples };
}
export function parseInsertStatementPaste(text: string): ParsedInsertStatementPaste | null {
const statements = splitTopLevelStatements(text);
// The first statement decides the paste's semantics; leading comments were
// already stripped by the statement splitter.
if (statements.length === 0 || !/^\s*insert\s+into\s/i.test(statements[0]!)) return null;
const rows: Array<Array<string | null>> = [];
let columnNames: string[] | null = null;
let sawColumnNames = false;
for (const statement of statements) {
const parsed = parseSingleInsertStatement(statement);
if (!parsed) return null;
if (parsed.columnNames) {
if (!sawColumnNames) {
columnNames = parsed.columnNames;
sawColumnNames = true;
} else if (columnNames && parsed.columnNames.join("\u0000") !== columnNames.join("\u0000")) {
columnNames = null;
}
}
rows.push(...parsed.tuples);
}
if (rows.length === 0) return null;
return { rows, columnNames };
}