Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(grid): include database name by default when copying rows as SQL DML (#12581)

lxk95544e47c3cdfff
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index c21d517244..00de0ca9f8 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -9144,7 +9144,16 @@ const {
sql: computed(() => props.sql),
exportSql: computed(() => props.exportSql),
pageSql: computed(() => props.pageSql),
- tableMeta: computed(() => (props.tableMeta ? { ...props.tableMeta } : undefined)),
+ tableMeta: computed(() => {
+ if (!props.tableMeta) return undefined;
+ const database = props.tableMeta.database ?? props.executionDatabase ?? props.database;
+ const schema = props.tableMeta.schema ?? props.schema;
+ return {
+ ...props.tableMeta,
+ ...(database && !props.tableMeta.database ? { database } : {}),
+ ...(schema && !props.tableMeta.schema ? { schema } : {}),
+ };
+ }),
includeDatabaseName: computed(() => settingsStore.editorSettings.generateSqlIncludeDatabaseName),
hasUniqueQueryInsertTarget: computed(() => props.hasUniqueQueryInsertTarget === true),
copyInsertTargetLabel: computed(() => props.tableMeta?.tableName ?? props.customSaveHandler?.targetLabel),
diff --git a/apps/desktop/src/components/grid/__tests__/DataGridExtractorDialog.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridExtractorDialog.spec.ts
index 56b25e2cf8..85bbfa9062 100644
--- a/apps/desktop/src/components/grid/__tests__/DataGridExtractorDialog.spec.ts
+++ b/apps/desktop/src/components/grid/__tests__/DataGridExtractorDialog.spec.ts
@@ -174,18 +174,18 @@ describe("extractor draft preview", () => {
expect(host.querySelector("pre")?.textContent).toBe("initial");
});
- it("offers the database-name option for SQL updates as well (#11195)", async () => {
+ it("offers the database-name option for SQL updates as well (#11195, #12146)", async () => {
const { props, host, save } = mountDialog();
props.preference = "sql-updates";
props.items = [{ value: "sql-updates", label: "UPDATE" }];
props.open = true;
await expandPreview(host);
- // 勾选后保存应带上 includeDatabaseName(复制为 UPDATE 也支持带库名/模式名)
+ // 默认开启,取消勾选后保存应带上 includeDatabaseName: false
await toggle(host, "copyExtractorIncludeDatabaseName");
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({ includeDatabaseName: true }) }) }));
+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ options: expect.objectContaining({ sql: expect.objectContaining({ includeDatabaseName: false }) }) }));
});
it("previews unsaved quote and temporal options without mutating saved settings", async () => {
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts
index 21d9b5bef1..06d9d26e89 100644
--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts
+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts
@@ -80,8 +80,8 @@ afterEach(() => {
describe("source dialog dependency integration", () => {
it("keeps the real CodeMirror draft, undo history and selection through dependency refresh", async () => {
const { open, onOpenObject } = mountDialog();
- await vi.waitFor(() => expect(button("contextMenu.editView")?.disabled).toBe(false));
- button("contextMenu.editView").click();
+ await vi.waitFor(() => expect(button("contextMenu.editObject")?.disabled).toBe(false));
+ button("contextMenu.editObject").click();
await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull());
const editor = document.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!;
const view = EditorView.findFromDOM(editor)!;
diff --git a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
index 3510537317..5384aac8f4 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridExport.spec.ts
@@ -1934,18 +1934,19 @@ describe("useDataGridExport prepared row statements", () => {
expect(vi.mocked(extractDataGridSelection).mock.lastCall?.[0].options.sql).toEqual(saved.sql);
});
- it("follows the extractor option for the copied SQL table qualifier (#11195)", async () => {
+ it("follows the extractor option for the copied SQL table qualifier (#11195, #12146)", async () => {
const tableMeta: DataGridTableMeta = { ...editableTable, schema: "SYSDBA" };
const matrix: CellSelectionMatrix = { rowIndexes: [0], columnIndexes: [0, 1], columns: ["id", "name"], rows: [[1, "Ada"]] };
vi.mocked(extractDataGridSelection).mockResolvedValue({ text: "copied", mimeType: "text/plain", fileExtension: "sql", rowCount: 1, columnCount: 2 });
- const withDatabaseName = { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, includeDatabaseName: true } };
- const enabled = createExportState(tableMeta, ["id", "name"], matrix, [1, "Ada"], undefined, matrix.rows, [], withDatabaseName, false, undefined, false, undefined, undefined, "dameng");
- await enabled.copyWithExtractor("sql-inserts");
+ // 默认开启 includeDatabaseName:保留模式名
+ const defaultEnabled = createExportState(tableMeta, ["id", "name"], matrix, [1, "Ada"], undefined, matrix.rows, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, undefined, false, undefined, undefined, "dameng");
+ await defaultEnabled.copyWithExtractor("sql-inserts");
expect(vi.mocked(extractDataGridSelection).mock.lastCall?.[0].tableMeta).toMatchObject({ schema: "SYSDBA", tableName: "users" });
- // 未勾选(默认)时保持既有行为:把可选的库名/模式名前缀交给后端省略
- const disabled = createExportState(tableMeta, ["id", "name"], matrix, [1, "Ada"], undefined, matrix.rows, [], DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, false, undefined, false, undefined, undefined, "dameng");
+ // 显式未勾选时把可选的库名/模式名前缀交给后端省略
+ const withoutDatabaseName = { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, includeDatabaseName: false } };
+ const disabled = createExportState(tableMeta, ["id", "name"], matrix, [1, "Ada"], undefined, matrix.rows, [], withoutDatabaseName, false, undefined, false, undefined, undefined, "dameng");
await disabled.copyWithExtractor("sql-inserts");
expect(vi.mocked(extractDataGridSelection).mock.lastCall?.[0].tableMeta?.schema).toBeUndefined();
});
diff --git a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
index ce593c3b6c..c69691ca55 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridExtractor.includeDatabaseName.spec.ts
@@ -96,17 +96,51 @@ describe("useDataGridExtractor includeDatabaseName payload", () => {
expect(request.options.sql.includeDatabaseName).toBe(true);
});
- it("strips optional qualifiers and keeps the flag off for non schema-qualified dialects", async () => {
+ it("keeps optional qualifiers and sets the flag on by default for MySQL", async () => {
const request = await capturedRequest("mysql", qualifiedMeta(undefined, "mydb"));
+ expect(request.tableMeta.database).toBe("mydb");
+ expect(request.options.sql.includeDatabaseName).toBe(true);
+ });
+
+ it("strips optional qualifiers when explicitly opted out", async () => {
+ const request = await capturedRequest("mysql", qualifiedMeta(undefined, "mydb"), { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, includeDatabaseName: false } });
expect(request.tableMeta.database).toBeUndefined();
expect(request.tableMeta.schema).toBeUndefined();
expect(request.options.sql.includeDatabaseName).toBe(false);
});
- it("preserves an explicit opt-in for non schema-qualified dialects", async () => {
- const request = await capturedRequest("mysql", qualifiedMeta(undefined, "mydb"), { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, sql: { ...DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql, includeDatabaseName: true } });
- expect(request.tableMeta.database).toBe("mydb");
- expect(request.options.sql.includeDatabaseName).toBe(true);
+ it("falls back to option database when tableMeta database is missing", async () => {
+ const allColumns = ["id", "name"];
+ const items = [{ id: 1, data: [1, "Ada"], isDraft: false }];
+ const state = useDataGridExtractor({
+ columns: computed(() => allColumns),
+ allColumns: computed(() => allColumns),
+ displayItems: computed(() => items),
+ allDisplayItems: computed(() => items),
+ allSourceColumns: computed(() => undefined),
+ visibleColumnIndexes: computed(() => [0, 1]),
+ columnTypes: computed(() => ["int", "varchar"]),
+ extractorOptions: computed(() => DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS),
+ databaseType: computed(() => "mysql"),
+ identifierQuote: computed(() => undefined),
+ tableMeta: computed(() => ({ tableName: "users", primaryKeys: ["id"], columns: [{ name: "id" }, { name: "name" }] })),
+ database: computed(() => "appdb"),
+ hasCellSelection: computed(() => false),
+ selectedCells: computed(() => ({ columns: [], rows: [] })),
+ selectedCellMatrix: computed(() => null),
+ hasRowSelection: computed(() => true),
+ hasColumnSelection: computed(() => false),
+ selectedRowIds: ref(new Set<number>([1])),
+ contextCell: ref(null),
+ contextSelectionIsSynthetic: ref(false),
+ copyText: vi.fn(async () => true),
+ canCopySqlInsert: () => true,
+ buildMongoInsert: vi.fn(async () => undefined),
+ });
+ const extraction = await state.extractWithExtractor("sql-inserts");
+ expect(extraction).not.toBeNull();
+ const req = mocks.extract.mock.calls.at(-1)![0];
+ expect(req.tableMeta.database).toBe("appdb");
});
it("passes real query types for reordered and hidden row columns without table metadata", async () => {
diff --git a/apps/desktop/src/composables/useDataGridExport.ts b/apps/desktop/src/composables/useDataGridExport.ts
index dd8f13901d..d67872f362 100644
--- a/apps/desktop/src/composables/useDataGridExport.ts
+++ b/apps/desktop/src/composables/useDataGridExport.ts
@@ -972,6 +972,7 @@ export function useDataGridExport(options: UseDataGridExportOptions) {
databaseType,
identifierQuote,
tableMeta,
+ database: options.database,
includeDatabaseName: options.includeDatabaseName,
hasCellSelection,
selectedCells,
diff --git a/apps/desktop/src/composables/useDataGridExtractor.ts b/apps/desktop/src/composables/useDataGridExtractor.ts
index 3bc17ad10a..7f8f4df37e 100644
--- a/apps/desktop/src/composables/useDataGridExtractor.ts
+++ b/apps/desktop/src/composables/useDataGridExtractor.ts
@@ -73,6 +73,7 @@ interface UseDataGridExtractorOptions {
databaseType: ComputedRef<DatabaseType | undefined>;
identifierQuote?: ComputedRef<string | undefined>;
tableMeta: ComputedRef<DataGridTableMeta | undefined>;
+ database?: ComputedRef<string | undefined>;
/** Editor setting "Include database name in generated SQL". When false, SQL extractors omit optional schema/database qualifiers. */
includeDatabaseName?: ComputedRef<boolean>;
hasCellSelection: ComputedRef<boolean>;
@@ -303,11 +304,17 @@ export function useDataGridExtractor(options: UseDataGridExtractorOptions) {
// (`generateSqlIncludeDatabaseName`)任一开启都保留库名/模式名;后者还会影响
// 保存 SQL、侧栏导出等其它路径,因此这里取“或”,不覆盖全局偏好。
const extractorOptionValues = normalizeDataGridExtractorOptions(extractorOptions);
+ const effectiveTableMeta = options.tableMeta.value
+ ? {
+ ...options.tableMeta.value,
+ database: options.tableMeta.value.database ?? options.database?.value,
+ }
+ : undefined;
const tableMeta =
descriptor.category === "sql"
? tableMetaWithoutOptionalDatabaseQualifier(
compactTableMeta(
- options.tableMeta.value,
+ effectiveTableMeta,
columns.map((column) => column.sourceName ?? column.displayName),
),
options.databaseType.value,
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
index 61081a8781..08f62aba61 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridCopyExtractor.spec.ts
@@ -28,13 +28,13 @@ describe("data-grid extractor options", () => {
expect(normalizeDataGridExtractorOptions({ sql: { primaryKeyMode: "exclude-all" } }).sql.primaryKeyMode).toBe("exclude-all");
});
- it("defaults to dropping database qualification and keeps an explicit opt-in", () => {
- expect(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql.includeDatabaseName).toBe(false);
- expect(normalizeDataGridExtractorOptions({ sql: {} }).sql.includeDatabaseName).toBe(false);
- const configured = normalizeDataGridExtractorOptions({ sql: { includeDatabaseName: true } });
- expect(configured.sql.includeDatabaseName).toBe(true);
- expect(normalizeDataGridExtractorOptions(JSON.parse(JSON.stringify(configured))).sql.includeDatabaseName).toBe(true);
- expect(normalizeDataGridExtractorOptions({ sql: { includeDatabaseName: "true" } }).sql.includeDatabaseName).toBe(false);
+ it("defaults to including database qualification and keeps an explicit opt-out", () => {
+ expect(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS.sql.includeDatabaseName).toBe(true);
+ expect(normalizeDataGridExtractorOptions({ sql: {} }).sql.includeDatabaseName).toBe(true);
+ const configured = normalizeDataGridExtractorOptions({ sql: { includeDatabaseName: false } });
+ expect(configured.sql.includeDatabaseName).toBe(false);
+ expect(normalizeDataGridExtractorOptions(JSON.parse(JSON.stringify(configured))).sql.includeDatabaseName).toBe(false);
+ expect(normalizeDataGridExtractorOptions({ sql: { includeDatabaseName: "false" } }).sql.includeDatabaseName).toBe(true);
});
it("defaults DSV NULL output to an empty spreadsheet field", () => {
diff --git a/apps/desktop/src/lib/__tests__/dataGrid/dataGridInsertPaste.spec.ts b/apps/desktop/src/lib/__tests__/dataGrid/dataGridInsertPaste.spec.ts
index 766a42c3d5..cd084b2bf4 100644
--- a/apps/desktop/src/lib/__tests__/dataGrid/dataGridInsertPaste.spec.ts
+++ b/apps/desktop/src/lib/__tests__/dataGrid/dataGridInsertPaste.spec.ts
@@ -125,6 +125,36 @@ describe("parseInsertStatementPaste", () => {
expect(parsed?.rows).toEqual([["1", "2"]]);
});
+ it("handles dot-separated quoted table references with and without column lists", () => {
+ const backtickQualified = parseInsertStatementPaste("INSERT INTO `db`.`t` (a) VALUES (1)");
+ expect(backtickQualified?.columnNames).toEqual(["a"]);
+ expect(backtickQualified?.rows).toEqual([["1"]]);
+
+ const doubleQuoteQualified = parseInsertStatementPaste('INSERT INTO "s"."t" (a, b) VALUES (1, 2)');
+ expect(doubleQuoteQualified?.columnNames).toEqual(["a", "b"]);
+ expect(doubleQuoteQualified?.rows).toEqual([["1", "2"]]);
+
+ const bracketQualified = parseInsertStatementPaste("INSERT INTO [db].[dbo].[t] (a) VALUES (1)");
+ expect(bracketQualified?.columnNames).toEqual(["a"]);
+ expect(bracketQualified?.rows).toEqual([["1"]]);
+
+ const noColumnsBacktick = parseInsertStatementPaste("INSERT INTO `db`.`t` VALUES (1, 'hello')");
+ expect(noColumnsBacktick?.columnNames).toBeNull();
+ expect(noColumnsBacktick?.rows).toEqual([["1", "hello"]]);
+
+ const noColumnsDoubleQuote = parseInsertStatementPaste('INSERT INTO "s"."t" VALUES (1, \'hello\')');
+ expect(noColumnsDoubleQuote?.columnNames).toBeNull();
+ expect(noColumnsDoubleQuote?.rows).toEqual([["1", "hello"]]);
+
+ const spacedDots = parseInsertStatementPaste("INSERT INTO `db` . `t` (a) VALUES (1)");
+ expect(spacedDots?.columnNames).toEqual(["a"]);
+ expect(spacedDots?.rows).toEqual([["1"]]);
+
+ const multiStatementQualified = parseInsertStatementPaste("INSERT INTO `db`.`t` (a) VALUES (1); INSERT INTO `db`.`t` (a) VALUES (2);");
+ expect(multiStatementQualified?.columnNames).toEqual(["a"]);
+ expect(multiStatementQualified?.rows).toEqual([["1"], ["2"]]);
+ });
+
it("returns null for INSERT ... SELECT", () => {
expect(parseInsertStatementPaste("INSERT INTO t (a) SELECT a FROM other")).toBeNull();
});
diff --git a/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts b/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts
index 54544ab366..388affe5a0 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridCopyExtractor.ts
@@ -57,9 +57,9 @@ export const DATA_GRID_DEFAULT_COPY_PREFERENCES: readonly DataGridCopyPreference
export const DATA_GRID_DEFAULT_VISIBLE_COPY_EXTRACTORS: readonly DataGridCopyExtractorId[] = DATA_GRID_COPY_EXTRACTOR_IDS;
export const DATA_GRID_EXTRACTOR_CONTRACT_VERSION = 1 as const;
-// v2:复制/导出 SQL 的「包含数据库名称」改为由提取器自身的勾选框决定,默认关闭(不带库名/模式名),
-// 历史持久化的 `true` 由 settingsStore 的迁移归位到新默认。
-export const DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION = 2 as const;
+// v3:复制/导出 SQL 的「包含数据库名称」默认恢复开启(带库名/模式名,#12146),
+// 历史被 v2 迁移归位为 false 的持久化配置升级到新默认 true。
+export const DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION = 3 as const;
export const DATA_GRID_COPY_EXTRACTOR_DESCRIPTORS: Record<DataGridCopyExtractorId, { category: DataGridExtractorCategory; separatorBefore?: boolean }> = {
raw: { category: "raw" },
@@ -213,7 +213,7 @@ export const DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS: DataGridExtractorOptions = {
skipGeneratedColumns: true,
insertMode: "merged",
primaryKeyMode: "include",
- includeDatabaseName: false,
+ includeDatabaseName: true,
quoteIdentifiers: true,
temporalFormat: "native",
},
@@ -260,7 +260,7 @@ export function normalizeDataGridExtractorOptions(value: unknown): DataGridExtra
skipGeneratedColumns: sql.skipGeneratedColumns !== false,
insertMode: sql.insertMode === "row-by-row" ? "row-by-row" : "merged",
primaryKeyMode: sql.primaryKeyMode === "exclude-generated" || sql.primaryKeyMode === "exclude-all" || sql.primaryKeyMode === "include" ? sql.primaryKeyMode : sql.excludePrimaryKeysFromInsert === true ? "exclude-generated" : "include",
- includeDatabaseName: sql.includeDatabaseName === true,
+ includeDatabaseName: sql.includeDatabaseName !== false,
quoteIdentifiers: sql.quoteIdentifiers !== false,
temporalFormat: sql.temporalFormat === "string" ? "string" : "native",
},
diff --git a/apps/desktop/src/lib/dataGrid/dataGridInsertPaste.ts b/apps/desktop/src/lib/dataGrid/dataGridInsertPaste.ts
index 808a178535..ab0bb4eba8 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridInsertPaste.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridInsertPaste.ts
@@ -171,33 +171,64 @@ function* readBracketedGroup(lexer: Lexer): Generator<DataGridRowPreparationProg
return null;
}
-function readValueToken(lexer: Lexer): string | null {
+function readTableReferenceToken(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++;
+
+ while (lexer.pos < lexer.source.length) {
+ skipWhitespace(lexer);
+ if (lexer.pos >= lexer.source.length) break;
+ 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++;
+ }
+ }
+ } else if (char === "[") {
+ lexer.pos++;
+ while (lexer.pos < lexer.source.length) {
+ const inner = lexer.source[lexer.pos++]!;
+ if (inner === "]") {
+ if (lexer.source[lexer.pos] === "]") lexer.pos++;
+ else break;
+ }
+ }
+ } else {
+ let readAny = false;
+ while (lexer.pos < lexer.source.length) {
+ const inner = lexer.source[lexer.pos]!;
+ if (inner === "." || inner === "," || inner === "(" || inner === ")" || inner === ";" || /\s/.test(inner)) {
+ break;
+ }
+ readAny = true;
+ lexer.pos++;
+ }
+ if (!readAny) {
+ break;
}
}
- 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++;
+
+ const savePos = lexer.pos;
+ skipWhitespace(lexer);
+ if (lexer.pos < lexer.source.length && lexer.source[lexer.pos] === ".") {
+ lexer.pos++;
+ } else {
+ lexer.pos = savePos;
+ break;
+ }
}
- return lexer.source.slice(start, lexer.pos).trim() || null;
+
+ const token = lexer.source.slice(start, lexer.pos).trim();
+ return token || null;
}
function unescapeSqlString(text: string): string {
@@ -241,7 +272,7 @@ function* parseSingleInsertStatement(statement: string, rows: ParsedInsertStatem
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;
+ if (!readTableReferenceToken(lexer)) return null;
// Optional column-name list: the next bracketed group before VALUES/VALUE.
const save = lexer.pos;
let columnNames: string[] | null = null;
diff --git a/apps/desktop/src/lib/table/tableDataTabMeta.ts b/apps/desktop/src/lib/table/tableDataTabMeta.ts
index ab76de2b84..ee0a4c0810 100644
--- a/apps/desktop/src/lib/table/tableDataTabMeta.ts
+++ b/apps/desktop/src/lib/table/tableDataTabMeta.ts
@@ -37,6 +37,7 @@ export function repairRestoredDataTabTableIdentity(tab: QueryTab, databaseType:
tab.tableMeta = {
...tab.tableMeta,
schema: source.qualifier,
+ database: tab.tableMeta?.database ?? tab.database,
tableName: source.name,
columns: tab.tableMeta?.columns ?? [],
primaryKeys: tab.tableMeta?.primaryKeys ?? [],
@@ -57,7 +58,18 @@ function fallbackColumnInfo(name: string): ColumnInfo {
export function tableMetaForDataTab(tab: QueryTab | undefined): DataTabTableMeta | undefined {
if (!tab || tab.mode !== "data") return undefined;
- if (tab.tableMeta?.columns.length) return tab.tableMeta;
+ if (tab.tableMeta?.columns.length) {
+ const database = tab.tableMeta.database ?? tab.database;
+ const schema = tab.tableMeta.schema ?? tab.schema;
+ if (database !== tab.tableMeta.database || schema !== tab.tableMeta.schema) {
+ return {
+ ...tab.tableMeta,
+ database,
+ schema,
+ };
+ }
+ return tab.tableMeta;
+ }
const tableName = tab.tableMeta?.tableName.trim() || titleTableName(tab);
if (!tableName) return undefined;
@@ -65,6 +77,7 @@ export function tableMetaForDataTab(tab: QueryTab | undefined): DataTabTableMeta
return {
...tab.tableMeta,
schema: tab.tableMeta?.schema ?? tab.schema,
+ database: tab.tableMeta?.database ?? tab.database,
tableName,
columns: (tab.result?.columns ?? []).map(fallbackColumnInfo),
primaryKeys: tab.tableMeta?.primaryKeys ?? [],
diff --git a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
index 3b8ad523aa..722d65ef90 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts
@@ -2616,6 +2616,7 @@ describe("queryStore hidden primary key editing", () => {
databaseType: "mysql",
identifierQuote: undefined,
catalog: undefined,
+ database: "app",
schema: "public",
tableName: "users",
whereInput: undefined,
@@ -2670,7 +2671,7 @@ describe("queryStore hidden primary key editing", () => {
databaseType: "gaussdb",
identifierQuote: undefined,
catalog: undefined,
- database: undefined,
+ database: "app",
schema: "public",
tableName: "users",
whereInput: undefined,
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
index fc6fa729dd..3010bd0152 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
@@ -697,21 +697,27 @@ describe("normalizeEditorSettings", () => {
expect(configured.dataGridExtractorOptions.dsv.nullText).toBe("NULL");
});
- it("resets the copy extractor database-name opt-in once when migrating to v2", () => {
+ it("restores the copy extractor database-name opt-in default when migrating to v3 (#12146)", () => {
const legacy = normalizeEditorSettings({
- dataGridExtractorOptionsMigrationVersion: 1,
- dataGridExtractorOptions: { sql: { includeDatabaseName: true } },
+ dataGridExtractorOptionsMigrationVersion: 2,
+ dataGridExtractorOptions: { sql: { includeDatabaseName: false } },
});
- // 历史持久化的「包含数据库名称」归位到新默认:复制/导出 SQL 默认不带库名/模式名
- expect(legacy.dataGridExtractorOptions.sql.includeDatabaseName).toBe(false);
+ // v2 中被重置为 false 的历史配置重新恢复为新默认:复制/导出 SQL 默认带库名/模式名
+ expect(legacy.dataGridExtractorOptions.sql.includeDatabaseName).toBe(true);
expect(legacy.dataGridExtractorOptionsMigrationVersion).toBe(DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION);
- const current = normalizeEditorSettings({
+ const currentExplicitFalse = normalizeEditorSettings({
+ dataGridExtractorOptionsMigrationVersion: DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION,
+ dataGridExtractorOptions: { sql: { includeDatabaseName: false } },
+ });
+ // v3 迁移之后用户的显式取消勾选必须被保留
+ expect(currentExplicitFalse.dataGridExtractorOptions.sql.includeDatabaseName).toBe(false);
+
+ const currentExplicitTrue = normalizeEditorSettings({
dataGridExtractorOptionsMigrationVersion: DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION,
dataGridExtractorOptions: { sql: { includeDatabaseName: true } },
});
- // 迁移之后用户的显式勾选必须被保留
- expect(current.dataGridExtractorOptions.sql.includeDatabaseName).toBe(true);
+ expect(currentExplicitTrue.dataGridExtractorOptions.sql.includeDatabaseName).toBe(true);
});
it("defaults retained result runs to tiled tabs and preserves list mode", () => {
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index f15731f602..10507ceb9b 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -1970,9 +1970,9 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
if (!isLegacyExtractorOptions) return normalizedExtractorOptions;
// v1:旧的 "NULL" 文本迁移为空串
const nullTextMigrated = normalizedExtractorOptions.dsv.nullText === "NULL" ? { ...normalizedExtractorOptions, dsv: { ...normalizedExtractorOptions.dsv, nullText: "" } } : normalizedExtractorOptions;
- // v2:复制/导出 SQL 的「包含数据库名称」改为由提取器勾选框决定且默认关闭,
- // 历史持久化的 true 一并归位到新默认(想带库名/模式名的用户重新勾选即可)
- return nullTextMigrated.sql.includeDatabaseName ? { ...nullTextMigrated, sql: { ...nullTextMigrated.sql, includeDatabaseName: false } } : nullTextMigrated;
+ // v3:复制/导出 SQL 的「包含数据库名称」默认恢复开启(带库名/模式名,#12146),
+ // 历史在 v2 中被强制归位为 false 的持久化配置重新提升到新默认 true。
+ return !nullTextMigrated.sql.includeDatabaseName ? { ...nullTextMigrated, sql: { ...nullTextMigrated.sql, includeDatabaseName: true } } : nullTextMigrated;
})();
// Preserve the explicit intent behind the legacy update controls. Disabling
// update reminders was a full opt-out; disabling automatic downloads only
@@ -2526,12 +2526,12 @@ export const useSettingsStore = defineStore("settings", () => {
const needsCompactTabTitleDefaultMigration = typeof savedSettings.compactTabTitleDefaultVersion !== "number" || savedSettings.compactTabTitleDefaultVersion < COMPACT_TAB_TITLE_DEFAULT_VERSION;
const needsTabNavigationShortcutMigration = needsTabNavigationHistoryShortcutMigration(savedSettings.shortcuts);
const savedNullText = (savedSettings.dataGridExtractorOptions as Partial<DataGridExtractorOptions> | undefined)?.dsv?.nullText;
- // v2 also resets a historically persisted includeDatabaseName=true, so
+ // v3 also resets a historically persisted includeDatabaseName=false (from v2), so
// trigger the eager persist for that stale disk value even when the
// v1 "NULL" marker is already migrated away.
const savedSqlIncludeDatabaseName = (savedSettings.dataGridExtractorOptions as Partial<DataGridExtractorOptions> | undefined)?.sql?.includeDatabaseName;
const needsDataGridExtractorOptionsMigration =
- (typeof savedSettings.dataGridExtractorOptionsMigrationVersion !== "number" || savedSettings.dataGridExtractorOptionsMigrationVersion < DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION) && (savedNullText === "NULL" || savedSqlIncludeDatabaseName === true);
+ (typeof savedSettings.dataGridExtractorOptionsMigrationVersion !== "number" || savedSettings.dataGridExtractorOptionsMigrationVersion < DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION) && (savedNullText === "NULL" || savedSqlIncludeDatabaseName === false);
const savedUpdateDownloadSource = (saved as { updateDownloadSource?: unknown }).updateDownloadSource;
if (savedUpdateDownloadSource === "atomgit" || needsExecuteModeDefaultMigration || needsWelcomePageDefaultMigration || needsCompactTabTitleDefaultMigration || needsTabNavigationShortcutMigration || needsSidebarBrowseObjectsMigration || needsDataGridExtractorOptionsMigration) {
// Persist one-time migrations so removed or unsafe defaults cannot reappear.
diff --git a/crates/dbx-sql-dialect/src/sql_dialect/table_select.rs b/crates/dbx-sql-dialect/src/sql_dialect/table_select.rs
index f7c585aab5..ac771a7a88 100644
--- a/crates/dbx-sql-dialect/src/sql_dialect/table_select.rs
+++ b/crates/dbx-sql-dialect/src/sql_dialect/table_select.rs
@@ -508,15 +508,19 @@ pub fn database_qualified_table_name(
database: Option<&str>,
table_name: &str,
) -> Option<String> {
- let database = database.map(str::trim).filter(|database| !database.is_empty())?;
+ let database = database.map(str::trim).filter(|database| !database.is_empty());
+ let schema = schema.map(str::trim).filter(|schema| !schema.is_empty());
match database_type {
- Some(DatabaseType::ClickHouse) => Some(format!(
- "{}.{}",
- quote_table_identifier(database_type, database),
- quote_table_identifier(database_type, table_name)
- )),
+ Some(DatabaseType::ClickHouse) => {
+ let namespace = database.or(schema)?;
+ Some(format!(
+ "{}.{}",
+ quote_table_identifier(database_type, namespace),
+ quote_table_identifier(database_type, table_name)
+ ))
+ }
Some(DatabaseType::Mysql | DatabaseType::Goldendb | DatabaseType::Doris | DatabaseType::StarRocks) => {
- let namespace = schema.map(str::trim).filter(|schema| !schema.is_empty()).unwrap_or(database);
+ let namespace = schema.or(database)?;
Some(qualified_table_name_with_catalog(
database_type,
catalog,
@@ -526,9 +530,10 @@ pub fn database_qualified_table_name(
))
}
Some(DatabaseType::SqlServer) => {
+ let database = database?;
// A linked-server schema already carries `server|catalog|schema`, so
// prefixing it with the local database would produce a bogus name.
- let schema = schema.map(str::trim).filter(|schema| !schema.is_empty())?;
+ let schema = schema?;
if parse_sqlserver_linked_schema_ref(schema).is_some() {
return None;
}
@@ -1341,11 +1346,19 @@ mod tests {
database_qualified_table_name(Some(DatabaseType::Mysql), None, Some("db_9"), Some("dbx"), "t").as_deref(),
Some("`db_9`.`t`")
);
+ assert_eq!(
+ database_qualified_table_name(Some(DatabaseType::Mysql), None, Some("db_9"), None, "t").as_deref(),
+ Some("`db_9`.`t`")
+ );
assert_eq!(
database_qualified_table_name(Some(DatabaseType::ClickHouse), None, Some("default"), Some("dbx"), "t")
.as_deref(),
Some("`dbx`.`t`")
);
+ assert_eq!(
+ database_qualified_table_name(Some(DatabaseType::ClickHouse), None, Some("default"), None, "t").as_deref(),
+ Some("`default`.`t`")
+ );
assert_eq!(
database_qualified_table_name(Some(DatabaseType::SqlServer), None, Some("dbo"), Some("dbx"), "t")
.as_deref(),
diff --git a/docs/content/docs/data-grid.cn.mdx b/docs/content/docs/data-grid.cn.mdx
index e49836a193..187fd25cf2 100644
--- a/docs/content/docs/data-grid.cn.mdx
+++ b/docs/content/docs/data-grid.cn.mdx
@@ -136,6 +136,7 @@ MySQL 按条件批量更新有所不同,因为条件匹配的数据可能并
- 使用字段注释作为复制列名(适合面向业务的表格)
- 为多行生成单条批量 `INSERT`,或逐行 `INSERT`
- 排除主键后复制为新记录模板
+- 复制为 SQL DML(`INSERT` / `UPDATE`)时默认包含数据库限定名(版本迁移会为此前手动关闭该选项的用户重新开启为默认值,可在数据提取器设置中按需调整)
当字段存在可识别外键关系时,可以从单元格跳转到被引用记录。这个入口依赖元数据和目标连接权限。
diff --git a/docs/content/docs/data-grid.mdx b/docs/content/docs/data-grid.mdx
index 98a3ea1d1d..98adba2513 100644
--- a/docs/content/docs/data-grid.mdx
+++ b/docs/content/docs/data-grid.mdx
@@ -136,6 +136,7 @@ The grid supports individual cells, rectangular ranges, full rows, and multiple
- Use column comments as copied names for business-facing extracts
- Generate one multi-row `INSERT` or separate `INSERT` statements
- Exclude primary keys when creating a template for new records
+- Include qualified database names by default when copying rows as SQL DML (`INSERT` and `UPDATE`); migration re-enables this by default for users who previously unchecked it, and it can be customized in extractor settings
When DBX can resolve a foreign-key relationship, a cell can navigate to the referenced record. This depends on metadata and target-connection permissions.
diff --git a/packages/app-tests/tableDataTabMeta.test.ts b/packages/app-tests/tableDataTabMeta.test.ts
index cfa4b3f5a4..123b60061e 100644
--- a/packages/app-tests/tableDataTabMeta.test.ts
+++ b/packages/app-tests/tableDataTabMeta.test.ts
@@ -38,7 +38,11 @@ test("returns persisted table metadata for a data tab", () => {
const restored = tab({ title: "public.users", schema: undefined, sql: 'SELECT * FROM "public"."users"', tableMeta });
assert.equal(repairRestoredDataTabTableIdentity(restored, "postgres"), false);
- assert.equal(tableMetaForDataTab(restored), tableMeta);
+ assert.deepEqual(tableMetaForDataTab(restored), {
+ ...tableMeta,
+ database: "app",
+ schema: undefined,
+ });
});
test("builds fallback metadata from a data tab when column metadata is unavailable", () => {
@@ -54,6 +58,7 @@ test("builds fallback metadata from a data tab when column metadata is unavailab
);
assert.deepEqual(meta, {
+ database: "app",
schema: "public",
tableName: "users",
columns: [
@@ -100,6 +105,7 @@ test("uses result columns when persisted table metadata has no columns", () => {
),
{
schema: "public",
+ database: "app",
tableName: "users",
columns: [
{