feat(editor): include database name in generated SQL
This commit is contained in:
34 files changed
+379
-23
No files matched your search
@@ -5,7 +5,7 @@ const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.v
|
||||
|
||||
describe("DataGrid context menu state", () => {
|
||||
it("clears the context target whenever the result is replaced", () => {
|
||||
expect(dataGridSource).toMatch(/watch\(\s*\(\) => props\.result,[\s\S]*?clearRowSelection\(\);\s*invalidateSyntheticContextSelection\(\);[\s\S]*?exitTransaction\(\);/);
|
||||
expect(dataGridSource).toMatch(/watch\(\s*\(\) => props\.result,[\s\S]*?clearRowSelection\(\);\s*invalidateContextMenuTarget\(\);[\s\S]*?exitTransaction\(\);/);
|
||||
});
|
||||
|
||||
it("uses the actual copyable row count in the copy menu", () => {
|
||||
|
||||
@@ -200,6 +200,10 @@ describe("buildSelectAllSql", () => {
|
||||
expect(buildSelectAllSql("mysql", { schema: "mydb", tableName: "users" })).toBe("SELECT * FROM `users`");
|
||||
});
|
||||
|
||||
it("includes the MySQL database when requested", () => {
|
||||
expect(buildSelectAllSql("mysql", { database: "mydb", tableName: "users" }, undefined, undefined, true)).toBe("SELECT * FROM `mydb`.`users`");
|
||||
});
|
||||
|
||||
it("qualifies and quotes a PostgreSQL table with its schema", () => {
|
||||
expect(buildSelectAllSql("postgres", { schema: "public", tableName: "users" })).toBe('SELECT * FROM "public"."users"');
|
||||
});
|
||||
|
||||
+86
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { qualifiedTableName, quoteTableDataIdentifier, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
|
||||
import { qualifiedTableName, qualifyTableReferencesInSql, quoteTableDataIdentifier, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
|
||||
|
||||
describe("qualifiedTableName — Doris/StarRocks multi-catalog", () => {
|
||||
it("prefixes external catalog for Doris (no schema)", () => {
|
||||
@@ -28,6 +28,91 @@ describe("qualifiedTableName — Doris/StarRocks multi-catalog", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifiedTableName — optional database qualification", () => {
|
||||
it("keeps MySQL table references unchanged unless enabled", () => {
|
||||
expect(qualifiedTableName({ databaseType: "mysql", database: "analytics", tableName: "events" })).toBe("`events`");
|
||||
expect(qualifiedTableName({ databaseType: "mysql", database: "analytics", tableName: "events", includeDatabaseName: true })).toBe("`analytics`.`events`");
|
||||
});
|
||||
|
||||
it("uses the dialect's identifier quoting for database-qualified names", () => {
|
||||
expect(qualifiedTableName({ databaseType: "clickhouse", database: "a`b", tableName: "c`d", includeDatabaseName: true })).toBe("`a``b`.`c``d`");
|
||||
});
|
||||
|
||||
it("uses MySQL-compatible quoting for GoldenDB", () => {
|
||||
expect(qualifiedTableName({ databaseType: "goldendb", database: "a`b", tableName: "c`d", includeDatabaseName: true })).toBe("`a``b`.`c``d`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifyTableReferencesInSql", () => {
|
||||
it("qualifies FROM and JOIN sources while preserving aliases", () => {
|
||||
expect(
|
||||
qualifyTableReferencesInSql("SELECT * FROM apis AS ap JOIN users AS u ON u.id = ap.user_id", {
|
||||
databaseType: "mysql",
|
||||
database: "aaa",
|
||||
includeDatabaseName: true,
|
||||
}),
|
||||
).toBe("SELECT * FROM `aaa`.`apis` AS ap JOIN `aaa`.`users` AS u ON u.id = ap.user_id");
|
||||
});
|
||||
|
||||
it("qualifies every source in a multi-line LEFT JOIN query", () => {
|
||||
const sql = "SELECT `u`.`id`, `g`.`group_name`\nFROM `users` AS `u`\nLEFT JOIN `group_users` AS `gu` ON `gu`.`user_id` = `u`.`id`\nLEFT JOIN `groups` AS `g` ON `g`.`id` = `gu`.`group_id`\nLEFT JOIN `user_roles` AS `ur` ON `ur`.`user_id` = `u`.`id`";
|
||||
const result = qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true });
|
||||
expect(result).toContain("FROM `aaa`.`users` AS `u`");
|
||||
expect(result).toContain("LEFT JOIN `aaa`.`group_users` AS `gu`");
|
||||
expect(result).toContain("LEFT JOIN `aaa`.`groups` AS `g`");
|
||||
expect(result).toContain("LEFT JOIN `aaa`.`user_roles` AS `ur`");
|
||||
});
|
||||
|
||||
it("leaves already-qualified sources unchanged", () => {
|
||||
const options = { databaseType: "mysql" as const, database: "aaa", includeDatabaseName: true };
|
||||
expect(qualifyTableReferencesInSql("SELECT * FROM `aaa`.`apis`", options)).toBe("SELECT * FROM `aaa`.`apis`");
|
||||
});
|
||||
|
||||
it("qualifies physical tables inside CTEs but never CTE references", () => {
|
||||
const sql = "WITH users AS (SELECT * FROM archived_users)\nSELECT * FROM users";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("WITH users AS (SELECT * FROM `aaa`.`archived_users`)\nSELECT * FROM users");
|
||||
});
|
||||
|
||||
it("preserves CTE references when the statement has a trailing semicolon", () => {
|
||||
const sql = "WITH users AS (SELECT * FROM archived_users) SELECT * FROM users;";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("WITH users AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM users;");
|
||||
});
|
||||
|
||||
it("keeps CTE visibility scoped to each statement", () => {
|
||||
const sql = "WITH users AS (SELECT * FROM archived_users) SELECT * FROM users; WITH roles AS (SELECT * FROM archived_roles) SELECT * FROM roles;";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("WITH users AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM users; WITH roles AS (SELECT * FROM `aaa`.`archived_roles`) SELECT * FROM roles;");
|
||||
});
|
||||
|
||||
it("does not treat a later CTE name as visible inside an earlier CTE", () => {
|
||||
const sql = "WITH first AS (SELECT * FROM second), second AS (SELECT * FROM archived_users) SELECT * FROM first";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("WITH first AS (SELECT * FROM `aaa`.`second`), second AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM first");
|
||||
});
|
||||
|
||||
it("does not leak a nested CTE name into the outer query", () => {
|
||||
const sql = "SELECT * FROM (WITH users AS (SELECT * FROM archived_users) SELECT * FROM users) nested JOIN users ON 1 = 1";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("SELECT * FROM (WITH users AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM users) nested JOIN `aaa`.`users` ON 1 = 1");
|
||||
});
|
||||
|
||||
it("keeps outer CTEs visible inside nested WITH queries", () => {
|
||||
const sql = "WITH users AS (SELECT * FROM archived_users) SELECT * FROM (WITH roles AS (SELECT * FROM users) SELECT * FROM roles) nested";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("WITH users AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM (WITH roles AS (SELECT * FROM users) SELECT * FROM roles) nested");
|
||||
});
|
||||
|
||||
it("does not let a nested CTE suppress an earlier outer physical table", () => {
|
||||
const sql = "SELECT * FROM users WHERE EXISTS (WITH users AS (SELECT * FROM archived_users) SELECT * FROM users)";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("SELECT * FROM `aaa`.`users` WHERE EXISTS (WITH users AS (SELECT * FROM `aaa`.`archived_users`) SELECT * FROM users)");
|
||||
});
|
||||
|
||||
it("does not rewrite FROM and JOIN text inside literals or comments", () => {
|
||||
const sql = "SELECT 'FROM users JOIN groups' AS note\nFROM users -- JOIN groups";
|
||||
expect(qualifyTableReferencesInSql(sql, { databaseType: "mysql", database: "aaa", includeDatabaseName: true })).toBe("SELECT 'FROM users JOIN groups' AS note\nFROM `aaa`.`users` -- JOIN groups");
|
||||
});
|
||||
|
||||
it("uses GoldenDB's MySQL-compatible identifier quoting", () => {
|
||||
expect(qualifyTableReferencesInSql("SELECT * FROM users", { databaseType: "goldendb", database: "aaa", includeDatabaseName: true })).toBe("SELECT * FROM `aaa`.`users`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualifiedTableName — SQLite attached databases", () => {
|
||||
it("qualifies tables with the attached database alias", () => {
|
||||
expect(qualifiedTableName({ databaseType: "sqlite", schema: "analytics", tableName: "events" })).toBe('"analytics"."events"');
|
||||
|
||||
@@ -1291,7 +1291,7 @@ export async function buildDroppedFilePreviewSql(options: DroppedFilePreviewSqlO
|
||||
}
|
||||
|
||||
export async function buildTableSelectSql(options: BuildTableSelectSqlOptions): Promise<string> {
|
||||
return post("/api/query/build-table-select-sql", { options });
|
||||
return post("/api/query/build-table-select-sql", { options, includeDatabaseName: options.includeDatabaseName === true });
|
||||
}
|
||||
|
||||
export async function buildDatabaseSearchSql(options: DatabaseSearchSqlOptions): Promise<DatabaseSearchSql | null> {
|
||||
|
||||
@@ -1452,7 +1452,7 @@ export async function buildDroppedFilePreviewSql(options: DroppedFilePreviewSqlO
|
||||
}
|
||||
|
||||
export async function buildTableSelectSql(options: BuildTableSelectSqlOptions): Promise<string> {
|
||||
return invoke("build_table_select_sql", { options });
|
||||
return invoke("build_table_select_sql", { options, includeDatabaseName: options.includeDatabaseName === true });
|
||||
}
|
||||
|
||||
export async function buildDatabaseSearchSql(options: DatabaseSearchSqlOptions): Promise<DatabaseSearchSql | null> {
|
||||
|
||||
@@ -186,6 +186,7 @@ describe("settings search", () => {
|
||||
{ titleKey: "settings.completionTriggerMode", category: "editor", targetId: "editor" },
|
||||
{ titleKey: "settings.autoAliasTables", category: "editor", targetId: "editor" },
|
||||
{ titleKey: "settings.clickTableNavigationTarget", category: "editor", targetId: "editor" },
|
||||
{ titleKey: "settings.generateSqlIncludeDatabaseName", category: "editor", targetId: "editor" },
|
||||
{ titleKey: "settings.sqlFormatterKeywordCase", category: "formatter", targetId: "formatter" },
|
||||
{ titleKey: "settings.sqlFormatterFunctionCase", category: "formatter", targetId: "formatter" },
|
||||
{ titleKey: "settings.sqlFormatterDataTypeCase", category: "formatter", targetId: "formatter" },
|
||||
|
||||
@@ -65,6 +65,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
|
||||
"dataTabReuseMode",
|
||||
"openDataTabsNextToActive",
|
||||
"prefillNewQueryWithSelect",
|
||||
"generateSqlIncludeDatabaseName",
|
||||
"updateNotificationsEnabled",
|
||||
"sidebarObjectInfoMode",
|
||||
"sidebarAllowHorizontalScroll",
|
||||
|
||||
@@ -120,6 +120,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
|
||||
{ id: "editor-unsaved-close", category: "editor", titleKey: "settings.confirmUnsavedSqlClose", descriptionKey: "settings.confirmUnsavedSqlCloseDescription", targetId: "editor" },
|
||||
{ id: "editor-app-close-unsaved-tabs", category: "editor", titleKey: "settings.appCloseUnsavedTabsMode", descriptionKey: "settings.appCloseUnsavedTabsModeDescription", targetId: "editor" },
|
||||
{ id: "editor-prefill-query", category: "editor", titleKey: "settings.prefillNewQueryWithSelect", descriptionKey: "settings.prefillNewQueryWithSelectDescription", targetId: "editor" },
|
||||
{ id: "editor-generate-sql-include-database", category: "editor", titleKey: "settings.generateSqlIncludeDatabaseName", descriptionKey: "settings.generateSqlIncludeDatabaseNameDescription", targetId: "editor" },
|
||||
{ id: "editor-diagnostics", category: "editor", titleKey: "settings.sqlSemanticDiagnosticsEnabled", descriptionKey: "settings.sqlSemanticDiagnosticsEnabledDescription", targetId: "editor" },
|
||||
{ id: "editor-sql-variables", category: "editor", titleKey: "settings.sqlVariableSyntax", descriptionKey: "settings.sqlVariableSyntaxDescription", targetId: "editor" },
|
||||
{ id: "editor-saved-sql-target", category: "editor", titleKey: "settings.savedSqlOpenTarget", targetId: "editor" },
|
||||
|
||||
@@ -92,6 +92,7 @@ export interface ResolveNewQueryInitialSqlInput extends ResolveNewQueryTableInpu
|
||||
databaseType?: DatabaseType;
|
||||
driverProfile?: string;
|
||||
identifierQuote?: string;
|
||||
includeDatabaseName?: boolean;
|
||||
}
|
||||
|
||||
// Database types whose "table" view does not use standard SQL `SELECT * FROM <table>`
|
||||
@@ -147,9 +148,9 @@ export function resolveNewQueryTable(input: ResolveNewQueryTableInput): NewQuery
|
||||
* the same per-dialect identifier quoting and schema/catalog qualification used
|
||||
* by the table-data view.
|
||||
*/
|
||||
export function buildSelectAllSql(databaseType: DatabaseType | undefined, table: Pick<NewQueryTable, "schema" | "catalog" | "tableName"> & Partial<Pick<NewQueryTable, "database">>, identifierQuote?: string, driverProfile?: string): string {
|
||||
export function buildSelectAllSql(databaseType: DatabaseType | undefined, table: Pick<NewQueryTable, "schema" | "catalog" | "tableName"> & Partial<Pick<NewQueryTable, "database">>, identifierQuote?: string, driverProfile?: string, includeDatabaseName = false): string {
|
||||
if (databaseType === "victoriametrics") return metricRangeQuery(table.tableName);
|
||||
const ref = qualifiedTableName({ databaseType, driverProfile, identifierQuote, database: table.database, schema: table.schema, catalog: table.catalog, tableName: table.tableName });
|
||||
const ref = qualifiedTableName({ databaseType, driverProfile, identifierQuote, database: table.database, schema: table.schema, catalog: table.catalog, tableName: table.tableName, includeDatabaseName });
|
||||
return `SELECT * FROM ${ref}`;
|
||||
}
|
||||
|
||||
@@ -164,5 +165,5 @@ export function resolveNewQueryInitialSql(input: ResolveNewQueryInitialSqlInput)
|
||||
const table = resolveNewQueryTable(input);
|
||||
if (!table || table.connectionId !== input.targetConnectionId || table.database !== input.targetDatabase) return undefined;
|
||||
|
||||
return buildSelectAllSql(input.databaseType, table, input.identifierQuote, input.driverProfile);
|
||||
return buildSelectAllSql(input.databaseType, table, input.identifierQuote, input.driverProfile, input.includeDatabaseName);
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import { jdbcDriverProfileUsesSchemaQualification } from "@/lib/database/jdbcDia
|
||||
import * as api from "@/lib/backend/api.ts";
|
||||
import { parseSqlServerLinkedSchema, sqlServerLinkedTableName } from "@/lib/database/sqlServerLinkedServers.ts";
|
||||
import { isExplicitlyQuotedSqlIdentifier, quoteGaussDbJdbcIdentifier } from "@/lib/sql/sqlIdentifier.ts";
|
||||
import { sqlSemanticDialectFor } from "@/lib/sql/semantic/dialect";
|
||||
import { sqlSemanticTableNameSpans } from "@/lib/sql/semantic/model";
|
||||
import { tokenIsIdentifier, tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
|
||||
import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
|
||||
|
||||
export interface BuildTableSelectSqlOptions {
|
||||
databaseType?: DatabaseType;
|
||||
@@ -25,6 +29,30 @@ export interface BuildTableSelectSqlOptions {
|
||||
includeRowId?: boolean;
|
||||
catalog?: string;
|
||||
database?: string;
|
||||
/** Include the active database when this dialect supports `database.table` references. */
|
||||
includeDatabaseName?: boolean;
|
||||
}
|
||||
|
||||
const DATABASE_QUALIFIED_TABLE_TYPES = new Set<DatabaseType>(["mysql", "clickhouse", "doris", "starrocks", "goldendb"]);
|
||||
|
||||
function sqlStatementSpans(sql: string, dialectId: string): Array<{ start: number; end: number }> {
|
||||
const spans: Array<{ start: number; end: number }> = [];
|
||||
let start = 0;
|
||||
const appendSpan = (end: number) => {
|
||||
let trimmedStart = start;
|
||||
let trimmedEnd = end;
|
||||
while (trimmedStart < trimmedEnd && /\s/.test(sql[trimmedStart] ?? "")) trimmedStart += 1;
|
||||
while (trimmedEnd > trimmedStart && /\s/.test(sql[trimmedEnd - 1] ?? "")) trimmedEnd -= 1;
|
||||
if (trimmedStart < trimmedEnd) spans.push({ start: trimmedStart, end: trimmedEnd });
|
||||
};
|
||||
|
||||
for (const token of tokenizeSqlSemantic(sql, dialectId)) {
|
||||
if (token.kind !== "punctuation" || token.text !== ";" || token.depth !== 0) continue;
|
||||
appendSpan(token.span.start);
|
||||
start = token.span.end;
|
||||
}
|
||||
appendSpan(sql.length);
|
||||
return spans;
|
||||
}
|
||||
|
||||
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
|
||||
@@ -49,7 +77,8 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
|
||||
databaseType === "tdengine" ||
|
||||
databaseType === "access" ||
|
||||
databaseType === "doris" ||
|
||||
databaseType === "starrocks"
|
||||
databaseType === "starrocks" ||
|
||||
databaseType === "goldendb"
|
||||
)
|
||||
return `\`${name.replace(/`/g, "``")}\``;
|
||||
if (databaseType === "informix" && /^[A-Za-z_][A-Za-z0-9_$]*$/.test(name)) return name;
|
||||
@@ -75,8 +104,8 @@ function quoteCypherIdentifier(name: string): string {
|
||||
return `\`${name.replace(/`/g, "``")}\``;
|
||||
}
|
||||
|
||||
export function qualifiedTableName(options: Pick<BuildTableSelectSqlOptions, "databaseType" | "driverProfile" | "identifierQuote" | "schema" | "tableName" | "catalog" | "database">): string {
|
||||
const { databaseType, driverProfile, identifierQuote, schema, tableName, catalog, database } = options;
|
||||
export function qualifiedTableName(options: Pick<BuildTableSelectSqlOptions, "databaseType" | "driverProfile" | "identifierQuote" | "schema" | "tableName" | "catalog" | "database" | "includeDatabaseName">): string {
|
||||
const { databaseType, driverProfile, identifierQuote, schema, tableName, catalog, database, includeDatabaseName } = options;
|
||||
if (databaseType === "informix" && driverProfile?.trim().toLowerCase() === "gbase8s") {
|
||||
return quoteTableDataIdentifier(databaseType, tableName, identifierQuote);
|
||||
}
|
||||
@@ -143,9 +172,111 @@ export function qualifiedTableName(options: Pick<BuildTableSelectSqlOptions, "da
|
||||
}
|
||||
return `${quoteTableIdentifier(databaseType, schema)}.${quoteTableIdentifier(databaseType, tableName)}`;
|
||||
}
|
||||
// MySQL-style engines use the selected database as their table namespace.
|
||||
// Keep this opt-in so existing generated SQL remains unchanged by default.
|
||||
const trimmedDatabase = database?.trim();
|
||||
if (includeDatabaseName && trimmedDatabase && databaseType && DATABASE_QUALIFIED_TABLE_TYPES.has(databaseType)) {
|
||||
return `${quoteTableIdentifier(databaseType, trimmedDatabase)}.${quoteTableIdentifier(databaseType, tableName)}`;
|
||||
}
|
||||
return quoteTableIdentifier(databaseType, tableName);
|
||||
}
|
||||
|
||||
interface SqlCteVisibility {
|
||||
name: string;
|
||||
visibleFrom: number;
|
||||
visibleUntil: number;
|
||||
}
|
||||
|
||||
function matchingSqlParenthesisToken(tokens: readonly SqlSemanticToken[], openIndex: number): number {
|
||||
const open = tokens[openIndex];
|
||||
if (open?.text !== "(") return -1;
|
||||
for (let index = openIndex + 1; index < tokens.length; index += 1) {
|
||||
if (tokens[index]?.text === ")" && tokens[index]?.depth === open.depth) return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function sqlCteVisibilities(tokens: readonly SqlSemanticToken[], sqlLength: number): SqlCteVisibility[] {
|
||||
const visibilities: SqlCteVisibility[] = [];
|
||||
for (let withIndex = 0; withIndex < tokens.length; withIndex += 1) {
|
||||
const withToken = tokens[withIndex];
|
||||
if (withToken?.kind !== "word" || withToken.normalized !== "with") continue;
|
||||
const depth = withToken.depth;
|
||||
const scopeEnd = tokens.find((token, index) => index > withIndex && token.depth < depth)?.span.start ?? sqlLength;
|
||||
let index = withIndex + 1;
|
||||
if (tokens[index]?.depth === depth && tokens[index]?.normalized === "recursive") index += 1;
|
||||
|
||||
while (index < tokens.length) {
|
||||
while (tokens[index]?.depth === depth && tokens[index]?.text === ",") index += 1;
|
||||
const nameToken = tokens[index];
|
||||
if (!nameToken || nameToken.depth !== depth || !tokenIsIdentifier(nameToken)) break;
|
||||
index += 1;
|
||||
|
||||
if (tokens[index]?.depth === depth && tokens[index]?.text === "(") {
|
||||
const columnsClose = matchingSqlParenthesisToken(tokens, index);
|
||||
if (columnsClose < 0) break;
|
||||
index = columnsClose + 1;
|
||||
}
|
||||
if (tokens[index]?.depth === depth && tokens[index]?.normalized === "as") index += 1;
|
||||
if (tokens[index]?.depth !== depth || tokens[index]?.text !== "(") break;
|
||||
const bodyOpen = index;
|
||||
const bodyClose = matchingSqlParenthesisToken(tokens, bodyOpen);
|
||||
if (bodyClose < 0) break;
|
||||
visibilities.push({
|
||||
name: unquoteSqlSemanticIdentifier(nameToken),
|
||||
visibleFrom: tokens[bodyOpen]!.span.end,
|
||||
visibleUntil: scopeEnd,
|
||||
});
|
||||
index = bodyClose + 1;
|
||||
if (tokens[index]?.depth !== depth || tokens[index]?.text !== ",") break;
|
||||
}
|
||||
}
|
||||
return visibilities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Qualifies physical table sources shown in a result footer without changing
|
||||
* the SQL that was actually executed. The semantic model deliberately skips
|
||||
* CTE names, strings, and comments that can happen to contain FROM/JOIN text.
|
||||
*/
|
||||
export function qualifyTableReferencesInSql(sql: string, options: Pick<BuildTableSelectSqlOptions, "databaseType" | "database" | "includeDatabaseName">): string {
|
||||
if (!options.includeDatabaseName || !options.databaseType || !DATABASE_QUALIFIED_TABLE_TYPES.has(options.databaseType) || !options.database?.trim()) return sql;
|
||||
const database = quoteTableIdentifier(options.databaseType, options.database.trim());
|
||||
// Build replacements from right to left so that every semantic span still
|
||||
// points at the original source text. Only one-part physical table names
|
||||
// need the active database prefix; CTEs and already-qualified tables do not.
|
||||
const semanticOptions = {
|
||||
databaseType: options.databaseType,
|
||||
dialect: options.databaseType === "goldendb" ? "mysql" : undefined,
|
||||
} as const;
|
||||
const dialectId = sqlSemanticDialectFor(semanticOptions).id;
|
||||
const replacements = sqlStatementSpans(sql, dialectId)
|
||||
.flatMap(({ start, end }) => {
|
||||
const statementSql = sql.slice(start, end);
|
||||
const tokens = tokenizeSqlSemantic(statementSql, dialectId);
|
||||
const cteVisibilities = sqlCteVisibilities(tokens, statementSql.length);
|
||||
const isCteReference = (name: string, span: { start: number; end: number }): boolean => cteVisibilities.some((cte) => cte.name.toLowerCase() === name.toLowerCase() && span.start >= cte.visibleFrom && span.end <= cte.visibleUntil);
|
||||
const tokensBySpan = new Map(tokens.map((token) => [`${token.span.start}:${token.span.end}`, token]));
|
||||
|
||||
return sqlSemanticTableNameSpans(statementSql, semanticOptions)
|
||||
.map((span) => ({ span, token: tokensBySpan.get(`${span.start}:${span.end}`) }))
|
||||
.filter(({ span, token }) => {
|
||||
if (!token || isCteReference(unquoteSqlSemanticIdentifier(token), span)) return false;
|
||||
// sqlSemanticTableNameSpans returns the final segment in a qualified
|
||||
// name, so a preceding dot identifies a database-qualified source.
|
||||
return !statementSql.slice(0, span.start).trimEnd().endsWith(".");
|
||||
})
|
||||
.map(({ span, token }) => ({
|
||||
span: { start: start + span.start, end: start + span.end },
|
||||
tableName: unquoteSqlSemanticIdentifier(token!),
|
||||
}));
|
||||
})
|
||||
.filter(({ span }, index, all) => all.findIndex((candidate) => candidate.span.start === span.start && candidate.span.end === span.end) === index)
|
||||
.sort((left, right) => right.span.start - left.span.start);
|
||||
|
||||
return replacements.reduce((qualifiedSql, { span, tableName }) => `${qualifiedSql.slice(0, span.start)}${database}.${quoteTableIdentifier(options.databaseType, tableName)}${qualifiedSql.slice(span.end)}`, sql);
|
||||
}
|
||||
|
||||
export function metricSelector(metricName: string): string {
|
||||
const escaped = metricName.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
|
||||
return `{__name__="${escaped}"}`;
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface TableSqlTemplateOptions {
|
||||
schema?: string;
|
||||
catalog?: string;
|
||||
database?: string;
|
||||
includeDatabaseName?: boolean;
|
||||
tableName: string;
|
||||
columns?: ColumnInfo[];
|
||||
tableType?: string;
|
||||
@@ -105,6 +106,7 @@ function templateTableName(options: TableSqlTemplateOptions): string {
|
||||
identifierQuote: options.identifierQuote,
|
||||
catalog: options.catalog,
|
||||
database: options.database,
|
||||
includeDatabaseName: options.includeDatabaseName,
|
||||
schema: options.schema,
|
||||
tableName: options.tableName,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user