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(mongodb): add an opt-in SQL query mode

Marcelo Tesla5a045f3e22c4
diff --git a/.github/pr-11955/alias-projection.png b/.github/pr-11955/alias-projection.png
new file mode 100644
index 0000000000..c2dbc66a85
Binary files /dev/null and b/.github/pr-11955/alias-projection.png differ
diff --git a/.github/pr-11955/group-owner.png b/.github/pr-11955/group-owner.png
new file mode 100644
index 0000000000..a244d29efe
Binary files /dev/null and b/.github/pr-11955/group-owner.png differ
diff --git a/.github/pr-11955/shell-mode.png b/.github/pr-11955/shell-mode.png
new file mode 100644
index 0000000000..8a3e67a11d
Binary files /dev/null and b/.github/pr-11955/shell-mode.png differ
diff --git a/.github/pr-11955/sort-before-project.png b/.github/pr-11955/sort-before-project.png
new file mode 100644
index 0000000000..68ee524e82
Binary files /dev/null and b/.github/pr-11955/sort-before-project.png differ
diff --git a/.github/pr-11955/sql-mode.png b/.github/pr-11955/sql-mode.png
new file mode 100644
index 0000000000..9da5df93ef
Binary files /dev/null and b/.github/pr-11955/sql-mode.png differ
diff --git a/.github/pr-11955/window-error.png b/.github/pr-11955/window-error.png
new file mode 100644
index 0000000000..dc92ddf1bf
Binary files /dev/null and b/.github/pr-11955/window-error.png differ
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index c3a51b60b0..e3ad78d5bb 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -1058,6 +1058,7 @@ async function resolveActiveExecutableSql(snapshot?: SqlExecutionSnapshot, execu
mode: settingsStore.editorSettings.executeMode,
cursorPos: snapshot?.cursorPos ?? (tab.id === activeTab.value?.id ? cursorPos.value : (selection?.head ?? 0)),
databaseType: connection?.db_type,
+ mongoQueryLanguage: tab.mongoQueryLanguage,
});
}
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 9d6f56b538..8877919af7 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -152,6 +152,7 @@ import * as api from "@/lib/backend/api";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { isMacOS } from "@/lib/backend/platform";
import { resolveSqlDialectId } from "@/lib/sql/semantic/dialect";
+import { queryEditorStatementDatabaseType } from "@/lib/mongo/mongoSql";
import { kingbaseSqlDatabaseType } from "@/lib/database/jdbcDialect";
import type { SqlCompletionColumn, SqlCompletionContext, SqlCompletionReferencedTable } from "@/lib/sql/sqlCompletion";
@@ -173,9 +174,14 @@ function sqlSyntaxDialect() {
function queryEditorSelectionLanguage(): "sql" | "text" {
const databaseType = props.databaseType;
+ if (databaseType === "mongodb" && props.mongoQueryLanguage === "sql") return "sql";
return databaseType === "redis" || databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "solr" || databaseType === "victoriametrics" ? "text" : "sql";
}
+function statementDatabaseType() {
+ return queryEditorStatementDatabaseType(props.databaseType, props.mongoQueryLanguage);
+}
+
const COMPLETION_REMOTE_LATENCY_BUDGET_MS = 120;
const COMPLETION_DEBOUNCE_DELAY_MS = 150;
const COMPLETION_TRIGGER_DEFER_DELAY_MS = 50;
@@ -1204,12 +1210,12 @@ function emitContextObjectAction(action: QueryContextObjectAction) {
}
function executableStatementRangeStartingAt(currentView: EditorViewType, lineFrom: number) {
- executableStatementRangeCache = executableStatementRangeCacheForDoc(executableStatementRangeCache, currentView.state.doc, props.databaseType, sqlStatementParameterOptions());
+ executableStatementRangeCache = executableStatementRangeCacheForDoc(executableStatementRangeCache, currentView.state.doc, statementDatabaseType(), sqlStatementParameterOptions());
return executableStatementRangeStartingAtLine(executableStatementRangeCache, lineFrom);
}
function executableStatementRangeAtPosition(currentView: EditorViewType, position: number): SqlTextRange | null {
- executableStatementRangeCache = executableStatementRangeCacheForDoc(executableStatementRangeCache, currentView.state.doc, props.databaseType, sqlStatementParameterOptions());
+ executableStatementRangeCache = executableStatementRangeCacheForDoc(executableStatementRangeCache, currentView.state.doc, statementDatabaseType(), sqlStatementParameterOptions());
return executableStatementRangeAtCursor(executableStatementRangeCache, position);
}
@@ -1905,7 +1911,7 @@ async function formatCurrentSql() {
let formatted: string;
let formattedAsSql = false;
let formatDiagnostic: SqlFormatterDiagnostic | undefined;
- if (props.databaseType === "mongodb") {
+ if (props.databaseType === "mongodb" && props.mongoQueryLanguage !== "sql") {
formatted = formatMongoShellText(source, settingsStore.editorSettings.sqlFormatter);
} else {
const esRequest = detectAndFormatElasticsearchRequests(source, props.databaseType, settingsStore.editorSettings.sqlFormatter.tabWidth);
@@ -2755,7 +2761,7 @@ watch([() => props.clientSessionId, () => props.completionContextVersion], () =>
});
watch(
- [() => props.tabId, () => props.databaseType, () => props.dialect, sqlSyntaxDialect, sqlDriverProfile, () => kingbaseConfig.value?.database_info?.compatibilityMode],
+ [() => props.tabId, () => props.databaseType, () => props.dialect, () => props.syntaxDialect, sqlSyntaxDialect, () => props.mongoQueryLanguage, sqlDriverProfile, () => kingbaseConfig.value?.database_info?.compatibilityMode],
() => {
completion.invalidateRequests();
refreshCompletionCache();
diff --git a/apps/desktop/src/components/editor/queryEditorSqlExtensions.ts b/apps/desktop/src/components/editor/queryEditorSqlExtensions.ts
index db911c2504..91a75f10c7 100644
--- a/apps/desktop/src/components/editor/queryEditorSqlExtensions.ts
+++ b/apps/desktop/src/components/editor/queryEditorSqlExtensions.ts
@@ -18,6 +18,7 @@ import { graphQueryLanguage, isGraphQueryDatabase } from "@/lib/graph/graphQuery
import { getGraphFunctionSignatureHelp } from "@/lib/graph/graphSignatureHelp";
import { sqlSemanticTableNameSpansForSyntaxTree } from "@/lib/editor/codemirrorSqlSemanticHighlight";
import { queryEditorCommentTokens, queryEditorLineCommentToken, queryEditorWordLanguageData } from "@/lib/editor/queryEditorLineComment";
+import { queryEditorStatementDatabaseType } from "@/lib/mongo/mongoSql";
import { createShellLineCommentHighlight } from "@/lib/editor/codemirrorShellLineCommentHighlight";
import type { StatementExecutionMarker } from "@/lib/tabs/tabPresentation";
import { resolveSqlDialectId } from "@/lib/sql/semantic/dialect";
@@ -338,21 +339,24 @@ export function configureQueryEditorSqlExtensions(options: QueryEditorSqlExtensi
const shellLineCommentHighlightPlugin = createShellLineCommentHighlight({ ViewPlugin, Decoration, highlightingFor, syntaxTree });
- codeMirrorRuntime.buildSqlLanguageExtension = () => [
- isGraphQueryDatabase(props.databaseType)
- ? graphQueryLanguage(props.databaseType)
- : supportsQueryEditorSqlLanguage(props.databaseType)
- ? langSql.sql({
- dialect: createDbxCodeMirrorSqlDialect(langSql, options.sqlSyntaxDialect?.() ?? props.syntaxDialect ?? props.dialect, props.databaseType, sqlDriverProfile.value),
- })
- : [],
- // Non-SQL editors (MongoDB shell) keep the SQL grammar for highlighting, so override the
- // comment marker that toggleLineComment reads from language data.
- Prec.highest(EditorState.languageData.of(() => [{ commentTokens: queryEditorCommentTokens(props.databaseType) }])),
- Prec.highest(EditorState.languageData.of(() => queryEditorWordLanguageData(options.sqlFunctionDatabaseType?.() ?? props.databaseType))),
- // The SQL grammar does not tokenize `//`, so those comments are highlighted by hand.
- queryEditorLineCommentToken(props.databaseType) === "//" ? shellLineCommentHighlightPlugin : [],
- ];
+ codeMirrorRuntime.buildSqlLanguageExtension = () => {
+ const commentDatabaseType = queryEditorStatementDatabaseType(props.databaseType, props.mongoQueryLanguage);
+ return [
+ isGraphQueryDatabase(props.databaseType)
+ ? graphQueryLanguage(props.databaseType)
+ : supportsQueryEditorSqlLanguage(props.databaseType)
+ ? langSql.sql({
+ dialect: createDbxCodeMirrorSqlDialect(langSql, options.sqlSyntaxDialect?.() ?? props.syntaxDialect ?? props.dialect, props.databaseType, sqlDriverProfile.value),
+ })
+ : [],
+ // Non-SQL editors (MongoDB shell) keep the SQL grammar for highlighting, so override the
+ // comment marker that toggleLineComment reads from language data.
+ Prec.highest(EditorState.languageData.of(() => [{ commentTokens: queryEditorCommentTokens(commentDatabaseType) }])),
+ Prec.highest(EditorState.languageData.of(() => queryEditorWordLanguageData(options.sqlFunctionDatabaseType?.() ?? props.databaseType))),
+ // The SQL grammar does not tokenize `//`, so those comments are highlighted by hand.
+ queryEditorLineCommentToken(commentDatabaseType) === "//" ? shellLineCommentHighlightPlugin : [],
+ ];
+ };
const MAX_SQL_SEMANTIC_HIGHLIGHT_WINDOWS = 32;
@@ -526,7 +530,7 @@ export function configureQueryEditorSqlExtensions(options: QueryEditorSqlExtensi
let range = currentExecutableStatementRange(view);
if (!range) {
const cursorLine = view.state.doc.lineAt(cursorPos);
- cache.value = executableStatementRangeCacheForDoc(cache.value, view.state.doc, props.databaseType, sqlStatementParameterOptions());
+ cache.value = executableStatementRangeCacheForDoc(cache.value, view.state.doc, queryEditorStatementDatabaseType(props.databaseType, props.mongoQueryLanguage), sqlStatementParameterOptions());
// Find ranges that overlap the cursor line, then expand to include
// adjacent ranges (handles parser fragments from edge cases like
// ultra-long comments splitting a statement).
diff --git a/apps/desktop/src/components/editor/queryEditorTypes.ts b/apps/desktop/src/components/editor/queryEditorTypes.ts
index b9aaf9ef5b..2562b2336e 100644
--- a/apps/desktop/src/components/editor/queryEditorTypes.ts
+++ b/apps/desktop/src/components/editor/queryEditorTypes.ts
@@ -3,6 +3,7 @@ import type { DatabaseType, QueryResult } from "@/types/database";
import type { CodeMirrorSqlDialectName } from "@/lib/editor/codemirrorSqlDialect";
import type { SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import type { StatementExecutionMarker } from "@/lib/tabs/tabPresentation";
+import type { MongoQueryLanguage } from "@/lib/mongo/mongoSql";
export interface QueryEditorProps {
modelValue: string;
@@ -41,6 +42,8 @@ export interface QueryEditorProps {
initialSelection?: { anchor: number; head: number };
revealRequest?: { id: number; line: number; column?: number };
statementExecutionMarkers?: StatementExecutionMarker[];
+ /** MongoDB query tabs: SQL mode uses the SQL statement splitter and formatter. */
+ mongoQueryLanguage?: MongoQueryLanguage;
}
export type CompletionMetadataScope = Pick<SqlCompletionScope, "database" | "schema">;
diff --git a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
index 02795baf12..79e547e67d 100644
--- a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
@@ -781,6 +781,7 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
if (isGraphQueryDatabase(props.databaseType)) return provideGraphCompletions(context, props.databaseType);
const fullDoc = currentState.doc.toString();
if (props.databaseType === "mongodb") {
+ if (props.mongoQueryLanguage === "sql") return null;
return provideMongoCompletions(currentState, position, explicit);
}
if (props.databaseType === "meilisearch" || props.databaseType === "solr" || props.databaseType === "couchdb") return null;
diff --git a/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts b/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
index 08ef085653..e5f661738d 100644
--- a/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
@@ -357,6 +357,10 @@ export function useQueryEditorDiagnostics(options: QueryEditorDiagnosticsOptions
return;
}
if (props.databaseType === "mongodb") {
+ if (props.mongoQueryLanguage === "sql") {
+ setSemanticDiagnostics([]);
+ return;
+ }
// Shell commands have no SQL semantics; surface the parser's own diagnosis instead of waiting for Run.
const cursor = currentView.state.selection.main.head;
setSemanticDiagnostics(buildMongoSyntaxDiagnostics(sql, cursor));
@@ -543,6 +547,7 @@ export function useQueryEditorDiagnostics(options: QueryEditorDiagnosticsOptions
async function loadSqlUnknownObjectSpans(currentView: EditorViewType): Promise<SqlUnknownObjectSpan[]> {
if (!SQL_UNKNOWN_OBJECT_HIGHLIGHT_ENABLED || !runtime.editorIsActive) return [];
if (options.queryEditorSelectionLanguage() !== "sql") return [];
+ if (props.databaseType === "mongodb") return [];
if (shouldSkipSqlSemanticDiagnostics()) return [];
if (props.databaseType && NON_SQL_UNKNOWN_OBJECT_DATABASE_TYPES.has(props.databaseType)) return [];
if (!props.connectionId || props.database == null) return [];
diff --git a/apps/desktop/src/components/editor/useQueryEditorStatementBoundaries.ts b/apps/desktop/src/components/editor/useQueryEditorStatementBoundaries.ts
index eacee4da5c..8dd805b4de 100644
--- a/apps/desktop/src/components/editor/useQueryEditorStatementBoundaries.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorStatementBoundaries.ts
@@ -1,6 +1,7 @@
import type { ShallowRef } from "vue";
import { RangeSet, RangeValue, type EditorState } from "@codemirror/state";
import type { EditorView as EditorViewType, ViewPlugin as ViewPluginType } from "@codemirror/view";
+import { queryEditorStatementDatabaseType } from "@/lib/mongo/mongoSql";
import { executableStatementRangeCacheForDoc, statementGutterStartIndexForCache, mapStatementGutterStartIndex, type ExecutableStatementRangeCache, type StatementGutterStartIndex } from "@/lib/sql/executableStatementRangeCache";
import type { SqlParameterOptions } from "@/lib/sql/sqlParameters";
import type { QueryEditorProps } from "./queryEditorTypes";
@@ -87,7 +88,7 @@ export function useQueryEditorStatementBoundaries(options: QueryEditorStatementB
if (pendingAnalysis?.doc === state.doc && pendingAnalysis.generation === statementBoundariesGeneration) return pendingAnalysis.result;
const generation = statementBoundariesGeneration;
const result = analysisWorker
- .analyze({ sql: state.doc.toString(), databaseType: props.databaseType, parameterOptions: sqlStatementParameterOptions(), includeFolds: true, syntaxDialect: options.syntaxDialect?.() ?? props.syntaxDialect ?? props.dialect, driverProfile: options.driverProfile?.() })
+ .analyze({ sql: state.doc.toString(), databaseType: queryEditorStatementDatabaseType(props.databaseType, props.mongoQueryLanguage), parameterOptions: sqlStatementParameterOptions(), includeFolds: true, syntaxDialect: options.syntaxDialect?.() ?? props.syntaxDialect ?? props.dialect, driverProfile: options.driverProfile?.() })
.then((analysis) => {
const currentView = view.value ?? trackedView;
if (!analysis || generation !== statementBoundariesGeneration || currentView?.state.doc !== state.doc) return null;
@@ -105,7 +106,7 @@ export function useQueryEditorStatementBoundaries(options: QueryEditorStatementB
if (shouldUseQueryEditorLargeDocumentModeForSize(state.doc.length, state.doc.lines)) {
void ensureStatementCache(state);
} else {
- installStatementBoundaries(state, executableStatementRangeCacheForDoc(cache.value, state.doc, props.databaseType, sqlStatementParameterOptions()));
+ installStatementBoundaries(state, executableStatementRangeCacheForDoc(cache.value, state.doc, queryEditorStatementDatabaseType(props.databaseType, props.mongoQueryLanguage), sqlStatementParameterOptions()));
}
}
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 907ade39d9..a5b1d1e9f9 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -2297,6 +2297,7 @@ defineExpose({
:client-session-id="activeTab.id"
:completion-context-version="activeTab.completionContextVersion"
:database-type="activeEffectiveDatabaseType"
+ :mongo-query-language="activeTab.mongoQueryLanguage"
:dialect="editorDialect"
:syntax-dialect="editorSyntaxDialect"
:format-dialect="activeSqlFormatDialect"
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 9132a5b883..86f01cac8e 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -32,6 +32,7 @@ import {
WrapText,
RefreshCw,
UserRound,
+ Copy,
} from "@lucide/vue";
import { supportsInsertValueHints } from "@/lib/editor/codemirrorInsertValueHints";
import { Button } from "@/components/ui/button";
@@ -61,7 +62,10 @@ import { resolveNextEditorToolbarTier, type EditorToolbarTier } from "@/lib/tabs
import { canSaveSqlTab } from "@/lib/tabs/sqlTabSaveTarget";
import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
import { canFormatSqlForDatabaseType } from "@/lib/sql/sqlFormatter";
+import { copyToClipboard } from "@/lib/common/clipboard";
+import { useToast } from "@/composables/useToast";
import type { QueryTab, ConnectionConfig } from "@/types/database";
+import type { MongoQueryLanguage } from "@/lib/mongo/mongoSql";
import { isObjectDependencySection } from "@/lib/database/objectDependencyDetails";
import { connectionDetailRows } from "@/lib/connection/connectionDetailRows";
import { findConnectionGroupPath } from "@/lib/sidebar/sidebarLayout";
@@ -135,9 +139,23 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
+const { toast } = useToast();
const connectionStore = useConnectionStore();
const queryStore = useQueryStore();
const settingsStore = useSettingsStore();
+const showMongoSqlToggle = computed(() => props.activeConnection?.db_type === "mongodb" && props.activeTab.mode === "query");
+const mongoQueryLanguage = computed(() => props.activeTab.mongoQueryLanguage ?? "shell");
+
+function setMongoQueryLanguage(language: MongoQueryLanguage) {
+ queryStore.setMongoQueryLanguage(props.activeTab.id, language);
+}
+
+async function copyGeneratedMongoShell() {
+ const shell = props.activeTab.mongoGeneratedShell;
+ if (!shell) return;
+ await copyToClipboard(shell);
+ toast(t("toolbar.mongoShellCopied"));
+}
const { databaseOptions, loadingDatabaseOptions, loadDatabaseOptions, catalogOptions, loadingCatalogOptions, loadCatalogOptions, catalogDatabaseOptions, loadingCatalogDatabaseOptions, loadCatalogDatabaseOptions } = useDatabaseOptions();
const { loadSchemaOptions, getSchemaOptionsForDb, isLoadingSchemas, isSchemaAware } = useSchemaOptions();
@@ -630,6 +648,22 @@ defineExpose({
</TooltipTrigger>
<TooltipContent>{{ activeTab.isExecuting ? t("toolbar.stopQuery") : executeShortcutTooltip }}</TooltipContent>
</Tooltip>
+ <div v-if="showMongoSqlToggle" class="ml-1 flex h-6 shrink-0 items-center rounded-md border bg-muted/40 p-0.5" role="group" :aria-label="t('toolbar.mongoQueryLanguage')">
+ <button type="button" class="h-5 rounded px-1.5 text-[11px] font-medium" :class="mongoQueryLanguage !== 'sql' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" :aria-pressed="mongoQueryLanguage !== 'sql'" @click="setMongoQueryLanguage('shell')">
+ {{ t("toolbar.mongoShellMode") }}
+ </button>
+ <button type="button" class="h-5 rounded px-1.5 text-[11px] font-medium" :class="mongoQueryLanguage === 'sql' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'" :aria-pressed="mongoQueryLanguage === 'sql'" @click="setMongoQueryLanguage('sql')">
+ {{ t("toolbar.mongoSqlMode") }}
+ </button>
+ </div>
+ <Tooltip v-if="showMongoSqlToggle && mongoQueryLanguage === 'sql' && activeTab.mongoGeneratedShell">
+ <TooltipTrigger as-child>
+ <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-foreground" :aria-label="t('toolbar.copyMongoShell')" @click="copyGeneratedMongoShell">
+ <Copy class="h-3.5 w-3.5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{{ t("toolbar.copyMongoShell") }}</TooltipContent>
+ </Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="h-6 w-6" :class="executeAllButtonClass" :disabled="activeTab.isExecuting || activeTab.isCancelling || activeTab.isExplaining || !activeTab.sql.trim()" :aria-label="t('toolbar.executeAllSql')" @click="onExecuteAllClick">
diff --git a/apps/desktop/src/components/layout/QueryMessagesView.vue b/apps/desktop/src/components/layout/QueryMessagesView.vue
index 51410af47a..dff61bc847 100644
--- a/apps/desktop/src/components/layout/QueryMessagesView.vue
+++ b/apps/desktop/src/components/layout/QueryMessagesView.vue
@@ -1,11 +1,21 @@
<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Copy } from "@lucide/vue";
+import { copyToClipboard } from "@/lib/common/clipboard";
+import { useToast } from "@/composables/useToast";
import type { QueryMessage } from "@/types/database";
defineProps<{ messages: QueryMessage[] }>();
const { t } = useI18n();
+const { toast } = useToast();
+
+async function copyShell(message: string) {
+ await copyToClipboard(message);
+ toast(t("toolbar.mongoShellCopied"));
+}
type SeverityTone = "muted" | "warning" | "error";
@@ -34,10 +44,17 @@ const severityBadgeClasses: Record<SeverityTone, string> = {
{{ message.severity }}
</Badge>
<div class="min-w-0 flex-1">
+ <div v-if="message.code === 'mongo-shell'" class="mb-1 flex items-center gap-2">
+ <span class="text-muted-foreground">{{ t("queryMessages.mongoShell") }}</span>
+ <Button variant="ghost" size="sm" class="h-5 gap-1 px-1.5 text-[10px]" @click="copyShell(message.message)">
+ <Copy class="h-3 w-3" />
+ {{ t("queryMessages.copyMongoShell") }}
+ </Button>
+ </div>
<div class="font-mono text-[11px] whitespace-pre-wrap break-words text-foreground">{{ message.message }}</div>
<div v-if="message.detail" class="mt-0.5 font-mono text-[11px] whitespace-pre-wrap break-words text-muted-foreground">{{ message.detail }}</div>
<div v-if="message.hint" class="mt-0.5 font-mono text-[11px] whitespace-pre-wrap break-words text-muted-foreground">{{ message.hint }}</div>
- <div v-if="message.code" class="mt-0.5 font-mono text-[10px] text-muted-foreground">{{ t("queryMessages.code", { code: message.code }) }}</div>
+ <div v-if="message.code && message.code !== 'mongo-shell'" class="mt-0.5 font-mono text-[10px] text-muted-foreground">{{ t("queryMessages.code", { code: message.code }) }}</div>
</div>
</div>
</div>
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 5c63f0e314..8b92656d81 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -303,6 +303,11 @@ export default withEnglishFallback({
alwaysOnTop: "Pəncərəni üstə saxla",
alwaysOnTopOff: "Üstdə saxlamanı ləğv et",
blockDangerousRedisCommands: "Təhlükəli əmrləri blokla",
+ mongoQueryLanguage: "MongoDB sorğu dili",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Yaradılmış shell-i kopyala",
+ mongoShellCopied: "Mongo shell əmri kopyalandı",
multiDbExecute: "Bir neçə verilənlər bazasında icra et",
},
multiDbExecute: {
@@ -1850,6 +1855,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Mesaj yoxdur",
code: "Kod: {code}",
+ mongoShell: "Yaradılmış mongo shell",
+ copyMongoShell: "Shell-i kopyala",
},
chart: {
title: "Diaqram",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 962b166746..557a012215 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1144,6 +1144,11 @@ export default {
alwaysOnTop: "Keep window on top",
alwaysOnTopOff: "Don't keep on top",
blockDangerousRedisCommands: "Block dangerous commands",
+ mongoQueryLanguage: "MongoDB query language",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Copy generated shell",
+ mongoShellCopied: "Mongo shell command copied",
multiDbExecute: "Multi-db execute",
},
multiDbExecute: {
@@ -2895,6 +2900,8 @@ export default {
queryMessages: {
empty: "No messages",
code: "Code: {code}",
+ mongoShell: "Generated mongo shell",
+ copyMongoShell: "Copy shell",
},
chart: {
title: "Chart",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index ca5a22790b..e92bdec5d3 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -941,6 +941,11 @@ export default withEnglishFallback({
alwaysOnTop: "Mantener ventana encima",
alwaysOnTopOff: "No mantener encima",
blockDangerousRedisCommands: "Bloquear comandos peligrosos",
+ mongoQueryLanguage: "Lenguaje de consulta de MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Copiar shell generado",
+ mongoShellCopied: "Comando de mongo shell copiado",
multiDbExecute: "Ejecución multi-base de datos",
executeAllSql: "Ejecutar todo el SQL",
},
@@ -2618,6 +2623,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Sin mensajes",
code: "Código: {code}",
+ mongoShell: "Shell de Mongo generado",
+ copyMongoShell: "Copiar shell",
},
chart: {
title: "Gráfico",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 21c6b86468..52d4643cf2 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -456,6 +456,11 @@ export default withEnglishFallback({
alwaysOnTop: "Tetap di atas jendela lain",
alwaysOnTopOff: "Jangan tetap di atas",
blockDangerousRedisCommands: "Blokir perintah berbahaya",
+ mongoQueryLanguage: "Bahasa kueri MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Salin shell yang dibuat",
+ mongoShellCopied: "Perintah mongo shell disalin",
multiDbExecute: "Eksekusi multi-database",
},
multiDbExecute: {
@@ -2118,6 +2123,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Tidak ada pesan",
code: "Kode: {code}",
+ mongoShell: "Shell mongo yang dibuat",
+ copyMongoShell: "Salin shell",
},
chart: {
title: "Chart",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 477a2923d1..4d4996c674 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -930,6 +930,11 @@ export default withEnglishFallback({
alwaysOnTop: "Mantieni in primo piano",
alwaysOnTopOff: "Non mantenere in primo piano",
blockDangerousRedisCommands: "Blocca comandi pericolosi",
+ mongoQueryLanguage: "Linguaggio di query MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Copia shell generata",
+ mongoShellCopied: "Comando mongo shell copiato",
multiDbExecute: "Esecuzione multi-DB",
executeAllSql: "Esegui tutto il SQL",
},
@@ -2516,6 +2521,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Nessun messaggio",
code: "Codice: {code}",
+ mongoShell: "Shell Mongo generata",
+ copyMongoShell: "Copia shell",
},
chart: {
title: "Grafico",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 3c42c6e218..64c646d212 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -931,6 +931,11 @@ export default withEnglishFallback({
alwaysOnTop: "常に手前に表示",
alwaysOnTopOff: "手前表示を解除",
blockDangerousRedisCommands: "危険なコマンドをブロック",
+ mongoQueryLanguage: "MongoDB のクエリ言語",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "生成した shell をコピー",
+ mongoShellCopied: "Mongo shell コマンドをコピーしました",
multiDbExecute: "複数DB実行",
executeAllSql: "すべての SQL を実行",
},
@@ -2538,6 +2543,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "メッセージなし",
code: "コード: {code}",
+ mongoShell: "生成された mongo shell",
+ copyMongoShell: "shell をコピー",
},
chart: {
title: "グラフ",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 1953edd0ce..996467b77a 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -936,6 +936,11 @@ export default withEnglishFallback({
alwaysOnTop: "항상 위에 표시",
alwaysOnTopOff: "항상 위 표시 해제",
blockDangerousRedisCommands: "위험한 명령 차단",
+ mongoQueryLanguage: "MongoDB 쿼리 언어",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "생성된 셸 복사",
+ mongoShellCopied: "Mongo 셸 명령이 복사되었습니다",
saveSqlFile: "원본 파일에 저장",
pluginCenter: "플러그인 센터",
executeAllSql: "모든 SQL 실행",
@@ -2516,6 +2521,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "메시지 없음",
code: "코드: {code}",
+ mongoShell: "생성된 mongo shell",
+ copyMongoShell: "셸 복사",
},
chart: {
title: "차트",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index ea300037fd..34ccebdfd8 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -931,6 +931,11 @@ export default withEnglishFallback({
alwaysOnTop: "Manter janela no topo",
alwaysOnTopOff: "Não manter no topo",
blockDangerousRedisCommands: "Bloquear comandos perigosos",
+ mongoQueryLanguage: "Linguagem de consulta do MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Copiar shell gerado",
+ mongoShellCopied: "Comando mongo shell copiado",
multiDbExecute: "Execução em múltiplos bancos",
executeAllSql: "Executar todo o SQL",
},
@@ -2518,6 +2523,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Nenhuma mensagem",
code: "Código: {code}",
+ mongoShell: "Shell do Mongo gerado",
+ copyMongoShell: "Copiar shell",
},
chart: {
title: "Gráfico",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index ef6a129704..5486271a6c 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -911,6 +911,11 @@ export default withEnglishFallback({
alwaysOnTop: "Поверх других окон",
alwaysOnTopOff: "Не оставлять поверх других окон",
blockDangerousRedisCommands: "Блокировать опасные команды",
+ mongoQueryLanguage: "Язык запросов MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Копировать сгенерированный shell",
+ mongoShellCopied: "Команда mongo shell скопирована",
multiDbExecute: "Выполнение на нескольких БД",
executeAllSql: "Выполнить весь SQL",
},
@@ -2605,6 +2610,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Нет сообщений",
code: "Код: {code}",
+ mongoShell: "Сгенерированный mongo shell",
+ copyMongoShell: "Копировать shell",
},
chart: {
title: "Диаграмма",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 427a398114..30c36d0b75 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -1012,6 +1012,11 @@ export default withEnglishFallback({
alwaysOnTopOff: "ไม่ให้อยู่ด้านบน",
blockDangerousRedisCommands: "บล็อกคำสั่งที่มีความเสี่ยง",
multiDbExecute: "การเรียกใช้หลายฐานข้อมูล",
+ mongoQueryLanguage: "ภาษาสอบถาม MongoDB",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "คัดลอก shell ที่สร้างขึ้น",
+ mongoShellCopied: "คัดลอกคำสั่ง Mongo shell แล้ว",
executeAllSql: "เรียกใช้ SQL ทั้งหมด",
},
multiDbExecute: {
@@ -2754,6 +2759,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "ไม่มีข้อความ",
code: "โค้ด: {code}",
+ mongoShell: "mongo shell ที่สร้างขึ้น",
+ copyMongoShell: "คัดลอก shell",
},
chart: {
title: "แผนภูมิ",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 4c03d5ff03..682c35f54c 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -303,6 +303,11 @@ export default withEnglishFallback({
alwaysOnTop: "Pencereyi üstte tut",
alwaysOnTopOff: "Üstte tutmayı kapat",
blockDangerousRedisCommands: "Tehlikeli komutları engelle",
+ mongoQueryLanguage: "MongoDB sorgu dili",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "Oluşturulan shell'i kopyala",
+ mongoShellCopied: "Mongo shell komutu kopyalandı",
multiDbExecute: "Çoklu veritabanı yürütme",
},
multiDbExecute: {
@@ -1848,6 +1853,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "Mesaj yok",
code: "Kod: {code}",
+ mongoShell: "Oluşturulan mongo shell",
+ copyMongoShell: "Shell'i kopyala",
},
chart: {
title: "Grafik",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index bd29f73d47..3322a8e2d3 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1080,6 +1080,11 @@ export default withEnglishFallback({
alwaysOnTop: "窗口置顶",
alwaysOnTopOff: "取消置顶",
blockDangerousRedisCommands: "拦截危险命令",
+ mongoQueryLanguage: "MongoDB 查询语言",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "复制生成的 shell",
+ mongoShellCopied: "已复制 Mongo shell 命令",
multiDbExecute: "多库执行",
},
multiDbExecute: {
@@ -2827,6 +2832,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "没有消息",
code: "代码:{code}",
+ mongoShell: "生成的 mongo shell",
+ copyMongoShell: "复制 shell",
},
chart: {
title: "图表",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index fa2648d9a5..48c9c61a13 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -914,6 +914,11 @@ export default withEnglishFallback({
alwaysOnTop: "視窗置頂",
alwaysOnTopOff: "取消置頂",
blockDangerousRedisCommands: "攔截危險命令",
+ mongoQueryLanguage: "MongoDB 查詢語言",
+ mongoShellMode: "Shell",
+ mongoSqlMode: "SQL",
+ copyMongoShell: "複製產生的 shell",
+ mongoShellCopied: "已複製 Mongo shell 命令",
multiDbExecute: "多庫執行",
immediateSync: "立即同步",
},
@@ -2496,6 +2501,8 @@ export default withEnglishFallback({
queryMessages: {
empty: "沒有訊息",
code: "代碼:{code}",
+ mongoShell: "產生的 mongo shell",
+ copyMongoShell: "複製 shell",
},
chart: {
title: "圖表",
diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.ts
index f1c0d11bf2..17f8b962cb 100644
--- a/apps/desktop/src/lib/app/openTabsPersistence.ts
+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts
@@ -81,6 +81,7 @@ export interface SavedOpenTab {
tableComment?: QueryTab["tableComment"];
tableMeta?: QueryTab["tableMeta"];
mongoEditTarget?: QueryTab["mongoEditTarget"];
+ mongoQueryLanguage?: QueryTab["mongoQueryLanguage"];
resultEvicted?: boolean;
resultCacheKey?: string;
resultRuns?: SavedQueryResultRun[];
@@ -234,6 +235,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
...(tab.tableComment !== undefined ? { tableComment: tab.tableComment } : {}),
tableMeta: tab.tableMeta,
...(tab.mongoEditTarget !== undefined ? { mongoEditTarget: tab.mongoEditTarget } : {}),
+ ...(tab.mongoQueryLanguage === "sql" ? { mongoQueryLanguage: "sql" as const } : {}),
...(tab.mode !== "data" && tab.resultEvicted ? { resultEvicted: true } : {}),
...(tab.mode !== "data" && tab.resultEvicted && tab.resultCacheKey !== undefined ? { resultCacheKey: tab.resultCacheKey } : {}),
...(tab.mode === "query" && tab.resultRuns?.length
@@ -308,6 +310,7 @@ function restoreOpenTabsArray(parsed: unknown, rawActiveTabId: string | null, op
return {
...tab,
mode,
+ mongoQueryLanguage: tab.mongoQueryLanguage === "sql" ? "sql" : undefined,
sql: typeof tab.sql === "string" ? tab.sql : "",
isExecuting: false,
redisMonitorActive: false,
diff --git a/apps/desktop/src/lib/mongo/__tests__/mongoSql.spec.ts b/apps/desktop/src/lib/mongo/__tests__/mongoSql.spec.ts
new file mode 100644
index 0000000000..d4c5514b56
--- /dev/null
+++ b/apps/desktop/src/lib/mongo/__tests__/mongoSql.spec.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it } from "vitest";
+import { splitMongoCommandRanges } from "@/lib/mongo/mongoShellCommand";
+import { MongoSqlError, prepareMongoQueryText, translateMongoSqlScript } from "@/lib/mongo/mongoSql";
+
+function shell(sql: string) {
+ const text = translateMongoSqlScript(sql);
+ const commands = splitMongoCommandRanges(text);
+ expect(commands, text).toHaveLength(1);
+ return { text, command: commands[0]!.command };
+}
+
+describe("translateMongoSqlScript", () => {
+ it("compiles a filtered, sorted, limited select into find", () => {
+ const { command } = shell("SELECT name, email FROM users WHERE age > 30 ORDER BY name LIMIT 50");
+ expect(command.kind).toBe("find");
+ if (command.kind !== "find") return;
+ expect(command.collection).toBe("users");
+ expect(JSON.parse(command.filter)).toEqual({ age: { $gt: 30 } });
+ expect(JSON.parse(command.projection ?? "{}")).toEqual({ name: 1, email: 1, _id: 0 });
+ expect(JSON.parse(command.sort ?? "{}")).toEqual({ name: 1 });
+ expect(command.limit).toBe(50);
+ });
+
+ it("keeps ObjectId and ISODate constructors in the filter", () => {
+ const { text, command } = shell("SELECT * FROM users WHERE _id = ObjectId('507f1f77bcf86cd799439011') AND created = ISODate('2020-01-02T03:04:05Z')");
+ expect(text).toContain("ObjectId(\"507f1f77bcf86cd799439011\")");
+ expect(text).toContain("ISODate(\"2020-01-02T03:04:05Z\")");
+ expect(command.kind).toBe("find");
+ if (command.kind !== "find") return;
+ expect(JSON.parse(command.filter)).toEqual({
+ _id: { $oid: "507f1f77bcf86cd799439011" },
+ created: { $date: "2020-01-02T03:04:05Z" },
+ });
+ });
+
+ it("compiles GROUP BY aggregates into an aggregation pipeline", () => {
+ const { command } = shell("SELECT status, COUNT(*) AS n FROM users WHERE active = true GROUP BY status ORDER BY n DESC");
+ expect(command.kind).toBe("aggregate");
+ if (command.kind !== "aggregate") return;
+ expect(JSON.parse(command.pipeline)).toEqual([
+ { $match: { active: true } },
+ { $group: { _id: "$status", n: { $sum: 1 } } },
+ { $project: { status: "$_id", n: 1, _id: 0 } },
+ { $sort: { n: -1 } },
+ ]);
+ });
+
+ it("compiles an equality join into $lookup", () => {
+ const { command } = shell("SELECT * FROM orders o INNER JOIN customers c ON o.customer_id = c._id WHERE o.total > 10");
+ expect(command.kind).toBe("aggregate");
+ if (command.kind !== "aggregate") return;
+ const pipeline = JSON.parse(command.pipeline) as Array<Record<string, unknown>>;
+ expect(pipeline[0]).toEqual({ $match: { total: { $gt: 10 } } });
+ expect(pipeline[1]).toEqual({ $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "c" } });
+ expect(pipeline[2]).toEqual({ $unwind: { path: "$c", preserveNullAndEmptyArrays: false } });
+ });
+
+ it("compiles writes into insertMany, updateMany, and deleteMany", () => {
+ const inserted = shell("INSERT INTO users (name, age) VALUES ('ada', 36), ('bea', 41)");
+ expect(inserted.command.kind).toBe("insert");
+ if (inserted.command.kind === "insert") {
+ expect(JSON.parse(inserted.command.docsJson)).toEqual([
+ { name: "ada", age: 36 },
+ { name: "bea", age: 41 },
+ ]);
+ }
+
+ const updated = shell("UPDATE users SET age = 31 WHERE name = 'ada'");
+ expect(updated.command.kind).toBe("update");
+ if (updated.command.kind === "update") {
+ expect(updated.command.many).toBe(true);
+ expect(JSON.parse(updated.command.filter)).toEqual({ name: "ada" });
+ expect(JSON.parse(updated.command.update)).toEqual({ $set: { age: 31 } });
+ }
+
+ const deleted = shell("DELETE FROM users WHERE age < 18");
+ expect(deleted.command.kind).toBe("delete");
+ if (deleted.command.kind === "delete") {
+ expect(deleted.command.many).toBe(true);
+ expect(JSON.parse(deleted.command.filter)).toEqual({ age: { $lt: 18 } });
+ }
+ });
+
+ it("translates each statement and leaves an existing shell command untouched", () => {
+ const script = translateMongoSqlScript("SELECT * FROM users LIMIT 5; DELETE FROM users WHERE inactive = true");
+ expect(splitMongoCommandRanges(script)).toHaveLength(2);
+ const generated = translateMongoSqlScript("SELECT * FROM users");
+ expect(prepareMongoQueryText(generated, "sql", "mongodb", generated)).toEqual({ sql: generated });
+ expect(() => prepareMongoQueryText("db.users.drop()", "sql", "mongodb")).toThrow(MongoSqlError);
+ expect(prepareMongoQueryText("SELECT * FROM users", "sql", "mysql").sql).toBe("SELECT * FROM users");
+ });
+
+ it("compiles array indexes in filters and projections", () => {
+ const filtered = shell("SELECT * FROM orders WHERE addresses[0].city = 'SP' ORDER BY items[0].name");
+ expect(filtered.command.kind).toBe("find");
+ if (filtered.command.kind !== "find") return;
+ expect(JSON.parse(filtered.command.filter)).toEqual({ "addresses.0.city": "SP" });
+ expect(JSON.parse(filtered.command.sort ?? "{}")).toEqual({ "items.0.name": 1 });
+
+ const projected = shell("SELECT items[0].name FROM orders");
+ expect(projected.command.kind).toBe("find");
+ if (projected.command.kind !== "find") return;
+ expect(JSON.parse(projected.command.projection ?? "{}")).toEqual({
+ "items.0.name": { $getField: { field: "name", input: { $arrayElemAt: ["$items", 0] } } },
+ _id: 0,
+ });
+
+ const updated = shell("UPDATE orders SET items[0].name = 'kit' WHERE addresses[0].city = 'SP'");
+ expect(updated.command.kind).toBe("update");
+ if (updated.command.kind !== "update") return;
+ expect(JSON.parse(updated.command.filter)).toEqual({ "addresses.0.city": "SP" });
+ expect(JSON.parse(updated.command.update)).toEqual({ $set: { "items.0.name": "kit" } });
+ });
+
+ it("keeps dotted ORDER BY paths and allows reserved words as names", () => {
+ const nested = shell("SELECT name FROM users ORDER BY address.city");
+ expect(nested.command.kind).toBe("find");
+ if (nested.command.kind !== "find") return;
+ expect(JSON.parse(nested.command.sort ?? "{}")).toEqual({ "address.city": 1 });
+
+ const qualified = shell("SELECT user.name FROM users ORDER BY user.name");
+ expect(qualified.command.kind).toBe("find");
+ if (qualified.command.kind !== "find") return;
+ expect(JSON.parse(qualified.command.sort ?? "{}")).toEqual({ "user.name": 1 });
+ expect(JSON.parse(qualified.command.projection ?? "{}")).toEqual({ "user.name": 1, _id: 0 });
+
+ const renamed = shell("SELECT address.city AS city FROM users ORDER BY address.city");
+ expect(renamed.command.kind).toBe("aggregate");
+ if (renamed.command.kind !== "aggregate") return;
+ expect(JSON.parse(renamed.command.pipeline)).toEqual([
+ { $sort: { "address.city": 1 } },
+ { $project: { city: "$address.city", _id: 0 } },
+ ]);
+
+ const named = shell("SELECT window FROM window WHERE over = 1");
+ expect(named.command.kind).toBe("find");
+ if (named.command.kind !== "find") return;
+ expect(JSON.parse(named.command.filter)).toEqual({ over: 1 });
+ });
+
+ it("strips table qualifiers from find projections", () => {
+ const aliased = shell("SELECT u.name FROM users u");
+ expect(aliased.command.kind).toBe("find");
+ if (aliased.command.kind !== "find") return;
+ expect(JSON.parse(aliased.command.projection ?? "{}")).toEqual({ name: 1, _id: 0 });
+
+ const collection = shell("SELECT users.name FROM users");
+ expect(collection.command.kind).toBe("find");
+ if (collection.command.kind !== "find") return;
+ expect(JSON.parse(collection.command.projection ?? "{}")).toEqual({ name: 1, _id: 0 });
+ });
+
+ it("keeps join owners in GROUP BY and aggregate fields", () => {
+ const grouped = shell("SELECT c.name, SUM(c.total) AS total FROM orders o INNER JOIN customers c ON o.customer_id = c._id GROUP BY c.name");
+ expect(grouped.command.kind).toBe("aggregate");
+ if (grouped.command.kind !== "aggregate") return;
+ const pipeline = JSON.parse(grouped.command.pipeline) as Array<Record<string, unknown>>;
+ expect(pipeline.find((stage) => "$group" in stage)).toEqual({ $group: { _id: "$c.name", total: { $sum: "$c.total" } } });
+
+ const multi = shell("SELECT a.x, b.x FROM lefts a INNER JOIN rights b ON a.id = b.id GROUP BY a.x, b.x");
+ expect(multi.command.kind).toBe("aggregate");
+ if (multi.command.kind !== "aggregate") return;
+ const stages = JSON.parse(multi.command.pipeline) as Array<Record<string, unknown>>;
+ expect(stages.find((stage) => "$group" in stage)).toEqual({ $group: { _id: { x: "$x", b: { x: "$b.x" } } } });
+
+ const nested = shell("SELECT address.city, profile.city FROM users GROUP BY address.city, profile.city");
+ expect(nested.command.kind).toBe("aggregate");
+ if (nested.command.kind !== "aggregate") return;
+ const nestedStages = JSON.parse(nested.command.pipeline) as Array<Record<string, unknown>>;
+ expect(nestedStages.find((stage) => "$group" in stage)).toEqual({
+ $group: { _id: { address: { city: "$address.city" }, profile: { city: "$profile.city" } } },
+ });
+ });
+
+ it("sorts before a projection removes the sort field", () => {
+ const { command } = shell("SELECT name AS n FROM users ORDER BY age");
+ expect(command.kind).toBe("aggregate");
+ if (command.kind !== "aggregate") return;
+ expect(JSON.parse(command.pipeline)).toEqual([
+ { $sort: { age: 1 } },
+ { $project: { n: "$name", _id: 0 } },
+ ]);
+ });
+
+ it("rejects negative array indexes on the query path", () => {
+ expect(() => translateMongoSqlScript("SELECT * FROM orders WHERE items[-1].name = 'kit'")).toThrow(/Negative array indexes/);
+ const projected = shell("SELECT items[-1].name FROM orders");
+ expect(projected.command.kind).toBe("find");
+ if (projected.command.kind !== "find") return;
+ expect(JSON.parse(projected.command.projection ?? "{}")).toEqual({
+ "items.-1.name": { $getField: { field: "name", input: { $arrayElemAt: ["$items", -1] } } },
+ _id: 0,
+ });
+ });
+
+ it("rejects SQL outside the supported subset", () => {
+ expect(() => translateMongoSqlScript("SELECT * FROM users UNION SELECT * FROM archived")).toThrow(MongoSqlError);
+ expect(() => translateMongoSqlScript("SELECT name, ROW_NUMBER() OVER (ORDER BY name) FROM users")).toThrow(/Window functions/);
+ expect(() => translateMongoSqlScript("SELECT * FROM users WHERE id IN (SELECT id FROM archived)")).toThrow(/Subqueries/);
+ expect(() => translateMongoSqlScript("WITH recent AS (SELECT * FROM users) SELECT * FROM recent")).toThrow(/WITH/);
+ });
+});
diff --git a/apps/desktop/src/lib/mongo/mongoSql.ts b/apps/desktop/src/lib/mongo/mongoSql.ts
new file mode 100644
index 0000000000..7598659adc
--- /dev/null
+++ b/apps/desktop/src/lib/mongo/mongoSql.ts
@@ -0,0 +1,1160 @@
+import type { DatabaseType } from "@/types/database";
+import { splitMongoCommandRanges } from "@/lib/mongo/mongoShellCommand";
+import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";
+
+/**
+ * Opt-in SQL language for a MongoDB query tab.
+ * Absent or "shell" keeps the mongo-shell editor.
+ */
+export type MongoQueryLanguage = "shell" | "sql";
+
+/**
+ * SQL → mongo-shell for the subset described in issue #11929.
+ *
+ * The published `@queryleaf/lib` package is AGPL-3.0, which cannot be linked
+ * into this Apache-2.0 app, and `node-sql-parser` unpacks to tens of megabytes.
+ * This compiler covers the same shell shapes (find / aggregate / insertMany /
+ * updateMany / deleteMany) and rejects everything outside that subset.
+ *
+ * `!=` becomes `$ne`, which also matches documents where the field is missing.
+ * Array-index projections use `$getField` and `$arrayElemAt`, which need MongoDB 4.4 or newer.
+ * Negative array indexes are rejected in WHERE, ORDER BY, GROUP BY, and UPDATE.
+ * A SELECT projection can still pass a negative index to `$arrayElemAt`.
+ */
+
+export class MongoSqlError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "MongoSqlError";
+ }
+}
+
+export function mongoSqlModeActive(databaseType: string | undefined, language: MongoQueryLanguage | undefined): boolean {
+ return databaseType === "mongodb" && language === "sql";
+}
+
+/** Statement splitter dialect. SQL mode must not use the mongo-shell splitter. */
+export function queryEditorStatementDatabaseType(databaseType: DatabaseType | undefined, language: MongoQueryLanguage | undefined): DatabaseType | undefined {
+ if (mongoSqlModeActive(databaseType, language)) return undefined;
+ return databaseType;
+}
+
+export function prepareMongoQueryText(sql: string, language: MongoQueryLanguage | undefined, databaseType: string | undefined, generatedShell?: string): { sql: string; generatedShell?: string } {
+ if (!mongoSqlModeActive(databaseType, language)) return { sql };
+ // Pagination and refresh re-run the shell command already produced here.
+ // Any other shell text is SQL and must fail, instead of being executed as written.
+ if (generatedShell !== undefined && sql === generatedShell && splitMongoCommandRanges(sql).length > 0) return { sql };
+ const translated = translateMongoSqlScript(sql);
+ return { sql: translated, generatedShell: translated };
+}
+
+export function translateMongoSqlScript(sql: string): string {
+ const statements = splitSqlStatementRanges(sql)
+ .map((range) => range.sql.trim())
+ .filter((statement) => statement.length > 0);
+ if (statements.length === 0) throw new MongoSqlError("Enter a SQL statement to run against MongoDB.");
+ return statements.map(translateMongoSqlStatement).join("\n");
+}
+
+class ShellCtor {
+ constructor(
+ readonly name: "ObjectId" | "ISODate",
+ readonly arg: string,
+ ) {}
+}
+
+type ShellValue = null | boolean | number | string | ShellCtor | ShellValue[] | { [key: string]: ShellValue };
+
+interface FieldPart {
+ name: string;
+ indexes: number[];
+}
+
+interface FieldRef {
+ parts: FieldPart[];
+}
+
+type Expr =
+ | { type: "cmp"; op: "=" | "!=" | ">" | "<" | ">=" | "<="; left: Primary; right: Primary }
+ | { type: "and" | "or"; items: Expr[] }
+ | { type: "not"; item: Expr }
+ | { type: "in"; field: FieldRef; values: ShellValue[]; negated: boolean }
+ | { type: "between"; field: FieldRef; low: ShellValue; high: ShellValue; negated: boolean }
+ | { type: "null"; field: FieldRef; negated: boolean }
+ | { type: "like"; field: FieldRef; pattern: string; insensitive: boolean; negated: boolean };
+
+type Primary = { type: "field"; field: FieldRef } | { type: "value"; value: ShellValue };
+
+interface SelectItem {
+ type: "star" | "field" | "agg";
+ field?: FieldRef;
+ fn?: "count" | "sum" | "avg" | "min" | "max";
+ star?: boolean;
+ alias?: string;
+}
+
+interface TableRef {
+ collection: string;
+ database?: string;
+ alias?: string;
+}
+
+interface Join {
+ kind: "inner" | "left";
+ table: TableRef;
+ local: FieldRef;
+ foreign: FieldRef;
+}
+
+interface OrderKey {
+ field: FieldRef;
+ direction: 1 | -1;
+}
+
+type Tok =
+ | { kind: "ident"; text: string }
+ | { kind: "string"; text: string }
+ | { kind: "number"; value: number }
+ | { kind: "op"; text: string }
+ | { kind: "eof" };
+
+const RESERVED = new Set(
+ "select from where group by order limit offset insert into values update set delete as join inner left right full cross outer on and or not in is null like ilike between union intersect except with distinct having over window true false".split(" "),
+);
+
+function translateMongoSqlStatement(sql: string): string {
+ const parser = new Parser(sql);
+ const keyword = parser.peekKeyword();
+ if (keyword === "select") return parser.parseSelect();
+ if (keyword === "insert") return parser.parseInsert();
+ if (keyword === "update") return parser.parseUpdate();
+ if (keyword === "delete") return parser.parseDelete();
+ if (keyword === "with") throw new MongoSqlError("WITH queries are not supported in MongoDB SQL mode.");
+ throw new MongoSqlError("Only SELECT, INSERT, UPDATE, and DELETE are supported in MongoDB SQL mode.");
+}
+
+class Parser {
+ private readonly tokens: Tok[];
+ private index = 0;
+
+ constructor(sql: string) {
+ this.tokens = tokenize(sql);
+ }
+
+ parseSelect(): string {
+ this.expectKeyword("select");
+ if (this.eatKeyword("distinct")) throw new MongoSqlError("DISTINCT is not supported in MongoDB SQL mode.");
+ const items = this.parseSelectList();
+ this.expectKeyword("from");
+ const from = this.parseTableRef();
+ const joins: Join[] = [];
+ while (this.canStartJoin()) joins.push(this.parseJoin(from));
+ const where = this.eatKeyword("where") ? this.parseExpr() : undefined;
+ return this.finishSelect(items, from, joins, where);
+ }
+
+ private finishSelect(items: SelectItem[], from: TableRef, joins: Join[], where: Expr | undefined): string {
+ let groupBy: FieldRef[] | undefined;
+ if (this.atKeyword("group")) {
+ this.expectKeyword("group");
+ this.expectKeyword("by");
+ groupBy = this.parseFieldList();
+ }
+ if (this.eatKeyword("having")) throw new MongoSqlError("HAVING is not supported in MongoDB SQL mode. Filter rows with WHERE before grouping.");
+ const orderBy = this.eatKeyword("order") ? (this.expectKeyword("by"), this.parseOrderBy()) : [];
+ const limit = this.eatKeyword("limit") ? this.parseInteger("LIMIT") : undefined;
+ const offset = this.eatKeyword("offset") ? this.parseInteger("OFFSET") : undefined;
+ this.expectEnd();
+ return compileSelect(items, from, joins, where, groupBy, orderBy, limit, offset);
+ }
+
+ parseInsert(): string {
+ this.expectKeyword("insert");
+ this.expectKeyword("into");
+ const table = this.parseTableRef();
+ this.expectOp("(");
+ const columns = this.parseIdentList();
+ this.expectOp(")");
+ this.expectKeyword("values");
+ const rows: ShellValue[][] = [];
+ do {
+ this.expectOp("(");
+ const values: ShellValue[] = [];
+ do values.push(this.parseLiteral());
+ while (this.eatOp(","));
+ this.expectOp(")");
+ if (values.length !== columns.length) throw new MongoSqlError("INSERT column count does not match the VALUES row.");
+ rows.push(values);
+ } while (this.eatOp(","));
+ this.expectEnd();
+ const documents = rows.map((values) => {
+ const document: Record<string, ShellValue> = {};
+ columns.forEach((column, index) => {
+ document[column] = values[index]!;
+ });
+ return document;
+ });
+ return mongoCall(table, "insertMany", printShell(documents));
+ }
+
+ parseUpdate(): string {
+ this.expectKeyword("update");
+ const table = this.parseTableRef();
+ this.expectKeyword("set");
+ const set: Record<string, ShellValue> = {};
+ const aliases = aliasMap(table, []);
+ do {
+ const field = this.parseFieldRef();
+ this.expectOp("=");
+ rejectNegativeIndex(field, "UPDATE");
+ set[qualifiedPath(fieldPath(field, aliases, table))] = this.parseLiteral();
+ } while (this.eatOp(","));
+ const where = this.eatKeyword("where") ? this.parseExpr() : undefined;
+ this.expectEnd();
+ const filter = where ? exprToFilter(where, aliasMap(table, [])) : {};
+ return mongoCall(table, "updateMany", `${printShell(filter)}, ${printShell({ $set: set })}`);
+ }
+
+ parseDelete(): string {
+ this.expectKeyword("delete");
+ this.expectKeyword("from");
+ const table = this.parseTableRef();
+ const where = this.eatKeyword("where") ? this.parseExpr() : undefined;
+ this.expectEnd();
+ const filter = where ? exprToFilter(where, aliasMap(table, [])) : {};
+ return mongoCall(table, "deleteMany", printShell(filter));
+ }
+
+ private parseSelectList(): SelectItem[] {
+ const items: SelectItem[] = [];
+ do items.push(this.parseSelectItem());
+ while (this.eatOp(","));
+ return items;
+ }
+
+ private parseSelectItem(): SelectItem {
+ if (this.eatOp("*")) return { type: "star" };
+ if (this.peek().kind === "ident" && this.lookaheadIsOp("(")) {
+ const name = this.nextIdent().toLowerCase();
+ this.expectOp("(");
+ if (name === "count" && this.eatOp("*")) {
+ this.expectOp(")");
+ return { type: "agg", fn: "count", star: true, alias: this.parseOptionalAlias() };
+ }
+ if (name === "count" || name === "sum" || name === "avg" || name === "min" || name === "max") {
+ const field = this.parseFieldRef();
+ this.expectOp(")");
+ return { type: "agg", fn: name, field, alias: this.parseOptionalAlias() };
+ }
+ this.skipUntilMatchingParen();
+ throw new MongoSqlError(`Function ${name.toUpperCase()}() is not supported in MongoDB SQL mode.`);
+ }
+ const field = this.parseFieldRef();
+ return { type: "field", field, alias: this.parseOptionalAlias() };
+ }
+
+ private parseOptionalAlias(): string | undefined {
+ if (this.eatKeyword("as")) return this.nextIdent();
+ if (this.peek().kind === "ident" && !RESERVED.has(this.peekText())) return this.nextIdent();
+ return undefined;
+ }
+
+ private parseTableRef(): TableRef {
+ const first = this.nextIdent();
+ if (this.eatOp(".")) {
+ const collection = this.nextIdent();
+ return { database: first, collection, alias: this.parseOptionalAlias() };
+ }
+ return { collection: first, alias: this.parseOptionalAlias() };
+ }
+
+ private canStartJoin(): boolean {
+ const keyword = this.peekKeyword();
+ return keyword === "join" || keyword === "inner" || keyword === "left" || keyword === "right" || keyword === "full" || keyword === "cross";
+ }
+
+ private parseJoin(base: TableRef): Join {
+ let kind: Join["kind"] = "inner";
+ if (this.eatKeyword("inner")) this.expectKeyword("join");
+ else if (this.eatKeyword("left")) {
+ this.eatKeyword("outer");
+ this.expectKeyword("join");
+ kind = "left";
+ } else if (this.eatKeyword("join")) kind = "inner";
+ else if (this.atKeyword("right") || this.atKeyword("full") || this.atKeyword("cross")) {
+ throw new MongoSqlError("Only INNER JOIN and LEFT JOIN are supported in MongoDB SQL mode.");
+ }
+ const table = this.parseTableRef();
+ if (!table.alias) table.alias = table.collection;
+ this.expectKeyword("on");
+ const left = this.parseFieldRef();
+ this.expectOp("=");
+ const right = this.parseFieldRef();
+ const baseNames = new Set([base.alias?.toLowerCase(), base.collection.toLowerCase()].filter((name): name is string => !!name));
+ const joinNames = new Set([table.alias?.toLowerCase(), table.collection.toLowerCase()].filter((name): name is string => !!name));
+ const leftOwner = left.parts[0]?.name.toLowerCase();
+ const rightOwner = right.parts[0]?.name.toLowerCase();
+ const local = baseNames.has(leftOwner ?? "") ? left : baseNames.has(rightOwner ?? "") ? right : undefined;
+ const foreign = joinNames.has(leftOwner ?? "") ? left : joinNames.has(rightOwner ?? "") ? right : undefined;
+ if (!local || !foreign || local === foreign) {
+ throw new MongoSqlError("JOIN only supports an equality between a base-collection field and a joined-collection field.");
+ }
+ return { kind, table, local, foreign };
+ }
+
+ private parseOrderBy(): OrderKey[] {
+ const keys: OrderKey[] = [];
+ do {
+ const field = this.parseFieldRef();
+ let direction: 1 | -1 = 1;
+ if (this.eatKeyword("desc")) direction = -1;
+ else this.eatKeyword("asc");
+ keys.push({ field, direction });
+ } while (this.eatOp(","));
+ return keys;
+ }
+
+ private parseFieldList(): FieldRef[] {
+ const fields: FieldRef[] = [];
+ do fields.push(this.parseFieldRef());
+ while (this.eatOp(","));
+ return fields;
+ }
+
+ private parseIdentList(): string[] {
+ const names: string[] = [];
+ do names.push(this.nextIdent());
+ while (this.eatOp(","));
+ return names;
+ }
+
+ private parseExpr(): Expr {
+ return this.parseOr();
+ }
+
+ private parseOr(): Expr {
+ const items = [this.parseAnd()];
+ while (this.eatKeyword("or")) items.push(this.parseAnd());
+ return items.length === 1 ? items[0]! : { type: "or", items };
+ }
+
+ private parseAnd(): Expr {
+ const items = [this.parseNot()];
+ while (this.eatKeyword("and")) items.push(this.parseNot());
+ return items.length === 1 ? items[0]! : { type: "and", items };
+ }
+
+ private parseNot(): Expr {
+ if (!this.eatKeyword("not")) return this.parsePredicate();
+ const item = this.parseNot();
+ if (item.type === "in") return { ...item, negated: !item.negated };
+ if (item.type === "like") return { ...item, negated: !item.negated };
+ if (item.type === "between") return { ...item, negated: !item.negated };
+ if (item.type === "null") return { ...item, negated: !item.negated };
+ return { type: "not", item };
+ }
+
+ private parsePredicate(): Expr {
+ if (this.peekKeyword() === "select") throw new MongoSqlError("Subqueries are not supported in MongoDB SQL mode.");
+ if (this.eatOp("(")) {
+ const inner = this.parseOr();
+ this.expectOp(")");
+ return inner;
+ }
+ const left = this.parsePrimary();
+ if (this.eatKeyword("is")) {
+ const negated = this.eatKeyword("not");
+ this.expectKeyword("null");
+ if (left.type !== "field") throw new MongoSqlError("IS NULL applies to a field.");
+ return { type: "null", field: left.field, negated };
+ }
+ if (this.eatKeyword("not")) {
+ if (this.eatKeyword("in")) return this.finishIn(left, true);
+ if (this.eatKeyword("like")) return this.finishLike(left, true);
+ if (this.eatKeyword("ilike")) return this.finishLike(left, true, true);
+ if (this.eatKeyword("between")) return this.finishBetween(left, true);
+ throw new MongoSqlError("NOT must be followed by IN, LIKE, BETWEEN, or a condition.");
+ }
+ if (this.eatKeyword("in")) return this.finishIn(left, false);
+ if (this.eatKeyword("like")) return this.finishLike(left, false);
+ if (this.eatKeyword("ilike")) return this.finishLike(left, false, true);
+ if (this.eatKeyword("between")) return this.finishBetween(left, false);
+ const op = this.peek().kind === "op" ? this.peek().text : undefined;
+ if (op === "=" || op === "!=" || op === "<>" || op === ">" || op === "<" || op === ">=" || op === "<=") {
+ this.next();
+ const right = this.parsePrimary();
+ const normalized = op === "<>" ? "!=" : op;
+ return { type: "cmp", op: normalized, left, right };
+ }
+ throw new MongoSqlError("WHERE supports comparisons, AND, OR, NOT, IN, BETWEEN, LIKE, and IS NULL.");
+ }
+
+ private finishIn(left: Primary, negated: boolean): Expr {
+ if (left.type !== "field") throw new MongoSqlError("IN applies to a field.");
+ this.expectOp("(");
+ if (this.peekKeyword() === "select") throw new MongoSqlError("Subqueries are not supported in MongoDB SQL mode.");
+ const values: ShellValue[] = [];
+ if (!this.atOp(")")) {
+ do values.push(this.parseLiteral());
+ while (this.eatOp(","));
+ }
+ this.expectOp(")");
+ return { type: "in", field: left.field, values, negated };
+ }
+
+ private finishLike(left: Primary, negated: boolean, insensitive = false): Expr {
+ if (this.peekKeyword() === "ilike") {
+ this.next();
+ insensitive = true;
+ }
+ if (left.type !== "field") throw new MongoSqlError("LIKE applies to a field.");
+ const pattern = this.parseLiteral();
+ if (typeof pattern !== "string") throw new MongoSqlError("LIKE requires a string pattern.");
+ return { type: "like", field: left.field, pattern, insensitive, negated };
+ }
+
+ private finishBetween(left: Primary, negated: boolean): Expr {
+ if (left.type !== "field") throw new MongoSqlError("BETWEEN applies to a field.");
+ const low = this.parseLiteral();
+ this.expectKeyword("and");
+ const high = this.parseLiteral();
+ return { type: "between", field: left.field, low, high, negated };
+ }
+
+ private parsePrimary(): Primary {
+ if (this.peekKeyword() === "select") throw new MongoSqlError("Subqueries are not supported in MongoDB SQL mode.");
+ if (this.peek().kind === "ident" && this.lookaheadIsOp("(")) {
+ return { type: "value", value: this.parseCtor() };
+ }
+ if (this.peek().kind === "string" || this.peek().kind === "number" || this.peekKeyword() === "true" || this.peekKeyword() === "false" || this.peekKeyword() === "null") {
+ return { type: "value", value: this.parseLiteral() };
+ }
+ return { type: "field", field: this.parseFieldRef() };
+ }
+
+ private parseCtor(): ShellValue {
+ const name = this.nextIdent();
+ const canonical = name.toLowerCase() === "objectid" ? "ObjectId" : name.toLowerCase() === "isodate" ? "ISODate" : undefined;
+ this.expectOp("(");
+ const arg = this.parseLiteral();
+ this.expectOp(")");
+ if (!canonical) throw new MongoSqlError(`Function ${name}() is not supported in MongoDB SQL mode. Use ObjectId('...') or ISODate('...').`);
+ if (typeof arg !== "string" || !arg) throw new MongoSqlError(`${canonical}() requires a non-empty string.`);
+ if (canonical === "ObjectId" && !/^[a-fA-F0-9]{24}$/.test(arg)) throw new MongoSqlError("ObjectId() requires a 24-character hex string.");
+ return new ShellCtor(canonical, arg);
+ }
+
+ private parseLiteral(): ShellValue {
+ if (this.peek().kind === "ident" && this.lookaheadIsOp("(")) return this.parseCtor();
+ const token = this.next();
+ if (token.kind === "string") return token.text;
+ if (token.kind === "number") return token.value;
+ if (token.kind === "ident") {
+ const keyword = token.text.toLowerCase();
+ if (keyword === "true") return true;
+ if (keyword === "false") return false;
+ if (keyword === "null") return null;
+ }
+ throw new MongoSqlError("MongoDB SQL mode only supports literal values here (strings, numbers, true, false, null, ObjectId(), ISODate()).");
+ }
+
+ private parseFieldRef(): FieldRef {
+ const parts = [this.parseFieldPart()];
+ while (this.eatOp(".")) parts.push(this.parseFieldPart());
+ return { parts };
+ }
+
+ private parseFieldPart(): FieldPart {
+ const name = this.nextIdent();
+ const indexes: number[] = [];
+ while (this.eatOp("[")) {
+ indexes.push(this.parseArrayIndex());
+ this.expectOp("]");
+ }
+ return { name, indexes };
+ }
+
+ private parseArrayIndex(): number {
+ const negative = this.eatOp("-");
+ const token = this.next();
+ if (token.kind !== "number" || !Number.isInteger(token.value) || token.value < 0) {
+ throw new MongoSqlError("Array index requires an integer.");
+ }
+ return negative ? -token.value : token.value;
+ }
+
+ private parseInteger(label: string): number {
+ const token = this.next();
+ if (token.kind !== "number" || !Number.isInteger(token.value) || token.value < 0) {
+ throw new MongoSqlError(`${label} requires a non-negative integer.`);
+ }
+ return token.value;
+ }
+
+ private skipUntilMatchingParen() {
+ let depth = 1;
+ while (depth > 0) {
+ const token = this.next();
+ if (token.kind === "eof") throw new MongoSqlError('Expected ")".');
+ if (token.kind === "op" && token.text === "(") depth += 1;
+ if (token.kind === "op" && token.text === ")") depth -= 1;
+ }
+ }
+
+ private expectEnd() {
+ if (this.atKeyword("union") || this.atKeyword("intersect") || this.atKeyword("except")) {
+ throw new MongoSqlError("UNION, INTERSECT, and EXCEPT are not supported in MongoDB SQL mode.");
+ }
+ if (this.peek().kind !== "eof") throw new MongoSqlError(`Unexpected ${this.describe(this.peek())} in MongoDB SQL mode.`);
+ }
+
+ private peek(): Tok {
+ return this.tokens[this.index] ?? { kind: "eof" };
+ }
+
+ private next(): Tok {
+ const token = this.peek();
+ if (token.kind !== "eof") this.index += 1;
+ if (token.kind === "op" && token.text === ")" && this.atKeyword("over")) {
+ throw new MongoSqlError("Window functions are not supported in MongoDB SQL mode.");
+ }
+ return token;
+ }
+
+ private peekKeyword(): string | undefined {
+ const token = this.peek();
+ return token.kind === "ident" ? token.text.toLowerCase() : undefined;
+ }
+
+ private peekText(): string {
+ const token = this.peek();
+ return token.kind === "ident" ? token.text.toLowerCase() : "";
+ }
+
+ private atKeyword(keyword: string): boolean {
+ return this.peekKeyword() === keyword;
+ }
+
+ private eatKeyword(keyword: string): boolean {
+ if (!this.atKeyword(keyword)) return false;
+ this.next();
+ return true;
+ }
+
+ private expectKeyword(keyword: string) {
+ if (!this.eatKeyword(keyword)) throw new MongoSqlError(`Expected ${keyword.toUpperCase()}.`);
+ }
+
+ private atOp(op: string): boolean {
+ const token = this.peek();
+ return token.kind === "op" && token.text === op;
+ }
+
+ private eatOp(op: string): boolean {
+ if (!this.atOp(op)) return false;
+ this.next();
+ return true;
+ }
+
+ private expectOp(op: string) {
+ if (!this.eatOp(op)) throw new MongoSqlError(`Expected "${op}".`);
+ }
+
+ private lookaheadIsOp(op: string): boolean {
+ const token = this.tokens[this.index + 1];
+ return token?.kind === "op" && token.text === op;
+ }
+
+ private nextIdent(): string {
+ const token = this.next();
+ if (token.kind !== "ident") throw new MongoSqlError(`Expected a name, got ${this.describe(token)}.`);
+ return token.text;
+ }
+
+ private describe(token: Tok): string {
+ if (token.kind === "eof") return "end of statement";
+ if (token.kind === "ident") return token.text;
+ if (token.kind === "string") return JSON.stringify(token.text);
+ if (token.kind === "number") return String(token.value);
+ return token.text;
+ }
+}
+
+function tokenize(sql: string): Tok[] {
+ const tokens: Tok[] = [];
+ let i = 0;
+ while (i < sql.length) {
+ const ch = sql[i]!;
+ if (/\s/.test(ch)) {
+ i += 1;
+ continue;
+ }
+ if (ch === "-" && sql[i + 1] === "-") {
+ i += 2;
+ while (i < sql.length && sql[i] !== "\n") i += 1;
+ continue;
+ }
+ if (ch === "/" && sql[i + 1] === "*") {
+ i += 2;
+ while (i < sql.length && !(sql[i] === "*" && sql[i + 1] === "/")) i += 1;
+ i = Math.min(sql.length, i + 2);
+ continue;
+ }
+ if (ch === "'" || ch === '"') {
+ const quote = ch;
+ i += 1;
+ let text = "";
+ while (i < sql.length) {
+ if (sql[i] === quote && sql[i + 1] === quote) {
+ text += quote;
+ i += 2;
+ continue;
+ }
+ if (sql[i] === "\\") {
+ text += sql[i + 1] ?? "";
+ i += 2;
+ continue;
+ }
+ if (sql[i] === quote) {
+ i += 1;
+ break;
+ }
+ text += sql[i];
+ i += 1;
+ }
+ tokens.push(quote === "'" ? { kind: "string", text } : { kind: "ident", text });
+ continue;
+ }
+ if (ch === "`") {
+ i += 1;
+ let text = "";
+ while (i < sql.length && sql[i] !== "`") {
+ text += sql[i];
+ i += 1;
+ }
+ i += 1;
+ tokens.push({ kind: "ident", text });
+ continue;
+ }
+ if (/[0-9]/.test(ch) || (ch === "." && /[0-9]/.test(sql[i + 1] ?? ""))) {
+ const start = i;
+ i += 1;
+ while (i < sql.length && /[0-9]/.test(sql[i]!)) i += 1;
+ if (sql[i] === "." && /[0-9]/.test(sql[i + 1] ?? "")) {
+ i += 1;
+ while (i < sql.length && /[0-9]/.test(sql[i]!)) i += 1;
+ }
+ const text = sql.slice(start, i);
+ const value = Number(text);
+ if (!Number.isFinite(value)) throw new MongoSqlError(`Invalid number ${text}.`);
+ tokens.push({ kind: "number", value });
+ continue;
+ }
+ if (/[A-Za-z_]/.test(ch)) {
+ const start = i;
+ i += 1;
+ while (i < sql.length && /[A-Za-z0-9_$]/.test(sql[i]!)) i += 1;
+ tokens.push({ kind: "ident", text: sql.slice(start, i) });
+ continue;
+ }
+ const two = sql.slice(i, i + 2);
+ if (two === ">=" || two === "<=" || two === "!=" || two === "<>") {
+ tokens.push({ kind: "op", text: two });
+ i += 2;
+ continue;
+ }
+ if ("(),.*=>[]".includes(ch) || ch === "<" || ch === "-") {
+ tokens.push({ kind: "op", text: ch });
+ i += 1;
+ continue;
+ }
+ throw new MongoSqlError(`Unexpected character ${JSON.stringify(ch)} in MongoDB SQL mode.`);
+ }
+ tokens.push({ kind: "eof" });
+ return tokens;
+}
+
+function compileSelect(items: SelectItem[], from: TableRef, joins: Join[], where: Expr | undefined, groupBy: FieldRef[] | undefined, orderBy: OrderKey[], limit: number | undefined, offset: number | undefined): string {
+ if (items.some((item) => item.type === "star") && items.length > 1) {
+ throw new MongoSqlError("SELECT * cannot be combined with other columns in MongoDB SQL mode.");
+ }
+ if (items.some((item) => item.type === "star") && groupBy) {
+ throw new MongoSqlError("SELECT * cannot be combined with GROUP BY in MongoDB SQL mode.");
+ }
+ const aliases = aliasMap(from, joins);
+ const needsAggregate = joins.length > 0 || groupBy !== undefined || items.some((item) => item.type === "agg" || (item.type === "field" && item.alias));
+ if (!needsAggregate) {
+ const filter = where ? exprToFilter(where, aliases) : {};
+ const projection = projectionForFind(items, aliases, from);
+ const args = projection ? `${printShell(filter)}, ${printShell(projection)}` : printShell(filter);
+ const chain = [orderBy.length ? `.sort(${printShell(orderDocument(orderBy, items, false, aliases, from))})` : "", offset ? `.skip(${offset})` : "", limit !== undefined ? `.limit(${limit})` : ""].join("");
+ return `${mongoCall(from, "find", args)}${chain}`;
+ }
+ if (items.some((item) => item.type === "agg") && !groupBy) {
+ const onlyCount = items.length === 1 && items[0]?.fn === "count" && items[0].star && !items[0].alias;
+ if (onlyCount && !orderBy.length && limit === undefined && offset === undefined && joins.length === 0) {
+ const filter = where ? exprToFilter(where, aliases) : {};
+ return mongoCall(from, "countDocuments", printShell(filter));
+ }
+ groupBy = [];
+ }
+ const pipeline: ShellValue[] = [];
+ const { base, rest } = where ? splitWhere(where, aliases, from, joins) : { base: undefined, rest: new Map<string, Expr>() };
+ if (base) pipeline.push({ $match: exprToFilter(base, aliases) });
+ for (const join of joins) {
+ const alias = join.table.alias ?? join.table.collection;
+ pipeline.push({
+ $lookup: {
+ from: join.table.collection,
+ localField: fieldPath(join.local, aliases, from).path,
+ foreignField: fieldPath(join.foreign, aliases, from).path,
+ as: alias,
+ },
+ });
+ pipeline.push({ $unwind: { path: `$${alias}`, preserveNullAndEmptyArrays: join.kind === "left" } });
+ const joined = rest.get((join.table.alias ?? "").toLowerCase()) ?? rest.get(join.table.collection.toLowerCase());
+ if (joined) pipeline.push({ $match: exprToFilter(joined, aliases, { qualifyJoin: true }) });
+ }
+ if ([...rest.keys()].some((alias) => !joins.some((join) => (join.table.alias ?? "").toLowerCase() === alias || join.table.collection.toLowerCase() === alias))) {
+ throw new MongoSqlError("A WHERE condition refers to a collection that is not part of this query.");
+ }
+ if (groupBy) {
+ assertGroupedColumns(items, groupBy, aliases, from);
+ pipeline.push({ $group: groupStage(items, groupBy, aliases, from) });
+ const project = groupProject(items, groupBy, aliases, from);
+ if (project) pipeline.push({ $project: project });
+ if (orderBy.length) pipeline.push({ $sort: orderDocument(orderBy, items, true, aliases, from, groupBy) });
+ } else {
+ if (orderBy.length) pipeline.push({ $sort: orderDocument(orderBy, items, false, aliases, from) });
+ if (joins.length && items.some((item) => item.type === "star")) {
+ const alias = joins[0]!.table.alias ?? joins[0]!.table.collection;
+ pipeline.push({ $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", `$${alias}`] } } });
+ pipeline.push({ $project: { [alias]: 0 } });
+ } else if (items.some((item) => item.type !== "star")) {
+ pipeline.push({ $project: projectStage(items, aliases, from) });
+ }
+ }
+ if (offset) pipeline.push({ $skip: offset });
+ if (limit !== undefined) pipeline.push({ $limit: limit });
+ return mongoCall(from, "aggregate", printShell(pipeline));
+}
+
+function projectionForFind(items: SelectItem[], aliases: AliasMap, from: TableRef): ShellValue | undefined {
+ if (items.some((item) => item.type === "star")) return undefined;
+ const projection: Record<string, ShellValue> = {};
+ let includesId = false;
+ for (const item of items) {
+ if (item.type !== "field" || !item.field) continue;
+ const resolved = fieldPath(item.field, aliases, from);
+ const path = qualifiedPath(resolved);
+ projection[path] = fieldHasIndex(item.field) ? arrayValueExpr(item.field, resolved) : 1;
+ if (path === "_id") includesId = true;
+ }
+ if (!includesId) projection._id = 0;
+ return projection;
+}
+
+function assertGroupedColumns(items: SelectItem[], groupBy: FieldRef[], aliases: AliasMap, from: TableRef) {
+ const grouped = new Set(groupBy.map((field) => fieldPath(field, aliases, from).path));
+ for (const item of items) {
+ if (item.type !== "field" || !item.field) continue;
+ const path = fieldPath(item.field, aliases, from).path;
+ if (!grouped.has(path)) {
+ throw new MongoSqlError(`Column ${expandedNames(item.field).join(".")} must appear in GROUP BY or inside an aggregate function.`);
+ }
+ }
+}
+
+function groupStage(items: SelectItem[], groupBy: FieldRef[], aliases: AliasMap, from: TableRef): ShellValue {
+ const id = groupId(groupBy, aliases, from);
+ const group: Record<string, ShellValue> = { _id: id };
+ const used = new Set<string>();
+ for (const item of items) {
+ if (item.type !== "agg" || !item.fn) continue;
+ const name = aggregateName(item, used);
+ if (item.field) rejectNegativeIndex(item.field, "an aggregate");
+ const path = item.star || !item.field ? undefined : `$${qualifiedPath(fieldPath(item.field, aliases, from))}`;
+ if (item.fn === "count") {
+ group[name] = item.star ? { $sum: 1 } : { $sum: { $cond: [{ $ne: [path, null] }, 1, 0] } };
+ } else {
+ if (!path) throw new MongoSqlError(`${item.fn.toUpperCase()}() requires a field.`);
+ group[name] = { [`$${item.fn}`]: path };
+ }
+ }
+ return group;
+}
+
+function groupId(groupBy: FieldRef[], aliases: AliasMap, from: TableRef): ShellValue {
+ if (groupBy.length === 0) return null;
+ for (const field of groupBy) rejectNegativeIndex(field, "GROUP BY");
+ if (groupBy.length === 1) return `$${qualifiedPath(fieldPath(groupBy[0]!, aliases, from))}`;
+ const id: Record<string, ShellValue> = {};
+ for (const field of groupBy) {
+ const qualified = qualifiedPath(fieldPath(field, aliases, from));
+ assignGroupKey(id, qualified, `$${qualified}`);
+ }
+ return id;
+}
+
+function assignGroupKey(target: Record<string, ShellValue>, path: string, value: ShellValue) {
+ const parts = path.split(".");
+ let cursor = target;
+ for (let index = 0; index < parts.length - 1; index += 1) {
+ const part = parts[index]!;
+ const current = cursor[part];
+ if (current === undefined) {
+ const next: Record<string, ShellValue> = {};
+ cursor[part] = next;
+ cursor = next;
+ continue;
+ }
+ if (!isDoc(current)) throw new MongoSqlError("GROUP BY keys overlap.");
+ cursor = current;
+ }
+ const leaf = parts[parts.length - 1]!;
+ if (leaf in cursor) throw new MongoSqlError("GROUP BY keys overlap.");
+ cursor[leaf] = value;
+}
+
+function groupProject(items: SelectItem[], groupBy: FieldRef[], aliases: AliasMap, from: TableRef): ShellValue | undefined {
+ if (groupBy.length !== 1) return undefined;
+ const grouped = fieldPath(groupBy[0]!, aliases, from).path.split(".").pop() ?? "";
+ const selected = items.filter((item) => item.type === "field");
+ if (selected.length === 0) return undefined;
+ const project: Record<string, ShellValue> = {};
+ for (const item of selected) {
+ const name = item.alias ?? item.field?.parts[item.field.parts.length - 1]?.name;
+ if (!name) continue;
+ project[name] = "$_id";
+ }
+ if (!(grouped in project) && selected.some((item) => (item.alias ?? item.field?.parts.at(-1)?.name) === grouped)) {
+ project[grouped] = "$_id";
+ }
+ const used = new Set<string>();
+ for (const item of items) {
+ if (item.type !== "agg") continue;
+ const name = aggregateName(item, used);
+ project[name] = 1;
+ }
+ project._id = 0;
+ return project;
+}
+
+function projectStage(items: SelectItem[], aliases: AliasMap, from: TableRef): ShellValue {
+ const project: Record<string, ShellValue> = {};
+ let includesId = false;
+ for (const item of items) {
+ if (item.type === "field" && item.field) {
+ const resolved = fieldPath(item.field, aliases, from);
+ const dotted = qualifiedPath(resolved);
+ const name = item.alias ?? (fieldHasIndex(item.field) ? dotted : (resolved.path.split(".").pop() ?? resolved.path));
+ const source = qualifiedPath(resolved);
+ project[name] = fieldHasIndex(item.field) ? arrayValueExpr(item.field, resolved) : item.alias || resolved.owner !== "base" ? `$${source}` : 1;
+ if (name === "_id") includesId = true;
+ }
+ }
+ if (!includesId) project._id = 0;
+ return project;
+}
+
+function aggregateName(item: SelectItem, used: Set<string>): string {
+ if (item.alias) {
+ used.add(item.alias);
+ return item.alias;
+ }
+ const base = item.fn === "count" && item.star ? "count" : `${item.fn}_${item.field?.parts.at(-1)?.name ?? "value"}`;
+ let name = base;
+ let n = 2;
+ while (used.has(name)) {
+ name = `${base}_${n}`;
+ n += 1;
+ }
+ used.add(name);
+ return name;
+}
+
+function orderDocument(orderBy: OrderKey[], items: SelectItem[], projectsFields: boolean, aliases: AliasMap, from: TableRef, groupBy?: FieldRef[]): ShellValue {
+ const sort: Record<string, ShellValue> = {};
+ for (const key of orderBy) sort[sortKey(key.field, items, projectsFields, aliases, from, groupBy)] = key.direction;
+ return sort;
+}
+
+function sortKey(field: FieldRef, items: SelectItem[], projectsFields: boolean, aliases: AliasMap, from: TableRef, groupBy?: FieldRef[]): string {
+ rejectNegativeIndex(field, "ORDER BY");
+ const resolved = fieldPath(field, aliases, from);
+ const full = qualifiedPath(resolved);
+ if (!projectsFields) {
+ const source = aliasSource(field, items);
+ return source ? qualifiedPath(fieldPath(source, aliases, from)) : full;
+ }
+ for (const item of items) {
+ if (item.alias && item.field && sameField(item.field, field)) return item.alias;
+ }
+ if (field.parts.length === 1 && field.parts[0]!.indexes.length === 0) {
+ const alias = items.find((item) => item.alias === field.parts[0]!.name);
+ if (alias?.alias) return alias.alias;
+ }
+ if (groupBy && groupBy.length > 1) return `_id.${full}`;
+ if (fieldHasIndex(field)) return full;
+ return resolved.path.split(".").pop() ?? full;
+}
+
+function aliasSource(field: FieldRef, items: SelectItem[]): FieldRef | undefined {
+ if (field.parts.length !== 1 || field.parts[0]!.indexes.length !== 0) return undefined;
+ return items.find((item) => item.alias === field.parts[0]!.name && item.field)?.field;
+}
+
+function qualifiedPath(resolved: ResolvedField): string {
+ return resolved.owner === "base" ? resolved.path : `${resolved.owner}.${resolved.path}`;
+}
+
+function rejectNegativeIndex(field: FieldRef, clause: string) {
+ if (field.parts.some((part) => part.indexes.some((index) => index < 0))) {
+ throw new MongoSqlError(`Negative array indexes are not supported in ${clause}.`);
+ }
+}
+
+function sameField(left: FieldRef, right: FieldRef): boolean {
+ return expandedNames(left).join(".") === expandedNames(right).join(".");
+}
+
+interface AliasMap {
+ base: TableRef;
+ joins: Map<string, TableRef>;
+}
+
+function aliasMap(base: TableRef, joins: Join[]): AliasMap {
+ const map = new Map<string, TableRef>();
+ for (const join of joins) {
+ map.set((join.table.alias ?? join.table.collection).toLowerCase(), join.table);
+ map.set(join.table.collection.toLowerCase(), join.table);
+ }
+ return { base, joins: map };
+}
+
+interface ResolvedField {
+ owner: "base" | string;
+ path: string;
+}
+
+function expandedNames(field: FieldRef): string[] {
+ const names: string[] = [];
+ for (const part of field.parts) {
+ names.push(part.name);
+ for (const index of part.indexes) names.push(String(index));
+ }
+ return names;
+}
+
+function fieldHasIndex(field: FieldRef): boolean {
+ return field.parts.some((part) => part.indexes.length > 0);
+}
+
+function applyArrayIndexes(expr: ShellValue, indexes: number[]): ShellValue {
+ for (const index of indexes) expr = { $arrayElemAt: [expr, index] };
+ return expr;
+}
+
+/** Positional projection. Inclusion `{ "items.0.name": 1 }` does not select the array element. */
+function arrayValueExpr(field: FieldRef, resolved: ResolvedField): ShellValue {
+ const parts = stripQualifier(field, resolved);
+ const head = parts[0];
+ if (!head) throw new MongoSqlError("Array index requires a field.");
+ if (resolved.owner !== "base") {
+ let expr: ShellValue = `$${resolved.owner}`;
+ for (const part of parts) {
+ expr = { $getField: { field: part.name, input: expr } };
+ expr = applyArrayIndexes(expr, part.indexes);
+ }
+ return expr;
+ }
+ let expr: ShellValue = `$${head.name}`;
+ expr = applyArrayIndexes(expr, head.indexes);
+ for (const part of parts.slice(1)) {
+ expr = { $getField: { field: part.name, input: expr } };
+ expr = applyArrayIndexes(expr, part.indexes);
+ }
+ return expr;
+}
+
+function stripQualifier(field: FieldRef, resolved: ResolvedField): FieldPart[] {
+ if (resolved.owner !== "base") return field.parts.slice(1);
+ if (expandedNames(field).join(".") !== resolved.path && field.parts.length > 1) return field.parts.slice(1);
+ return field.parts;
+}
+
+function fieldPath(field: FieldRef, aliases: AliasMap, from: TableRef): ResolvedField {
+ const names = expandedNames(field);
+ const baseNames = new Set([from.alias?.toLowerCase(), from.collection.toLowerCase()].filter((name): name is string => !!name));
+ if (names.length === 1) return { owner: "base", path: names[0]! };
+ const head = names[0]!.toLowerCase();
+ const path = names.slice(1).join(".");
+ if (baseNames.has(head)) return { owner: "base", path };
+ const joined = aliases.joins.get(head);
+ if (joined) return { owner: joined.alias ?? joined.collection, path };
+ return { owner: "base", path: names.join(".") };
+}
+
+function exprToFilter(expr: Expr, aliases: AliasMap, options?: { qualifyJoin?: boolean }): ShellValue {
+ if (expr.type === "and") return mergeAnd(expr.items.map((item) => exprToFilter(item, aliases, options)));
+ if (expr.type === "or") return { $or: expr.items.map((item) => exprToFilter(item, aliases, options)) };
+ if (expr.type === "not") return { $nor: [exprToFilter(expr.item, aliases, options)] };
+ if (expr.type === "null") {
+ const key = filterKey(expr.field, aliases, options);
+ return expr.negated ? { [key]: { $ne: null } } : { [key]: null };
+ }
+ if (expr.type === "in") {
+ const key = filterKey(expr.field, aliases, options);
+ return { [key]: { [expr.negated ? "$nin" : "$in"]: expr.values } };
+ }
+ if (expr.type === "between") {
+ const key = filterKey(expr.field, aliases, options);
+ const range = { $gte: expr.low, $lte: expr.high };
+ return expr.negated ? { [key]: { $not: range } } : { [key]: range };
+ }
+ if (expr.type === "like") {
+ const key = filterKey(expr.field, aliases, options);
+ const regex: Record<string, ShellValue> = { $regex: likeToRegex(expr.pattern) };
+ if (expr.insensitive) regex.$options = "i";
+ return expr.negated ? { [key]: { $not: regex } } : { [key]: regex };
+ }
+ return comparisonToFilter(expr, aliases, options);
+}
+
+function comparisonToFilter(expr: Extract<Expr, { type: "cmp" }>, aliases: AliasMap, options?: { qualifyJoin?: boolean }): ShellValue {
+ const mongoOp = expr.op === "=" ? undefined : expr.op === "!=" ? "$ne" : expr.op === ">" ? "$gt" : expr.op === "<" ? "$lt" : expr.op === ">=" ? "$gte" : "$lte";
+ const leftField = expr.left.type === "field";
+ const rightField = expr.right.type === "field";
+ if (leftField && rightField) {
+ const left = `$${filterKey(expr.left.field, aliases, options)}`;
+ const right = `$${filterKey(expr.right.field, aliases, options)}`;
+ const op = mongoOp ?? "$eq";
+ return { $expr: { [op]: [left, right] } };
+ }
+ if (!leftField && !rightField) throw new MongoSqlError("A comparison needs a field.");
+ const field = leftField ? expr.left.field : expr.right.field;
+ const value = leftField ? (expr.right as Extract<Primary, { type: "value" }>).value : (expr.left as Extract<Primary, { type: "value" }>).value;
+ let op = mongoOp;
+ if (!leftField && op) {
+ op = op === "$gt" ? "$lt" : op === "$lt" ? "$gt" : op === "$gte" ? "$lte" : op === "$lte" ? "$gte" : op;
+ }
+ const key = filterKey(field, aliases, options);
+ if (!op) return { [key]: value };
+ return { [key]: { [op]: value } };
+}
+
+function filterKey(field: FieldRef, aliases: AliasMap, options?: { qualifyJoin?: boolean }): string {
+ rejectNegativeIndex(field, "WHERE");
+ const resolved = fieldPath(field, aliases, aliases.base);
+ if (options?.qualifyJoin && resolved.owner !== "base") return `${resolved.owner}.${resolved.path}`;
+ return resolved.path;
+}
+
+function mergeAnd(parts: ShellValue[]): ShellValue {
+ const merged: Record<string, ShellValue> = {};
+ const extras: ShellValue[] = [];
+ for (const part of parts) {
+ if (!isDoc(part)) {
+ extras.push(part);
+ continue;
+ }
+ for (const [key, value] of Object.entries(part)) {
+ if (!(key in merged)) {
+ merged[key] = value;
+ continue;
+ }
+ const combined = combineField(merged[key]!, value);
+ if (combined) merged[key] = combined;
+ else extras.push({ [key]: value });
+ }
+ }
+ if (!extras.length) return merged;
+ const clauses = [merged, ...extras].filter((part) => !isDoc(part) || Object.keys(part).length > 0);
+ return { $and: clauses };
+}
+
+function combineField(existing: ShellValue, incoming: ShellValue): ShellValue | null {
+ if (!isDoc(existing) || !isDoc(incoming)) return null;
+ const existingKeys = Object.keys(existing);
+ const incomingKeys = Object.keys(incoming);
+ if (!existingKeys.every((key) => key.startsWith("$")) || !incomingKeys.every((key) => key.startsWith("$"))) return null;
+ if (incomingKeys.some((key) => key in existing)) return null;
+ return { ...existing, ...incoming };
+}
+
+function isDoc(value: ShellValue): value is { [key: string]: ShellValue } {
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof ShellCtor);
+}
+
+function splitWhere(expr: Expr, aliases: AliasMap, from: TableRef, joins: Join[]): { base?: Expr; rest: Map<string, Expr> } {
+ const conjuncts = expr.type === "and" ? expr.items : [expr];
+ let base: Expr | undefined;
+ const rest = new Map<string, Expr>();
+ for (const item of conjuncts) {
+ const owners = exprOwners(item, aliases, from);
+ if (owners.size > 1) {
+ throw new MongoSqlError("MongoDB SQL mode cannot split one condition across collections. AND each comparison separately.");
+ }
+ const owner = [...owners][0];
+ if (!owner || owner === "base") base = base ? { type: "and", items: [base, item] } : item;
+ else {
+ const key = owner.toLowerCase();
+ const current = rest.get(key);
+ rest.set(key, current ? { type: "and", items: [current, item] } : item);
+ }
+ }
+ if (joins.length === 0 && rest.size > 0) throw new MongoSqlError("WHERE refers to a collection that is not in FROM.");
+ return { base, rest };
+}
+
+function exprOwners(expr: Expr, aliases: AliasMap, from: TableRef): Set<string> {
+ const owners = new Set<string>();
+ const visitField = (field: FieldRef) => {
+ const resolved = fieldPath(field, aliases, from);
+ owners.add(resolved.owner === "base" ? "base" : resolved.owner);
+ };
+ const visit = (node: Expr) => {
+ if (node.type === "and" || node.type === "or") node.items.forEach(visit);
+ else if (node.type === "not") visit(node.item);
+ else if (node.type === "cmp") {
+ if (node.left.type === "field") visitField(node.left.field);
+ if (node.right.type === "field") visitField(node.right.field);
+ } else visitField(node.field);
+ };
+ visit(expr);
+ return owners;
+}
+
+function likeToRegex(pattern: string): string {
+ let out = "^";
+ for (let i = 0; i < pattern.length; i += 1) {
+ const ch = pattern[i]!;
+ if (ch === "%") out += ".*";
+ else if (ch === "_") out += ".";
+ else if ("\\^$.*+?()[]{}|".includes(ch)) out += `\\${ch}`;
+ else out += ch;
+ }
+ return `${out}$`;
+}
+
+function mongoCall(table: TableRef, method: string, args: string): string {
+ const collection = /^[A-Za-z_$][\w$]*$/.test(table.collection) ? `.${table.collection}` : `.getCollection(${JSON.stringify(table.collection)})`;
+ const db = table.database ? `db.getSiblingDB(${JSON.stringify(table.database)})` : "db";
+ return `${db}${collection}.${method}(${args})`;
+}
+
+function printShell(value: ShellValue): string {
+ if (value instanceof ShellCtor) return `${value.name}(${JSON.stringify(value.arg)})`;
+ if (value === null) return "null";
+ if (typeof value === "boolean") return value ? "true" : "false";
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
+ if (typeof value === "string") return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(printShell).join(", ")}]`;
+ const entries = Object.entries(value);
+ if (!entries.length) return "{}";
+ return `{ ${entries.map(([key, entry]) => `${shellKey(key)}: ${printShell(entry)}`).join(", ")} }`;
+}
+
+function shellKey(key: string): string {
+ return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
+}
diff --git a/apps/desktop/src/lib/sql/sqlExecutionTarget.ts b/apps/desktop/src/lib/sql/sqlExecutionTarget.ts
index 630c02bc13..681283735a 100644
--- a/apps/desktop/src/lib/sql/sqlExecutionTarget.ts
+++ b/apps/desktop/src/lib/sql/sqlExecutionTarget.ts
@@ -1,5 +1,6 @@
import * as api from "@/lib/backend/api";
-import { mongoCommandRangeAtCursor } from "@/lib/sql/sqlStatementRanges";
+import { mongoCommandRangeAtCursor, statementRangeAtCursor } from "@/lib/sql/sqlStatementRanges";
+import type { MongoQueryLanguage } from "@/lib/mongo/mongoSql";
import type { DatabaseType } from "@/types/database";
export type ExecuteMode = "all" | "current";
@@ -60,10 +61,17 @@ export function resolveExecutableSql(fullSql: string, selectedSql: string, optio
return fullSql;
}
-export async function resolveExecutableSqlWithBackend(fullSql: string, selectedSql: string, options?: { mode?: ExecuteMode; cursorPos?: number; databaseType?: DatabaseType }): Promise<string> {
+export async function resolveExecutableSqlWithBackend(fullSql: string, selectedSql: string, options?: { mode?: ExecuteMode; cursorPos?: number; databaseType?: DatabaseType; mongoQueryLanguage?: MongoQueryLanguage }): Promise<string> {
const trimmedSelection = selectedSql.trim();
if (trimmedSelection) return trimmedSelection;
+ if (options?.databaseType === "mongodb" && options.mongoQueryLanguage === "sql") {
+ if (options.mode === "current" && options.cursorPos !== undefined) {
+ return statementRangeAtCursor(fullSql, options.cursorPos)?.sql ?? fullSql;
+ }
+ return fullSql;
+ }
+
if (options?.databaseType === "mongodb") {
if (options.mode === "current" && options.cursorPos !== undefined) {
return mongoCommandRangeAtCursor(fullSql, options.cursorPos)?.sql ?? fullSql;
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index a604090abd..1d76800749 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -79,6 +79,7 @@ import {
splitSiblingDbPrefix,
type MongoAggregateSafetyOptions,
} from "@/lib/mongo/mongoShellCommand";
+import { prepareMongoQueryText, type MongoQueryLanguage } from "@/lib/mongo/mongoSql";
import { refreshLoadedMongoIndexes } from "@/lib/mongo/mongoIndexMetadata";
import { redisCommandResultToQueryResult } from "@/lib/redis/redisQueryResult";
import { nextRedisCommandDb } from "@/lib/redis/redisCommandSession";
@@ -6170,6 +6171,12 @@ export const useQueryStore = defineStore("query", () => {
return start;
}
+ function setMongoQueryLanguage(id: string, language: MongoQueryLanguage) {
+ const tab = tabs.value.find((item) => item.id === id);
+ if (!tab || tab.mongoQueryLanguage === language) return;
+ tab.mongoQueryLanguage = language === "sql" ? "sql" : undefined;
+ }
+
function setAutoCommit(id: string, autoCommit: boolean) {
const tab = tabs.value.find((t) => t.id === id);
if (tab) {
@@ -8271,7 +8278,7 @@ export const useQueryStore = defineStore("query", () => {
sourceTraceId: options?.sourceTraceId,
sqlLength: sql.length,
});
- const queryBaseSql = options?.resultBaseSql ?? sql;
+ let queryBaseSql = options?.resultBaseSql ?? sql;
let sqlToExecute = sql;
let resultSortedSql = options?.resultSortedSql;
let queryMetadataSql = queryBaseSql;
@@ -8313,7 +8320,22 @@ export const useQueryStore = defineStore("query", () => {
const executionTarget = resumedExecutionTarget ?? options?.executionTarget;
const usesExternalExecutionTarget = !!executionTarget;
let conn = connStore.getConfig(executionConnectionId);
- const parsedMongoCommands = conn?.db_type === "mongodb" ? splitMongoCommandRanges(sql) : undefined;
+ let mongoGeneratedShell: string | undefined;
+ let mongoSqlConsidered = false;
+ const applyMongoSql = (dbType: string | undefined) => {
+ if (mongoSqlConsidered || dbType !== "mongodb") return;
+ mongoSqlConsidered = true;
+ const prepared = prepareMongoQueryText(sqlToExecute, tab.mongoQueryLanguage, dbType, tab.mongoGeneratedShell);
+ if (!prepared.generatedShell) return;
+ mongoGeneratedShell = prepared.generatedShell;
+ sqlToExecute = prepared.sql;
+ queryBaseSql = prepared.sql;
+ queryMetadataSql = prepared.sql;
+ tab.lastExecutedSql = prepared.sql;
+ tab.mongoGeneratedShell = prepared.sql;
+ };
+ applyMongoSql(conn?.db_type);
+ const parsedMongoCommands = conn?.db_type === "mongodb" ? splitMongoCommandRanges(sqlToExecute) : undefined;
let mongoCommands = parsedMongoCommands ?? [];
const mongoNeedsConnection = mongoCommands.some(({ command }) => command.kind !== "use");
@@ -8332,7 +8354,8 @@ export const useQueryStore = defineStore("query", () => {
}
conn = connStore.getConfig(executionConnectionId);
if (parsedMongoCommands === undefined && conn?.db_type === "mongodb") {
- mongoCommands = splitMongoCommandRanges(sql);
+ applyMongoSql(conn.db_type);
+ mongoCommands = splitMongoCommandRanges(sqlToExecute);
}
const effectiveDbType = effectiveDatabaseTypeForConnection(conn);
if (effectiveDbType === "mysql") {
@@ -8552,6 +8575,9 @@ export const useQueryStore = defineStore("query", () => {
const commandTiming = createQueryRequestTiming(commandIndex === 0 ? startedAt : commandStartedAt);
const annotateMongoResult = (result: QueryResult): QueryResult => {
const annotated = annotateQueryResultSource(result, sourceStatement, undefined, undefined, sourceRange);
+ if (mongoGeneratedShell) {
+ annotated.messages = [...(annotated.messages ?? []), { severity: "INFO", code: "mongo-shell", message: sourceStatement }];
+ }
if ("collection" in mongoCommand) {
annotated.sourceQualifier = currentDatabase || undefined;
annotated.sourceName = mongoCommand.collection;
@@ -11756,6 +11782,7 @@ export const useQueryStore = defineStore("query", () => {
updateObjectBrowserFilter,
updateDatabaseSearchState,
updateNacosConfigEditorViewport,
+ setMongoQueryLanguage,
setAutoCommit,
markManualTransactionDirty,
commitTransaction,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 8570286e82..0493b50f6b 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -2972,6 +2972,13 @@ export interface QueryTab {
collection: string;
idColumn: "_id";
};
+ /**
+ * MongoDB query tabs only. "sql" compiles the editor text to a mongo-shell
+ * command before the existing execution path runs it. Absent means shell.
+ */
+ mongoQueryLanguage?: "shell" | "sql";
+ /** Shell text produced by the latest SQL-mode execution. Not persisted. */
+ mongoGeneratedShell?: string;
mongoBucket?: {
bucketName: string;
};