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): toggle SQL keyword case

t8y293a6a6570799
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index c2f6b9ece6..6a08634326 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -395,6 +395,16 @@ function formatActiveSql() {
};
}
+function toggleSqlKeywordCase() {
+ const sqlFormatter = settingsStore.editorSettings.sqlFormatter;
+ settingsStore.updateEditorSettings({
+ sqlFormatter: {
+ ...sqlFormatter,
+ keywordCase: sqlFormatter.keywordCase === "lower" ? "upper" : "lower",
+ },
+ });
+}
+
function defaultSavedSqlName(title: string) {
const trimmed = title.trim() || "query";
const normalized = trimmed.replace(/\s+/g, "_");
@@ -1237,12 +1247,14 @@ onUnmounted(() => {
:executable-sql="executableSql"
:explain-mode="explainMode"
:block-dangerous-redis-commands="blockDangerousRedisCommands"
+ :sql-keyword-case="settingsStore.editorSettings.sqlFormatter.keywordCase"
@update:explain-mode="(m: 'explain' | 'autotrace') => (explainMode = m)"
@update:block-dangerous-redis-commands="(v: boolean) => (blockDangerousRedisCommands = v)"
@execute="tryExecute($event)"
@cancel="cancelActiveExecution()"
@explain="tryExplain()"
@format-sql="formatActiveSql"
+ @toggle-sql-keyword-case="toggleSqlKeywordCase"
@save-sql="void openSaveSqlDialog()"
@open-sql="openSqlFile"
@import-result-archive="importResultArchive"
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index f033cab04c..b159b5c633 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -1062,6 +1062,7 @@ async function provideSqlCompletions(currentState: import("@codemirror/state").E
snippets: settingsStore.editorSettings.snippets,
dialect: props.dialect,
databaseType: props.databaseType,
+ keywordCase: settingsStore.editorSettings.sqlFormatter.keywordCase,
});
return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
@@ -1079,6 +1080,7 @@ async function provideSqlCompletions(currentState: import("@codemirror/state").E
snippets: settingsStore.editorSettings.snippets,
dialect: props.dialect,
databaseType: props.databaseType,
+ keywordCase: settingsStore.editorSettings.sqlFormatter.keywordCase,
});
return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
}
@@ -1222,6 +1224,7 @@ function buildLocalSqlCompletionResult(completionContext: ReturnType<typeof getS
snippets: settingsStore.editorSettings.snippets,
dialect: props.dialect,
databaseType: props.databaseType,
+ keywordCase: settingsStore.editorSettings.sqlFormatter.keywordCase,
});
return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
@@ -1508,6 +1511,7 @@ async function performAsyncCompletionWithResult(epoch: number, completionContext
snippets: settingsStore.editorSettings.snippets,
dialect: props.dialect,
databaseType: props.databaseType,
+ keywordCase: settingsStore.editorSettings.sqlFormatter.keywordCase,
});
return buildCompletionResult(items, position - completionContext.prefix.length, getSqlCompletionResultValidFor(fullDoc, position));
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 19c3c0eda9..d95225a1ae 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -24,6 +24,7 @@ const props = defineProps<{
executableSql: string;
explainMode?: string;
blockDangerousRedisCommands?: boolean;
+ sqlKeywordCase: "preserve" | "upper" | "lower";
}>();
const emit = defineEmits<{
@@ -32,6 +33,7 @@ const emit = defineEmits<{
explain: [];
"update:explainMode": [mode: "explain" | "autotrace"];
formatSql: [];
+ toggleSqlKeywordCase: [];
saveSql: [];
openSql: [];
importResultArchive: [];
@@ -65,6 +67,8 @@ const isSingleDb = computed(() => isSingleDatabase(props.activeConnection?.db_ty
const hasDefaultDatabaseOption = computed(() => activeDatabaseOptions.value.includes(""));
const schemaDatabaseKey = computed(() => props.activeTab.database || (isSingleDb.value ? "_" : ""));
const saveTooltip = computed(() => (props.activeTab.objectSource ? t("objects.saveSource") : t("toolbar.saveSql")));
+const keywordCaseIsLower = computed(() => props.sqlKeywordCase === "lower");
+const keywordCaseToggleTooltip = computed(() => (keywordCaseIsLower.value ? t("toolbar.keywordCaseUpper") : t("toolbar.keywordCaseLower")));
const showSchemaSelector = computed(() => {
const connection = props.activeConnection;
@@ -162,6 +166,21 @@ function connectionById(connectionId: string): ConnectionConfig | undefined {
</TooltipTrigger>
<TooltipContent>{{ t("toolbar.formatSql") }}</TooltipContent>
</Tooltip>
+ <Tooltip>
+ <TooltipTrigger as-child>
+ <Button
+ variant="ghost"
+ size="icon"
+ class="h-6 w-6 font-mono text-[11px] leading-none"
+ :class="keywordCaseIsLower ? 'bg-amber-500/10 text-amber-700 hover:bg-amber-500/20 hover:text-amber-800 dark:text-amber-300 dark:hover:text-amber-200' : 'text-muted-foreground hover:bg-muted hover:text-foreground'"
+ :aria-label="keywordCaseToggleTooltip"
+ @click="emit('toggleSqlKeywordCase')"
+ >
+ {{ keywordCaseIsLower ? "a" : "A" }}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ keywordCaseToggleTooltip }}</TooltipContent>
+ </Tooltip>
<Tooltip v-if="activeConnection?.db_type === 'redis'">
<TooltipTrigger as-child>
<Button
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index e371fbea30..5c64005a62 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "Stop explain",
formatSql: "Format SQL",
formatSqlFailed: "Failed to format SQL",
+ keywordCaseLower: "Use lower-case SQL keywords",
+ keywordCaseUpper: "Use upper-case SQL keywords",
previewSql: "Preview SQL",
hidePreviewSql: "Hide SQL Preview",
saveSql: "Save to SQL Library",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 9673647179..683c9bb322 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "Detener análisis",
formatSql: "Formatear SQL",
formatSqlFailed: "Error al formatear el SQL",
+ keywordCaseLower: "Usar palabras clave SQL en minúsculas",
+ keywordCaseUpper: "Usar palabras clave SQL en mayúsculas",
saveSql: "Guardar en biblioteca SQL",
openSql: "Abrir archivo SQL",
theme: "Tema",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 2c4cf72107..03d0578230 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "Interrompi spiegazione",
formatSql: "Formatta SQL",
formatSqlFailed: "Impossibile formattare SQL",
+ keywordCaseLower: "Usa parole chiave SQL minuscole",
+ keywordCaseUpper: "Usa parole chiave SQL maiuscole",
saveSql: "Salva nella Libreria SQL",
openSql: "Apri file SQL",
theme: "Tema",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index f7f9745dd5..9b226748f8 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "実行計画の表示を停止",
formatSql: "SQLをフォーマット",
formatSqlFailed: "SQLのフォーマットに失敗しました",
+ keywordCaseLower: "SQLキーワードを小文字にする",
+ keywordCaseUpper: "SQLキーワードを大文字にする",
previewSql: "SQLをプレビュー",
hidePreviewSql: "SQLプレビューを非表示",
saveSql: "SQLライブラリに保存",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 37b898c914..021ceaddca 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "Parar explicação",
formatSql: "Formatar SQL",
formatSqlFailed: "Falha ao formatar SQL",
+ keywordCaseLower: "Usar palavras-chave SQL em minúsculas",
+ keywordCaseUpper: "Usar palavras-chave SQL em maiúsculas",
saveSql: "Salvar na Biblioteca SQL",
openSql: "Abrir arquivo SQL",
theme: "Tema",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 44cb55cbb1..7470efd4cd 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "停止执行计划",
formatSql: "格式化 SQL",
formatSqlFailed: "SQL 格式化失败",
+ keywordCaseLower: "使用小写 SQL 关键字",
+ keywordCaseUpper: "使用大写 SQL 关键字",
previewSql: "预览 SQL",
hidePreviewSql: "隐藏 SQL 预览",
saveSql: "保存到 SQL 库",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index c9708ce517..24fcbea7d9 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -32,6 +32,8 @@ export default {
stopExplain: "停止執行計畫",
formatSql: "格式化 SQL",
formatSqlFailed: "SQL 格式化失敗",
+ keywordCaseLower: "使用小寫 SQL 關鍵字",
+ keywordCaseUpper: "使用大寫 SQL 關鍵字",
saveSql: "儲存到 SQL 庫",
openSql: "開啟 SQL 檔案",
theme: "主題",
diff --git a/apps/desktop/src/lib/sqlCompletion.ts b/apps/desktop/src/lib/sqlCompletion.ts
index 466ec332c0..b23248eb37 100644
--- a/apps/desktop/src/lib/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sqlCompletion.ts
@@ -1051,6 +1051,8 @@ export interface SqlCompletionItem {
boost: number;
}
+export type SqlKeywordCase = "preserve" | "upper" | "lower";
+
export interface SqlCompletionReferencedTable {
name: string;
schema?: string;
@@ -1117,6 +1119,7 @@ export interface SqlCompletionProviderInput {
snippets?: SqlSnippet[];
dialect?: "mysql" | "postgres" | "sqlserver";
databaseType?: DatabaseType;
+ keywordCase?: SqlKeywordCase;
}
export function buildSqlCompletionItems(
@@ -1131,6 +1134,7 @@ export function buildSqlCompletionItems(
translations?: SqlCompletionTranslations;
dialect?: "mysql" | "postgres" | "sqlserver";
databaseType?: DatabaseType;
+ keywordCase?: SqlKeywordCase;
},
): SqlCompletionItem[] {
const context = getSqlCompletionContext(sql, cursor);
@@ -1165,7 +1169,7 @@ class SqlCompletionProvider {
if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions) {
const snippets = this.databaseType === "manticoresearch" ? [...(this.input.snippets ?? DEFAULT_SQL_SNIPPETS), ...MANTICORESEARCH_SQL_SNIPPETS] : (this.input.snippets ?? DEFAULT_SQL_SNIPPETS);
- this.items.push(...buildSnippetItems(context.prefix, snippets));
+ this.items.push(...buildSnippetItems(context.prefix, snippets, this.input.keywordCase));
this.items.push(...buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(this.t), this.databaseType));
}
@@ -1174,12 +1178,13 @@ class SqlCompletionProvider {
...buildSnippetItems(
context.prefix,
MANTICORESEARCH_SQL_SNIPPETS.filter((snippet) => snippet.id === "builtin-manticore-call-pq"),
+ this.input.keywordCase,
),
);
}
if (context.preferredKeywords.length > 0) {
- this.items.push(...buildPreferredKeywordItems(context.prefix, context.preferredKeywords));
+ this.items.push(...buildPreferredKeywordItems(context.prefix, context.preferredKeywords, this.input.keywordCase));
}
if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions && context.prioritizeSelectAliases) {
@@ -1191,11 +1196,11 @@ class SqlCompletionProvider {
}
if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions && !context.exclusiveRoutineSuggestions && context.suggestJoinConditions) {
- this.items.push(...buildJoinConditionItems(context, this.input.columnsByTable, this.input.foreignKeysByTable, this.dialect));
+ this.items.push(...buildJoinConditionItems(context, this.input.columnsByTable, this.input.foreignKeysByTable, this.dialect, this.input.keywordCase));
}
if (context.suggestKeywords && !context.exclusiveRoutineSuggestions) {
- this.items.push(...buildKeywordItems(context.prefix, context, this.databaseType));
+ this.items.push(...buildKeywordItems(context.prefix, context, this.databaseType, this.input.keywordCase));
}
if (!context.exclusiveTableSuggestions && context.suggestColumns) {
@@ -1222,7 +1227,7 @@ class SqlCompletionProvider {
}
if (context.comparisonLeftColumn && context.suggestKeywords) {
- this.items.push(...buildComparisonValueItems(context, this.input.columnsByTable, this.t));
+ this.items.push(...buildComparisonValueItems(context, this.input.columnsByTable, this.t, this.input.keywordCase));
}
if (context.onStar) {
@@ -2378,11 +2383,30 @@ function buildOracleTableFunctionItems(prefix: string): SqlCompletionItem[] {
}));
}
-function buildPreferredKeywordItems(prefix: string, keywords: string[]): SqlCompletionItem[] {
+function applySqlKeywordCase(value: string, keywordCase?: SqlKeywordCase): string {
+ if (keywordCase === "lower") return value.toLowerCase();
+ return value.toUpperCase();
+}
+
+function keywordJoiner(keywordCase?: SqlKeywordCase): string {
+ return keywordCase === "lower" ? " and " : " AND ";
+}
+
+function shouldFormatBuiltinSnippet(snippet: SqlSnippet): boolean {
+ return snippet.id.startsWith("builtin-");
+}
+
+function applyBuiltinSnippetKeywordCase(snippet: SqlSnippet, keywordCase?: SqlKeywordCase): string {
+ if (!shouldFormatBuiltinSnippet(snippet)) return snippet.body;
+ if (keywordCase === "lower") return snippet.body.toLowerCase();
+ return snippet.body;
+}
+
+function buildPreferredKeywordItems(prefix: string, keywords: string[], keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
return keywords
.filter((keyword) => matchesPrefix(keyword, prefix))
.map((keyword, index) => ({
- label: keyword,
+ label: applySqlKeywordCase(keyword, keywordCase),
type: "keyword" as const,
boost: computeBoost(keyword, prefix) + 6200 - index,
}));
@@ -2409,7 +2433,7 @@ function buildStarExpansionItem(columnsByTable: Map<string, SqlCompletionColumn[
};
}
-function buildComparisonValueItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations): SqlCompletionItem[] {
+function buildComparisonValueItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, t?: SqlCompletionTranslations, keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
const colName = context.comparisonLeftColumn!;
const parts = colName.split(".");
const unqualified = parts.length > 1 ? parts[parts.length - 1]! : colName;
@@ -2446,19 +2470,19 @@ function buildComparisonValueItems(context: SqlCompletionContext, columnsByTable
// NULL check — always useful
items.push({
- label: "NULL",
+ label: applySqlKeywordCase("NULL", keywordCase),
type: "keyword" as const,
detail: t?.nullValue ?? "NULL value",
boost: 1300,
});
items.push({
- label: "IS NULL",
+ label: applySqlKeywordCase("IS NULL", keywordCase),
type: "keyword" as const,
detail: t?.isNull ?? "Checks whether the value is NULL",
boost: 1250,
});
items.push({
- label: "IS NOT NULL",
+ label: applySqlKeywordCase("IS NOT NULL", keywordCase),
type: "keyword" as const,
detail: t?.isNotNull ?? "Checks whether the value is not NULL",
boost: 1200,
@@ -2715,7 +2739,7 @@ function buildColumnInfo(column: SqlCompletionColumn): string | undefined {
return parts.length > 1 ? parts.join("\n") : undefined;
}
-function buildJoinConditionItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
+function buildJoinConditionItems(context: SqlCompletionContext, columnsByTable: Map<string, SqlCompletionColumn[]>, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, dialect?: "mysql" | "postgres" | "sqlserver", keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
const refs = context.referencedTables;
if (refs.length < 2) return [];
@@ -2726,7 +2750,7 @@ function buildJoinConditionItems(context: SqlCompletionContext, columnsByTable:
for (const previous of previousRefs) {
const previousColumns = columnsForReferencedTable(previous, columnsByTable);
const latestColumns = columnsForReferencedTable(latest, columnsByTable);
- items.push(...buildForeignKeyJoinConditionItemsForPair(previous, latest, foreignKeysByTable, context.prefix, dialect), ...buildJoinConditionItemsForPair(previous, previousColumns, latest, latestColumns, context.prefix, dialect));
+ items.push(...buildForeignKeyJoinConditionItemsForPair(previous, latest, foreignKeysByTable, context.prefix, dialect, keywordCase), ...buildJoinConditionItemsForPair(previous, previousColumns, latest, latestColumns, context.prefix, dialect, keywordCase));
}
return items;
@@ -2751,21 +2775,25 @@ function foreignKeysForReferencedTable(table: SqlCompletionReferencedTable, fore
return [];
}
-function buildForeignKeyJoinConditionItemsForPair(left: SqlCompletionReferencedTable, right: SqlCompletionReferencedTable, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, prefix = "", dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
+function buildForeignKeyJoinConditionItemsForPair(left: SqlCompletionReferencedTable, right: SqlCompletionReferencedTable, foreignKeysByTable?: Map<string, SqlCompletionForeignKey[]>, prefix = "", dialect?: "mysql" | "postgres" | "sqlserver", keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
if (!foreignKeysByTable) return [];
- return [...buildDirectionalForeignKeyJoinConditionItems(left, right, foreignKeysForReferencedTable(left, foreignKeysByTable), prefix, dialect), ...buildDirectionalForeignKeyJoinConditionItems(right, left, foreignKeysForReferencedTable(right, foreignKeysByTable), prefix, dialect)];
+ return [
+ ...buildDirectionalForeignKeyJoinConditionItems(left, right, foreignKeysForReferencedTable(left, foreignKeysByTable), prefix, dialect, keywordCase),
+ ...buildDirectionalForeignKeyJoinConditionItems(right, left, foreignKeysForReferencedTable(right, foreignKeysByTable), prefix, dialect, keywordCase),
+ ];
}
-function buildDirectionalForeignKeyJoinConditionItems(owner: SqlCompletionReferencedTable, referenced: SqlCompletionReferencedTable, foreignKeys: SqlCompletionForeignKey[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
+function buildDirectionalForeignKeyJoinConditionItems(owner: SqlCompletionReferencedTable, referenced: SqlCompletionReferencedTable, foreignKeys: SqlCompletionForeignKey[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver", keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
const matchingForeignKeys = foreignKeys.filter((foreignKey) => referencedTableMatchesName(referenced, foreignKey.ref_table, foreignKey.ref_schema));
const groups = groupForeignKeysByConstraint(matchingForeignKeys);
const items: SqlCompletionItem[] = [];
for (const group of groups) {
const parts = group.map((foreignKey) => buildJoinConditionPart(owner, foreignKey.column, referenced, foreignKey.ref_column, dialect));
- const label = parts.map((part) => part.label).join(" AND ");
+ const joiner = keywordJoiner(keywordCase);
+ const label = parts.map((part) => part.label).join(joiner);
if (!label || (prefix && !matchesPrefix(label, prefix))) continue;
- const apply = parts.map((part) => part.apply).join(" AND ");
+ const apply = parts.map((part) => part.apply).join(joiner);
items.push({
label,
type: "snippet",
@@ -2819,7 +2847,7 @@ function normalizeIdentifierPart(name: string): string {
return name.replace(/^["`[]|["`\]]$/g, "").toLowerCase();
}
-function buildJoinConditionItemsForPair(left: SqlCompletionReferencedTable, leftColumns: SqlCompletionColumn[], right: SqlCompletionReferencedTable, rightColumns: SqlCompletionColumn[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver"): SqlCompletionItem[] {
+function buildJoinConditionItemsForPair(left: SqlCompletionReferencedTable, leftColumns: SqlCompletionColumn[], right: SqlCompletionReferencedTable, rightColumns: SqlCompletionColumn[], prefix: string, dialect?: "mysql" | "postgres" | "sqlserver", keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
const items: SqlCompletionItem[] = [];
const leftRef = left.alias || left.name;
const rightRef = right.alias || right.name;
@@ -2887,7 +2915,7 @@ function buildJoinConditionItemsForPair(left: SqlCompletionReferencedTable, left
if (rightName !== "id" && rightName.endsWith("_id")) addPair(leftId, rightColumn, 1650);
}
- items.push(...buildCompositeHeuristicJoinConditionItems(left, leftColumns, right, leftByName, rightByName, prefix, dialect));
+ items.push(...buildCompositeHeuristicJoinConditionItems(left, leftColumns, right, leftByName, rightByName, prefix, dialect, keywordCase));
return items;
}
@@ -2911,6 +2939,7 @@ function buildCompositeHeuristicJoinConditionItems(
rightByName: Map<string, SqlCompletionColumn[]>,
prefix: string,
dialect?: "mysql" | "postgres" | "sqlserver",
+ keywordCase?: SqlKeywordCase,
): SqlCompletionItem[] {
const leftId = leftByName.get("id")?.[0];
const rightId = rightByName.get("id")?.[0];
@@ -2953,13 +2982,14 @@ function buildCompositeHeuristicJoinConditionItems(
} else {
parts.push(buildHeuristicJoinConditionPart(leftRef, leftApplyRef, candidate.childFk, rightRef, rightApplyRef, candidate.parentId, dialect));
}
- const label = parts.map((part) => part.label).join(" AND ");
+ const joiner = keywordJoiner(keywordCase);
+ const label = parts.map((part) => part.label).join(joiner);
if (prefix && !matchesPrefix(label, prefix)) continue;
items.push({
label,
type: "snippet",
detail: "Likely composite JOIN condition",
- apply: parts.map((part) => part.apply).join(" AND "),
+ apply: parts.map((part) => part.apply).join(joiner),
boost: 2400 + parts.length,
});
}
@@ -3035,7 +3065,7 @@ export function buildSnippetItemsForTest(prefix: string, snippets: SqlSnippet[])
return buildSnippetItems(prefix, snippets);
}
-function buildSnippetItems(prefix: string, snippets: SqlSnippet[]): SqlCompletionItem[] {
+function buildSnippetItems(prefix: string, snippets: SqlSnippet[], keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
if (!prefix) return [];
return snippets
.filter((snippet) => {
@@ -3051,11 +3081,12 @@ function buildSnippetItems(prefix: string, snippets: SqlSnippet[]): SqlCompletio
// they are likely typing the actual keyword — reduce the base boost so
// the real keyword can rank higher.
const baseBoost = matchesByPrefix ? 4000 : 0;
+ const body = applyBuiltinSnippetKeywordCase(snippet, keywordCase);
return {
label: snippet.label,
type: "snippet" as const,
- detail: snippet.body,
- apply: snippet.body,
+ detail: body,
+ apply: body,
boost: Math.max(boostByPrefix, boostByLabel) + baseBoost,
};
});
@@ -3178,7 +3209,7 @@ function isOracleLikeDatabase(databaseType?: DatabaseType): boolean {
return databaseType === "oracle" || databaseType === "oceanbase-oracle";
}
-function buildKeywordItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType): SqlCompletionItem[] {
+function buildKeywordItems(prefix: string, context: SqlCompletionContext, databaseType?: DatabaseType, keywordCase?: SqlKeywordCase): SqlCompletionItem[] {
const isDml = context.statementKind === "select" || context.statementKind === "insert" || context.statementKind === "update" || context.statementKind === "delete";
const showDdl = !isDml || context.suggestTables;
@@ -3195,7 +3226,7 @@ function buildKeywordItems(prefix: string, context: SqlCompletionContext, databa
const base = computeBoost(keyword, prefix);
const freqBoost = HIGH_FREQUENCY_KEYWORDS.has(keyword) ? 100 : 0;
return {
- label: keyword,
+ label: applySqlKeywordCase(keyword, keywordCase),
type: "keyword" as const,
boost: base + freqBoost,
};
diff --git a/packages/app-tests/sqlCompletion.test.ts b/packages/app-tests/sqlCompletion.test.ts
index 660ec85b2d..7a9fcb6b7e 100644
--- a/packages/app-tests/sqlCompletion.test.ts
+++ b/packages/app-tests/sqlCompletion.test.ts
@@ -90,6 +90,21 @@ test("suggests SQL keywords for generic keyword input", () => {
assert.equal(keyword.type, "keyword");
});
+test("suggests lower-case SQL keywords when configured", () => {
+ const items = buildSqlCompletionItems("sel", 3, {
+ tables,
+ columnsByTable,
+ keywordCase: "lower",
+ });
+
+ const keyword = items.find((item) => item.type === "keyword" && item.label === "select");
+ assert.ok(keyword);
+ assert.equal(
+ items.some((item) => item.type === "keyword" && item.label === "SELECT"),
+ false,
+ );
+});
+
test("suggests PostgreSQL-specific data types and functions", () => {
const typeItems = buildSqlCompletionItems("create table events (payload js", "create table events (payload js".length, {
tables: [],
@@ -159,15 +174,11 @@ test("suggests Manticore Search SQL functions and command snippets", () => {
databaseType: "manticoresearch",
});
- assert.ok(
- matchItems.some((item) => item.type === "function" && item.label === "MATCH" && item.apply === "MATCH(${query})"),
- );
+ assert.ok(matchItems.some((item) => item.type === "function" && item.label === "MATCH" && item.apply === "MATCH(${query})"));
assert.ok(facetItems.some((item) => item.type === "keyword" && item.label === "FACET"));
assert.ok(showItems.some((item) => item.type === "snippet" && item.label === "show meta" && item.apply === "SHOW META;"));
assert.ok(showTablesItems.some((item) => item.type === "snippet" && item.label === "show tables" && item.apply === "SHOW TABLES;"));
- assert.ok(
- callPqItems.some((item) => item.type === "snippet" && item.label === "call pq" && item.apply === "CALL PQ ('pq', ('{\"title\":\"query\"}'));"),
- );
+ assert.ok(callPqItems.some((item) => item.type === "snippet" && item.label === "call pq" && item.apply === "CALL PQ ('pq', ('{\"title\":\"query\"}'));"));
assert.ok(rankingItems.some((item) => item.type === "function" && item.label === "BM25F"));
});
@@ -780,6 +791,18 @@ test("suggests SQL snippets for common abbreviations", () => {
assert.equal(snippet.apply, "SELECT *\nFROM table\nLIMIT 100;");
});
+test("applies keyword case to built-in SQL snippets", () => {
+ const items = buildSqlCompletionItems("sel", 3, {
+ tables,
+ columnsByTable,
+ keywordCase: "lower",
+ });
+
+ const snippet = items.find((item) => item.type === "snippet" && item.label === "select *");
+ assert.ok(snippet);
+ assert.equal(snippet.apply, "select *\nfrom table\nlimit 100;");
+});
+
test("suggests DATE_FORMAT as parameter snippet", () => {
const sql = "select date_";
const items = buildSqlCompletionItems(sql, sql.length, {
@@ -1424,6 +1447,48 @@ test("prefers explicit foreign-key join condition with table aliases", () => {
});
});
+test("applies keyword case to composite join condition snippets", () => {
+ const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([
+ [
+ "public.order_lines",
+ [
+ { name: "order_lines_product_fkey", column: "tenant_id", ref_table: "products", ref_column: "tenant_id" },
+ { name: "order_lines_product_fkey", column: "product_id", ref_table: "products", ref_column: "id" },
+ ],
+ ],
+ ]);
+ const cols = new Map<string, SqlCompletionColumn[]>([
+ [
+ "public.order_lines",
+ [
+ { name: "tenant_id", table: "order_lines", schema: "public", dataType: "bigint" },
+ { name: "product_id", table: "order_lines", schema: "public", dataType: "bigint" },
+ ],
+ ],
+ [
+ "public.products",
+ [
+ { name: "tenant_id", table: "products", schema: "public", dataType: "bigint" },
+ { name: "id", table: "products", schema: "public", dataType: "bigint" },
+ ],
+ ],
+ ]);
+ const sql = "select * from public.order_lines ol join public.products p on ";
+ const items = buildSqlCompletionItems(sql, sql.length, {
+ tables: [
+ { name: "order_lines", schema: "public", type: "table" },
+ { name: "products", schema: "public", type: "table" },
+ ],
+ columnsByTable: cols,
+ foreignKeysByTable,
+ keywordCase: "lower",
+ });
+
+ const fkJoin = items.find((item) => item.detail === "JOIN condition from composite foreign key");
+ assert.equal(fkJoin?.label, "ol.tenant_id = p.tenant_id and ol.product_id = p.id");
+ assert.equal(fkJoin?.apply, "ol.tenant_id = p.tenant_id and ol.product_id = p.id");
+});
+
test("suggests explicit foreign-key join when the joined table owns the key", () => {
const foreignKeysByTable = new Map<string, SqlCompletionForeignKey[]>([["public.orders", [{ name: "orders_customer_id_fkey", column: "customer_id", ref_table: "customers", ref_column: "id" }]]]);
const sql = "select * from public.customers c join public.orders o on ";