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(editor): add SQL compression

gggaiitx9602cc3329d1
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index b7bf7ffb34..bcac82df6d 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -204,6 +204,7 @@ const contentAreaRef = ref<InstanceType<typeof ContentArea> | null>(null);
const selectedSql = ref("");
const cursorPos = ref(0);
const formatSqlRequest = ref<{ id: number; tabId: string } | null>(null);
+const compressSqlRequest = ref<{ id: number; tabId: string } | null>(null);
const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result");
const newQueryContextSource = ref<"tab" | "sidebar">("tab");
const queryEditorDdlTarget = ref<{ connectionId: string; database: string; catalog?: string; schema?: string; tableName: string; objectType?: ObjectSourceKind } | null>(null);
@@ -668,6 +669,15 @@ function formatActiveSql() {
};
}
+function compressActiveSql() {
+ const tab = activeTab.value;
+ if (!tab || tab.mode !== "query" || !tab.sql.trim()) return;
+ compressSqlRequest.value = {
+ id: (compressSqlRequest.value?.id ?? 0) + 1,
+ tabId: tab.id,
+ };
+}
+
function toggleSqlKeywordCase() {
const sqlFormatter = settingsStore.editorSettings.sqlFormatter;
settingsStore.updateEditorSettings({
@@ -2177,6 +2187,7 @@ onUnmounted(() => {
@cancel="cancelActiveExecution()"
@explain="tryExplain()"
@format-sql="formatActiveSql"
+ @compress-sql="compressActiveSql"
@toggle-sql-keyword-case="toggleSqlKeywordCase"
@save-sql="void openSaveSqlDialog()"
@open-sql="openSqlFile"
@@ -2197,6 +2208,7 @@ onUnmounted(() => {
:executable-sql="executableSql"
:active-output-view="activeOutputView"
:format-sql-request="formatSqlRequest"
+ :compress-sql-request="compressSqlRequest"
:selected-sql="selectedSql"
:cursor-pos="cursorPos"
:block-dangerous-redis-commands="blockDangerousRedisCommands"
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index a20cae334e..5687195b61 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -17,7 +17,7 @@ import { executableStatementRangeAtCursor, executableStatementRangeCacheForDoc,
import { currentStatementFrameRangeTo, visualSqlColumnsWithInlineHints } from "@/lib/sql/currentStatementFrame";
import { expandToSqlStatementWindow, parseInsertValueHints } from "@/lib/sql/insertValueHints";
import { insertValueHintColumnNames } from "@/lib/sql/insertValueHintColumns";
-import { formatSqlText, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
+import { formatSqlText, compressSqlText, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { blankLineDeletionChanges, replaceSelectedEditorText } from "@/lib/editor/queryEditorTextEdits";
import { buildSqlInConditionFromPasteSource, insertTextForSqlInCondition } from "@/lib/sql/sqlInListPaste";
import { resolveSqlSingleQuoteKeyAction } from "@/lib/sql/sqlQuoteCaret";
@@ -106,6 +106,7 @@ const props = defineProps<{
syntaxDialect?: "mysql" | "postgres" | "sqlserver";
formatDialect?: SqlFormatDialect;
formatRequestId?: number;
+ compressRequestId?: number;
executionError?: string;
executionErrorSql?: string;
readOnly?: boolean;
@@ -2112,6 +2113,30 @@ async function formatCurrentSql() {
}
}
+function compressCurrentSql() {
+ if (props.readOnly) return;
+ const currentView = view.value;
+ if (!currentView) return;
+
+ const originalState = currentView.state;
+ const selection = originalState.selection.main;
+ const compressesSelection = !selection.empty;
+ const from = compressesSelection ? selection.from : 0;
+ const to = compressesSelection ? selection.to : originalState.doc.length;
+ const source = originalState.sliceDoc(from, to);
+ if (!source.trim()) return;
+
+ const compressed = compressSqlText(source, props.formatDialect ?? props.dialect ?? "generic");
+ if (currentView !== view.value || currentView.state !== originalState || currentView.state.sliceDoc(from, to) !== source) {
+ return;
+ }
+ if (compressed === source) return;
+ currentView.dispatch({
+ changes: { from, to, insert: compressed },
+ selection: compressesSelection ? { anchor: from, head: from + compressed.length } : { anchor: from + compressed.length },
+ });
+}
+
function droppedTableReference(event: DragEvent) {
return activeTableReferencePayloadValue() ?? parseTableReferencePayload(event.dataTransfer?.getData(DBX_TABLE_REFERENCE_MIME));
}
@@ -3911,6 +3936,13 @@ watch(
},
);
+watch(
+ () => props.compressRequestId,
+ (val, oldVal) => {
+ if (val && val !== oldVal) compressCurrentSql();
+ },
+);
+
watch(
() => props.executionError,
() => {
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index c44bb75f67..e84a142fd4 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -129,6 +129,7 @@ const props = defineProps<{
executableSql: string;
activeOutputView: "result" | "summary" | "explain" | "chart";
formatSqlRequest: { id: number; tabId: string } | null;
+ compressSqlRequest: { id: number; tabId: string } | null;
selectedSql: string;
cursorPos: number;
blockDangerousRedisCommands: boolean;
@@ -833,6 +834,7 @@ defineExpose({ focusSearch, refreshData, refreshQueryEditorCompletionCache, hand
:syntax-dialect="editorSyntaxDialect"
:format-dialect="activeSqlFormatDialect"
:format-request-id="formatSqlRequest?.tabId === activeTab.id ? formatSqlRequest.id : undefined"
+ :compress-request-id="compressSqlRequest?.tabId === activeTab.id ? compressSqlRequest.id : undefined"
:execution-error="activeQueryError"
:execution-error-sql="activeTab.lastExecutedSql"
:statement-execution-markers="activeStatementExecutionMarkers"
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index eb90a716b3..21fe1a229c 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref, watch, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
-import { Play, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, Layers, X, Shield, Download, RotateCcw, AlertTriangle, ClipboardPaste } from "@lucide/vue";
+import { Play, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, Layers, X, Shield, Download, RotateCcw, AlertTriangle, ClipboardPaste, Minimize2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { SearchableSelect } from "@/components/ui/searchable-select";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
@@ -39,6 +39,7 @@ const emit = defineEmits<{
explain: [];
"update:explainMode": [mode: "explain" | "autotrace"];
formatSql: [];
+ compressSql: [];
toggleSqlKeywordCase: [];
saveSql: [];
openSql: [];
@@ -253,6 +254,14 @@ function databaseOptionIsProduction(database: string): boolean {
</TooltipTrigger>
<TooltipContent>{{ t("toolbar.formatSql") }}</TooltipContent>
</Tooltip>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-amber-600 hover:bg-amber-500/10 hover:text-amber-700 dark:text-amber-300 dark:hover:text-amber-200" :disabled="activeTab.isExecuting || activeTab.isExplaining || !activeTab.sql.trim()" @click="emit('compressSql')">
+ <Minimize2 class="h-3.5 w-3.5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("toolbar.compressSql") }}</TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 70ffbbe674..ddb280bd15 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -32,6 +32,7 @@ export default {
stopExplain: "Stop explain",
formatSql: "Format SQL",
formatSqlFailed: "Failed to format SQL",
+ compressSql: "Compress SQL",
keywordCaseLower: "Use lower-case SQL keywords",
keywordCaseUpper: "Use upper-case SQL keywords",
autoCommit: "Auto Commit",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index abcc3d1d28..b4186a4e71 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -34,6 +34,7 @@ export default withEnglishFallback({
stopExplain: "Detener análisis",
formatSql: "Formatear SQL",
formatSqlFailed: "Error al formatear el SQL",
+ compressSql: "Comprimir SQL",
keywordCaseLower: "Usar palabras clave SQL en minúsculas",
keywordCaseUpper: "Usar palabras clave SQL en mayúsculas",
autoCommit: "Auto Commit",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index bd38ff2cf6..22ff362452 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -33,6 +33,7 @@ export default withEnglishFallback({
stopExplain: "Interrompi spiegazione",
formatSql: "Formatta SQL",
formatSqlFailed: "Impossibile formattare SQL",
+ compressSql: "Comprimi SQL",
keywordCaseLower: "Usa parole chiave SQL minuscole",
keywordCaseUpper: "Usa parole chiave SQL maiuscole",
autoCommit: "Auto Commit",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 69e067872b..4bf6049602 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -34,6 +34,7 @@ export default withEnglishFallback({
stopExplain: "実行計画の表示を停止",
formatSql: "SQLをフォーマット",
formatSqlFailed: "SQLのフォーマットに失敗しました",
+ compressSql: "SQLを圧縮",
keywordCaseLower: "SQLキーワードを小文字にする",
keywordCaseUpper: "SQLキーワードを大文字にする",
autoCommit: "自動コミット",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index ad36ee428b..4739a4e8a1 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -34,6 +34,7 @@ export default withEnglishFallback({
stopExplain: "Parar explicação",
formatSql: "Formatar SQL",
formatSqlFailed: "Falha ao formatar SQL",
+ compressSql: "Comprimir SQL",
keywordCaseLower: "Usar palavras-chave SQL em minúsculas",
keywordCaseUpper: "Usar palavras-chave SQL em maiúsculas",
autoCommit: "Auto Commit",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 2d24f32743..c7e900a404 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -34,6 +34,7 @@ export default withEnglishFallback({
stopExplain: "停止执行计划",
formatSql: "格式化 SQL",
formatSqlFailed: "SQL 格式化失败",
+ compressSql: "压缩 SQL",
keywordCaseLower: "使用小写 SQL 关键字",
keywordCaseUpper: "使用大写 SQL 关键字",
autoCommit: "自动提交",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 68a1fcf433..26dd0e20cb 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -34,6 +34,7 @@ export default withEnglishFallback({
stopExplain: "停止執行計畫",
formatSql: "格式化 SQL",
formatSqlFailed: "SQL 格式化失敗",
+ compressSql: "壓縮 SQL",
keywordCaseLower: "使用小寫 SQL 關鍵字",
keywordCaseUpper: "使用大寫 SQL 關鍵字",
autoCommit: "自動提交",
diff --git a/apps/desktop/src/lib/sql/sqlFormatter.ts b/apps/desktop/src/lib/sql/sqlFormatter.ts
index db6ec32afe..6e7ec8a5f0 100644
--- a/apps/desktop/src/lib/sql/sqlFormatter.ts
+++ b/apps/desktop/src/lib/sql/sqlFormatter.ts
@@ -85,6 +85,247 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
}
}
+/**
+ * 压缩 SQL 时使用的方言。不同方言对引号、注释、转义的处理不同:
+ * - `mysql`:保留 MySQL 可执行注释与 optimizer hint;单引号字符串支持反斜杠转义
+ * - `postgres`:支持 dollar-quoted 字符串
+ * - `sqlserver`:支持方括号标识符
+ * - `generic` / 其它:仅处理标准单/双引号与块/行注释
+ */
+export type SqlCompressDialect = SqlFormatDialect;
+
+/**
+ * 将 SQL 压缩成一行可执行文本:折叠所有空白(含换行)为单个空格,
+ * 移除普通行注释(-- ...)与普通块注释(/* ... *\/),
+ * 同时按方言完整保留字符串字面量、引号标识符、可执行注释与 optimizer hint。
+ *
+ * 方言感知说明:
+ * - MySQL:可执行注释作为可执行代码原样保留(仅折叠内部空白);
+ * optimizer hint 原样保留;单引号字符串内反斜杠转义保留
+ * - PostgreSQL:dollar-quoted 字符串原样保留(含标签形式)
+ * - SQL Server:方括号标识符原样保留(双右括号为转义)
+ * - 所有方言:单引号字符串、双引号标识符、反引号标识符均保留
+ */
+export function compressSqlText(sql: string, dialect: SqlCompressDialect = "generic"): string {
+ if (!sql.trim()) return sql;
+
+ const len = sql.length;
+ let out = "";
+ let i = 0;
+
+ const isWhitespace = (c: string) => c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f" || c === "\v";
+ const isIdentifierPart = (c: string | undefined) => c !== undefined && /[A-Za-z0-9_$]/.test(c);
+ const isMysqlDashComment = (c: string | undefined) => c === undefined || c.charCodeAt(0) <= 32 || c.charCodeAt(0) === 127;
+ const supportsNestedBlockComments = dialect === "postgres" || dialect === "sqlserver" || dialect === "clickhouse";
+
+ const dollarQuoteTagAt = (position: number): string | null => {
+ if (sql[position] !== "$" || isIdentifierPart(sql[position - 1])) return null;
+ if (sql[position + 1] === "$") return "$$";
+ if (!/[A-Za-z_]/.test(sql[position + 1] ?? "")) return null;
+ let end = position + 2;
+ while (/[A-Za-z0-9_]/.test(sql[end] ?? "")) end++;
+ return sql[end] === "$" ? sql.slice(position, end + 1) : null;
+ };
+
+ // 折叠一段空白为单个空格(仅在 out 非空且不以空格结尾时追加)
+ const collapseWhitespace = () => {
+ let containsLineBreak = false;
+ while (i < len && isWhitespace(sql[i])) i++;
+ for (let j = i - 1; j >= 0 && isWhitespace(sql[j]); j--) {
+ if (sql[j] === "\n" || sql[j] === "\r") {
+ containsLineBreak = true;
+ break;
+ }
+ }
+ // PostgreSQL only concatenates adjacent string literals when their separating
+ // whitespace contains a newline, so flattening this case would make valid SQL invalid.
+ if (dialect === "postgres" && containsLineBreak && out.endsWith("'") && sql[i] === "'") {
+ out += "\n";
+ } else if (out && !out.endsWith(" ")) {
+ out += " ";
+ }
+ };
+
+ while (i < len) {
+ const ch = sql[i];
+ const next = sql[i + 1];
+
+ // 块注释 /* ... */ —— 需区分普通块注释、MySQL 可执行注释 /*! */、optimizer hint /*+ */
+ if (ch === "/" && next === "*") {
+ const third = sql[i + 2];
+ const isExecutableMysql = third === "!";
+ const isOptimizerHint = third === "+";
+
+ if (isExecutableMysql || isOptimizerHint) {
+ const contentStart = i + 3;
+ const end = sql.indexOf("*/", contentStart);
+ if (end < 0) {
+ // Keep malformed input malformed instead of silently turning it into executable SQL.
+ out += sql.slice(i);
+ break;
+ }
+ const content = sql.slice(contentStart, end);
+ const leadingSpace = /^\s/.test(content) ? " " : "";
+ const trailingSpace = /\s$/.test(content) ? " " : "";
+ const compressedContent = content.trim() ? compressSqlText(content, dialect) : "";
+ out += `/*${third}${leadingSpace}${compressedContent}${trailingSpace}*/`;
+ i = end + 2;
+ continue;
+ }
+
+ // 普通块注释 —— 移除
+ const commentStart = i;
+ i += 2;
+ let depth = 1;
+ while (i < len && depth > 0) {
+ if (supportsNestedBlockComments && sql[i] === "/" && sql[i + 1] === "*") {
+ depth++;
+ i += 2;
+ } else if (sql[i] === "*" && sql[i + 1] === "/") {
+ depth--;
+ i += 2;
+ } else {
+ i++;
+ }
+ }
+ if (depth > 0) {
+ // Removing an unterminated comment can expose a destructive statement that was invalid before.
+ out += sql.slice(commentStart);
+ break;
+ }
+ if (out && !out.endsWith(" ")) out += " ";
+ continue;
+ }
+
+ // MySQL additionally supports # comments and requires whitespace/control after --.
+ const startsDashComment = ch === "-" && next === "-" && (dialect !== "mysql" || isMysqlDashComment(sql[i + 2]));
+ if (startsDashComment || (dialect === "mysql" && ch === "#")) {
+ i += startsDashComment ? 2 : 1;
+ while (i < len && sql[i] !== "\n" && sql[i] !== "\r") i++;
+ continue;
+ }
+
+ // PostgreSQL dollar-quoted 字符串:$$...$$ 或 $tag$...$tag$
+ if (dialect === "postgres" && ch === "$") {
+ const tag = dollarQuoteTagAt(i);
+ if (tag) {
+ out += tag;
+ i += tag.length;
+ const end = sql.indexOf(tag, i);
+ if (end < 0) {
+ out += sql.slice(i);
+ break;
+ }
+ out += sql.slice(i, end + tag.length);
+ i = end + tag.length;
+ continue;
+ }
+ }
+
+ // 单引号字符串字面量(处理 '' 转义;MySQL 额外处理反斜杠转义)
+ if (ch === "'") {
+ out += "'";
+ i++;
+ const postgresEscapeString = dialect === "postgres" && (sql[i - 2] === "E" || sql[i - 2] === "e") && !isIdentifierPart(sql[i - 3]);
+ while (i < len) {
+ const c = sql[i];
+ // MySQL strings and PostgreSQL E'...' strings use backslash escapes.
+ if ((dialect === "mysql" || postgresEscapeString) && c === "\\" && i + 1 < len) {
+ out += c;
+ out += sql[i + 1];
+ i += 2;
+ continue;
+ }
+ out += c;
+ if (c === "'") {
+ if (sql[i + 1] === "'") {
+ out += sql[i + 1];
+ i += 2;
+ continue;
+ }
+ i++;
+ break;
+ }
+ i++;
+ }
+ continue;
+ }
+
+ // 双引号标识符(处理 "" 转义)
+ if (ch === '"') {
+ out += '"';
+ i++;
+ while (i < len) {
+ if (dialect === "mysql" && sql[i] === "\\" && i + 1 < len) {
+ out += sql[i];
+ out += sql[i + 1];
+ i += 2;
+ continue;
+ }
+ out += sql[i];
+ if (sql[i] === '"') {
+ if (sql[i + 1] === '"') {
+ out += sql[i + 1];
+ i += 2;
+ continue;
+ }
+ i++;
+ break;
+ }
+ i++;
+ }
+ continue;
+ }
+
+ // 反引号标识符(MySQL)
+ if (ch === "`") {
+ out += "`";
+ i++;
+ while (i < len && sql[i] !== "`") {
+ out += sql[i];
+ i++;
+ }
+ if (i < len) {
+ out += "`";
+ i++;
+ }
+ continue;
+ }
+
+ // SQL Server 方括号标识符 [...](]] 为转义 ])
+ if (dialect === "sqlserver" && ch === "[") {
+ out += "[";
+ i++;
+ while (i < len) {
+ const c = sql[i];
+ out += c;
+ if (c === "]") {
+ if (sql[i + 1] === "]") {
+ out += sql[i + 1];
+ i += 2;
+ continue;
+ }
+ i++;
+ break;
+ }
+ i++;
+ }
+ continue;
+ }
+
+ // 空白 —— 折叠为单个空格
+ if (isWhitespace(ch)) {
+ collapseWhitespace();
+ continue;
+ }
+
+ out += ch;
+ i++;
+ }
+
+ return out.trim();
+}
+
/**
* Format SQL for *display* (object source, view/table DDL viewers).
*
diff --git a/packages/app-tests/sqlFormatter.test.ts b/packages/app-tests/sqlFormatter.test.ts
index 7ce915a586..de75faf3fb 100644
--- a/packages/app-tests/sqlFormatter.test.ts
+++ b/packages/app-tests/sqlFormatter.test.ts
@@ -1,6 +1,6 @@
import { strict as assert } from "node:assert";
import { afterEach, test, vi } from "vitest";
-import { formatSqlText, MAX_SQL_FORMAT_CHARS } from "../../apps/desktop/src/lib/sql/sqlFormatter.ts";
+import { compressSqlText, formatSqlText, MAX_SQL_FORMAT_CHARS } from "../../apps/desktop/src/lib/sql/sqlFormatter.ts";
afterEach(() => {
vi.doUnmock("sql-formatter");
@@ -52,3 +52,184 @@ test("leaves blank SQL unchanged", async () => {
test("rejects very large SQL before loading formatter work", async () => {
await assert.rejects(() => formatSqlText("x".repeat(MAX_SQL_FORMAT_CHARS + 1), "generic"), /too large/i);
});
+
+test("compressSqlText collapses whitespace into single spaces", () => {
+ const sql = "SELECT id,\n\t\tname\n FROM\n users\nWHERE active = 1";
+ assert.equal(compressSqlText(sql), "SELECT id, name FROM users WHERE active = 1");
+});
+
+test("compressSqlText collapses leading/trailing whitespace and trims", () => {
+ const sql = "\n\n SELECT 1 \n\n";
+ assert.equal(compressSqlText(sql), "SELECT 1");
+});
+
+test("compressSqlText collapses a multi-statement script into one line", () => {
+ const sql = "SELECT 1;\nSELECT 2;\n SELECT 3;";
+ assert.equal(compressSqlText(sql), "SELECT 1; SELECT 2; SELECT 3;");
+});
+
+test("compressSqlText removes single-line comments", () => {
+ const sql = "-- top comment\nSELECT id -- trailing\nFROM users -- table\nWHERE 1 = 1";
+ assert.equal(compressSqlText(sql), "SELECT id FROM users WHERE 1 = 1");
+});
+
+test("compressSqlText removes block comments and collapses surrounding whitespace", () => {
+ const sql = "SELECT id /* inline */ , name /*\n multi\n line */ FROM users";
+ assert.equal(compressSqlText(sql), "SELECT id , name FROM users");
+});
+
+test("compressSqlText preserves single-quoted string literals including escaped quotes", () => {
+ const sql = "SELECT 'hello world'\n, 'it''s ok' FROM t";
+ assert.equal(compressSqlText(sql), "SELECT 'hello world' , 'it''s ok' FROM t");
+});
+
+test("compressSqlText does not strip -- inside single-quoted strings", () => {
+ const sql = "SELECT 'a -- b'\nFROM t";
+ assert.equal(compressSqlText(sql), "SELECT 'a -- b' FROM t");
+});
+
+test("compressSqlText preserves double-quoted identifiers including escaped quotes", () => {
+ const sql = 'SELECT "my column"\n, "quote""inside" FROM "my table"';
+ assert.equal(compressSqlText(sql), 'SELECT "my column" , "quote""inside" FROM "my table"');
+});
+
+test("compressSqlText preserves backtick-quoted identifiers with internal whitespace", () => {
+ const sql = "SELECT `my col`\nFROM `weird\t name`";
+ assert.equal(compressSqlText(sql), "SELECT `my col` FROM `weird\t name`");
+});
+
+test("compressSqlText returns empty/whitespace input unchanged", () => {
+ assert.equal(compressSqlText(""), "");
+ assert.equal(compressSqlText(" \n\t "), " \n\t ");
+});
+
+test("compressSqlText leaves already-compressed SQL unchanged", () => {
+ const sql = "SELECT id FROM users WHERE active = 1";
+ assert.equal(compressSqlText(sql), sql);
+});
+
+test("compressSqlText keeps SQL executable: commas stay adjacent-free via single space", () => {
+ const sql = "SELECT a\n , b\n , c FROM t";
+ assert.equal(compressSqlText(sql), "SELECT a , b , c FROM t");
+});
+
+// ── 方言感知回归测试 ──
+
+test("MySQL: preserves /*! ... */ executable comment content", () => {
+ const sql = "SELECT /*! SQL_CALC_FOUND_ROWS */ id\nFROM users";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT /*! SQL_CALC_FOUND_ROWS */ id FROM users");
+});
+
+test("MySQL: preserves /*!50000 ... */ versioned executable comment", () => {
+ const sql = "SELECT /*!50000 id, */ name\nFROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT /*!50000 id, */ name FROM t");
+});
+
+test("MySQL: preserves /*+ ... */ optimizer hint", () => {
+ const sql = "SELECT /*+ NO_RANGE_OPTIMIZATION(t) */ id\nFROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT /*+ NO_RANGE_OPTIMIZATION(t) */ id FROM t");
+});
+
+test("MySQL: removes ordinary /* ... */ block comment while preserving executable comments", () => {
+ const sql = "SELECT /* plain */ /*! KEEP */ id\nFROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT /*! KEEP */ id FROM t");
+});
+
+test("MySQL: preserves backslash escapes inside single-quoted strings", () => {
+ const sql = "SELECT 'it\\'s ok'\n, 'tab\\there' FROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT 'it\\'s ok' , 'tab\\there' FROM t");
+});
+
+test("MySQL: backslash escape prevents premature string termination", () => {
+ // \' should not end the string; the real closing quote is the last one
+ const sql = "SELECT 'a\\'b'\nFROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT 'a\\'b' FROM t");
+});
+
+test("MySQL: preserves backslash escapes inside double-quoted strings", () => {
+ const sql = 'SELECT "a\\" -- still a string"\nFROM t';
+ assert.equal(compressSqlText(sql, "mysql"), 'SELECT "a\\" -- still a string" FROM t');
+});
+
+test("MySQL: removes # line comments", () => {
+ const sql = "SELECT 1 # comment\n+ 2";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT 1 + 2");
+});
+
+test("MySQL: does not treat -- without following whitespace as a comment", () => {
+ const sql = "SELECT 1--2\nFROM t";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT 1--2 FROM t");
+});
+
+test("MySQL: executable comments preserve whitespace inside strings", () => {
+ const sql = "SELECT /*! CONCAT('a b',\n'c') */ 1";
+ assert.equal(compressSqlText(sql, "mysql"), "SELECT /*! CONCAT('a b', 'c') */ 1");
+});
+
+test("generic dialect does NOT apply MySQL backslash escaping", () => {
+ // In standard SQL, backslash is not an escape; the string 'a\' ends at the second quote
+ const sql = "SELECT 'a\\' + 1\nFROM t";
+ assert.equal(compressSqlText(sql), "SELECT 'a\\' + 1 FROM t");
+});
+
+test("PostgreSQL: preserves dollar-quoted string $$...$$", () => {
+ const sql = "SELECT $$a -- b\n c$$\nFROM t";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT $$a -- b\n c$$ FROM t");
+});
+
+test("PostgreSQL: preserves tagged dollar-quoted string $tag$...$tag$", () => {
+ const sql = "SELECT $body$ /* not a comment */\n x := 1;$body$\nFROM fn()";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT $body$ /* not a comment */\n x := 1;$body$ FROM fn()");
+});
+
+test("PostgreSQL: dollar-quoted string preserves internal $$ without early termination", () => {
+ // $$...$$ body may contain $$ only as the closing delimiter; inner content is verbatim
+ const sql = "SELECT $$line1\nline2$$\nFROM t";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT $$line1\nline2$$ FROM t");
+});
+
+test("PostgreSQL: removes ordinary block comment but preserves dollar-quoted content", () => {
+ const sql = "SELECT /* plain */ $$keep me$$\nFROM t";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT $$keep me$$ FROM t");
+});
+
+test("PostgreSQL: preserves backslash escapes inside E strings", () => {
+ const sql = "SELECT E'a\\' -- still a string'\nFROM t";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT E'a\\' -- still a string' FROM t");
+});
+
+test("PostgreSQL: removes nested block comments", () => {
+ const sql = "SELECT 1 /* outer /* inner */ still outer */ + 2";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT 1 + 2");
+});
+
+test("PostgreSQL: keeps the newline required between adjacent string literals", () => {
+ const sql = "SELECT 'foo'\n'bar'";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT 'foo'\n'bar'");
+});
+
+test("PostgreSQL: dollar tags inside identifiers are not treated as strings", () => {
+ const sql = "SELECT foo$tag$bar -- comment\nFROM t";
+ assert.equal(compressSqlText(sql, "postgres"), "SELECT foo$tag$bar FROM t");
+});
+
+test("SQL Server: preserves bracket identifiers [weird name]", () => {
+ const sql = "SELECT [my column]\nFROM [order]";
+ assert.equal(compressSqlText(sql, "sqlserver"), "SELECT [my column] FROM [order]");
+});
+
+test("SQL Server: preserves escaped ]] inside bracket identifiers", () => {
+ const sql = "SELECT [a]]b]\nFROM t";
+ assert.equal(compressSqlText(sql, "sqlserver"), "SELECT [a]]b] FROM t");
+});
+
+test("generic dialect does NOT treat [ as identifier delimiter", () => {
+ // In generic mode, [ is just a normal character
+ const sql = "SELECT [1, 2, 3]\nFROM t";
+ assert.equal(compressSqlText(sql), "SELECT [1, 2, 3] FROM t");
+});
+
+test("compressSqlText preserves unterminated block comments", () => {
+ const sql = "DELETE FROM users /* unfinished";
+ assert.equal(compressSqlText(sql), sql);
+});