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(salesforce): add Salesforce SOQL data source

邹超f87b5d15681a
diff --git a/apps/desktop/public/icons/database/salesforce.svg b/apps/desktop/public/icons/database/salesforce.svg
new file mode 100644
index 0000000000..7281c0b676
--- /dev/null
+++ b/apps/desktop/public/icons/database/salesforce.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="Salesforce">
+ <path fill="#00A1E0" d="M82 60c4.5-11 15.5-19 28-19 10 0 19 5 24 13 3-1 6-2 9-2 13 0 23 10 23 23 0 2 0 3-.5 5 9 4 15 13 15 23 0 15-12 27-27 27H58c-18 0-33-15-33-33 0-16 12-30 27-33 3-12 15-21 28-21 1 0 2 0 2 0Z"/>
+</svg>
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index fb5874c614..d027c013c5 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -36,6 +36,8 @@ import type {
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES, CONNECTION_PROFILE_ICONS, type ConnectionPickerOption, type ConnectionProfileCategory, type ConnectionProfileDefinition } from "@/types/generated/connectionProfiles";
import type { InfluxDbExternalConfig, InfluxDbVersion } from "@/types/influxdb";
import type { VictoriaMetricsExternalConfig } from "@/types/victoriametrics";
+import type { SalesforceAuthContext, SalesforceAuthMode, SalesforceEnvironment, SalesforceExternalConfig, SalesforceOAuthAuthorizeParams, SalesforceOAuthDevicePollResult } from "@/types/salesforce";
+import { SALESFORCE_OAUTH_CALLBACK_URL } from "@/types/salesforce";
import type { MqAdminConfig, MqAuth, MqSystemKind } from "@/types/mq";
import type { MqttConnectionConfig } from "@/types/mqtt";
import type { NacosAdminConfig, NacosApiPlane, NacosAuthConfig, NacosImplementation, NacosMetricsMode, NacosNamespaceInfo, NacosRNacosConsoleAuth, NacosVersionMode } from "@/types/nacos";
@@ -1574,6 +1576,390 @@ function buildVictoriaMetricsExternalConfig(): VictoriaMetricsExternalConfig {
return { apiPath, lookback };
}
+// ---------------------------------------------------------------------------
+// Salesforce OAuth / device-code flow state
+// ---------------------------------------------------------------------------
+
+const salesforceAuthMode = ref<SalesforceAuthMode>("token");
+const salesforceEnvironment = ref<SalesforceEnvironment>("production");
+const salesforceLoginUrl = ref("");
+const salesforceClientId = ref("");
+const salesforceClientSecret = ref("");
+// Username-password (ROPC) mode credentials. The password is never
+// round-tripped from the backend; blank on edit unless re-typed.
+const salesforceUsername = ref("");
+const salesforceUserPassword = ref("");
+
+const salesforceOauthRunning = ref(false);
+const salesforceOauthError = ref("");
+const salesforceOauthSuccess = ref("");
+// When editing an existing connection whose credentials live in the backend's
+// secret store, refreshToken/clientSecret are intentionally not sent back to
+// the UI. Track "we have previously authorized" separately from whether we
+// still hold the tokens in-memory so the form can show a status chip.
+const salesforceOauthPreviouslyAuthorized = ref(false);
+
+type SalesforceDevicePhase = "idle" | "polling" | "success" | "expired" | "denied" | "error";
+const salesforceDevicePhase = ref<SalesforceDevicePhase>("idle");
+const salesforceDeviceUserCode = ref("");
+const salesforceDeviceVerificationUri = ref("");
+const salesforceDeviceCode = ref("");
+const salesforceDeviceIntervalSecs = ref(5);
+const salesforceDeviceSecondsLeft = ref(0);
+const salesforceDeviceError = ref("");
+const salesforceDeviceUserCodeCopied = ref(false);
+const salesforceDeviceVerificationCopied = ref(false);
+
+let salesforceDevicePollTimer: ReturnType<typeof setTimeout> | null = null;
+let salesforceDevicePollAbortId = 0;
+let salesforceDeviceExpiresTimer: ReturnType<typeof setInterval> | null = null;
+
+function salesforceAuthModeFromConfig(externalConfig: unknown, fallbackPassword?: string): SalesforceAuthMode {
+ const cfg = (externalConfig as SalesforceExternalConfig | undefined) ?? undefined;
+ const mode = cfg?.auth?.mode;
+ if (mode === "oauth" || mode === "device" || mode === "password") return mode;
+ if (cfg?.auth && (cfg.auth.refreshToken || cfg.auth.clientId || cfg.auth.authorizedAt)) return "oauth";
+ // No persisted auth context: if a password/token is present, treat as manual token.
+ if (fallbackPassword?.trim()) return "token";
+ return "token";
+}
+
+function resetSalesforceOAuthFields(externalConfig?: unknown, fallbackPassword?: string) {
+ const cfg = (externalConfig as SalesforceExternalConfig | undefined) ?? undefined;
+ const auth = cfg?.auth;
+ salesforceAuthMode.value = salesforceAuthModeFromConfig(externalConfig, fallbackPassword);
+ salesforceEnvironment.value = (auth?.environment as SalesforceEnvironment) || "production";
+ salesforceLoginUrl.value = auth?.loginUrl?.trim() || "";
+ salesforceClientId.value = auth?.clientId?.trim() || "";
+ // Client secret is never round-tripped from the backend for security; the
+ // input is blank on edit and only sent when the user re-types it.
+ salesforceClientSecret.value = "";
+ salesforceUsername.value = auth?.username?.trim() || "";
+ salesforceUserPassword.value = "";
+ salesforceOauthRunning.value = false;
+ salesforceOauthError.value = "";
+ salesforceOauthSuccess.value = "";
+ // A Client ID alone only means the form was filled in, not that anybody ever
+ // signed in; claiming "authorized" from it showed a false reassurance banner.
+ salesforceOauthPreviouslyAuthorized.value = !!(auth?.refreshToken || auth?.authorizedAt);
+ salesforceDevicePhase.value = "idle";
+ salesforceDeviceUserCode.value = "";
+ salesforceDeviceVerificationUri.value = "";
+ salesforceDeviceCode.value = "";
+ salesforceDeviceIntervalSecs.value = 5;
+ salesforceDeviceSecondsLeft.value = 0;
+ salesforceDeviceError.value = "";
+ salesforceDeviceUserCodeCopied.value = false;
+ salesforceDeviceVerificationCopied.value = false;
+ salesforceDeviceStopPolling();
+}
+
+function hydrateSalesforceOAuthFields(value: unknown, fallbackPassword?: string) {
+ resetSalesforceOAuthFields(value, fallbackPassword);
+}
+
+function salesforceBuildAuthorizeParams(): SalesforceOAuthAuthorizeParams {
+ const clientId = salesforceClientId.value.trim();
+ if (!clientId) throw new Error(t("connection.salesforceOauthClientIdRequired"));
+ const environment = salesforceEnvironment.value;
+ const loginUrl = environment === "custom" ? salesforceLoginUrl.value.trim() : undefined;
+ if (environment === "custom" && !loginUrl) {
+ throw new Error(t("connection.salesforceOauthLoginUrlRequired"));
+ }
+ const clientSecret = salesforceClientSecret.value.trim() || undefined;
+ return { environment, loginUrl, clientId, clientSecret };
+}
+
+function salesforceApplyTokenToForm(token: { accessToken: string; instanceUrl: string }) {
+ form.value.password = token.accessToken;
+ // The backend normalizes bare hostnames; we mirror it so the card preview
+ // shows the final instance URL even before the backend canonicalizes it.
+ let instanceUrl = token.instanceUrl.trim();
+ if (instanceUrl && !/^https?:\/\//i.test(instanceUrl)) {
+ instanceUrl = `https://${instanceUrl.replace(/\/+$/, "")}`;
+ }
+ if (instanceUrl) {
+ form.value.host = instanceUrl.replace(/\/+$/, "");
+ }
+}
+
+function salesforceBuildAuthContext(mode: SalesforceAuthMode, token?: { refreshToken?: string }): SalesforceAuthContext | undefined {
+ if (mode === "token") return undefined;
+ const context: SalesforceAuthContext = {
+ mode,
+ environment: salesforceEnvironment.value,
+ clientId: salesforceClientId.value.trim() || undefined,
+ authorizedAt: new Date().toISOString(),
+ };
+ if (salesforceEnvironment.value === "custom") {
+ context.loginUrl = salesforceLoginUrl.value.trim() || undefined;
+ }
+ // Only forward the client secret when the user explicitly typed it in this
+ // session — otherwise we would overwrite the backend-stored secret with "".
+ if (salesforceClientSecret.value.trim()) {
+ context.clientSecret = salesforceClientSecret.value.trim();
+ }
+ if (mode === "password") {
+ context.username = salesforceUsername.value.trim() || undefined;
+ if (salesforceUserPassword.value) {
+ context.password = salesforceUserPassword.value;
+ }
+ }
+ if (token?.refreshToken) {
+ context.refreshToken = token.refreshToken;
+ }
+ return context;
+}
+
+function salesforceMergeAuthIntoExternalConfig(mode: SalesforceAuthMode, token?: { refreshToken?: string }) {
+ const existing = (form.value.external_config && typeof form.value.external_config === "object" ? (form.value.external_config as Record<string, unknown>) : {}) as SalesforceExternalConfig & Record<string, unknown>;
+ const auth = salesforceBuildAuthContext(mode, token);
+ if (!auth) {
+ const { auth: _dropped, ...rest } = existing;
+ form.value.external_config = Object.keys(rest).length > 0 ? rest : undefined;
+ return;
+ }
+ // Preserve an existing refreshToken when the user re-authorizes without the
+ // backend returning a new one (e.g. refresh flow that omits a rotation).
+ if (!auth.refreshToken && existing.auth?.refreshToken) {
+ auth.refreshToken = existing.auth.refreshToken;
+ }
+ // Same for the ROPC password: it is not round-tripped for display, so an
+ // edit-without-retype must not clobber the stored credential.
+ if (!auth.password && existing.auth?.password) {
+ auth.password = existing.auth.password;
+ }
+ form.value.external_config = { ...existing, auth };
+}
+
+async function salesforceStartBrowserAuthorize() {
+ salesforceOauthError.value = "";
+ salesforceOauthSuccess.value = "";
+ salesforceOauthPreviouslyAuthorized.value = false;
+ let params: SalesforceOAuthAuthorizeParams;
+ try {
+ params = salesforceBuildAuthorizeParams();
+ } catch (e) {
+ salesforceOauthError.value = errorMessage(e);
+ return;
+ }
+ salesforceOauthRunning.value = true;
+ try {
+ const token = await api.salesforceOauthBrowserAuthorize(params);
+ salesforceApplyTokenToForm(token);
+ salesforceMergeAuthIntoExternalConfig("oauth", token);
+ salesforceOauthSuccess.value = t("connection.salesforceOauthSuccess", { instanceUrl: token.instanceUrl });
+ salesforceOauthPreviouslyAuthorized.value = true;
+ } catch (e) {
+ salesforceOauthError.value = errorMessage(e);
+ } finally {
+ salesforceOauthRunning.value = false;
+ }
+}
+
+async function salesforceStartPasswordLogin() {
+ salesforceOauthError.value = "";
+ salesforceOauthSuccess.value = "";
+ salesforceOauthPreviouslyAuthorized.value = false;
+ let params: SalesforceOAuthAuthorizeParams;
+ try {
+ params = salesforceBuildAuthorizeParams();
+ } catch (e) {
+ salesforceOauthError.value = errorMessage(e);
+ return;
+ }
+ const username = salesforceUsername.value.trim();
+ if (!username) {
+ salesforceOauthError.value = t("connection.salesforceUsernameRequired");
+ return;
+ }
+ if (!salesforceUserPassword.value) {
+ salesforceOauthError.value = t("connection.salesforceUserPasswordRequired");
+ return;
+ }
+ salesforceOauthRunning.value = true;
+ try {
+ const token = await api.salesforceOauthPasswordLogin(params, username, salesforceUserPassword.value);
+ salesforceApplyTokenToForm(token);
+ salesforceMergeAuthIntoExternalConfig("password", token);
+ salesforceOauthSuccess.value = t("connection.salesforceOauthSuccess", { instanceUrl: token.instanceUrl });
+ salesforceOauthPreviouslyAuthorized.value = true;
+ } catch (e) {
+ salesforceOauthError.value = errorMessage(e);
+ } finally {
+ salesforceOauthRunning.value = false;
+ }
+}
+
+function salesforceDeviceStopPolling() {
+ salesforceDevicePollAbortId++;
+ if (salesforceDevicePollTimer) {
+ clearTimeout(salesforceDevicePollTimer);
+ salesforceDevicePollTimer = null;
+ }
+ if (salesforceDeviceExpiresTimer) {
+ clearInterval(salesforceDeviceExpiresTimer);
+ salesforceDeviceExpiresTimer = null;
+ }
+}
+
+function salesforceDeviceStartExpiryCountdown(expiresInSecs: number) {
+ salesforceDeviceSecondsLeft.value = Math.max(0, Math.floor(expiresInSecs));
+ if (salesforceDeviceExpiresTimer) clearInterval(salesforceDeviceExpiresTimer);
+ salesforceDeviceExpiresTimer = setInterval(() => {
+ salesforceDeviceSecondsLeft.value = Math.max(0, salesforceDeviceSecondsLeft.value - 1);
+ if (salesforceDeviceSecondsLeft.value <= 0 && salesforceDevicePhase.value === "polling") {
+ salesforceDeviceStopPolling();
+ salesforceDevicePhase.value = "expired";
+ }
+ }, 1000);
+}
+
+async function salesforceDeviceRequestCode() {
+ salesforceOauthError.value = "";
+ salesforceOauthSuccess.value = "";
+ salesforceOauthPreviouslyAuthorized.value = false;
+ salesforceDeviceError.value = "";
+ salesforceDeviceUserCode.value = "";
+ salesforceDeviceVerificationUri.value = "";
+ salesforceDeviceUserCodeCopied.value = false;
+ salesforceDeviceVerificationCopied.value = false;
+ let params: SalesforceOAuthAuthorizeParams;
+ try {
+ params = salesforceBuildAuthorizeParams();
+ } catch (e) {
+ salesforceDeviceError.value = errorMessage(e);
+ salesforceDevicePhase.value = "error";
+ return;
+ }
+ salesforceOauthRunning.value = true;
+ salesforceDevicePhase.value = "idle";
+ try {
+ const start = await api.salesforceOauthDeviceStart(params);
+ salesforceDeviceUserCode.value = start.userCode;
+ salesforceDeviceVerificationUri.value = start.verificationUri;
+ salesforceDeviceCode.value = start.deviceCode;
+ salesforceDeviceIntervalSecs.value = Math.max(1, start.intervalSecs || 5);
+ salesforceDevicePhase.value = "polling";
+ salesforceDeviceStartExpiryCountdown(start.expiresInSecs);
+ await salesforceDevicePollLoop(params, start.deviceCode, salesforceDeviceIntervalSecs.value, salesforceDevicePollAbortId);
+ } catch (e) {
+ salesforceDeviceError.value = errorMessage(e);
+ salesforceDevicePhase.value = "error";
+ salesforceDeviceStopPolling();
+ } finally {
+ salesforceOauthRunning.value = false;
+ }
+}
+
+async function salesforceDevicePollLoop(params: SalesforceOAuthAuthorizeParams, deviceCode: string, intervalSecs: number, abortId: number): Promise<void> {
+ while (salesforceDevicePhase.value === "polling" && abortId === salesforceDevicePollAbortId) {
+ await new Promise<void>((resolve) => {
+ salesforceDevicePollTimer = setTimeout(() => resolve(), intervalSecs * 1000);
+ });
+ if (abortId !== salesforceDevicePollAbortId) return;
+ let result: SalesforceOAuthDevicePollResult;
+ try {
+ result = await api.salesforceOauthDevicePoll(params, deviceCode, intervalSecs);
+ } catch (e) {
+ // Transient network error: keep polling until the code expires.
+ if (salesforceDeviceSecondsLeft.value <= 0) {
+ salesforceDevicePhase.value = "expired";
+ salesforceDeviceStopPolling();
+ return;
+ }
+ salesforceDeviceError.value = errorMessage(e);
+ continue;
+ }
+ if (abortId !== salesforceDevicePollAbortId) return;
+ if (result.status === "pending") {
+ salesforceDeviceIntervalSecs.value = Math.max(1, result.intervalSecs || intervalSecs);
+ continue;
+ }
+ salesforceDeviceStopPolling();
+ if (result.status === "success") {
+ salesforceApplyTokenToForm(result.token);
+ salesforceMergeAuthIntoExternalConfig("device", result.token);
+ salesforceOauthSuccess.value = t("connection.salesforceOauthSuccess", { instanceUrl: result.token.instanceUrl });
+ salesforceOauthPreviouslyAuthorized.value = true;
+ salesforceDevicePhase.value = "success";
+ return;
+ }
+ if (result.status === "expired") {
+ salesforceDevicePhase.value = "expired";
+ return;
+ }
+ if (result.status === "denied") {
+ salesforceDeviceError.value = result.reason || t("connection.salesforceDeviceDenied");
+ salesforceDevicePhase.value = "denied";
+ return;
+ }
+ }
+}
+
+function salesforceDeviceCancel() {
+ salesforceDeviceStopPolling();
+ salesforceDevicePhase.value = "idle";
+ salesforceDeviceUserCode.value = "";
+ salesforceDeviceVerificationUri.value = "";
+ salesforceDeviceCode.value = "";
+}
+
+function salesforceDeviceRestart() {
+ salesforceDeviceCancel();
+ salesforceDeviceError.value = "";
+ salesforceOauthError.value = "";
+}
+
+async function salesforceCopyUserCode() {
+ if (!salesforceDeviceUserCode.value) return;
+ await copyToClipboard(salesforceDeviceUserCode.value);
+ salesforceDeviceUserCodeCopied.value = true;
+ setTimeout(() => {
+ salesforceDeviceUserCodeCopied.value = false;
+ }, 1500);
+}
+
+async function salesforceCopyVerificationUri() {
+ if (!salesforceDeviceVerificationUri.value) return;
+ await copyToClipboard(salesforceDeviceVerificationUri.value);
+ salesforceDeviceVerificationCopied.value = true;
+ setTimeout(() => {
+ salesforceDeviceVerificationCopied.value = false;
+ }, 1500);
+}
+
+function salesforceOpenVerificationPage() {
+ if (!salesforceDeviceVerificationUri.value) return;
+ // Same pattern as the update-flow "open release notes" action: defer to the
+ // shell helper that picks the right opener for desktop vs. web.
+ void (async () => {
+ try {
+ if (isDesktop) {
+ const { open } = await import("@tauri-apps/plugin-shell");
+ await open(salesforceDeviceVerificationUri.value);
+ } else {
+ globalThis.open(salesforceDeviceVerificationUri.value, "_blank", "noopener,noreferrer");
+ }
+ } catch (e) {
+ salesforceDeviceError.value = errorMessage(e);
+ }
+ })();
+}
+
+function salesforceSetAuthMode(mode: SalesforceAuthMode) {
+ // Switching modes resets any in-flight state so stale tokens from one flow
+ // never leak into another.
+ if (salesforceOauthRunning.value && mode !== salesforceAuthMode.value) return;
+ salesforceAuthMode.value = mode;
+ salesforceOauthError.value = "";
+ salesforceOauthSuccess.value = "";
+ if (mode !== "device") {
+ salesforceDeviceCancel();
+ salesforceDeviceError.value = "";
+ }
+}
+
watch(influxDbVersion, (version, previousVersion) => {
if (form.value.db_type !== "influxdb") return;
if (version === "2" || version === "3") {
@@ -2546,6 +2932,9 @@ function applyProfile(val: string, preserveConnectionFields = false) {
form.value.connection_string = undefined;
form.value.url_params = "";
}
+ if (profile.type === "salesforce") {
+ resetSalesforceOAuthFields(form.value.external_config, form.value.password);
+ }
resetHiveKerberosFields(profile.type === "hive" || profile.type === "argo" || profile.type === "kyuubi" || profile.type === "impala" ? form.value : undefined);
}
if (profile.type === "meilisearch") {
@@ -2777,6 +3166,11 @@ watch(
} else {
resetVictoriaMetricsFields();
}
+ if (config.db_type === "salesforce") {
+ hydrateSalesforceOAuthFields(config.external_config, config.password);
+ } else {
+ resetSalesforceOAuthFields(undefined, undefined);
+ }
resetElasticsearchProxyFields(config.db_type === "elasticsearch" ? config.external_config : undefined);
resetHiveKerberosFields(config.db_type === "hive" || config.db_type === "argo" || config.db_type === "kyuubi" || config.db_type === "impala" ? config : undefined);
resetDamengJvmOptions(config.db_type === "dameng" ? config : undefined);
@@ -4426,6 +4820,51 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
config.connection_string = undefined;
config.database = "metrics";
config.username = config.username.trim();
+ } else if (config.db_type === "salesforce") {
+ // Token-mode connections never carry auth context (the access token itself is
+ // the credential in `password`). OAuth/device modes merge the auth context
+ // into `external_config.auth`; the backend handles refreshToken encryption.
+ config.connection_string = undefined;
+ config.database = undefined;
+ config.username = config.username.trim();
+ const existing = (config.external_config && typeof config.external_config === "object" ? (config.external_config as Record<string, unknown>) : {}) as SalesforceExternalConfig & Record<string, unknown>;
+ if (salesforceAuthMode.value === "token") {
+ const { auth: _dropped, ...rest } = existing;
+ config.external_config = Object.keys(rest).length > 0 ? rest : undefined;
+ } else {
+ // Preserve an existing refreshToken/clientSecret when the user saves the
+ // form without re-authorizing or re-typing them (they're not round-tripped
+ // from the backend). The hydrate step flagged this via
+ // `salesforceOauthPreviouslyAuthorized`.
+ const auth: SalesforceAuthContext = {
+ mode: salesforceAuthMode.value,
+ environment: salesforceEnvironment.value,
+ clientId: salesforceClientId.value.trim() || existing.auth?.clientId,
+ authorizedAt: existing.auth?.authorizedAt,
+ };
+ if (salesforceEnvironment.value === "custom") {
+ auth.loginUrl = salesforceLoginUrl.value.trim() || existing.auth?.loginUrl;
+ }
+ if (salesforceClientSecret.value.trim()) {
+ auth.clientSecret = salesforceClientSecret.value.trim();
+ } else if (existing.auth?.clientSecret) {
+ // Preserve secret indicator without leaking the value to the client.
+ auth.clientSecret = existing.auth.clientSecret;
+ }
+ if (salesforceAuthMode.value === "password") {
+ auth.username = salesforceUsername.value.trim() || existing.auth?.username;
+ if (salesforceUserPassword.value) {
+ auth.password = salesforceUserPassword.value;
+ } else if (existing.auth?.password) {
+ // Stored ROPC credential (scrubbed into the backend secret store);
+ // keep it when the user edits the connection without retyping.
+ auth.password = existing.auth.password;
+ }
+ } else if (existing.auth?.refreshToken) {
+ auth.refreshToken = existing.auth.refreshToken;
+ }
+ config.external_config = { ...existing, auth };
+ }
} else if (config.db_type === "elasticsearch") {
config.external_config = buildElasticsearchExternalConfig(elasticsearchConnectionMode.value, elasticsearchKibanaBasePath.value, elasticsearchConnectivityCheckPath.value, elasticsearchIndexGroupingPattern.value, elasticsearchConnectivityCheckDisabled.value);
} else if (config.db_type === "meilisearch") {
@@ -5476,6 +5915,7 @@ function resetForm(options: { preservePickerState?: boolean } = {}) {
appliedConnectionUrlInput.value = "";
resetMeilisearchHostInput();
oracleTnsAdminPath.value = "";
+ resetSalesforceOAuthFields(undefined, undefined);
if (!options.preservePickerState) {
dialogStep.value = "select";
dbSearchQuery.value = "";
@@ -6366,6 +6806,9 @@ onMounted(async () => {
onUnmounted(() => {
unlistenAgentInstallProgress?.();
unlistenAgentInstallProgress = null;
+ // Stop any in-flight Salesforce device-code poll / expiry countdown so
+ // closing the dialog does not leave orphan timers running.
+ salesforceDeviceStopPolling();
});
function openExternalUrl(url: string) {
@@ -6521,7 +6964,7 @@ function openExternalUrl(url: string) {
<TabsContent value="connection" class="m-0 flex min-h-0 flex-1 flex-col overflow-hidden">
<div class="connection-form-body grid min-h-0 flex-1 scroll-pb-6 gap-4 overflow-y-auto pt-4 pr-2 pb-6" :class="{ 'connection-form-body--nacos': form.db_type === 'nacos' }">
- <div v-if="!isPluginConnection && !isJdbcConnection && form.db_type !== 'nacos' && form.db_type !== 'consul' && form.db_type !== 'mq'" class="grid grid-cols-4 items-center gap-4">
+ <div v-if="!isPluginConnection && !isJdbcConnection && form.db_type !== 'nacos' && form.db_type !== 'consul' && form.db_type !== 'mq' && form.db_type !== 'salesforce'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.connectionUrlOptional") }}</Label>
<div class="col-span-3 flex items-center gap-1">
<Input v-model="connectionUrlInput" class="flex-1" :placeholder="connectionUrlPlaceholder" @keydown.enter.prevent="applyConnectionUrl" />
@@ -7943,6 +8386,289 @@ function openExternalUrl(url: string) {
<CloudflareD1ConnectionFields v-model:account-id="form.host" v-model:database-id="form.database" v-model:api-token="form.password" />
</template>
+ <!-- Salesforce: instance URL + access token (SOQL) -->
+ <template v-else-if="form.db_type === 'salesforce'">
+ <!-- Instance URL (always visible so the user can confirm the
+ target org; OAuth/device flows overwrite it after a
+ successful authorize) -->
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.salesforceInstanceUrl") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <div class="flex gap-2">
+ <Input v-model="form.host" class="flex-1" :placeholder="t('connection.salesforceInstanceUrlPlaceholder')" />
+ <Input v-model.number="form.port" type="number" class="w-24 shrink-0" />
+ </div>
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceInstanceUrlHint") }}</p>
+ </div>
+ </div>
+
+ <!-- Authentication mode picker -->
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.salesforceAuthMode") }}</Label>
+ <div class="col-span-3 grid h-8 grid-cols-4 overflow-hidden rounded-md border border-input bg-muted/30 p-0.5">
+ <button
+ type="button"
+ class="h-7 rounded-sm px-2 text-xs transition-colors"
+ :class="salesforceAuthMode === 'token' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="salesforceAuthMode === 'token'"
+ :disabled="salesforceOauthRunning"
+ @click="salesforceSetAuthMode('token')"
+ >
+ {{ t("connection.salesforceAuthModeToken") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-2 text-xs transition-colors"
+ :class="salesforceAuthMode === 'oauth' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground disabled:text-muted-foreground/50'"
+ :aria-pressed="salesforceAuthMode === 'oauth'"
+ :disabled="salesforceOauthRunning || !isDesktop"
+ :title="!isDesktop ? t('connection.salesforceAuthModeOauthDesktopOnly') : undefined"
+ @click="salesforceSetAuthMode('oauth')"
+ >
+ {{ t("connection.salesforceAuthModeOauth") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-2 text-xs transition-colors"
+ :class="salesforceAuthMode === 'device' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="salesforceAuthMode === 'device'"
+ :disabled="salesforceOauthRunning"
+ @click="salesforceSetAuthMode('device')"
+ >
+ {{ t("connection.salesforceAuthModeDevice") }}
+ </button>
+ <button
+ type="button"
+ class="h-7 rounded-sm px-2 text-xs transition-colors"
+ :class="salesforceAuthMode === 'password' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'"
+ :aria-pressed="salesforceAuthMode === 'password'"
+ :disabled="salesforceOauthRunning"
+ @click="salesforceSetAuthMode('password')"
+ >
+ {{ t("connection.salesforceAuthModePassword") }}
+ </button>
+ </div>
+ </div>
+ <div v-if="!isDesktop && salesforceAuthMode === 'oauth'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceAuthModeOauthDesktopOnly") }}</p>
+ </div>
+
+ <!-- Manual access token -->
+ <template v-if="salesforceAuthMode === 'token'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.salesforceAccessToken") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="t('connection.salesforceAccessTokenPlaceholder')" />
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceAccessTokenHint") }}</p>
+ </div>
+ </template>
+
+ <!-- Shared OAuth / device-code fields -->
+ <template v-else>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.salesforceEnvironment") }}</Label>
+ <Select v-model="salesforceEnvironment" :disabled="salesforceOauthRunning">
+ <SelectTrigger class="col-span-3">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="production">{{ t("connection.salesforceEnvironmentProduction") }}</SelectItem>
+ <SelectItem value="sandbox">{{ t("connection.salesforceEnvironmentSandbox") }}</SelectItem>
+ <SelectItem value="custom">{{ t("connection.salesforceEnvironmentCustom") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div v-if="salesforceEnvironment === 'custom'" class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.salesforceLoginUrl") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input v-model="salesforceLoginUrl" :placeholder="t('connection.salesforceLoginUrlPlaceholder')" :disabled="salesforceOauthRunning" />
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceLoginUrlHint") }}</p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">
+ {{ t("connection.salesforceClientId") }}
+ <span class="ml-1 text-destructive">*</span>
+ </Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input v-model="salesforceClientId" :placeholder="t('connection.salesforceClientIdPlaceholder')" :disabled="salesforceOauthRunning" autocomplete="off" />
+ <!-- The callback URL only matters for the browser redirect flow; the
+ other two modes never see one, so keep it out of their way. -->
+ <p v-if="salesforceAuthMode === 'oauth'" class="text-xs leading-5 text-muted-foreground">
+ {{ t("connection.salesforceClientIdHint", { callbackUrl: SALESFORCE_OAUTH_CALLBACK_URL }) }}
+ </p>
+ <p v-else class="text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceClientIdHintShared") }}</p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.salesforceClientSecret") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <PasswordInput v-model="salesforceClientSecret" :placeholder="t('connection.salesforceClientSecretPlaceholder')" :disabled="salesforceOauthRunning" autocomplete="new-password" />
+ </div>
+ </div>
+
+ <!-- Username & password (ROPC) credentials -->
+ <template v-if="salesforceAuthMode === 'password'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.salesforceUsernameLabel") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <Input v-model="salesforceUsername" :placeholder="t('connection.salesforceUsernamePlaceholder')" :disabled="salesforceOauthRunning" autocomplete="off" />
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceUsernameHint") }}</p>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.salesforceUserPasswordLabel") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <PasswordInput v-model="salesforceUserPassword" :placeholder="t('connection.salesforceUserPasswordPlaceholder')" :disabled="salesforceOauthRunning" autocomplete="new-password" />
+ <p class="text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceUserPasswordHint") }}</p>
+ </div>
+ </div>
+ </template>
+
+ <!-- Previously-authorized banner (edit flow) -->
+ <div v-if="salesforceOauthPreviouslyAuthorized && !salesforceOauthRunning && salesforceDevicePhase !== 'polling'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs text-emerald-700 dark:text-emerald-300">
+ <ShieldCheck class="h-4 w-4 shrink-0" />
+ <span>{{ t("connection.salesforceOauthAuthorized") }}</span>
+ </div>
+ </div>
+
+ <!-- Browser OAuth action -->
+ <template v-if="salesforceAuthMode === 'oauth'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-2">
+ <Button type="button" :disabled="salesforceOauthRunning || !salesforceClientId.trim() || !isDesktop" @click="salesforceStartBrowserAuthorize">
+ <Loader2 v-if="salesforceOauthRunning" class="mr-2 h-4 w-4 animate-spin" />
+ {{ salesforceOauthRunning ? t("connection.salesforceOauthAuthorizing") : salesforceOauthPreviouslyAuthorized ? t("connection.salesforceOauthReauthorize") : t("connection.salesforceOauthAuthorize") }}
+ </Button>
+ </div>
+ </div>
+ <div v-if="salesforceOauthRunning" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceOauthAuthorizingHint") }}</p>
+ </div>
+ </template>
+
+ <!-- Username-password sign in -->
+ <template v-if="salesforceAuthMode === 'password'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-2">
+ <Button type="button" :disabled="salesforceOauthRunning || !salesforceClientId.trim() || !salesforceUsername.trim() || !salesforceUserPassword" @click="salesforceStartPasswordLogin">
+ <Loader2 v-if="salesforceOauthRunning" class="mr-2 h-4 w-4 animate-spin" />
+ {{ salesforceOauthRunning ? t("connection.salesforceOauthAuthorizing") : salesforceOauthPreviouslyAuthorized ? t("connection.salesforcePasswordSignInAgain") : t("connection.salesforcePasswordSignIn") }}
+ </Button>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforcePasswordRopcNote") }}</p>
+ </div>
+ </template>
+
+ <!-- Device-code flow -->
+ <template v-if="salesforceAuthMode === 'device'">
+ <div v-if="salesforceDevicePhase === 'idle' || salesforceDevicePhase === 'error'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-2">
+ <Button type="button" :disabled="salesforceOauthRunning || !salesforceClientId.trim()" @click="salesforceDeviceRequestCode">
+ <Loader2 v-if="salesforceOauthRunning" class="mr-2 h-4 w-4 animate-spin" />
+ {{ t("connection.salesforceDeviceGetCode") }}
+ </Button>
+ </div>
+ </div>
+ <div v-if="salesforceDevicePhase === 'idle' || salesforceDevicePhase === 'error'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceDeviceFlowNote") }}</p>
+ </div>
+
+ <template v-if="salesforceDevicePhase === 'polling'">
+ <div class="grid grid-cols-4 items-start gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.salesforceDeviceUserCodeLabel") }}</Label>
+ <div class="col-span-3 space-y-1.5">
+ <div class="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2">
+ <span class="font-mono text-lg font-semibold tracking-widest">{{ salesforceDeviceUserCode }}</span>
+ <Button type="button" variant="ghost" size="icon" class="h-7 w-7" @click="salesforceCopyUserCode">
+ <Check v-if="salesforceDeviceUserCodeCopied" class="h-4 w-4 text-emerald-600" />
+ <Copy v-else class="h-4 w-4" />
+ </Button>
+ </div>
+ <div v-if="salesforceDeviceVerificationUri" class="flex items-center gap-2 text-xs">
+ <a class="text-primary underline underline-offset-2 hover:no-underline" href="#" @click.prevent="salesforceOpenVerificationPage">{{ t("connection.salesforceDeviceOpenVerification") }}</a>
+ <code class="truncate rounded bg-muted px-1 py-0.5 text-[11px]">{{ salesforceDeviceVerificationUri }}</code>
+ <Button type="button" variant="ghost" size="icon" class="h-6 w-6" @click="salesforceCopyVerificationUri">
+ <Check v-if="salesforceDeviceVerificationCopied" class="h-3.5 w-3.5 text-emerald-600" />
+ <Copy v-else class="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-3 text-xs text-muted-foreground">
+ <Loader2 class="h-4 w-4 animate-spin" />
+ <span>{{ t("connection.salesforceDevicePolling") }}</span>
+ <span v-if="salesforceDeviceSecondsLeft > 0">· {{ t("connection.salesforceDeviceSecondsLeft", { seconds: salesforceDeviceSecondsLeft }) }}</span>
+ <Button type="button" variant="outline" size="sm" class="ml-auto" @click="salesforceDeviceCancel">
+ {{ t("connection.salesforceDeviceCancel") }}
+ </Button>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <p class="col-span-3 text-xs leading-5 text-muted-foreground">{{ t("connection.salesforceDevicePollingHint") }}</p>
+ </div>
+ </template>
+
+ <div v-else-if="salesforceDevicePhase === 'expired'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex flex-col gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs">
+ <span class="text-amber-700 dark:text-amber-300">{{ t("connection.salesforceDeviceExpired") }}</span>
+ <Button type="button" size="sm" variant="outline" class="self-start" @click="salesforceDeviceRestart">
+ {{ t("connection.salesforceDeviceRestart") }}
+ </Button>
+ </div>
+ </div>
+
+ <div v-else-if="salesforceDevicePhase === 'denied'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex flex-col gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs">
+ <span class="text-destructive">{{ salesforceDeviceError || t("connection.salesforceDeviceDenied") }}</span>
+ <Button type="button" size="sm" variant="outline" class="self-start" @click="salesforceDeviceRestart">
+ {{ t("connection.salesforceDeviceRestart") }}
+ </Button>
+ </div>
+ </div>
+ </template>
+ </template>
+
+ <!-- Shared status / error strip (oauth success + any error) -->
+ <div v-if="salesforceOauthSuccess && (salesforceAuthMode === 'oauth' || salesforceAuthMode === 'password' || salesforceDevicePhase === 'success')" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 flex items-center gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-xs text-emerald-700 dark:text-emerald-300">
+ <ShieldCheck class="h-4 w-4 shrink-0" />
+ <span>{{ salesforceOauthSuccess }}</span>
+ </div>
+ </div>
+ <div v-if="salesforceOauthError && (salesforceAuthMode === 'oauth' || salesforceAuthMode === 'password')" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">
+ {{ salesforceOauthError }}
+ </div>
+ </div>
+ <div v-if="salesforceDeviceError && salesforceAuthMode === 'device' && salesforceDevicePhase !== 'polling' && salesforceDevicePhase !== 'denied'" class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <div class="col-span-3 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive">
+ {{ salesforceDeviceError }}
+ </div>
+ </div>
+ </template>
+
<!-- MySQL / PostgreSQL: host, port, user, password, database -->
<template v-else>
<div v-if="form.db_type === 'ignite' || form.db_type === 'ignite3'" class="grid grid-cols-4 items-start gap-4">
diff --git a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.salesforcePasswordMode.spec.ts b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.salesforcePasswordMode.spec.ts
new file mode 100644
index 0000000000..303eb37708
--- /dev/null
+++ b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.salesforcePasswordMode.spec.ts
@@ -0,0 +1,266 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { ConnectionConfig } from "@/types/database";
+
+const { store, settings, backend } = vi.hoisted(() => ({
+ store: {
+ connectionGroupOptions: [],
+ newConnectionGroupId: null,
+ selectedConnectionGroupId: null,
+ addConnection: vi.fn(),
+ updateConnection: vi.fn(),
+ connect: vi.fn(),
+ ensureConnected: vi.fn(),
+ addEphemeralConnection: vi.fn(),
+ removeConnection: vi.fn(),
+ startEditing: vi.fn(),
+ stopEditing: vi.fn(),
+ clearConnectionError: vi.fn(),
+ updateConnectionDatabaseInfo: vi.fn(),
+ applyGlobalTimeouts: vi.fn((config) => config),
+ getConfig: vi.fn(),
+ },
+ settings: {
+ editorSettings: { sidebarShowConnectionNotes: false, globalConnectTimeoutSecs: 10, globalQueryTimeoutSecs: 0 },
+ rememberedDatabaseForConnection: vi.fn(() => ""),
+ persistEditorSettings: vi.fn(),
+ updateEditorSettings: vi.fn(),
+ updateEditorSettingsAndPersist: vi.fn(),
+ },
+ backend: {
+ connectDb: vi.fn(),
+ disconnectDb: vi.fn(),
+ testConnectionWithInfo: vi.fn(),
+ listDatabases: vi.fn(),
+ listPlugins: vi.fn(),
+ listJdbcDrivers: vi.fn(),
+ listJdbcMavenBundles: vi.fn(),
+ listJdbcLocalBundles: vi.fn(),
+ listSshConfigHosts: vi.fn(),
+ listInstalledAgentsLocal: vi.fn(),
+ listenAgentInstallProgress: vi.fn(),
+ },
+}));
+
+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => store, CONNECTION_ATTEMPT_CANCELLED_MESSAGE: "cancelled" }));
+vi.mock("@/stores/settingsStore", async (original) => ({ ...(await original<typeof import("@/stores/settingsStore")>()), useSettingsStore: () => settings }));
+vi.mock("@/stores/tunnelProfileStore", () => ({ useTunnelProfileStore: () => ({ profiles: [], profileById: () => undefined, init: vi.fn() }) }));
+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));
+vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));
+
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const passthrough = defineComponent({
+ setup:
+ (_props, { slots }) =>
+ () =>
+ h("div", slots.default?.()),
+ });
+ const Dialog = defineComponent({
+ props: { open: Boolean },
+ emits: ["update:open"],
+ setup:
+ (props, { slots, emit }) =>
+ () =>
+ props.open ? h("section", [h("button", { "data-testid": "dismiss-dialog", onClick: () => emit("update:open", false) }, "Dismiss"), slots.default?.()]) : null,
+ });
+ return { Dialog, DialogContent: passthrough, DialogHeader: passthrough, DialogTitle: passthrough, DialogFooter: passthrough };
+});
+vi.mock("@/components/ui/button", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Button: defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("button", attrs, slots.default?.()),
+ }),
+ };
+});
+vi.mock("@/components/ui/input", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Input: defineComponent({
+ props: ["modelValue"],
+ emits: ["update:modelValue"],
+ setup:
+ (props, { attrs, emit }) =>
+ () =>
+ h("input", { ...attrs, value: props.modelValue, onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) }),
+ }),
+ };
+});
+vi.mock("@/components/ui/PasswordInput.vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ default: defineComponent({
+ props: ["modelValue"],
+ setup:
+ (props, { attrs }) =>
+ () =>
+ h("input", { ...attrs, type: "password", value: props.modelValue }),
+ }),
+ };
+});
+vi.mock("@/components/ui/tabs", async () => {
+ const { defineComponent, h } = await import("vue");
+ const pass = defineComponent({
+ setup:
+ (_props, { slots }) =>
+ () =>
+ h("div", slots.default?.()),
+ });
+ const TabsContent = defineComponent({
+ props: ["value"],
+ setup:
+ (props, { slots }) =>
+ () =>
+ props.value === "connection" ? h("div", slots.default?.()) : null,
+ });
+ return { Tabs: pass, TabsContent, TabsList: pass, TabsTrigger: pass };
+});
+vi.mock("@/components/ui/tooltip", async () => {
+ const { defineComponent, h } = await import("vue");
+ const pass = defineComponent({
+ setup:
+ (_props, { slots }) =>
+ () =>
+ h("span", slots.default?.()),
+ });
+ return { HelpTooltip: pass, Tooltip: pass, TooltipContent: pass, TooltipTrigger: pass };
+});
+
+import ConnectionDialog from "@/components/connection/ConnectionDialog.vue";
+
+const mountedApps: App[] = [];
+
+function salesforceConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
+ return {
+ id: "sfdc-sandbox",
+ name: "Salesforce sandbox",
+ db_type: "salesforce",
+ driver_profile: "salesforce",
+ driver_label: "Salesforce",
+ host: "https://acme--qas1.sandbox.my.salesforce.com",
+ port: 443,
+ password: "saved-access-token",
+ ssl: true,
+ save_password: true,
+ ...overrides,
+ } as ConnectionConfig;
+}
+
+async function settle() {
+ for (let i = 0; i < 8; i++) await nextTick();
+}
+
+async function mountDialog(config: ConnectionConfig) {
+ const props = reactive({ open: true, editConfig: config });
+ store.getConfig.mockReturnValue(config);
+ const container = document.createElement("div");
+ document.body.append(container);
+ const app = createApp(
+ defineComponent({
+ setup: () => () =>
+ h(ConnectionDialog, {
+ ...props,
+ "onUpdate:open": (value: boolean) => {
+ props.open = value;
+ },
+ }),
+ }),
+ );
+ app.use(i18n);
+ mountedApps.push(app);
+ app.mount(container);
+ await settle();
+ return props;
+}
+
+function findModeButton(label: string): HTMLButtonElement | undefined {
+ return [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === label) as HTMLButtonElement | undefined;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ i18n.global.locale.value = "en";
+ for (const fn of Object.values(backend)) fn.mockResolvedValue([]);
+ backend.listenAgentInstallProgress.mockResolvedValue(() => {});
+ store.updateConnection.mockResolvedValue(undefined);
+ store.addConnection.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+});
+
+describe("ConnectionDialog Salesforce username-password mode", () => {
+ it("switches to password mode and reveals the credential inputs", async () => {
+ await mountDialog(salesforceConnection());
+
+ const passwordTab = findModeButton("Username & Password");
+ expect(passwordTab, "password mode button should exist").toBeTruthy();
+ expect(passwordTab!.disabled, "password mode button should be clickable").toBe(false);
+
+ passwordTab!.click();
+ await settle();
+
+ expect(passwordTab!.getAttribute("aria-pressed")).toBe("true");
+ const username = [...document.querySelectorAll("input")].find((input) => input.getAttribute("placeholder") === "[email protected]");
+ expect(username, "username input should render in password mode").toBeTruthy();
+ expect((username as HTMLInputElement).disabled).toBe(false);
+ const signIn = findModeButton("Sign In");
+ expect(signIn, "sign-in button should render in password mode").toBeTruthy();
+ });
+
+ it("keeps the password mode button enabled while a browser OAuth authorize is not running", async () => {
+ await mountDialog(salesforceConnection({ external_config: { auth: { mode: "oauth", environment: "sandbox", clientId: "consumer-key", authorizedAt: "2026-09-21T00:00:00.000Z" } } } as Partial<ConnectionConfig>));
+
+ const passwordTab = findModeButton("Username & Password");
+ expect(passwordTab).toBeTruthy();
+ expect(passwordTab!.disabled).toBe(false);
+ passwordTab!.click();
+ await settle();
+ expect(passwordTab!.getAttribute("aria-pressed")).toBe("true");
+ });
+
+ it("shows each mode only the guidance that applies to it", async () => {
+ const bodyText = () => document.body.textContent ?? "";
+
+ // Token mode carries no Connected App at all: neither client-ID hint renders,
+ // and Salesforce has no TLS toggle (the driver always speaks HTTPS).
+ await mountDialog(salesforceConnection());
+ expect(bodyText()).not.toContain("The Connected App consumer key.");
+ expect(bodyText()).not.toContain("Create a Connected App in Salesforce Setup");
+ expect(bodyText()).not.toContain("Enable encrypted connection");
+
+ const passwordTab = findModeButton("Username & Password");
+ passwordTab!.click();
+ await settle();
+ expect(bodyText()).toContain("The Connected App consumer key.");
+ expect(bodyText()).toContain("No callback URL needed");
+ expect(bodyText()).not.toContain("Create a Connected App in Salesforce Setup");
+
+ const deviceTab = findModeButton("Device Code");
+ deviceTab!.click();
+ await settle();
+ expect(bodyText()).toContain("If requesting the code fails");
+ expect(bodyText()).not.toContain("No callback URL needed");
+ });
+
+ it("reserves the callback-URL guidance for browser OAuth", async () => {
+ await mountDialog(salesforceConnection({ external_config: { auth: { mode: "oauth", environment: "sandbox", clientId: "consumer-key" } } } as Partial<ConnectionConfig>));
+ await settle();
+
+ const text = document.body.textContent ?? "";
+ expect(text).toContain("Create a Connected App in Salesforce Setup");
+ expect(text).not.toContain("The Connected App consumer key.");
+ expect(text).not.toContain("If requesting the code fails");
+ });
+});
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index 2bd43027e3..fc7e47e113 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -114,7 +114,7 @@ let initializingPrefillGeneration = 0;
let componentUnmounted = false;
let shownSessionError = "";
-const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(connection.db_type)));
+const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(connection.db_type)));
const selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
// Bridge the shared TableMultiSelect `string[]` v-model with the Set-based selection store.
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
index f7590813f5..551072969f 100644
--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
@@ -84,7 +84,7 @@ const targetSchemas = ref<string[]>([]);
const sourceDbVersion = ref<string | null>(null);
const targetDbVersion = ref<string | null>(null);
-const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "meilisearch", "solr", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "meilisearch", "solr", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(c.db_type)));
const sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 4d8f99a8dd..e71dc40bd6 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -3471,6 +3471,7 @@ async function saveMcpPolicy(
databaseScope: "all" | "selected" | "none";
allowedDatabases: string[];
databasePolicies: { databaseName: string; readOnly: boolean; allowDangerousSql: boolean }[];
+ allowSalesforceDml: boolean;
}[];
groupPolicies?: McpGroupPolicy[];
queryTimeoutSecs?: number | null;
@@ -3659,6 +3660,14 @@ function onMcpGroupExecutionModeChange(groupId: string, mode: McpConnectionExecu
void saveMcpPolicy({ groupPolicies });
}
+// A connection rule is only worth persisting when it actually changes something: an
+// explicit execution mode, a narrowed database scope, a per-database override, or the
+// Salesforce DML opt-in. Rules that merely restate the inherited defaults are dropped so
+// the stored policy stays readable and keeps following later global changes.
+function mcpConnectionPolicyIsMeaningful(rule: McpConnectionPolicy): boolean {
+ return rule.executionModeConfigured || rule.databaseScope !== "all" || rule.databasePolicies.length > 0 || rule.allowSalesforceDml;
+}
+
function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConnectionExecutionMode | "inherit") {
if (mode === "high_risk_write" && !window.confirm(t("settings.mcpExecutionModeHighRiskConfirm"))) return;
const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId);
@@ -3682,8 +3691,38 @@ function onMcpConnectionExecutionModeChange(connectionId: string, mode: McpConne
databaseScope: existing?.databaseScope ?? ("all" as const),
allowedDatabases: existing?.allowedDatabases ?? [],
databasePolicies: selectedMode.databasePolicies,
+ // Switching a connection to read-only silently revokes the DML opt-in, matching
+ // the backend's ceiling: an agent must never keep a write path it lost.
+ allowSalesforceDml: (existing?.allowSalesforceDml ?? false) && !selectedMode.readOnly,
+ };
+ if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
+ void saveMcpPolicy({ connectionPolicies: rules });
+}
+
+function onMcpConnectionSalesforceDmlChange(connectionId: string, allowed: boolean) {
+ const existing = settingsStore.mcpGlobalPolicy.connectionPolicies.find((item) => item.connectionId === connectionId);
+ if (allowed) {
+ // Read-only is a hard ceiling on the server too, so letting the box stay checked
+ // here would only advertise a write path that every prepare call then refuses.
+ const effectiveMode = mcpEffectiveExecutionMode(mcpInheritedGroupExecutionMode(connectionId), mcpConnectionExecutionMode(connectionId), "inherit");
+ if (effectiveMode === "read_only") {
+ toast(t("settings.mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked"), 5000);
+ return;
+ }
+ }
+ const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId);
+ const next: McpConnectionPolicy = {
+ connectionId,
+ readOnly: existing?.readOnly ?? false,
+ allowDangerousSql: existing?.allowDangerousSql ?? false,
+ executionModeConfigured: existing?.executionModeConfigured ?? false,
+ executionModePolicyVersion: existing?.executionModePolicyVersion ?? null,
+ databaseScope: existing?.databaseScope ?? "all",
+ allowedDatabases: existing?.allowedDatabases ?? [],
+ databasePolicies: existing?.databasePolicies ?? [],
+ allowSalesforceDml: allowed,
};
- if (next.executionModeConfigured || next.databaseScope !== "all" || next.databasePolicies.length > 0) rules.push(next);
+ if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules });
}
@@ -3703,7 +3742,7 @@ function onMcpDatabaseExecutionModeChange(connectionId: string, databaseName: st
databasePolicies,
};
const rules = settingsStore.mcpGlobalPolicy.connectionPolicies.filter((item) => item.connectionId !== connectionId);
- if (next.executionModeConfigured || next.databaseScope !== "all" || next.databasePolicies.length > 0) rules.push(next);
+ if (mcpConnectionPolicyIsMeaningful(next)) rules.push(next);
void saveMcpPolicy({ connectionPolicies: rules });
}
@@ -9938,6 +9977,7 @@ LIMIT 100;</pre
@update:scope="onMcpResourceScopeChange"
@set:group-policy="onMcpGroupExecutionModeChange"
@set:connection-policy="onMcpConnectionExecutionModeChange"
+ @set:connection-salesforce-dml="onMcpConnectionSalesforceDmlChange"
/>
</div>
</template>
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 2e9d586acd..5bb3111d51 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -139,7 +139,9 @@ import type { SqlCompletionColumn, SqlCompletionContext, SqlCompletionReferenced
const props = defineProps<QueryEditorProps>();
function sqlBehaviorDialect(): "mysql" | "postgres" | "sqlserver" | undefined {
- return props.syntaxDialect === "clickhouse" ? props.dialect : (props.syntaxDialect ?? props.dialect);
+ // clickhouse and soql ride the SQL editor but have no matching behavior dialect;
+ // fall back to the connection's dialect (undefined for Salesforce).
+ return props.syntaxDialect === "clickhouse" || props.syntaxDialect === "soql" ? props.dialect : (props.syntaxDialect ?? props.dialect);
}
function queryEditorSelectionLanguage(): "sql" | "text" {
diff --git a/apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts b/apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts
index e02d480b86..84497255a0 100644
--- a/apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts
@@ -9,9 +9,10 @@ import { type ElasticsearchCompletionItem } from "@/lib/elasticsearch/elasticsea
import { type MongoCompletionItem } from "@/lib/mongo/mongoCompletion";
import { batchColumnSelectionColumnList, batchColumnSelectionInsertReplacement, batchColumnSelectionReplaceTo, isBatchColumnSelectionCompletionActive } from "@/lib/editor/batchColumnSelection";
import { type RedisCompletionItem } from "@/lib/redis/redisCompletion";
+import { type SoqlCompletionItem } from "@/lib/soql/soqlCompletion";
import type { SqlCompletionItem } from "@/lib/sql/sqlCompletion";
-export type QueryCompletionItem = SqlCompletionItem | ElasticsearchCompletionItem | RedisCompletionItem | MongoCompletionItem;
+export type QueryCompletionItem = SqlCompletionItem | ElasticsearchCompletionItem | RedisCompletionItem | MongoCompletionItem | SoqlCompletionItem;
export interface BatchColumnSelectionActionItem {
label: string;
diff --git a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
index 695046c1f6..db41d3ec05 100644
--- a/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorCompletion.ts
@@ -25,6 +25,7 @@ import { sqlCompletionContextFromSemantic } from "@/lib/sql/semantic/completion"
import { buildSqlSemanticModel } from "@/lib/sql/semantic/model";
import { buildElasticsearchCompletionItemsFromContext, elasticsearchCompletionNeedsFields, getElasticsearchCompletionContext, getElasticsearchCompletionResultValidFor, shouldAutoOpenElasticsearchCompletion, type ElasticsearchCompletionField } from "@/lib/elasticsearch/elasticsearchCompletion";
import { buildMongoCompletionItemsFromContext, getMongoCompletionContext, getMongoCompletionResultValidFor, mongoCompletionNeedsCollections, mongoCompletionNeedsFields, shouldAutoOpenMongoCompletion } from "@/lib/mongo/mongoCompletion";
+import { buildSoqlCompletionItems, getSoqlCompletionContext, getSoqlCompletionResultValidFor, resolveSoqlFieldCandidates, resolveSoqlValueField, shouldAutoOpenSoqlCompletion, soqlCompletionNeedsObjects, type SoqlCompletionField, type SoqlCompletionObject } from "@/lib/soql/soqlCompletion";
import {
buildSqlServerUseDatabaseCompletionItems,
mergeSqlCompletionQualifierNames,
@@ -361,7 +362,16 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
}
function shouldInsertSqlCompletionSpace(): boolean {
- return props.databaseType !== "mongodb" && props.databaseType !== "redis" && props.databaseType !== "elasticsearch" && props.databaseType !== "easysearch" && props.databaseType !== "meilisearch" && props.databaseType !== "solr" && props.databaseType !== "victoriametrics";
+ return (
+ props.databaseType !== "mongodb" &&
+ props.databaseType !== "redis" &&
+ props.databaseType !== "elasticsearch" &&
+ props.databaseType !== "easysearch" &&
+ props.databaseType !== "meilisearch" &&
+ props.databaseType !== "solr" &&
+ props.databaseType !== "victoriametrics" &&
+ props.databaseType !== "salesforce"
+ );
}
// Snippet expansion normally follows from the item type; a provider can also
@@ -591,6 +601,59 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
};
}
+ async function provideSoqlCompletions(currentState: import("@codemirror/state").EditorState, position: number, explicit: boolean) {
+ if (!props.connectionId) return null;
+ const epoch = ++completionEpoch;
+ const fullDoc = currentState.doc.toString();
+ if (!explicit && !shouldAutoOpenSoqlCompletion(fullDoc, position)) return null;
+
+ const completionContext = getSoqlCompletionContext(fullDoc, position);
+ if (completionContext.mode === "none") return null;
+ // The Salesforce backend ignores the database parameter for metadata (the whole
+ // org is one synthesized database), so completion must not gate on props.database
+ // being populated — a restored/toolbar-opened tab can carry an empty database
+ // while the connection works fine. Pass it through (possibly "") and let the
+ // store/backend resolve it.
+ const database = props.database ?? "";
+
+ let objects: SoqlCompletionObject[] = [];
+ let fields: SoqlCompletionField[] = [];
+ let valueField: SoqlCompletionField | null = null;
+
+ // Field loader backed by the store (which reads the backend describe cache), so
+ // relationship traversal costs at most one describe per distinct sObject.
+ const loadFields = (objectName: string) => connectionStore.listSoqlCompletionFields(props.connectionId!, database, objectName);
+
+ try {
+ if (soqlCompletionNeedsObjects(completionContext.mode)) {
+ objects = await connectionStore.listSoqlCompletionObjects(props.connectionId, database);
+ }
+ if (completionContext.mode === "field") {
+ fields = await resolveSoqlFieldCandidates(completionContext, loadFields);
+ }
+ if (completionContext.mode === "value") {
+ valueField = await resolveSoqlValueField(completionContext, loadFields);
+ }
+ } catch (error) {
+ // Metadata load failed (offline, describe error, no cache yet): fall back to
+ // keyword/function-only completion. Logged so a persistent empty field list is
+ // diagnosable instead of silently looking like "custom fields are excluded".
+ console.debug("[soql-completion] metadata load failed", error);
+ objects = [];
+ fields = [];
+ valueField = null;
+ }
+ if (epoch !== completionEpoch) return null;
+
+ const items = buildSoqlCompletionItems(completionContext, { objects, fields, valueField });
+ if (items.length === 0) return null;
+ return {
+ from: completionContext.from,
+ options: items.map((item) => completionOptionForItem(item)),
+ validFor: getSoqlCompletionResultValidFor(completionContext),
+ };
+ }
+
async function provideSqlCompletions(context: CompletionContext) {
const currentState = context.state;
const position = context.pos;
@@ -612,6 +675,9 @@ export function useQueryEditorCompletion(options: QueryEditorCompletionOptions)
return provideRedisCompletions(currentState, position, explicit);
}
if (props.databaseType === "victoriametrics") return null;
+ if (props.databaseType === "salesforce") {
+ return provideSoqlCompletions(currentState, position, explicit);
+ }
const hasDatabase = props.database != null;
const sequenceLiteralContext = getPostgresSequenceLiteralCompletionContext(fullDoc, position, props.databaseType);
const databaseLinkContext = oracleDatabaseLinkCompletionContext(fullDoc, position, props.databaseType);
diff --git a/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts b/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
index a5a08632f3..88907a7c6c 100644
--- a/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
+++ b/apps/desktop/src/components/editor/useQueryEditorDiagnostics.ts
@@ -195,7 +195,7 @@ export function useQueryEditorDiagnostics(options: QueryEditorDiagnosticsOptions
}
function shouldSkipSqlSemanticDiagnostics() {
- return props.databaseType === "victoriametrics" || (props.databaseType !== "redis" && props.databaseType !== "mongodb" && !settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled);
+ return props.databaseType === "victoriametrics" || props.databaseType === "salesforce" || (props.databaseType !== "redis" && props.databaseType !== "mongodb" && !settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled);
}
function rangesOverlap(left: { from: number; to: number }, right: { from: number; to: number }): boolean {
@@ -337,7 +337,7 @@ export function useQueryEditorDiagnostics(options: QueryEditorDiagnosticsOptions
setSemanticDiagnostics([]);
return;
}
- if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch" || props.databaseType === "meilisearch" || props.databaseType === "solr" || props.databaseType === "victoriametrics") {
+ if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch" || props.databaseType === "meilisearch" || props.databaseType === "solr" || props.databaseType === "victoriametrics" || props.databaseType === "salesforce") {
setSemanticDiagnostics([]);
return;
}
diff --git a/apps/desktop/src/components/export/DatabaseExportDialog.vue b/apps/desktop/src/components/export/DatabaseExportDialog.vue
index 51d32e5efa..24b808431d 100644
--- a/apps/desktop/src/components/export/DatabaseExportDialog.vue
+++ b/apps/desktop/src/components/export/DatabaseExportDialog.vue
@@ -115,7 +115,7 @@ const exportElapsedText = computed(() => {
return formatDataTransferDuration((exportFinishedAt.value ?? currentTime.value) - exportStartedAt.value);
});
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(c.db_type)));
const canExport = computed(() => {
const hasContent = includeStructure.value || includeData.value || includeObjects.value;
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index e55d4b9992..a7a169391e 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -119,6 +119,8 @@ import {
hiveTablePropertiesIndicateTransactional,
isClickHouseExistingRowReadonlyColumn,
isHiddenGridColumn,
+ isSalesforceExistingRowReadonlyColumn,
+ isSalesforceNewRowReadonlyColumn,
isTdengineExistingRowReadonlyColumn,
shouldIncludeSyntheticRowId,
} from "@/lib/table/tableEditing";
@@ -369,6 +371,7 @@ import { useDataGridColumnFormatter } from "@/composables/useDataGridColumnForma
import { useDataGridTableMetadataLoaders } from "@/composables/useDataGridTableMetadataLoaders";
import { DATA_GRID_SERVER_COLUMN_FILTER_LIMIT, useDataGridColumnFilters } from "@/composables/useDataGridColumnFilters";
import { useDataGridLargeValues } from "@/composables/useDataGridLargeValues";
+import { useSalesforceSaveConfirmation } from "@/composables/useSalesforceSaveConfirmation";
const SqlPreviewPanel = defineAsyncComponent(() => import("@/components/editor/SqlPreviewPanel.vue"));
const ImagePreviewDialog = defineAsyncComponent(() => import("@/components/grid/ImagePreviewDialog.vue"));
@@ -3797,6 +3800,57 @@ async function refreshSavedRows(request: { dirtyRows: ReadonlyMap<number, Readon
return true;
}
+// Salesforce applies one REST call per record with no transaction, so every grid
+// save is reviewed here first. The identity lines are advisory only — Salesforce
+// enforces the real object/field permissions, and a failed identity lookup just
+// omits the line rather than blocking the write.
+const {
+ open: salesforceSaveConfirmOpen,
+ updates: salesforceSaveConfirmUpdates,
+ inserts: salesforceSaveConfirmInserts,
+ deletes: salesforceSaveConfirmDeletes,
+ total: salesforceSaveConfirmTotal,
+ targetLabel: salesforceSaveConfirmTarget,
+ statements: salesforceSaveConfirmStatements,
+ request: requestSalesforceSaveConfirmation,
+ confirm: confirmSalesforceSave,
+} = useSalesforceSaveConfirmation();
+const isSalesforceGrid = computed(() => resolvedDatabaseType.value === "salesforce");
+const salesforceIdentity = computed(() => (isSalesforceGrid.value && props.connectionId ? connectionStore.salesforceCurrentUser(props.connectionId) : null));
+const salesforceIdentityLabel = computed(() => {
+ const identity = salesforceIdentity.value;
+ if (!identity) return "";
+ return identity.username || identity.name || identity.email;
+});
+const salesforceSaveConfirmSummary = computed(() => {
+ const parts: string[] = [];
+ if (salesforceSaveConfirmUpdates.value > 0) parts.push(t("grid.salesforceSaveUpdates", { count: salesforceSaveConfirmUpdates.value }));
+ if (salesforceSaveConfirmInserts.value > 0) parts.push(t("grid.salesforceSaveInserts", { count: salesforceSaveConfirmInserts.value }));
+ if (salesforceSaveConfirmDeletes.value > 0) parts.push(t("grid.salesforceSaveDeletes", { count: salesforceSaveConfirmDeletes.value }));
+ return parts.join(" · ");
+});
+// The save dialog names the profile alongside the user: writability comes from
+// the profile's FLS plus record sharing, not from the admin flag alone.
+const salesforceIdentityProfile = computed(() => {
+ const profileName = salesforceIdentity.value?.profileName;
+ return profileName ? t("grid.salesforceSaveProfile", { name: profileName }) : t("toolbar.salesforceIdentityUnknownProfile");
+});
+const salesforceSaveConfirmDetails = computed(() => {
+ const lines = [salesforceSaveConfirmSummary.value, t("grid.salesforceSaveTarget", { object: salesforceSaveConfirmTarget.value || t("grid.salesforceSaveUnknownObject") })];
+ if (salesforceIdentity.value) {
+ const identity = { user: salesforceIdentityLabel.value, profile: salesforceIdentityProfile.value };
+ if (salesforceIdentity.value.isAdmin === true) lines.push(t("grid.salesforceSaveAdminIdentity", identity));
+ else if (salesforceIdentity.value.isAdmin === false) lines.push(t("grid.salesforceSaveNonAdminIdentity", identity));
+ else lines.push(t("grid.salesforceSaveUnknownRights", identity));
+ }
+ return lines.filter((line) => !!line).join("\n");
+});
+const salesforceSaveConfirmSql = computed(() => salesforceSaveConfirmStatements.value.join("\n"));
+watch(salesforceSaveConfirmOpen, (isOpen) => {
+ if (!isOpen || !props.connectionId) return;
+ void connectionStore.loadSalesforceCurrentUser(props.connectionId);
+});
+
const editor = useDataGridEditor({
result: computed(() => props.result),
editable: computed(() => props.editable),
@@ -3821,6 +3875,8 @@ const editor = useDataGridEditor({
rowStatusFilter,
dataGridQuickEntryEnabled: computed(() => settingsStore.editorSettings.dataGridQuickEntry),
confirmDangerousRowDeletion: computed(() => settingsStore.editorSettings.confirmDangerousSqlExecution),
+ // Only Salesforce opts in: its writes cannot be rolled back once issued.
+ confirmSaveRequest: computed(() => (isSalesforceGrid.value ? requestSalesforceSaveConfirmation : undefined)),
includeDatabaseNameInSaveSql: computed(() => settingsStore.editorSettings.generateSqlIncludeDatabaseName),
initialEditColumn: firstVisibleColumnIndex,
cellEditorText: cellEditorTextForValue,
@@ -4018,10 +4074,14 @@ function canEditCellItem(item: RowItem | undefined, columnIndex: number): boolea
if (isSavingNewRow(item)) return false;
const column = props.result.columns[columnIndex] ?? "";
if (customReadonlyColumns.value.has(column.toLowerCase())) return false;
- if (!item?.isNew && !item?.isDraft) {
- const sourceColumn = props.sourceColumns?.[columnIndex] ?? column;
+ const sourceColumn = props.sourceColumns?.[columnIndex] ?? column;
+ if (item?.isNew || item?.isDraft) {
+ // A new Salesforce record cannot carry non-createable fields (Id, CreatedDate, …).
+ if (isSalesforceNewRowReadonlyColumn(props.databaseType, sourceColumn, props.tableMeta?.columns ?? [])) return false;
+ } else {
if (isClickHouseExistingRowReadonlyColumn(props.databaseType, sourceColumn, props.tableMeta?.primaryKeys ?? [], props.tableMeta?.columns ?? [])) return false;
if (isTdengineExistingRowReadonlyColumn(props.databaseType, column, props.tableMeta?.columns ?? [])) return false;
+ if (isSalesforceExistingRowReadonlyColumn(props.databaseType, sourceColumn, props.tableMeta?.primaryKeys ?? [], props.tableMeta?.columns ?? [])) return false;
}
return true;
}
@@ -14211,6 +14271,18 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
:close-on-confirm="false"
@confirm="confirmDropAllMongoIndexes"
/>
+ <!-- Salesforce applies each record with its own REST call and cannot roll back, so the
+ save is reviewed here first. Cancel (or closing) denies it and keeps the edits staged. -->
+ <DangerConfirmDialog
+ v-model:open="salesforceSaveConfirmOpen"
+ :title="t('grid.salesforceSaveConfirmTitle')"
+ :message="t('grid.salesforceSaveConfirmMessage', { count: salesforceSaveConfirmTotal })"
+ :details-text="salesforceSaveConfirmDetails"
+ :sql="salesforceSaveConfirmSql"
+ :confirm-label="t('grid.salesforceSaveConfirm')"
+ :close-on-confirm="false"
+ @confirm="confirmSalesforceSave"
+ />
<ImagePreviewDialog v-if="imagePreviewMounted" v-model:open="imagePreviewOpen" :src="imagePreviewSrc" :title="imagePreviewTitle" />
<component v-if="previewDialogOpen && previewDialogConfig" :is="previewDialogConfig.component" v-model:open="previewDialogOpen" v-bind="previewDialogConfig.props" />
<ExportProgressDialog
diff --git a/apps/desktop/src/components/icons/DatabaseIcon.vue b/apps/desktop/src/components/icons/DatabaseIcon.vue
index 741f1ed90f..03c88d30af 100644
--- a/apps/desktop/src/components/icons/DatabaseIcon.vue
+++ b/apps/desktop/src/components/icons/DatabaseIcon.vue
@@ -123,6 +123,7 @@ const assetIcons: Record<string, string> = {
jdbcx: "jdbcx",
mqtt: "mqtt",
dolt: "dolt",
+ salesforce: "salesforce",
};
const normalizedType = computed(() => (props.dbType || "").toLowerCase().replace(/[\s-]+/g, "_"));
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 2ba0a6ebae..d6fbaf7928 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, nextTick, onUnmounted, ref, watch, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
-import { Play, CirclePlay, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, X, Shield, Download, RotateCcw, AlertTriangle, ClipboardPaste, Minimize2, SpellCheck2, Layers, MoreHorizontal, BetweenVerticalStart, Eye, WrapText, RefreshCw } from "@lucide/vue";
+import { Play, CirclePlay, Loader2, Square, Database, Check, Table2, AlignLeft, GitBranch, Save, FolderOpen, X, Shield, Download, RotateCcw, AlertTriangle, ClipboardPaste, Minimize2, SpellCheck2, Layers, MoreHorizontal, BetweenVerticalStart, Eye, WrapText, RefreshCw, UserRound } from "@lucide/vue";
import { supportsInsertValueHints } from "@/lib/editor/codemirrorInsertValueHints";
import { Button } from "@/components/ui/button";
import { SearchableSelect } from "@/components/ui/searchable-select";
@@ -215,6 +215,38 @@ const showConnectionProductionBadge = computed(() => activeProductionContext.val
const showDatabaseProductionBadge = computed(() => activeProductionContext.value.reason === "database");
const activeConnectionValue = computed(() => props.activeConnection?.id || "");
const activeSchemaValue = computed(() => props.activeTab.schema || "");
+// Salesforce identity badge. A Salesforce tab talks to one live org and every grid
+// save is a real REST write, so the signed-in user stays visible next to the
+// connection controls. Advisory only: Salesforce enforces the actual permissions.
+const isSalesforceTab = computed(() => props.activeConnection?.db_type === "salesforce");
+const salesforceIdentity = computed(() => (props.activeConnection ? connectionStore.salesforceCurrentUser(props.activeConnection.id) : null));
+const salesforceIdentityLabel = computed(() => {
+ const identity = salesforceIdentity.value;
+ if (!identity) return "";
+ const user = identity.username || identity.name || identity.email;
+ const org = identity.orgName || identity.organizationId;
+ if (user && org) return `${user} @ ${org}`;
+ return user || org;
+});
+const salesforceIdentityTooltip = computed(() => {
+ const identity = salesforceIdentity.value;
+ if (!identity) return "";
+ const lines = [identity.name || identity.username || identity.email, identity.profileName || t("toolbar.salesforceIdentityUnknownProfile")];
+ if (identity.isAdmin === true) lines.push(t("toolbar.salesforceIdentityAdmin"));
+ else if (identity.isAdmin === false) lines.push(t("toolbar.salesforceIdentityNonAdmin"));
+ else lines.push(t("toolbar.salesforceIdentityUnknownRights"));
+ return lines.filter((line) => !!line).join("\n");
+});
+watch(
+ () => [isSalesforceTab.value, props.activeConnection?.id ?? "", connectionStore.connectedIds.has(props.activeConnection?.id ?? "")] as const,
+ ([salesforce, connectionId, connected]) => {
+ // Never connect on a tab switch: only resolve the identity once the user has
+ // established the connection themselves. A failed lookup hides the badge.
+ if (!salesforce || !connected || !connectionId) return;
+ void connectionStore.loadSalesforceCurrentUser(connectionId);
+ },
+ { immediate: true },
+);
const supportsExplain = computed(() => {
const dbType = props.activeConnection?.db_type;
return (
@@ -233,7 +265,8 @@ const supportsExplain = computed(() => {
dbType !== "consul" &&
dbType !== "mq" &&
dbType !== "nacos" &&
- dbType !== "victoriametrics"
+ dbType !== "victoriametrics" &&
+ dbType !== "salesforce"
);
});
const isSingleDb = computed(() => isSingleDatabase(props.activeConnection?.db_type));
@@ -285,7 +318,7 @@ const sqlSemanticDiagnosticsEnabled = computed(() => settingsStore.editorSetting
const sqlSemanticDiagnosticsToggleTooltip = computed(() => (sqlSemanticDiagnosticsEnabled.value ? t("toolbar.sqlSemanticDiagnosticsToggleOn") : t("toolbar.sqlSemanticDiagnosticsToggleOff")));
const supportsSqlSemanticDiagnosticsToggle = computed(() => {
const dbType = props.activeConnection?.db_type;
- return dbType !== "redis" && dbType !== "victoriametrics";
+ return dbType !== "redis" && dbType !== "victoriametrics" && dbType !== "salesforce";
});
function toggleSqlSemanticDiagnostics() {
settingsStore.updateEditorSettings({
@@ -926,6 +959,11 @@ async function changeCatalog(selectedCatalog: string) {
<Table2 class="h-3.5 w-3.5 shrink-0" />
<span class="truncate">{{ activeTab.tableMeta.columns.length }} {{ t("tree.columns") }}</span>
</div>
+ <div v-if="salesforceIdentity" data-testid="salesforce-identity-badge" class="ml-2 inline-flex max-w-[20rem] shrink-0 items-center gap-1 rounded border border-border bg-muted/30 px-2 py-0.5 font-medium text-muted-foreground" :title="salesforceIdentityTooltip">
+ <Shield v-if="salesforceIdentity.isAdmin === true" class="h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
+ <UserRound v-else class="h-3.5 w-3.5 shrink-0" />
+ <span class="truncate">{{ salesforceIdentityLabel }}</span>
+ </div>
</div>
<div v-if="autoCommitTxnRolledBack" data-auto-commit-txn-rolled-back class="flex items-center gap-2 px-3 py-1 text-xs bg-amber-500/10 text-amber-700 dark:text-amber-300 border-b border-amber-500/20">
<AlertTriangle class="h-3.5 w-3.5 shrink-0" />
diff --git a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
index 6a94064e33..4dca8c7dc7 100644
--- a/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
+++ b/apps/desktop/src/components/settings/McpDatabaseScopePicker.vue
@@ -89,6 +89,7 @@ function policyFor(connectionId: string): McpConnectionPolicy {
databaseScope: "all",
allowedDatabases: [],
databasePolicies: [],
+ allowSalesforceDml: false,
}
);
}
diff --git a/apps/desktop/src/components/settings/McpResourceScopePicker.vue b/apps/desktop/src/components/settings/McpResourceScopePicker.vue
index 338b71fb0d..af12b9f1c8 100644
--- a/apps/desktop/src/components/settings/McpResourceScopePicker.vue
+++ b/apps/desktop/src/components/settings/McpResourceScopePicker.vue
@@ -37,7 +37,7 @@ const props = withDefaults(
allowedGroupIds: readonly string[];
allowedConnectionIds: readonly string[] | null;
groupPolicies?: readonly { groupId: string; readOnly: boolean; allowDangerousSql: boolean }[];
- connectionPolicies?: readonly { connectionId: string; readOnly: boolean; allowDangerousSql: boolean; executionModeConfigured?: boolean }[];
+ connectionPolicies?: readonly { connectionId: string; readOnly: boolean; allowDangerousSql: boolean; executionModeConfigured?: boolean; allowSalesforceDml?: boolean }[];
disabled?: boolean;
busy?: boolean;
}>(),
@@ -48,6 +48,7 @@ const emit = defineEmits<{
"update:scope": [value: { allowedGroupIds: string[]; allowedConnectionIds: string[] | null }];
"set:group-policy": [groupId: string, mode: ExecutionMode | "inherit"];
"set:connection-policy": [connectionId: string, mode: ExecutionMode | "inherit"];
+ "set:connection-salesforce-dml": [connectionId: string, allowed: boolean];
}>();
const { t } = useI18n();
@@ -264,6 +265,18 @@ function groupPolicyMode(groupId: string): ExecutionMode | "inherit" {
function connectionPolicyMode(connectionId: string): ExecutionMode | "inherit" {
return policyMode(props.connectionPolicies?.find((policy) => policy.connectionId === connectionId));
}
+
+// Salesforce writes are the one permission that cannot be expressed as an execution
+// mode: SOQL has no write verb, so a DML toggle is the only gate an agent can be given.
+// It is per-connection because it is per-org, and it stays hidden for every other driver.
+function isSalesforceConnection(node: ResourceNode): boolean {
+ return node.type === "connection" && node.connection.db_type === "salesforce";
+}
+
+function connectionAllowsSalesforceDml(connectionId: string): boolean {
+ const policy = props.connectionPolicies?.find((item) => item.connectionId === connectionId);
+ return policy?.allowSalesforceDml === true && policy.readOnly !== true;
+}
</script>
<template>
@@ -349,6 +362,23 @@ function connectionPolicyMode(connectionId: string): ExecutionMode | "inherit" {
<SelectItem value="high_risk_write">{{ t("settings.mcpConnectionPolicyHighRiskWrite") }}</SelectItem>
</SelectContent>
</Select>
+ <label
+ v-if="isSalesforceConnection(node) && (explicitConnectionIds.has(node.id) || Boolean(selectedAncestor(node)))"
+ class="flex h-7 shrink-0 cursor-pointer items-center gap-1 rounded border bg-background px-1.5 text-[11px]"
+ :class="connectionAllowsSalesforceDml(node.id) ? 'border-primary/50 text-foreground' : 'text-muted-foreground'"
+ :title="t('settings.mcpConnectionPolicyAllowSalesforceDmlHint')"
+ >
+ <input
+ type="checkbox"
+ class="size-3"
+ :checked="connectionAllowsSalesforceDml(node.id)"
+ :disabled="disabled || busy"
+ :aria-label="t('settings.mcpConnectionPolicyAllowSalesforceDml')"
+ @click.stop
+ @change="emit('set:connection-salesforce-dml', node.id, ($event.target as HTMLInputElement).checked)"
+ />
+ {{ t("settings.mcpConnectionPolicyAllowSalesforceDml") }}
+ </label>
<Badge v-if="selectedAncestor(node)" variant="secondary" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopeInherited", { group: groupLabel(selectedAncestor(node)!) }) }}</Badge>
<Badge v-else-if="node.type === 'group' && selectedGroupIds.has(node.id)" variant="outline" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopeDynamic") }}</Badge>
<Badge v-else-if="node.type === 'group' && groupHasSelectedDescendant(node)" variant="secondary" class="shrink-0 rounded font-normal">{{ t("settings.mcpResourceScopePartial") }}</Badge>
diff --git a/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts b/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts
index 37f4dc9959..c43468f923 100644
--- a/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts
+++ b/apps/desktop/src/components/settings/__tests__/McpDatabaseScopePicker.spec.ts
@@ -90,6 +90,7 @@ function emptyPolicy(connectionId: string, scope: McpConnectionPolicy["databaseS
databaseScope: scope,
allowedDatabases: [],
databasePolicies: [],
+ allowSalesforceDml: false,
};
}
diff --git a/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts b/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts
index 1d70b1817b..c5c9f7c77c 100644
--- a/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts
+++ b/apps/desktop/src/components/settings/__tests__/McpResourceScopePicker.spec.ts
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { dispatch, findOne, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
+import { dispatch, findAll, findOne, mountComponent } from "@/components/grid/__tests__/vueHostHarness";
import type { ConnectionConfig, SidebarLayout } from "@/types/database";
vi.mock("vue-i18n", () => ({
@@ -44,6 +44,12 @@ function connection(id: string): ConnectionConfig {
};
}
+const DML_LABEL = "settings.mcpConnectionPolicyAllowSalesforceDml";
+
+function salesforceDmlCheckboxes(root: ReturnType<typeof mountComponent>["root"]) {
+ return findAll(root, (node) => node.type === "input" && node.props["aria-label"] === DML_LABEL);
+}
+
const layout: SidebarLayout = {
groups: [{ id: "g1", name: "Group 1", collapsed: false }],
order: [
@@ -169,3 +175,65 @@ describe("McpResourceScopePicker", () => {
expect(update).not.toHaveBeenCalled();
});
});
+
+describe("McpResourceScopePicker Salesforce DML opt-in", () => {
+ const sfdc = { ...connection("c2"), db_type: "salesforce" } as unknown as ConnectionConfig;
+
+ function mountWithSalesforce(props: Record<string, unknown> = {}) {
+ const setDml = vi.fn();
+ const mounted = mountComponent(McpResourceScopePicker, {
+ layout,
+ connections: [connection("c1"), sfdc],
+ allowedGroupIds: [],
+ allowedConnectionIds: ["c1", "c2"],
+ "onSet:connection-salesforce-dml": setDml,
+ ...props,
+ });
+ return { mounted, setDml };
+ }
+
+ it("offers the write opt-in only on Salesforce connections", () => {
+ const { mounted } = mountWithSalesforce();
+
+ const checkboxes = salesforceDmlCheckboxes(mounted.root);
+ expect(checkboxes).toHaveLength(1);
+ expect(checkboxes[0].props.checked).toBe(false);
+ });
+
+ it("hides the opt-in until the connection is inside the exposed scope", async () => {
+ const { mounted } = mountWithSalesforce({ allowedConnectionIds: ["c1"] });
+ expect(salesforceDmlCheckboxes(mounted.root)).toHaveLength(0);
+
+ await mounted.setProps({ allowedConnectionIds: ["c1", "c2"] });
+ expect(salesforceDmlCheckboxes(mounted.root)).toHaveLength(1);
+ });
+
+ it("emits the connection id and the requested state", () => {
+ const { mounted, setDml } = mountWithSalesforce();
+
+ dispatch(salesforceDmlCheckboxes(mounted.root)[0], "change", { target: { checked: true } });
+
+ expect(setDml).toHaveBeenCalledWith("c2", true);
+ });
+
+ it("shows a persisted opt-in as checked and a read-only rule as off", () => {
+ const optedIn = mountWithSalesforce({
+ connectionPolicies: [{ connectionId: "c2", readOnly: false, allowDangerousSql: false, allowSalesforceDml: true }],
+ });
+ expect(salesforceDmlCheckboxes(optedIn.mounted.root)[0].props.checked).toBe(true);
+
+ // Read-only is a hard ceiling server-side, so the switch must not look enabled here.
+ const readOnly = mountWithSalesforce({
+ connectionPolicies: [{ connectionId: "c2", readOnly: true, allowDangerousSql: false, allowSalesforceDml: true }],
+ });
+ expect(salesforceDmlCheckboxes(readOnly.mounted.root)[0].props.checked).toBe(false);
+ });
+
+ it("does not emit while the policy controls are disabled", () => {
+ const { mounted, setDml } = mountWithSalesforce({ disabled: true });
+
+ dispatch(salesforceDmlCheckboxes(mounted.root)[0], "change", { target: { checked: true } });
+
+ expect(setDml).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 29f241c5a5..867244922e 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -4689,7 +4689,7 @@ const canOpenSqlFileExecution = computed(() => {
const canExportAllDatabases = computed(() => {
if (activeNode.value.type !== "connection" || !activeNode.value.connectionId) return false;
const dbType = connectionStore.getConfig(activeNode.value.connectionId)?.db_type;
- return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "solr", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin"].includes(dbType || "");
+ return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin", "salesforce"].includes(dbType || "");
});
const canOpenScheduledBackups = computed(() => {
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
index d8f65deae7..822a708398 100644
--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
@@ -169,7 +169,7 @@ function resetPerFileState() {
currentFileName.value = "";
}
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "salesforce"].includes(c.db_type)));
// Mirrors the core executor gate (`relational_constraint_bypass_kind` in
// sql_file_import.rs): MySQL-family types use the session-scoped
// FOREIGN_KEY_CHECKS toggle, PostgreSQL-family types use DISABLE/ENABLE
diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
index 0106bad0e7..5f584766ac 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.spec.ts
@@ -948,11 +948,13 @@ describe("useDataGridEditor saveChanges reload", () => {
currentPage?: Ref<number>;
prepareFullReload?: () => void;
customSaveHandler?: { save: ReturnType<typeof vi.fn> };
+ confirmSaveRequest?: (request: import("@/composables/useDataGridEditor").DataGridSaveConfirmationRequest) => Promise<boolean>;
manualTransactionSessionId?: string;
ensureManualTransactionSession?: () => Promise<string>;
refreshSavedRows?: ReturnType<typeof vi.fn>;
onManualTransactionMutation?: ReturnType<typeof vi.fn>;
connectionId?: string;
+ databaseType?: import("@/types/database").DatabaseType;
primaryKeys?: string[];
onExecuteSql?: (sql: string) => Promise<void>;
} = {},
@@ -971,7 +973,7 @@ describe("useDataGridEditor saveChanges reload", () => {
const editor = useDataGridEditor({
result: computed(() => result.value),
editable: computed(() => true),
- databaseType: computed(() => "mysql"),
+ databaseType: computed(() => options.databaseType ?? "mysql"),
connectionId: computed(() => ("connectionId" in options ? options.connectionId : "connection-1")),
database: computed(() => "app"),
tableMeta: computed(() => ({
@@ -986,6 +988,7 @@ describe("useDataGridEditor saveChanges reload", () => {
joinedWriteTargets: computed(() => options.joinedWriteTargets),
onExecuteSql: computed(() => options.onExecuteSql),
customSaveHandler: computed(() => options.customSaveHandler),
+ confirmSaveRequest: computed(() => options.confirmSaveRequest),
manualTransactionSessionId: computed(() => options.manualTransactionSessionId),
ensureManualTransactionSession: computed(() => ensureManualTransactionSession.value),
onManualTransactionMutation: options.onManualTransactionMutation,
@@ -1390,6 +1393,62 @@ describe("useDataGridEditor saveChanges reload", () => {
expect(prepareFullReload).not.toHaveBeenCalled();
expect(emit).not.toHaveBeenCalledWith("reload", expect.anything());
});
+
+ // Engines that cannot roll a partial batch back (Salesforce: one REST call per
+ // record) hand the operation list to the host for review before it is written.
+ it("summarizes inserts, updates and deletes for the host save confirmation and writes once accepted", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["stmt-1", "stmt-2", "stmt-3"], rollbackStatements: [] });
+ mocks.executeBatch.mockResolvedValue({ affected_rows: 1 });
+ const confirmSaveRequest = vi.fn().mockResolvedValue(true);
+
+ const { editor } = createSaveTestEditor({ confirmSaveRequest, databaseType: "salesforce" });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+ editor.addRows(1);
+ editor.deletedRows.value.add(1);
+
+ await editor.saveChanges();
+
+ expect(confirmSaveRequest).toHaveBeenCalledTimes(1);
+ expect(confirmSaveRequest.mock.calls[0]?.[0]).toMatchObject({
+ updates: 1,
+ inserts: 1,
+ deletes: 1,
+ targetLabel: "orders_test",
+ statements: ["stmt-1", "stmt-2", "stmt-3"],
+ });
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(1);
+ expect(editor.saveError.value).toBeFalsy();
+ });
+
+ it("keeps every edit staged and reports no error when the host declines the save", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["stmt-1"], rollbackStatements: [] });
+ const confirmSaveRequest = vi.fn().mockResolvedValue(false);
+
+ const { editor } = createSaveTestEditor({ confirmSaveRequest, databaseType: "salesforce" });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+
+ await editor.saveChanges();
+
+ expect(confirmSaveRequest).toHaveBeenCalledTimes(1);
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ expect(editor.dirtyRows.value.get(0)?.get(1)).toBe("shipped");
+ expect(editor.isSaving.value).toBe(false);
+ expect(editor.saveError.value).toBeFalsy();
+ });
+
+ it("never writes an auto-save past a required confirmation", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["stmt-1"], rollbackStatements: [] });
+ const confirmSaveRequest = vi.fn().mockResolvedValue(true);
+
+ const { editor } = createSaveTestEditor({ confirmSaveRequest, databaseType: "salesforce" });
+ editor.dirtyRows.value.set(0, new Map([[1, "shipped"]]));
+
+ await editor.saveChanges({ autoSave: true });
+
+ expect(confirmSaveRequest).not.toHaveBeenCalled();
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ expect(editor.dirtyRows.value.get(0)?.get(1)).toBe("shipped");
+ });
});
describe("useDataGridEditor cell edit focus", () => {
diff --git a/apps/desktop/src/composables/__tests__/useSalesforceSaveConfirmation.spec.ts b/apps/desktop/src/composables/__tests__/useSalesforceSaveConfirmation.spec.ts
new file mode 100644
index 0000000000..1a47a94c11
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useSalesforceSaveConfirmation.spec.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from "vitest";
+import { effectScope, type EffectScope } from "vue";
+import { useSalesforceSaveConfirmation } from "@/composables/useSalesforceSaveConfirmation";
+import type { DataGridSaveConfirmationRequest } from "@/composables/useDataGridEditor";
+
+const saveRequest: DataGridSaveConfirmationRequest = {
+ updates: 2,
+ inserts: 1,
+ deletes: 0,
+ targetLabel: "Account",
+ statements: ['DBX SALESFORCE DML\n{"op":"update","object":"Account","id":"001xx000003DGbY","fields":{"Name":"Acme"}}'],
+};
+
+function createConfirmation(): { scope: EffectScope; confirmation: ReturnType<typeof useSalesforceSaveConfirmation> } {
+ const scope = effectScope();
+ const confirmation = scope.run(() => useSalesforceSaveConfirmation());
+ if (!confirmation) throw new Error("useSalesforceSaveConfirmation must run inside an effect scope");
+ return { scope, confirmation };
+}
+
+describe("useSalesforceSaveConfirmation", () => {
+ it("parks the save until the dialog confirms and exposes the batch summary", async () => {
+ const { confirmation } = createConfirmation();
+ const decision = confirmation.request(saveRequest);
+
+ expect(confirmation.open.value).toBe(true);
+ expect(confirmation.pending.value).toEqual(saveRequest);
+ expect(confirmation.updates.value).toBe(2);
+ expect(confirmation.inserts.value).toBe(1);
+ expect(confirmation.deletes.value).toBe(0);
+ expect(confirmation.total.value).toBe(3);
+ expect(confirmation.targetLabel.value).toBe("Account");
+ expect(confirmation.statements.value).toEqual(saveRequest.statements);
+ // The save stays parked: nothing is written to Salesforce until the operator decides.
+ await Promise.resolve();
+ expect(confirmation.open.value).toBe(true);
+
+ confirmation.confirm();
+
+ await expect(decision).resolves.toBe(true);
+ expect(confirmation.open.value).toBe(false);
+ expect(confirmation.pending.value).toBeNull();
+ });
+
+ it("denies the save when the dialog is dismissed", async () => {
+ const { confirmation } = createConfirmation();
+ const decision = confirmation.request(saveRequest);
+
+ // `v-model:open` writes false on Cancel, Escape and backdrop clicks alike.
+ confirmation.open.value = false;
+
+ await expect(decision).resolves.toBe(false);
+ expect(confirmation.pending.value).toBeNull();
+ });
+
+ it("denies a second concurrent save instead of leaving it waiting on a hidden dialog", async () => {
+ const { confirmation } = createConfirmation();
+ const first = confirmation.request(saveRequest);
+
+ await expect(confirmation.request({ ...saveRequest, updates: 5 })).resolves.toBe(false);
+
+ expect(confirmation.open.value).toBe(true);
+ expect(confirmation.updates.value).toBe(2);
+ confirmation.confirm();
+ await expect(first).resolves.toBe(true);
+ });
+
+ it("denies a parked save when the grid is torn down mid-review", async () => {
+ const { scope, confirmation } = createConfirmation();
+ const decision = confirmation.request(saveRequest);
+
+ scope.stop();
+
+ await expect(decision).resolves.toBe(false);
+ });
+
+ it("reports an empty summary before any save is requested", () => {
+ const { confirmation } = createConfirmation();
+
+ expect(confirmation.open.value).toBe(false);
+ expect(confirmation.total.value).toBe(0);
+ expect(confirmation.statements.value).toEqual([]);
+ expect(confirmation.targetLabel.value).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts
index fe056b462b..ec77ffc400 100644
--- a/apps/desktop/src/composables/useDataGridEditor.ts
+++ b/apps/desktop/src/composables/useDataGridEditor.ts
@@ -87,6 +87,22 @@ export interface CustomSaveHandler {
targetLabel?: string;
}
+/**
+ * Summary handed to `confirmSaveRequest` so an engine whose writes cannot be
+ * rolled back (Salesforce REST: one record per request, no transactions) can
+ * show the operator exactly what is about to happen before anything is sent.
+ */
+export interface DataGridSaveConfirmationRequest {
+ /** Rows with edited cells (one write per row). */
+ updates: number;
+ inserts: number;
+ deletes: number;
+ /** Save target name (table / sObject), when known. */
+ targetLabel?: string;
+ /** The statements about to be executed — for Salesforce these are `DBX SALESFORCE DML` pseudo-commands. */
+ statements: string[];
+}
+
export interface UseDataGridEditorOptions {
result: ComputedRef<{ columns: string[]; rows: CellValue[][] }>;
editable: ComputedRef<boolean | undefined>;
@@ -119,6 +135,12 @@ export interface UseDataGridEditorOptions {
rowStatusFilter: Ref<RowStatusFilter>;
dataGridQuickEntryEnabled?: ComputedRef<boolean>;
confirmDangerousRowDeletion?: ComputedRef<boolean>;
+ /**
+ * Optional operator review before a save is executed. Return `false` to cancel:
+ * the pending edits stay in the grid and nothing is sent. Engines whose writes
+ * cannot be rolled back (Salesforce REST) use this; auto-save never bypasses it.
+ */
+ confirmSaveRequest?: ComputedRef<((request: DataGridSaveConfirmationRequest) => Promise<boolean>) | undefined>;
/** `生成 SQL 时包含数据库名` — qualify saved tables with their database. */
includeDatabaseNameInSaveSql?: ComputedRef<boolean>;
initialEditColumn?: ComputedRef<number>;
@@ -1994,6 +2016,28 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return;
}
}
+ // Engines without transactional rollback (Salesforce: one REST call per record,
+ // a failure leaves earlier records applied) let the host review the operation
+ // list first. Auto-save never writes without that review, matching the
+ // production-database interlock above.
+ const confirmSaveRequest = options.confirmSaveRequest?.value;
+ if (confirmSaveRequest) {
+ if (saveOptions.autoSave) {
+ await finishInterruptedSaveChanges(snapshot);
+ return;
+ }
+ const saveConfirmed = await confirmSaveRequest({
+ updates: snapshot.dirtyRows.size,
+ inserts: snapshot.newRows.length,
+ deletes: snapshot.deletedRows.size,
+ targetLabel: tableMeta.value?.tableName,
+ statements: stmts,
+ });
+ if (!saveConfirmed) {
+ await finishInterruptedSaveChanges(snapshot);
+ return;
+ }
+ }
if (!editable.value || stmtOptions?.tableMeta !== tableMeta.value) {
await finishInterruptedSaveChanges(snapshot);
return;
diff --git a/apps/desktop/src/composables/useNavigationTargets.ts b/apps/desktop/src/composables/useNavigationTargets.ts
index ec12b249ac..22c6ddc55f 100644
--- a/apps/desktop/src/composables/useNavigationTargets.ts
+++ b/apps/desktop/src/composables/useNavigationTargets.ts
@@ -3,7 +3,7 @@ import { connectionObjectTreeNodeSchema, effectiveDatabaseTypeForConnection, met
import { invalidateTableMetadataCache, loadTableMetadata } from "@/lib/metadata/tableMetadataCache";
import { canApplyDataTabMetadata, canReuseActiveMongoTab, type DataTabReuseMode } from "@/lib/sidebar/dataTabOpenPolicy";
import { isNoSnapshotErrorResult, isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
-import { buildTableSelectSql } from "@/lib/table/tableSelectSql";
+import { buildTableSelectSql, requiresEagerTableMetadataForDataOpen } from "@/lib/table/tableSelectSql";
import { resolveTableDefaultSort, applyTableDefaultSortResult } from "@/lib/table/tableDefaultSort";
import { tableDataLargeValuePreviewOptions } from "@/lib/dataGrid/dataGridLargeValues";
import { editableRowIdentifierColumns, physicalTablePrimaryKeys, shouldIncludeSyntheticRowId } from "@/lib/table/tableEditing";
@@ -179,7 +179,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
return;
}
let eagerMetadata: Awaited<ReturnType<typeof loadTableMetadata>> | undefined;
- if (effectiveDbType === "mysql" || effectiveDbType === "postgres" || (settingsStore.editorSettings.tableOpenSortMode ?? "none") !== "none") {
+ if (requiresEagerTableMetadataForDataOpen(effectiveDbType) || (settingsStore.editorSettings.tableOpenSortMode ?? "none") !== "none") {
try {
eagerMetadata = await loadTableMetadata({
connectionId: target.connectionId,
diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts
index 982d18cca4..1f2a6e909f 100644
--- a/apps/desktop/src/composables/useQuickOpen.ts
+++ b/apps/desktop/src/composables/useQuickOpen.ts
@@ -25,7 +25,7 @@ const INITIAL_SQL_FILE_LIMIT = 20;
const CONTENT_SEARCH_DEBOUNCE_MS = 200;
const CONTENT_SEARCH_MAX_RESULTS = 500;
-const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos", "consul"]);
+const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos", "consul", "salesforce"]);
export interface QuickOpenItem {
id: string;
diff --git a/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts b/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts
new file mode 100644
index 0000000000..0f283c5d34
--- /dev/null
+++ b/apps/desktop/src/composables/useSalesforceSaveConfirmation.ts
@@ -0,0 +1,76 @@
+import { computed, onScopeDispose, ref, type ComputedRef, type Ref, type WritableComputedRef } from "vue";
+import type { DataGridSaveConfirmationRequest } from "@/composables/useDataGridEditor";
+
+/**
+ * Salesforce writes go out as one REST call per record and cannot be rolled back,
+ * so every grid save is reviewed before it runs. This composable turns the
+ * `confirmSaveRequest` hook from `useDataGridEditor` into a dialog decision:
+ * `request()` parks the save on a promise the dialog settles.
+ *
+ * The pending request is transient — never persisted and never outliving the
+ * component — so a dismissed grid denies the write instead of leaving it hanging.
+ */
+export function useSalesforceSaveConfirmation(): {
+ pending: Ref<DataGridSaveConfirmationRequest | null>;
+ open: WritableComputedRef<boolean>;
+ updates: ComputedRef<number>;
+ inserts: ComputedRef<number>;
+ deletes: ComputedRef<number>;
+ total: ComputedRef<number>;
+ targetLabel: ComputedRef<string | undefined>;
+ statements: ComputedRef<string[]>;
+ request: (request: DataGridSaveConfirmationRequest) => Promise<boolean>;
+ confirm: () => void;
+ cancel: () => void;
+} {
+ const pending = ref<DataGridSaveConfirmationRequest | null>(null);
+ let resolvePending: ((confirmed: boolean) => void) | undefined;
+
+ const open = computed({
+ get: () => !!pending.value,
+ set: (next: boolean) => {
+ if (!next) settle(false);
+ },
+ });
+
+ const updates = computed(() => pending.value?.updates ?? 0);
+ const inserts = computed(() => pending.value?.inserts ?? 0);
+ const deletes = computed(() => pending.value?.deletes ?? 0);
+ const total = computed(() => updates.value + inserts.value + deletes.value);
+ const targetLabel = computed(() => pending.value?.targetLabel);
+ const statements = computed(() => pending.value?.statements ?? []);
+
+ function settle(confirmed: boolean) {
+ const resolve = resolvePending;
+ resolvePending = undefined;
+ pending.value = null;
+ resolve?.(confirmed);
+ }
+
+ function request(saveRequest: DataGridSaveConfirmationRequest): Promise<boolean> {
+ return new Promise<boolean>((resolve) => {
+ if (pending.value) {
+ // A grid only saves once at a time, but never strand a second caller:
+ // deny it so that save unwinds instead of waiting on a dialog it cannot see.
+ resolve(false);
+ return;
+ }
+ pending.value = saveRequest;
+ resolvePending = resolve;
+ });
+ }
+
+ function confirm() {
+ settle(true);
+ }
+
+ function cancel() {
+ settle(false);
+ }
+
+ // The dialog is the only way to settle the promise; if it goes away first (tab
+ // closed mid-review) the parked save must be denied, not leaked.
+ onScopeDispose(() => settle(false));
+
+ return { pending, open, updates, inserts, deletes, total, targetLabel, statements, request, confirm, cancel };
+}
diff --git a/apps/desktop/src/composables/useSidebarDataOpenRuntime.ts b/apps/desktop/src/composables/useSidebarDataOpenRuntime.ts
index 3405be2494..ea4d3e5d47 100644
--- a/apps/desktop/src/composables/useSidebarDataOpenRuntime.ts
+++ b/apps/desktop/src/composables/useSidebarDataOpenRuntime.ts
@@ -10,7 +10,7 @@ import { getCachedTableMetadata, loadTableMetadata, TABLE_METADATA_CACHE_TTL_MS,
import { canApplyDataTabMetadata, dataTabMetadataNeedsRefresh, findExistingDataTabCandidate, isDataTabMetadataLifecycleStale, type DataTabOpenMode, type DataTabReuseMode } from "@/lib/sidebar/dataTabOpenPolicy";
import type { SidebarDataOpenRequest } from "@/lib/sidebar/sidebarDataOpenCoordinator";
import { hasTreeNodeDatabaseContext } from "@/lib/sidebar/treeNodeContext";
-import { buildTableSelectSql } from "@/lib/table/tableSelectSql";
+import { buildTableSelectSql, requiresEagerTableMetadataForDataOpen } from "@/lib/table/tableSelectSql";
import { resolveTableDefaultSort, applyTableDefaultSortResult } from "@/lib/table/tableDefaultSort";
import { physicalTablePrimaryKeys, shouldIncludeSyntheticRowId } from "@/lib/table/tableEditing";
import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";
@@ -354,7 +354,7 @@ export function useSidebarDataOpenRuntime() {
}
const metadataRefresh = shouldRefreshTableMeta && !deferTableMetaRefresh ? refreshTableMetaInBackground(tabId) : undefined;
- if (!cachedTableMeta && (effectiveDbType === "mysql" || effectiveDbType === "postgres" || defaultSortMode !== "none")) {
+ if (!cachedTableMeta && (requiresEagerTableMetadataForDataOpen(effectiveDbType) || defaultSortMode !== "none")) {
// No query is in flight yet, so deferred drivers can safely load metadata serially.
if (deferTableMetaRefresh) await refreshTableMetaInBackground(tabId);
await metadataRefresh;
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index 0c7d6d6e4c..ea31c092e3 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -981,7 +981,7 @@ export function supportsSqlTemplateParameters(connection: Pick<ConnectionConfig,
if (!connection) return false;
if (connection.db_type === "meilisearch" || connection.db_type === "solr") return false;
if (connection.db_type === "elasticsearch" || connection.db_type === "easysearch") return !isElasticsearchRestRequestText(sql);
- return connection.db_type !== "redis" && connection.db_type !== "mongodb" && connection.db_type !== "victoriametrics";
+ return connection.db_type !== "redis" && connection.db_type !== "mongodb" && connection.db_type !== "victoriametrics" && connection.db_type !== "salesforce";
}
export function requiresDatabaseSelection(tab: QueryTab, connection: ConnectionConfig | undefined, _sql = ""): boolean {
diff --git a/apps/desktop/src/i18n/__tests__/salesforceIdentityCopy.spec.ts b/apps/desktop/src/i18n/__tests__/salesforceIdentityCopy.spec.ts
new file mode 100644
index 0000000000..4c63879b3b
--- /dev/null
+++ b/apps/desktop/src/i18n/__tests__/salesforceIdentityCopy.spec.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import en from "../locales/en";
+import es from "../locales/es";
+import zhCN from "../locales/zh-CN";
+
+// The Salesforce save dialog and the toolbar identity badge explain *why* a
+// write may fail. The first wording claimed a non-administrator's records "are
+// rejected by Salesforce row by row", which conflates two independent layers:
+// field writability comes from the profile's field-level security (the grid
+// already renders those columns read-only from describe's `updateable` /
+// `createable`, which Salesforce computes for the current user), while
+// record-level failures come from sharing rules, validation rules, Flow or
+// Apex. The `Modify All Data` flag only says whether the profile bypasses
+// those layers — it never decides whether a field is editable.
+//
+// These assertions pin the corrected contract so the misleading claim cannot
+// silently return: every identity line names the profile as well as the user,
+// the non-administrator line talks about permissions instead of rank, and the
+// old key is gone rather than left behind unused.
+const locales: Array<[string, Record<string, unknown>]> = [
+ ["en", en as Record<string, unknown>],
+ ["es", es],
+ ["zh-CN", zhCN],
+];
+
+const saveIdentityKeys = ["salesforceSaveAdminIdentity", "salesforceSaveNonAdminIdentity", "salesforceSaveUnknownRights"] as const;
+
+/** Words that would put the admin flag back at the centre of a field-level warning. */
+const adminWords = ["administrator", "administrador", "administrateur", "系统管理员", "管理员"] as const;
+
+function entry(locale: Record<string, unknown>, namespace: string, key: string): string | undefined {
+ const section = locale[namespace];
+ if (!section || typeof section !== "object") return undefined;
+ const value = (section as Record<string, unknown>)[key];
+ return typeof value === "string" ? value : undefined;
+}
+
+describe("salesforce identity copy", () => {
+ it.each(locales)("%s interpolates user and profile into every save identity line", (name, locale) => {
+ for (const key of saveIdentityKeys) {
+ const value = entry(locale, "grid", key);
+ expect(value, `${name} grid.${key} missing`).toBeTypeOf("string");
+ expect(value, `${name} grid.${key} must name the user`).toContain("{user}");
+ expect(value, `${name} grid.${key} must name the profile`).toContain("{profile}");
+ }
+ expect(entry(locale, "grid", "salesforceSaveProfile"), `${name} grid.salesforceSaveProfile missing`).toContain("{name}");
+ });
+
+ it.each(locales)("%s dropped the admin-blaming save warning", (name, locale) => {
+ // The renamed key must not linger: a stale copy invites someone to reuse it.
+ expect(entry(locale, "grid", "salesforceSaveNonAdminWarning"), `${name} still ships the old key`).toBeUndefined();
+ });
+
+ it.each(locales)("%s explains the non-administrator save case with permissions, not rank", (name, locale) => {
+ const value = entry(locale, "grid", "salesforceSaveNonAdminIdentity") ?? "";
+ for (const word of adminWords) {
+ expect(value.toLowerCase(), `${name} grid.salesforceSaveNonAdminIdentity mentions "${word}"`).not.toContain(word.toLowerCase());
+ }
+ });
+
+ it.each(locales)("%s attributes the toolbar rights line to the profile", (name, locale) => {
+ for (const key of ["salesforceIdentityAdmin", "salesforceIdentityNonAdmin", "salesforceIdentityUnknownRights"] as const) {
+ expect(entry(locale, "toolbar", key), `${name} toolbar.${key} missing`).toBeTypeOf("string");
+ }
+ // `is_admin` is read from `Profile.PermissionsModifyAllData` only, so a
+ // permission set can still grant the right: the wording has to stay about
+ // the profile, never a flat "this user is not an administrator".
+ const nonAdmin = (entry(locale, "toolbar", "salesforceIdentityNonAdmin") ?? "").toLowerCase();
+ expect(
+ ["profile", "perfil", "简档"].some((word) => nonAdmin.includes(word)),
+ `${name} toolbar.salesforceIdentityNonAdmin should scope the claim to the profile`,
+ ).toBe(true);
+ });
+
+ it("zh-CN translates Profile as 简档, not 配置文件", () => {
+ // "配置文件" reads as a config file; Salesforce's Profile is 简档.
+ expect(entry(zhCN, "toolbar", "salesforceIdentityUnknownProfile")).toBe("简档未知");
+ expect(entry(zhCN, "grid", "salesforceSaveProfile")).toContain("简档");
+ });
+});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 4bd88c775a..d60f3322bf 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -8111,6 +8111,10 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "Yalnız oxuma",
mcpConnectionPolicySafeWrite: "Təhlükəsiz yazma əməliyyatlarına icazə ver",
mcpConnectionPolicyHighRiskWrite: "Yüksək riskli əməliyyatlara icazə ver",
+ mcpConnectionPolicyAllowSalesforceDml: "DML-ə icazə ver",
+ mcpConnectionPolicyAllowSalesforceDmlHint:
+ "Süni intellekt agentinə iki mərhələli təsdiqlə (əvvəlcə hazırla, sonra tətbiq et) bu orqanizasyonda tək Salesforce qeydlərini yaratmağa, yeniləməyə və ya silməyə imkan verir. Yalnız oxumaq rejimləri bu açarı nəzərə almır. Salesforce yazılışları geri qaytarıla bilməz.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "Bu bağlantı yalnız oxumaq üçün olduğundan Salesforce DML bağlı qalır. Əvvəlcə yazmağa icazə verən icra rejimini seçin.",
mcpToolPermissionsTitle: "MCP alət icazələri",
mcpToolPermissionsDescription: "Yalnız ehtiyacınız olan MCP alətlərini təqdim edin. Seçim ləğv edildikdə, müştərilər alət təriflərini keşdə saxlamış olsalar belə, server onların müraciətlərini rədd edir.",
mcpToolListConnections: "Əlaqələri siyahıla",
@@ -8128,6 +8132,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "Tranzaksiyanı geri qaytar",
mcpToolCloseSession: "Sorğu sessiyasını bağla",
mcpToolExecuteRedisCommand: "Redis əmrini icra et",
+ mcpToolSalesforceCurrentUser: "Salesforce cari istifadəçisi",
+ mcpToolSalesforcePrepareWrite: "Salesforce yazılışını hazırla",
+ mcpToolSalesforceApplyWrite: "Salesforce yazılışını tətbiq et",
mcpToolPeekMessages: "Kafka mesajlarını oxu",
mcpToolSendMessage: "Mesaj növbəsinə mesaj göndər",
mcpToolAddConnection: "Əlaqə əlavə et",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index f754cf73dd..99502e4a65 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -400,6 +400,10 @@ export default {
commit: "Commit",
rollback: "Rollback",
txnAutoRolledBack: "Transaction auto-rolled back after 5 minutes of inactivity",
+ salesforceIdentityAdmin: "Profile has “Modify All Data” — bypasses field-level security and record sharing",
+ salesforceIdentityNonAdmin: "Profile has no “Modify All Data” — field permissions and record sharing apply",
+ salesforceIdentityUnknownRights: "Could not determine whether the profile has “Modify All Data”",
+ salesforceIdentityUnknownProfile: "Profile unknown",
autoCommitTxnRolledBack: 'An explicit transaction left open by this tab was rolled back automatically; turn on "Keep explicit auto-commit transactions" to keep it across executions',
autoCommitSessionTxnRolledBack: "This connection runs with auto-commit off (SET autocommit = 0), so its implicit transaction was rolled back after the execution; DBX reports that once per connection",
previewSql: "Preview SQL",
@@ -857,6 +861,65 @@ export default {
victoriametricsLookbackHint: "Used for metric discovery and label columns, for example 1h or 7d. Metric previews use 1h and remain editable.",
victoriametricsInvalidApiPath: "The VictoriaMetrics API path must be empty or start with /.",
victoriametricsInvalidLookback: "Invalid VictoriaMetrics lookback. Use a value such as 15m, 1h, or 7d.",
+ salesforceInstanceUrl: "Instance URL",
+ salesforceInstanceUrlPlaceholder: "https://acme.my.salesforce.com",
+ salesforceInstanceUrlHint: "Org hostname or full instance URL; refreshed automatically from the token response after a successful sign-in.",
+ salesforceAccessToken: "Access Token",
+ salesforceAccessTokenPlaceholder: "Session ID or access token",
+ salesforceAccessTokenHint: "Paste a Salesforce access token or session ID. Use the OAuth options below for browser-based login or device-code authorization.",
+ salesforceApiVersion: "API Version",
+ salesforceApiVersionHint: "Salesforce REST API version, e.g. v62.0. Leave empty to use the default pinned version.",
+ salesforceAuthMode: "Authentication",
+ salesforceAuthModeToken: "Access Token",
+ salesforceAuthModeOauth: "Browser OAuth",
+ salesforceAuthModeDevice: "Device Code",
+ salesforceAuthModePassword: "Username & Password",
+ salesforceAuthModeOauthDesktopOnly: "Browser OAuth is only available in the desktop app.",
+ salesforceEnvironment: "Environment",
+ salesforceEnvironmentProduction: "Production",
+ salesforceEnvironmentSandbox: "Sandbox",
+ salesforceEnvironmentCustom: "Custom",
+ salesforceLoginUrl: "Login URL",
+ salesforceLoginUrlPlaceholder: "https://login.salesforce.com",
+ salesforceLoginUrlHint: "Override the Salesforce login URL when your org uses a custom identity endpoint.",
+ salesforceClientId: "Client ID",
+ salesforceClientIdPlaceholder: "Consumer Key from your Connected App",
+ salesforceClientIdHint: "Create a Connected App in Salesforce Setup → App Manager, enable OAuth with PKCE, and set the Callback URL to {callbackUrl}.",
+ salesforceClientIdHintShared: "The Connected App consumer key. These two modes use no callback URL, so an app your admin already created works as-is.",
+ salesforceClientSecret: "Client Secret",
+ salesforceClientSecretPlaceholder: "Optional — confidential Connected Apps only; leave empty for PKCE public clients",
+ salesforceOauthAuthorize: "Authorize with Salesforce",
+ salesforceOauthAuthorizing: "Waiting for browser login…",
+ salesforceOauthAuthorizingHint: "A browser window should be open. Complete the login in Salesforce; this view will update automatically when it finishes.",
+ salesforceOauthAuthorized: "Authorized (credentials saved)",
+ salesforceOauthReauthorize: "Re-authorize",
+ salesforceOauthClientIdRequired: "Salesforce Client ID is required.",
+ salesforceOauthLoginUrlRequired: "Salesforce custom Login URL is required.",
+ salesforceDeviceGetCode: "Get Device Code",
+ salesforceDeviceFlowNote: "If requesting the code fails with an unsupported or disabled-flow error, an admin must enable Device Flow in the Connected App's OAuth settings.",
+ salesforceDeviceUserCodeLabel: "User Code",
+ salesforceDeviceUserCodeCopied: "User code copied",
+ salesforceDeviceOpenVerification: "Open verification page",
+ salesforceDeviceVerificationCopied: "Verification URL copied",
+ salesforceDevicePolling: "Waiting for authorization…",
+ salesforceDevicePollingHint: "Open the verification page in any browser and enter the user code shown above.",
+ salesforceDeviceCancel: "Cancel",
+ salesforceDeviceExpired: "Device code expired. Click below to request a new one.",
+ salesforceDeviceDenied: "Authorization denied",
+ salesforceDeviceRestart: "Start over",
+ salesforceDeviceSecondsLeft: "{seconds}s remaining",
+ salesforceUsernameLabel: "Username",
+ salesforceUsernamePlaceholder: "user{'@'}example.com",
+ salesforceUsernameHint: "Salesforce username. For sandboxes, include the sandbox suffix (e.g. user{'@'}example.com.qas1).",
+ salesforceUserPasswordLabel: "User Password",
+ salesforceUserPasswordPlaceholder: "Password (optionally + security token)",
+ salesforceUserPasswordHint: "Your Salesforce password. If your IP is not trusted by the org, append your security token directly after the password. Sessions are re-authenticated automatically with these saved credentials.",
+ salesforcePasswordRopcNote: "No callback URL needed — an existing Connected App works. Your profile needs API Enabled and the app's user policy must cover you. The password never returns to this form, so the sign-in button needs it typed again.",
+ salesforcePasswordSignIn: "Sign In",
+ salesforcePasswordSignInAgain: "Sign In Again",
+ salesforceUsernameRequired: "Salesforce username is required.",
+ salesforceUserPasswordRequired: "Salesforce password is required.",
+ salesforceOauthSuccess: "Connected to {instanceUrl}",
driverInstallHintPrefix: "Install the required driver from ",
driverInstallHintSuffix: " in the top toolbar before connecting.",
driverName: "Driver Name",
@@ -2675,6 +2738,18 @@ export default {
rollback: "Rollback",
transactionSaveHint: "Commit {count} pending change(s) in a transaction.",
nonTransactionalSaveHint: "Save {count} pending change(s) one by one. If one fails, earlier successful changes will not be rolled back.",
+ salesforceSaveConfirmTitle: "Apply Changes to Salesforce",
+ salesforceSaveConfirmMessage: "{count} pending change(s) are sent to Salesforce as one REST call per record. There is no transaction: if a call fails partway, the records already written stay changed.",
+ salesforceSaveUpdates: "{count} update(s)",
+ salesforceSaveInserts: "{count} new record(s)",
+ salesforceSaveDeletes: "{count} delete(s)",
+ salesforceSaveTarget: "Object: {object}",
+ salesforceSaveUnknownObject: "unknown",
+ salesforceSaveProfile: "profile {name}",
+ salesforceSaveAdminIdentity: "Writing as {user} ({profile}); this profile has “Modify All Data”, which bypasses field-level security and record sharing — please double-check.",
+ salesforceSaveNonAdminIdentity: "Signed in as {user} ({profile}).\nFields you cannot write are already read-only here;\nfailures from record sharing or validation rules come back per row, in Salesforce’s own words.",
+ salesforceSaveUnknownRights: "Signed in as {user} ({profile}); could not determine whether this profile has “Modify All Data” — Salesforce still enforces its own permissions and reports failures per row.",
+ salesforceSaveConfirm: "Apply to Salesforce",
keylessEditWarning: "No primary key",
keylessEditWarningHint: "This table has no primary key. Updates and deletes use all original row values in the WHERE clause; exact duplicate rows may be affected together.",
queryEditReadOnly: "Read-only result",
@@ -8678,6 +8753,9 @@ export default {
mcpConnectionPolicyReadOnly: "Read only",
mcpConnectionPolicySafeWrite: "Allow safe writes",
mcpConnectionPolicyHighRiskWrite: "Allow high-risk operations",
+ mcpConnectionPolicyAllowSalesforceDml: "Allow DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint: "Lets an AI agent create, update, or delete single Salesforce records in this org through a two-step confirmation (prepare, then apply). Read-only modes ignore this switch. Salesforce writes cannot be rolled back.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "This connection is read-only, so Salesforce DML stays disabled. Choose a write-capable execution mode first.",
mcpToolPermissionsTitle: "MCP tool permissions",
mcpToolPermissionsDescription: "Expose only the MCP tools you need. Once deselected, clients are rejected by the server even if they cached the tool definitions.",
mcpToolListConnections: "List connections",
@@ -8695,6 +8773,9 @@ export default {
mcpToolRollbackTransaction: "Roll back transaction",
mcpToolCloseSession: "Close query session",
mcpToolExecuteRedisCommand: "Execute Redis command",
+ mcpToolSalesforceCurrentUser: "Salesforce current user",
+ mcpToolSalesforcePrepareWrite: "Prepare Salesforce write",
+ mcpToolSalesforceApplyWrite: "Apply Salesforce write",
mcpToolPeekMessages: "Read Kafka messages",
mcpToolSendMessage: "Send message queue message",
mcpToolAddConnection: "Add connection",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 2a6fa1c857..c2dfbb5acc 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -391,6 +391,10 @@ export default withEnglishFallback({
commit: "Confirmar",
rollback: "Revertir",
txnAutoRolledBack: "Transacción revertida automáticamente tras 5 minutos de inactividad",
+ salesforceIdentityAdmin: "El perfil tiene “Modify All Data”: omite la seguridad a nivel de campo y el uso compartido de registros",
+ salesforceIdentityNonAdmin: "El perfil no tiene “Modify All Data”: los permisos de campos y el uso compartido siguen aplicándose",
+ salesforceIdentityUnknownRights: "No se pudo determinar si el perfil tiene “Modify All Data”",
+ salesforceIdentityUnknownProfile: "Perfil desconocido",
autoCommitTxnRolledBack: 'La transacción explícita que esta pestaña dejó abierta se revirtió automáticamente; activa "Mantener transacciones explícitas en modo autocommit" para conservarla entre ejecuciones',
autoCommitSessionTxnRolledBack: "Esta conexión trabaja con autocommit desactivado (SET autocommit = 0), así que su transacción implícita se revirtió tras la ejecución; DBX lo avisa una vez por conexión",
previewSql: "Vista previa de SQL",
@@ -837,6 +841,65 @@ export default withEnglishFallback({
victoriametricsLookbackHint: "Se usa para descubrir métricas y columnas de etiquetas, por ejemplo, 1h o 7d. Las vistas previas de métricas usan 1h y se pueden editar.",
victoriametricsInvalidApiPath: "La ruta de la API de VictoriaMetrics debe estar vacía o comenzar por /.",
victoriametricsInvalidLookback: "El intervalo retrospectivo de VictoriaMetrics no es válido. Use un valor como 15m, 1h o 7d.",
+ salesforceInstanceUrl: "URL de la instancia",
+ salesforceInstanceUrlPlaceholder: "https://acme.my.salesforce.com",
+ salesforceInstanceUrlHint: "Nombre de host del org o URL de instancia completa; se rellena sola desde la respuesta del token tras iniciar sesión.",
+ salesforceAccessToken: "Token de acceso",
+ salesforceAccessTokenPlaceholder: "ID de sesión o token de acceso",
+ salesforceAccessTokenHint: "Pega un token de acceso o ID de sesión de Salesforce. También puedes usar las opciones OAuth de abajo para iniciar sesión en el navegador o mediante código de dispositivo.",
+ salesforceApiVersion: "Versión de la API",
+ salesforceApiVersionHint: "Versión de la API REST de Salesforce, por ejemplo v62.0. Déjalo vacío para usar la versión fija por defecto.",
+ salesforceAuthMode: "Autenticación",
+ salesforceAuthModeToken: "Token de acceso",
+ salesforceAuthModeOauth: "OAuth en navegador",
+ salesforceAuthModeDevice: "Código de dispositivo",
+ salesforceAuthModePassword: "Usuario y contraseña",
+ salesforceAuthModeOauthDesktopOnly: "OAuth en navegador solo está disponible en la aplicación de escritorio.",
+ salesforceEnvironment: "Entorno",
+ salesforceEnvironmentProduction: "Producción",
+ salesforceEnvironmentSandbox: "Sandbox",
+ salesforceEnvironmentCustom: "Personalizado",
+ salesforceLoginUrl: "URL de inicio de sesión",
+ salesforceLoginUrlPlaceholder: "https://login.salesforce.com",
+ salesforceLoginUrlHint: "Sobrescribe la URL de inicio de sesión de Salesforce cuando tu organización usa un endpoint de identidad personalizado.",
+ salesforceClientId: "Client ID",
+ salesforceClientIdPlaceholder: "Consumer Key de tu Connected App",
+ salesforceClientIdHint: "Crea una Connected App en Salesforce Setup → App Manager, habilita OAuth con PKCE y establece la Callback URL en {callbackUrl}.",
+ salesforceClientIdHintShared: "La consumer key de la Connected App. Estos dos modos no usan callback URL, así que sirve una app que tu admin ya haya creado.",
+ salesforceClientSecret: "Client Secret",
+ salesforceClientSecretPlaceholder: "Opcional — solo Connected Apps confidenciales; déjalo vacío en clientes públicos con PKCE",
+ salesforceOauthAuthorize: "Autorizar con Salesforce",
+ salesforceOauthAuthorizing: "Esperando el inicio de sesión en el navegador…",
+ salesforceOauthAuthorizingHint: "Debería haber una ventana del navegador abierta. Completa el inicio de sesión en Salesforce; esta vista se actualizará automáticamente al terminar.",
+ salesforceOauthAuthorized: "Autorizado (credenciales guardadas)",
+ salesforceOauthReauthorize: "Volver a autorizar",
+ salesforceOauthClientIdRequired: "El Client ID de Salesforce es obligatorio.",
+ salesforceOauthLoginUrlRequired: "La URL de inicio de sesión personalizada de Salesforce es obligatoria.",
+ salesforceDeviceGetCode: "Obtener código de dispositivo",
+ salesforceDeviceFlowNote: "Si al pedir el código falla con un error de flujo no soportado o deshabilitado, un admin debe habilitar Device Flow en los ajustes OAuth de la Connected App.",
+ salesforceDeviceUserCodeLabel: "Código de usuario",
+ salesforceDeviceUserCodeCopied: "Código de usuario copiado",
+ salesforceDeviceOpenVerification: "Abrir página de verificación",
+ salesforceDeviceVerificationCopied: "URL de verificación copiada",
+ salesforceDevicePolling: "Esperando la autorización…",
+ salesforceDevicePollingHint: "Abre la página de verificación en cualquier navegador e introduce el código de usuario mostrado arriba.",
+ salesforceDeviceCancel: "Cancelar",
+ salesforceDeviceExpired: "El código de dispositivo ha expirado. Haz clic abajo para solicitar uno nuevo.",
+ salesforceDeviceDenied: "Autorización denegada",
+ salesforceDeviceRestart: "Empezar de nuevo",
+ salesforceDeviceSecondsLeft: "Quedan {seconds} s",
+ salesforceUsernameLabel: "Usuario",
+ salesforceUsernamePlaceholder: "user{'@'}example.com",
+ salesforceUsernameHint: "Usuario de Salesforce. En sandboxes, incluye el sufijo del sandbox (p. ej. user{'@'}example.com.qas1).",
+ salesforceUserPasswordLabel: "Contraseña",
+ salesforceUserPasswordPlaceholder: "Contraseña (opcional + token de seguridad)",
+ salesforceUserPasswordHint: "Tu contraseña de Salesforce. Si tu IP no es de confianza para la organización, añade el token de seguridad justo después de la contraseña. Las sesiones se reautentican automáticamente con estas credenciales guardadas.",
+ salesforcePasswordRopcNote: "No hace falta callback URL: sirve una Connected App existente. Tu perfil necesita API Enabled y la política de usuarios de la app debe cubrirte. La contraseña no vuelve a este formulario, así que el botón de inicio de sesión necesita que la escribas de nuevo.",
+ salesforcePasswordSignIn: "Iniciar sesión",
+ salesforcePasswordSignInAgain: "Volver a iniciar sesión",
+ salesforceUsernameRequired: "El usuario de Salesforce es obligatorio.",
+ salesforceUserPasswordRequired: "La contraseña de Salesforce es obligatoria.",
+ salesforceOauthSuccess: "Conectado a {instanceUrl}",
driverInstallHintPrefix: "Instala el driver requerido desde ",
driverInstallHintSuffix: " en la barra superior antes de conectar.",
driverName: "Nombre del driver",
@@ -2499,6 +2562,18 @@ export default withEnglishFallback({
rollback: "Revertir",
transactionSaveHint: "Confirma {count} cambio(s) pendiente(s) en una transacción.",
nonTransactionalSaveHint: "Guarda {count} cambio(s) pendiente(s) uno por uno. Si uno falla, los cambios anteriores correctos no se revierten.",
+ salesforceSaveConfirmTitle: "Aplicar cambios en Salesforce",
+ salesforceSaveConfirmMessage: "{count} cambio(s) pendiente(s) se envían a Salesforce con una llamada REST por registro. No hay transacción: si una llamada falla a mitad de camino, los registros ya escritos permanecen modificados.",
+ salesforceSaveUpdates: "{count} actualización(es)",
+ salesforceSaveInserts: "{count} registro(s) nuevo(s)",
+ salesforceSaveDeletes: "{count} eliminación(es)",
+ salesforceSaveTarget: "Objeto: {object}",
+ salesforceSaveUnknownObject: "desconocido",
+ salesforceSaveProfile: "perfil {name}",
+ salesforceSaveAdminIdentity: "Se escribirá como {user} ({profile}); este perfil tiene “Modify All Data”, que omite la seguridad a nivel de campo y el uso compartido de registros. Confirma con cuidado.",
+ salesforceSaveNonAdminIdentity: "Sesión iniciada como {user} ({profile}).\nLos campos que no puedes escribir ya están en solo lectura;\nlos fallos por uso compartido de registros o reglas de validación se devuelven fila por fila, con el mensaje original de Salesforce.",
+ salesforceSaveUnknownRights: "Sesión iniciada como {user} ({profile}); no se pudo determinar si este perfil tiene “Modify All Data”. Salesforce sigue aplicando sus propios permisos e informa los fallos fila por fila.",
+ salesforceSaveConfirm: "Aplicar en Salesforce",
keylessEditWarning: "Sin clave primaria",
keylessEditWarningHint: "Esta tabla no tiene clave primaria. Las actualizaciones y eliminaciones usan todos los valores originales de la fila en WHERE; filas duplicadas exactas pueden verse afectadas juntas.",
queryEditReadOnly: "Resultado de solo lectura",
@@ -8011,6 +8086,10 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "Solo lectura",
mcpConnectionPolicySafeWrite: "Permitir escrituras seguras",
mcpConnectionPolicyHighRiskWrite: "Permitir operaciones de alto riesgo",
+ mcpConnectionPolicyAllowSalesforceDml: "Permitir DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint:
+ "Permite que un agente de IA cree, actualice o elimine registros individuales de Salesforce en esta organización mediante una confirmación en dos pasos (preparar y luego aplicar). Los modos de solo lectura ignoran este interruptor. Las escrituras en Salesforce no se pueden revertir.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "Esta conexión es de solo lectura, por lo que DML de Salesforce permanece desactivado. Elija primero un modo de ejecución que permita escrituras.",
mcpToolPermissionsTitle: "Permisos de herramientas MCP",
mcpToolPermissionsDescription: "Expón solo las herramientas MCP que necesitas. Al desmarcarlas, el servidor rechaza las solicitudes aunque el cliente haya cacheado las definiciones.",
mcpToolListConnections: "Listar conexiones",
@@ -8028,6 +8107,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "Revertir transacción",
mcpToolCloseSession: "Cerrar sesión de consulta",
mcpToolExecuteRedisCommand: "Ejecutar comando Redis",
+ mcpToolSalesforceCurrentUser: "Usuario actual de Salesforce",
+ mcpToolSalesforcePrepareWrite: "Preparar escritura en Salesforce",
+ mcpToolSalesforceApplyWrite: "Aplicar escritura en Salesforce",
mcpToolPeekMessages: "Leer mensajes de Kafka",
mcpToolSendMessage: "Enviar mensaje de cola de mensajes",
mcpToolAddConnection: "Añadir conexión",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 91e3341b50..edb2740e5f 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8010,6 +8010,10 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "Sola lettura",
mcpConnectionPolicySafeWrite: "Consenti scritture sicure",
mcpConnectionPolicyHighRiskWrite: "Consenti operazioni ad alto rischio",
+ mcpConnectionPolicyAllowSalesforceDml: "Consenti DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint:
+ "Consente a un agente IA di creare, aggiornare o eliminare singoli record Salesforce in questa organizzazione tramite una conferma in due passaggi (prepara, poi applica). Le modalità di sola lettura ignorano questa opzione. Le scritture Salesforce non possono essere annullate.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "Questa connessione è in sola lettura, quindi DML Salesforce resta disattivato. Scegli prima una modalità di esecuzione che consenta le scritture.",
mcpToolPermissionsTitle: "Permessi degli strumenti MCP",
mcpToolPermissionsDescription: "Esporre solo gli strumenti MCP necessari. Dopo la deselezione, le richieste vengono rifiutate dal server anche se il client ha le definizioni in cache.",
mcpToolListConnections: "Elenca connessioni",
@@ -8027,6 +8031,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "Annulla transazione",
mcpToolCloseSession: "Chiudi sessione di query",
mcpToolExecuteRedisCommand: "Esegui comando Redis",
+ mcpToolSalesforceCurrentUser: "Utente Salesforce corrente",
+ mcpToolSalesforcePrepareWrite: "Prepara scrittura Salesforce",
+ mcpToolSalesforceApplyWrite: "Applica scrittura Salesforce",
mcpToolPeekMessages: "Leggi messaggi Kafka",
mcpToolSendMessage: "Invia messaggio in coda",
mcpToolAddConnection: "Aggiungi connessione",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index e53249ef9b..6908e7f0ff 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8014,6 +8014,9 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "読み取り専用のみ",
mcpConnectionPolicySafeWrite: "安全な書き込みを許可",
mcpConnectionPolicyHighRiskWrite: "高リスク操作を許可",
+ mcpConnectionPolicyAllowSalesforceDml: "DML を許可",
+ mcpConnectionPolicyAllowSalesforceDmlHint: "AI エージェントが 2 段階の確認(準備してから適用)を経て、この組織の Salesforce レコードを 1 件ずつ作成・更新・削除できるようにします。読み取り専用モードではこのスイッチは無視されます。Salesforce の書き込みはロールバックできません。",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "この接続は読み取り専用のため、Salesforce DML は無効のままです。先に書き込みを許可する実行モードを選択してください。",
mcpToolPermissionsTitle: "MCP ツール権限",
mcpToolPermissionsDescription: "必要な MCP ツールのみ公開します。選択を解除すると、ツール定義をキャッシュしたクライアントもサーバー側で拒否されます。",
mcpToolListConnections: "接続を一覧",
@@ -8031,6 +8034,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "トランザクションをロールバック",
mcpToolCloseSession: "クエリセッションを閉じる",
mcpToolExecuteRedisCommand: "Redis コマンドを実行",
+ mcpToolSalesforceCurrentUser: "Salesforce の現在のユーザー",
+ mcpToolSalesforcePrepareWrite: "Salesforce 書き込みを準備",
+ mcpToolSalesforceApplyWrite: "Salesforce 書き込みを適用",
mcpToolPeekMessages: "Kafka メッセージを読み取る",
mcpToolSendMessage: "メッセージキューのメッセージを送信",
mcpToolAddConnection: "接続を追加",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index d8a65d9d50..f1e72b7586 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7789,6 +7789,9 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "읽기 전용만",
mcpConnectionPolicySafeWrite: "안전한 쓰기 허용",
mcpConnectionPolicyHighRiskWrite: "고위험 작업 허용",
+ mcpConnectionPolicyAllowSalesforceDml: "DML 허용",
+ mcpConnectionPolicyAllowSalesforceDmlHint: "AI 에이전트가 2단계 확인(준비 후 적용)을 거쳐 이 조직의 Salesforce 레코드를 하나씩 생성·수정·삭제할 수 있게 합니다. 읽기 전용 모드에서는 이 스위치가 무시됩니다. Salesforce 쓰기는 롤백할 수 없습니다.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "이 연결은 읽기 전용이므로 Salesforce DML은 비활성 상태로 유지됩니다. 먼저 쓰기를 허용하는 실행 모드를 선택하세요.",
mcpToolPermissionsTitle: "MCP 도구 권한",
mcpToolPermissionsDescription: "필요한 MCP 도구만 노출하세요. 선택 해제하면 도구 정의를 캐시한 클라이언트도 서버에서 거부됩니다.",
mcpToolListConnections: "연결 나열",
@@ -7806,6 +7809,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "트랜잭션 롤백",
mcpToolCloseSession: "쿼리 세션 닫기",
mcpToolExecuteRedisCommand: "Redis 명령 실행",
+ mcpToolSalesforceCurrentUser: "Salesforce 현재 사용자",
+ mcpToolSalesforcePrepareWrite: "Salesforce 쓰기 준비",
+ mcpToolSalesforceApplyWrite: "Salesforce 쓰기 적용",
mcpToolPeekMessages: "Kafka 메시지 읽기",
mcpToolSendMessage: "메시지 큐 메시지 전송",
mcpToolAddConnection: "연결 추가",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index f55ef22268..884a0ae097 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8012,6 +8012,10 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "Somente leitura",
mcpConnectionPolicySafeWrite: "Permitir escritas seguras",
mcpConnectionPolicyHighRiskWrite: "Permitir operações de alto risco",
+ mcpConnectionPolicyAllowSalesforceDml: "Permitir DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint:
+ "Permite que um agente de IA crie, atualize ou exclua registros individuais do Salesforce nesta organização por meio de uma confirmação em duas etapas (preparar e depois aplicar). Modos somente leitura ignoram esta opção. Gravações no Salesforce não podem ser revertidas.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "Esta conexão é somente leitura, então o DML do Salesforce permanece desativado. Escolha primeiro um modo de execução que permita gravações.",
mcpToolPermissionsTitle: "Permissões de ferramentas MCP",
mcpToolPermissionsDescription: "Exponha apenas as ferramentas MCP necessárias. Ao desmarcá-las, o servidor recusa as solicitações mesmo que o cliente tenha as definições em cache.",
mcpToolListConnections: "Listar conexões",
@@ -8029,6 +8033,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "Reverter transação",
mcpToolCloseSession: "Fechar sessão de consulta",
mcpToolExecuteRedisCommand: "Executar comando Redis",
+ mcpToolSalesforceCurrentUser: "Usuário atual do Salesforce",
+ mcpToolSalesforcePrepareWrite: "Preparar gravação no Salesforce",
+ mcpToolSalesforceApplyWrite: "Aplicar gravação no Salesforce",
mcpToolPeekMessages: "Ler mensagens Kafka",
mcpToolSendMessage: "Enviar mensagem da fila",
mcpToolAddConnection: "Adicionar conexão",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index e1abd3a350..07034b7b57 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -8009,6 +8009,10 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "Salt okunur",
mcpConnectionPolicySafeWrite: "Güvenli yazmalara izin ver",
mcpConnectionPolicyHighRiskWrite: "Yüksek riskli işlemlere izin ver",
+ mcpConnectionPolicyAllowSalesforceDml: "DML'ye izin ver",
+ mcpConnectionPolicyAllowSalesforceDmlHint:
+ "Bir yapay zekâ aracısının iki adımlı onay (önce hazırla, sonra uygula) ile bu kuruluştaki tek tek Salesforce kayıtlarını oluşturmasına, güncellemesine veya silmesine izin verir. Salt okunur modlar bu anahtarı yok sayar. Salesforce yazmaları geri alınamaz.",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "Bu bağlantı salt okunur olduğundan Salesforce DML devre dışı kalır. Önce yazmaya izin veren bir çalıştırma modu seçin.",
mcpToolPermissionsTitle: "MCP araç yetkileri",
mcpToolPermissionsDescription: "Yalnızca ihtiyacınız olan MCP araçlarını açın. Seçim kaldırıldığında, araç tanımlarını önbelleğe almış olsalar bile istemciler sunucu tarafından reddedilir.",
mcpToolListConnections: "Bağlantıları listele",
@@ -8026,6 +8030,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "İşlemi geri al",
mcpToolCloseSession: "Sorgu oturumunu kapat",
mcpToolExecuteRedisCommand: "Redis komutunu çalıştır",
+ mcpToolSalesforceCurrentUser: "Salesforce geçerli kullanıcısı",
+ mcpToolSalesforcePrepareWrite: "Salesforce yazmasını hazırla",
+ mcpToolSalesforceApplyWrite: "Salesforce yazmasını uygula",
mcpToolPeekMessages: "Kafka mesajlarını oku",
mcpToolSendMessage: "Mesaj kuyruğu mesajı gönder",
mcpToolAddConnection: "Bağlantı ekle",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 113cc2df5d..efde0fbccc 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -316,6 +316,10 @@ export default withEnglishFallback({
commit: "提交",
rollback: "回滚",
txnAutoRolledBack: "事务已因 5 分钟无操作而自动回滚",
+ salesforceIdentityAdmin: "简档具有“修改所有数据”权限——会绕过字段级安全与记录共享",
+ salesforceIdentityNonAdmin: "简档不含“修改所有数据”权限——字段权限与记录共享照常生效",
+ salesforceIdentityUnknownRights: "无法确认简档是否具有“修改所有数据”权限",
+ salesforceIdentityUnknownProfile: "简档未知",
autoCommitTxnRolledBack: "该标签页遗留的显式事务已被自动回滚;如需跨多次执行保留事务,可在设置中开启「自动提交模式下保留显式事务」",
autoCommitSessionTxnRolledBack: "该连接处于 autocommit=0,本次执行留下的隐式事务已被自动回滚;同一连接只提示一次",
previewSql: "预览 SQL",
@@ -773,6 +777,65 @@ export default withEnglishFallback({
victoriametricsLookbackHint: "用于指标列表和标签列,例如 1h、7d。双击指标默认预览 1h,并可直接修改查询。",
victoriametricsInvalidApiPath: "VictoriaMetrics API 路径必须为空或以 / 开头。",
victoriametricsInvalidLookback: "VictoriaMetrics 回看范围格式无效,请使用 15m、1h、7d 等格式。",
+ salesforceInstanceUrl: "实例 URL",
+ salesforceInstanceUrlPlaceholder: "https://acme.my.salesforce.com",
+ salesforceInstanceUrlHint: "org 域名或完整实例 URL;登录成功后由令牌响应自动回填。",
+ salesforceAccessToken: "访问令牌 (Access Token)",
+ salesforceAccessTokenPlaceholder: "Session ID 或访问令牌",
+ salesforceAccessTokenHint: "粘贴 Salesforce 访问令牌或 Session ID;也可使用下方的 OAuth 浏览器授权或设备码方式登录。",
+ salesforceApiVersion: "API 版本",
+ salesforceApiVersionHint: "Salesforce REST API 版本,例如 v62.0。留空则使用默认固定版本。",
+ salesforceAuthMode: "认证方式",
+ salesforceAuthModeToken: "访问令牌",
+ salesforceAuthModeOauth: "浏览器 OAuth",
+ salesforceAuthModeDevice: "设备码",
+ salesforceAuthModePassword: "用户名密码",
+ salesforceAuthModeOauthDesktopOnly: "浏览器 OAuth 仅在桌面应用中可用。",
+ salesforceEnvironment: "环境",
+ salesforceEnvironmentProduction: "生产",
+ salesforceEnvironmentSandbox: "沙箱",
+ salesforceEnvironmentCustom: "自定义",
+ salesforceLoginUrl: "登录 URL",
+ salesforceLoginUrlPlaceholder: "https://login.salesforce.com",
+ salesforceLoginUrlHint: "当您的组织使用自定义身份端点时,可在此覆盖 Salesforce 登录 URL。",
+ salesforceClientId: "客户端 ID (Client ID)",
+ salesforceClientIdPlaceholder: "Connected App 的 Consumer Key",
+ salesforceClientIdHint: "在 Salesforce Setup → App Manager 创建 Connected App,启用 OAuth 并勾选 PKCE,回调 URL 设置为 {callbackUrl}。",
+ salesforceClientIdHintShared: "Connected App 的 Consumer Key。这两种方式不使用回调 URL,可直接复用管理员已创建的 Connected App。",
+ salesforceClientSecret: "客户端密钥 (Client Secret)",
+ salesforceClientSecretPlaceholder: "可选 — 仅机密 Connected App 需要;PKCE 公共客户端留空",
+ salesforceOauthAuthorize: "通过 Salesforce 授权",
+ salesforceOauthAuthorizing: "正在等待浏览器登录…",
+ salesforceOauthAuthorizingHint: "浏览器窗口应当已打开。请在 Salesforce 完成登录,完成后此界面会自动更新。",
+ salesforceOauthAuthorized: "已授权(凭据已保存)",
+ salesforceOauthReauthorize: "重新授权",
+ salesforceOauthClientIdRequired: "需要填写 Salesforce 客户端 ID。",
+ salesforceOauthLoginUrlRequired: "需要填写 Salesforce 自定义登录 URL。",
+ salesforceDeviceGetCode: "获取设备码",
+ salesforceDeviceFlowNote: "若获取设备码时报 unsupported / disabled 类错误,需管理员在该 Connected App 的 OAuth 设置中启用 Device Flow。",
+ salesforceDeviceUserCodeLabel: "用户码",
+ salesforceDeviceUserCodeCopied: "已复制用户码",
+ salesforceDeviceOpenVerification: "打开验证页面",
+ salesforceDeviceVerificationCopied: "已复制验证 URL",
+ salesforceDevicePolling: "正在等待授权…",
+ salesforceDevicePollingHint: "在任意浏览器打开验证页面,然后输入上方显示的用户码。",
+ salesforceDeviceCancel: "取消",
+ salesforceDeviceExpired: "设备码已过期。点击下方重新获取。",
+ salesforceDeviceDenied: "授权被拒绝",
+ salesforceDeviceRestart: "重新开始",
+ salesforceDeviceSecondsLeft: "剩余 {seconds} 秒",
+ salesforceUsernameLabel: "用户名",
+ salesforceUsernamePlaceholder: "user{'@'}example.com",
+ salesforceUsernameHint: "Salesforce 用户名。沙盒环境需带上沙盒后缀(例如 user{'@'}example.com.qas1)。",
+ salesforceUserPasswordLabel: "用户密码",
+ salesforceUserPasswordPlaceholder: "密码(可选附加安全令牌)",
+ salesforceUserPasswordHint: "你的 Salesforce 密码。若当前 IP 未被组织信任,请在密码后直接拼接安全令牌。会话过期时会用已保存的凭据自动重新登录。",
+ salesforcePasswordRopcNote: "无需回调 URL,复用已有 Connected App 即可;要求你的 Profile 有 API Enabled,且该 app 的授权策略覆盖当前用户。密码不会回传到界面,「重新登录」需重新输入密码。",
+ salesforcePasswordSignIn: "登录",
+ salesforcePasswordSignInAgain: "重新登录",
+ salesforceUsernameRequired: "请填写 Salesforce 用户名。",
+ salesforceUserPasswordRequired: "请填写 Salesforce 密码。",
+ salesforceOauthSuccess: "已连接 {instanceUrl}",
driverInstallHintPrefix: "需要在顶部导航栏「",
driverInstallHintSuffix: "」中安装对应的驱动才能连接。",
driverName: "驱动名称",
@@ -2588,6 +2651,18 @@ export default withEnglishFallback({
rollback: "回滚",
transactionSaveHint: "在事务中提交 {count} 项待保存更改。",
nonTransactionalSaveHint: "逐条保存 {count} 项更改;如果中途失败,前面已成功的更改不会回滚。",
+ salesforceSaveConfirmTitle: "将更改写入 Salesforce",
+ salesforceSaveConfirmMessage: "{count} 项待保存更改会逐条以 REST 调用写入 Salesforce。没有事务:如果中途某条失败,之前已写入的记录不会回滚。",
+ salesforceSaveUpdates: "更新 {count} 条",
+ salesforceSaveInserts: "新增 {count} 条",
+ salesforceSaveDeletes: "删除 {count} 条",
+ salesforceSaveTarget: "对象:{object}",
+ salesforceSaveUnknownObject: "未知",
+ salesforceSaveProfile: "简档 {name}",
+ salesforceSaveAdminIdentity: "将以 {user}({profile})身份写入;该简档具有“修改所有数据”权限,会绕过字段级安全与记录共享——请格外确认。",
+ salesforceSaveNonAdminIdentity: "当前身份:{user}({profile})\n不可写字段已按你的权限设为只读;\n记录级共享或验证规则导致的失败会按行返回 Salesforce 原文。",
+ salesforceSaveUnknownRights: "当前身份:{user}({profile});未能确认该简档是否具有“修改所有数据”权限——Salesforce 仍会按自身权限校验,失败按行返回原文。",
+ salesforceSaveConfirm: "写入 Salesforce",
keylessEditWarning: "无主键",
keylessEditWarningHint: "这张表没有主键。保存更新或删除时会使用整行原始值作为 WHERE 条件;如果存在完全重复的行,可能会影响多行。",
queryEditReadOnly: "只读结果",
@@ -8651,6 +8726,9 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "仅只读",
mcpConnectionPolicySafeWrite: "允许安全写入",
mcpConnectionPolicyHighRiskWrite: "允许高风险操作",
+ mcpConnectionPolicyAllowSalesforceDml: "允许 DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint: "允许 AI 代理通过两步确认(先准备、再应用)在该组织中新增、更新或删除单条 Salesforce 记录。只读模式会忽略此开关。Salesforce 写入无法回滚。",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "该连接为只读,Salesforce DML 保持关闭。请先选择允许写入的执行模式。",
mcpToolPermissionsTitle: "MCP 工具权限",
mcpToolPermissionsDescription: "只暴露当前需要的 MCP 工具。取消选择后,客户端即使缓存了工具定义也会被服务端拒绝。",
mcpToolListConnections: "列出连接",
@@ -8668,6 +8746,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "回滚事务",
mcpToolCloseSession: "关闭查询会话",
mcpToolExecuteRedisCommand: "执行 Redis 命令",
+ mcpToolSalesforceCurrentUser: "Salesforce 当前用户",
+ mcpToolSalesforcePrepareWrite: "准备 Salesforce 写入",
+ mcpToolSalesforceApplyWrite: "应用 Salesforce 写入",
mcpToolPeekMessages: "读取 Kafka 消息",
mcpToolSendMessage: "发送消息队列消息",
mcpToolAddConnection: "新增连接",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index bab55fa4a3..cf68d1d73d 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7373,6 +7373,9 @@ export default withEnglishFallback({
mcpConnectionPolicyReadOnly: "僅唯讀",
mcpConnectionPolicySafeWrite: "允許安全寫入",
mcpConnectionPolicyHighRiskWrite: "允許高風險操作",
+ mcpConnectionPolicyAllowSalesforceDml: "允許 DML",
+ mcpConnectionPolicyAllowSalesforceDmlHint: "允許 AI 代理透過兩步驟確認(先準備、再套用)在該組織中新增、更新或刪除單筆 Salesforce 記錄。唯讀模式會忽略此開關。Salesforce 寫入無法復原。",
+ mcpConnectionPolicyAllowSalesforceDmlReadOnlyBlocked: "該連線為唯讀,Salesforce DML 保持關閉。請先選擇允許寫入的執行模式。",
mcpToolPermissionsTitle: "MCP 工具權限",
mcpToolPermissionsDescription: "只暴露目前需要的 MCP 工具。取消選擇後,用戶端即使快取了工具定義也會被服務端拒絕。",
mcpToolListConnections: "列出連線",
@@ -7390,6 +7393,9 @@ export default withEnglishFallback({
mcpToolRollbackTransaction: "回滾交易",
mcpToolCloseSession: "關閉查詢工作階段",
mcpToolExecuteRedisCommand: "執行 Redis 命令",
+ mcpToolSalesforceCurrentUser: "Salesforce 目前使用者",
+ mcpToolSalesforcePrepareWrite: "準備 Salesforce 寫入",
+ mcpToolSalesforceApplyWrite: "套用 Salesforce 寫入",
mcpToolPeekMessages: "讀取 Kafka 訊息",
mcpToolSendMessage: "傳送訊息佇列訊息",
mcpToolAddConnection: "新增連線",
diff --git a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
index 028f6ff3b2..abbd628903 100644
--- a/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
+++ b/apps/desktop/src/lib/__tests__/mcp/mcpPolicySelection.spec.ts
@@ -89,6 +89,19 @@ describe("MCP tool permission selection", () => {
expect(MCP_TOOL_OPTIONS.map((tool) => tool.name).sort()).toEqual(registeredToolNames);
});
+ it("keeps the Salesforce tools individually switchable, writes included", () => {
+ expect(MCP_TOOL_OPTIONS.filter((tool) => tool.name.startsWith("dbx_salesforce_")).map((tool) => [tool.name, tool.labelKey])).toEqual([
+ ["dbx_salesforce_current_user", "settings.mcpToolSalesforceCurrentUser"],
+ ["dbx_salesforce_prepare_write", "settings.mcpToolSalesforcePrepareWrite"],
+ ["dbx_salesforce_apply_write", "settings.mcpToolSalesforceApplyWrite"],
+ ]);
+
+ // An admin can expose reading (identity + SOQL) without handing over the write path.
+ const readOnlySfdc = toggleMcpAllowedToolName(null, "dbx_salesforce_apply_write", false);
+ expect(toggleMcpAllowedToolName(readOnlySfdc, "dbx_salesforce_prepare_write", false)).not.toContain("dbx_salesforce_prepare_write");
+ expect(readOnlySfdc).toContain("dbx_salesforce_current_user");
+ });
+
it("keeps batch execution allowed when allow-all becomes an explicit allowlist", () => {
const next = toggleMcpAllowedToolName(null, "dbx_send_message", false);
diff --git a/apps/desktop/src/lib/__tests__/table/tableEditing.spec.ts b/apps/desktop/src/lib/__tests__/table/tableEditing.spec.ts
index 4f58508349..27cf018462 100644
--- a/apps/desktop/src/lib/__tests__/table/tableEditing.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/tableEditing.spec.ts
@@ -12,8 +12,11 @@ import {
hasCompleteTdengineRowIdentity,
isClickHouseExistingRowReadonlyColumn,
isHiddenGridColumn,
+ isSalesforceExistingRowReadonlyColumn,
+ isSalesforceNewRowReadonlyColumn,
isTdengineExistingRowReadonlyColumn,
isTableDataEditable,
+ parseSalesforceColumnExtra,
supportsDataGridTransaction,
shouldIncludeSyntheticRowId,
usesSyntheticRowIdKey,
@@ -171,4 +174,62 @@ describe("tableEditing", () => {
expect(isClickHouseExistingRowReadonlyColumn("clickhouse", "event_date", ["id"], [{ ...column("event_date"), extra: "partition_key" }])).toBe(true);
expect(isClickHouseExistingRowReadonlyColumn("postgres", "id", ["id"])).toBe(false);
});
+
+ describe("salesforce", () => {
+ const describeColumns = [
+ { ...column("Id", true), extra: JSON.stringify({ updateable: false, createable: false, custom: false, label: "Record ID" }) },
+ { ...column("Name"), extra: JSON.stringify({ updateable: true, createable: true, custom: false, label: "Account Name" }) },
+ { ...column("CreatedDate"), extra: JSON.stringify({ updateable: false, createable: false, custom: false, label: "Created Date" }) },
+ { ...column("Revenue_Rollup__c"), extra: JSON.stringify({ updateable: false, createable: false, custom: true, label: "Revenue Rollup" }) },
+ { ...column("First_Name__c"), extra: JSON.stringify({ updateable: true, createable: true, custom: true, label: "First Name" }) },
+ { ...column("OwnerId"), extra: JSON.stringify({ updateable: true, createable: true, custom: false, label: "Owner ID", referenceTo: ["User"], relationshipName: "Owner" }) },
+ ];
+
+ it("reads describe flags defensively", () => {
+ expect(parseSalesforceColumnExtra('{"updateable":false,"label":"Created Date"}')).toEqual({ updateable: false, label: "Created Date" });
+ // ClickHouse packs a bare marker string; a non-object must never be read as flags.
+ expect(parseSalesforceColumnExtra("partition_key")).toBeNull();
+ expect(parseSalesforceColumnExtra("[1,2]")).toBeNull();
+ expect(parseSalesforceColumnExtra("")).toBeNull();
+ expect(parseSalesforceColumnExtra(null)).toBeNull();
+ });
+
+ it("keeps the record Id and non-updateable fields readonly on existing rows", () => {
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Id", ["Id"], describeColumns)).toBe(true);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "id", ["Id"], describeColumns)).toBe(true);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "CreatedDate", ["Id"], describeColumns)).toBe(true);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Revenue_Rollup__c", ["Id"], describeColumns)).toBe(true);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Name", ["Id"], describeColumns)).toBe(false);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "first_name__c", ["Id"], describeColumns)).toBe(false);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "OwnerId", ["Id"], describeColumns)).toBe(false);
+ expect(isSalesforceExistingRowReadonlyColumn("postgres", "Id", ["Id"], describeColumns)).toBe(false);
+ });
+
+ it("fails open when describe metadata is missing so Salesforce decides", () => {
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Unknown__c", ["Id"], describeColumns)).toBe(false);
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Name", ["Id"])).toBe(false);
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "Unknown__c", describeColumns)).toBe(false);
+ });
+
+ it("blocks non-createable fields on new rows only", () => {
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "Id", describeColumns)).toBe(true);
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "CreatedDate", describeColumns)).toBe(true);
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "Revenue_Rollup__c", describeColumns)).toBe(true);
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "Name", describeColumns)).toBe(false);
+ expect(isSalesforceNewRowReadonlyColumn("salesforce", "First_Name__c", describeColumns)).toBe(false);
+ expect(isSalesforceNewRowReadonlyColumn("mysql", "Id", describeColumns)).toBe(false);
+ // `Id` is not updateable either, but the primary-key rule covers existing rows.
+ expect(isSalesforceExistingRowReadonlyColumn("salesforce", "Id", [], describeColumns)).toBe(true);
+ });
+
+ it("edits table data row by row without a transaction", () => {
+ expect(isTableDataEditable("salesforce", ["Id"], "TABLE")).toBe(true);
+ expect(canEditExistingTableRows("salesforce", undefined, ["Id"])).toBe(true);
+ expect(canEditExistingTableRows("salesforce", undefined, [])).toBe(false);
+ expect(canInsertTableRows("salesforce")).toBe(true);
+ expect(supportsDataGridTransaction("salesforce")).toBe(false);
+ expect(canUseKeylessRowPredicate("salesforce", [])).toBe(false);
+ expect(canDeleteExistingTdengineRows("salesforce", ["Id"])).toBe(true);
+ });
+ });
});
diff --git a/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts b/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
index 3165b03869..17848bb00b 100644
--- a/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/tableSelectSql.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { encodeSqlServerLinkedSchema } from "@/lib/database/sqlServerLinkedServers";
-import { qualifiedTableName, qualifyTableReferencesInSql, quoteTableDataIdentifier, quoteTableIdentifier, quoteTableIdentifierIfNeeded, tableMetaWithoutOptionalDatabaseQualifier } from "@/lib/table/tableSelectSql";
+import { qualifiedTableName, qualifyTableReferencesInSql, quoteTableDataIdentifier, quoteTableIdentifier, quoteTableIdentifierIfNeeded, requiresEagerTableMetadataForDataOpen, tableMetaWithoutOptionalDatabaseQualifier } from "@/lib/table/tableSelectSql";
describe("qualifiedTableName — Doris/StarRocks multi-catalog", () => {
it("prefixes external catalog for Doris (no schema)", () => {
@@ -305,6 +305,28 @@ describe("quoteTableIdentifier", () => {
expect(quoteTableIdentifier("bigquery", "a`b")).toBe("`a\\`b`");
});
+ it("never quotes Salesforce SOQL identifiers", () => {
+ // SOQL has no delimited identifiers and reads `"` as a string literal, so the
+ // grid's ORDER BY / filter must send object and field API names bare — the
+ // quoted form the backend used to produce failed with MALFORMED_QUERY.
+ expect(quoteTableIdentifier("salesforce", "Account")).toBe("Account");
+ expect(quoteTableIdentifier("salesforce", "First_Name__c")).toBe("First_Name__c");
+ expect(quoteTableDataIdentifier("salesforce", "Account")).toBe("Account");
+ // An org is a single scope: no schema or database qualifier.
+ expect(qualifiedTableName({ databaseType: "salesforce", schema: "sales", database: "org", tableName: "Account" })).toBe("Account");
+ });
+
+ it("awaits table metadata before building Salesforce data-preview SQL", () => {
+ // Without a column list the backend falls back to `FIELDS(ALL)`, which the org
+ // only accepts with LIMIT 200 or less, so the describe has to land first.
+ expect(requiresEagerTableMetadataForDataOpen("salesforce")).toBe(true);
+ expect(requiresEagerTableMetadataForDataOpen("mysql")).toBe(true);
+ expect(requiresEagerTableMetadataForDataOpen("postgres")).toBe(true);
+ // Drivers whose preview works from `SELECT *` keep loading metadata lazily.
+ expect(requiresEagerTableMetadataForDataOpen("sqlite")).toBe(false);
+ expect(requiresEagerTableMetadataForDataOpen(undefined)).toBe(false);
+ });
+
it("backtick-quotes Cloud Spanner GoogleSQL identifiers by default", () => {
expect(quoteTableIdentifier("spanner", "order")).toBe("`order`");
expect(quoteTableIdentifier("spanner", "a`b")).toBe("`a\\`b`");
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 936773e624..feab2aa52e 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -58,6 +58,12 @@ function forward<K extends keyof Backend>(name: K): Backend[K] {
export const testConnection = forward("testConnection");
export const testSshTunnel = forward("testSshTunnel");
export const testConnectionWithInfo = forward("testConnectionWithInfo");
+export const salesforceOauthBrowserAuthorize = forward("salesforceOauthBrowserAuthorize");
+export const salesforceOauthDeviceStart = forward("salesforceOauthDeviceStart");
+export const salesforceOauthDevicePoll = forward("salesforceOauthDevicePoll");
+export const salesforceOauthRefresh = forward("salesforceOauthRefresh");
+export const salesforceOauthPasswordLogin = forward("salesforceOauthPasswordLogin");
+export const salesforceCurrentUser = forward("salesforceCurrentUser");
export const connectDb = forward("connectDb");
export const connectionDatabaseInfo = forward("connectionDatabaseInfo");
export const saveConnectionDatabaseInfo = forward("saveConnectionDatabaseInfo");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index ab7097e610..0e715f130f 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -84,6 +84,7 @@ import type { SchemaDiffPreparation, SchemaDiffPreparationOptions, SchemaSyncSql
import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";
import type { AiConfig, AiTestConnectionResult } from "@/stores/settingsStore";
import type { AiChatSelectionState, AiEffortCapability } from "@/types/ai";
+import type { SalesforceCurrentUser, SalesforceOAuthAuthorizeParams, SalesforceOAuthDevicePollResult, SalesforceOAuthDeviceStartResult, SalesforceOAuthRefreshResult, SalesforceOAuthToken } from "@/types/salesforce";
import type {
AgentDriverInfo,
AiCompletionRequest,
@@ -463,6 +464,39 @@ export async function testConnectionWithInfo(config: ConnectionConfig): Promise<
return normalizeConnectionTestResult(await response.json(), config);
}
+// ---------------------------------------------------------------------------
+// Salesforce OAuth (browser redirect + device-code flows)
+// ---------------------------------------------------------------------------
+// Web mode only supports the device-code flow end-to-end; the browser-redirect
+// flow is gated by the desktop shell (it binds a localhost callback server).
+// The HTTP endpoints mirror the Tauri commands one-for-one so `api.ts` can
+// forward both transports through the same surface.
+
+export async function salesforceOauthBrowserAuthorize(params: SalesforceOAuthAuthorizeParams): Promise<SalesforceOAuthToken> {
+ return post("/api/connection/salesforce-oauth-browser-authorize", { params });
+}
+
+export async function salesforceOauthDeviceStart(params: SalesforceOAuthAuthorizeParams): Promise<SalesforceOAuthDeviceStartResult> {
+ return post("/api/connection/salesforce-oauth-device-start", { params });
+}
+
+export async function salesforceOauthDevicePoll(params: SalesforceOAuthAuthorizeParams, deviceCode: string, intervalSecs: number): Promise<SalesforceOAuthDevicePollResult> {
+ return post("/api/connection/salesforce-oauth-device-poll", { params, deviceCode, intervalSecs });
+}
+
+export async function salesforceOauthRefresh(params: SalesforceOAuthAuthorizeParams, refreshToken: string): Promise<SalesforceOAuthRefreshResult> {
+ return post("/api/connection/salesforce-oauth-refresh", { params, refreshToken });
+}
+
+export async function salesforceOauthPasswordLogin(params: SalesforceOAuthAuthorizeParams, username: string, password: string): Promise<SalesforceOAuthToken> {
+ return post("/api/connection/salesforce-oauth-password-login", { params, username, password });
+}
+
+/** Identity of the user an established Salesforce connection is authenticated as (cached backend-side). */
+export async function salesforceCurrentUser(connectionId: string): Promise<SalesforceCurrentUser> {
+ return get(`/api/salesforce/current-user?${qs({ connection_id: connectionId })}`);
+}
+
export async function connectDb(config: ConnectionConfig, clientAttempt?: number): Promise<string> {
return post("/api/connection/connect", { config, clientAttempt });
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 6160fa7690..5800bd9b46 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -113,6 +113,7 @@ import type { AnnotationFile, SchemaSnapshot } from "@/docs/types";
import type { CollectionInfo } from "@/types/database";
import type { SidebarObjectKind } from "@/lib/database/databaseObjectCapabilities";
import type { AiChatSelectionState, AiConfig, AiConfigItem, AiEffortCapability, AiEffortLevel, AiTestConnectionResult } from "@/types/ai";
+import type { SalesforceCurrentUser, SalesforceOAuthAuthorizeParams, SalesforceOAuthDevicePollResult, SalesforceOAuthDeviceStartResult, SalesforceOAuthRefreshResult, SalesforceOAuthToken } from "@/types/salesforce";
import type { QueryEditability } from "@/lib/sql/sqlAnalysis";
import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";
import type {
@@ -349,6 +350,8 @@ export interface McpConnectionPolicy {
databaseScope: "all" | "selected" | "none";
allowedDatabases: string[];
databasePolicies: McpDatabasePolicy[];
+ /** Opt-in for AI-agent DML against a Salesforce org; forced off by `readOnly`. */
+ allowSalesforceDml: boolean;
}
export interface McpDatabasePolicy {
@@ -1317,6 +1320,35 @@ export async function testConnectionWithInfo(config: ConnectionConfig): Promise<
}
}
+// ---------------------------------------------------------------------------
+// Salesforce OAuth (browser redirect + device-code flows)
+// ---------------------------------------------------------------------------
+
+export async function salesforceOauthBrowserAuthorize(params: SalesforceOAuthAuthorizeParams): Promise<SalesforceOAuthToken> {
+ return invokeBackend("salesforce_oauth_browser_authorize", { params });
+}
+
+export async function salesforceOauthDeviceStart(params: SalesforceOAuthAuthorizeParams): Promise<SalesforceOAuthDeviceStartResult> {
+ return invokeBackend("salesforce_oauth_device_start", { params });
+}
+
+export async function salesforceOauthDevicePoll(params: SalesforceOAuthAuthorizeParams, deviceCode: string, intervalSecs: number): Promise<SalesforceOAuthDevicePollResult> {
+ return invokeBackend("salesforce_oauth_device_poll", { params, deviceCode, intervalSecs });
+}
+
+export async function salesforceOauthRefresh(params: SalesforceOAuthAuthorizeParams, refreshToken: string): Promise<SalesforceOAuthRefreshResult> {
+ return invokeBackend("salesforce_oauth_refresh", { params, refreshToken });
+}
+
+export async function salesforceOauthPasswordLogin(params: SalesforceOAuthAuthorizeParams, username: string, password: string): Promise<SalesforceOAuthToken> {
+ return invokeBackend("salesforce_oauth_password_login", { params, username, password });
+}
+
+/** Identity of the user an established Salesforce connection is authenticated as (cached backend-side). */
+export async function salesforceCurrentUser(connectionId: string): Promise<SalesforceCurrentUser> {
+ return invokeBackend("salesforce_current_user", { connectionId });
+}
+
export async function connectDb(config: ConnectionConfig, clientAttempt?: number): Promise<string> {
return invokeBackend("connect_db", { config, clientAttempt });
}
diff --git a/apps/desktop/src/lib/connection/connectionPresentation.ts b/apps/desktop/src/lib/connection/connectionPresentation.ts
index 1eb5ad075e..640ac1c233 100644
--- a/apps/desktop/src/lib/connection/connectionPresentation.ts
+++ b/apps/desktop/src/lib/connection/connectionPresentation.ts
@@ -152,6 +152,7 @@ export function connectionDisplayUrlScheme(connection: Pick<ConnectionConfig, "d
case "dynamodb":
case "mq":
case "consul":
+ case "salesforce":
return connection.ssl ? "https" : "http";
case "cloudflare-d1":
return "https";
@@ -273,6 +274,9 @@ export function connectionUrlPlaceholder(dbType: DatabaseType, driverProfile?: s
case "victoriametrics":
return "http://user:password@host:port/prometheus";
+ case "salesforce":
+ return "https://acme.my.salesforce.com";
+
case "jdbc":
return "jdbc:mysql://host:3306/database";
diff --git a/apps/desktop/src/lib/connection/connectionUrl.ts b/apps/desktop/src/lib/connection/connectionUrl.ts
index b6c36ba6f6..28d70fee37 100644
--- a/apps/desktop/src/lib/connection/connectionUrl.ts
+++ b/apps/desktop/src/lib/connection/connectionUrl.ts
@@ -84,6 +84,7 @@ const SCHEME_PROFILES: Record<string, ConnectionProfile> = {
iotdb: { type: "iotdb", profile: "iotdb", label: "Apache IoTDB", defaultPort: 6667 },
iris: { type: "iris", profile: "iris", label: "IRIS", defaultPort: 1972 },
victoriametrics: { type: "victoriametrics", profile: "victoriametrics", label: "VictoriaMetrics", defaultPort: 8428 },
+ salesforce: { type: "salesforce", profile: "salesforce", label: "Salesforce", defaultPort: 443 },
};
const OCEANBASE_ORACLE_PROFILE: ConnectionProfile = {
@@ -105,6 +106,7 @@ const HTTP_SELECTED_PROFILES: Record<string, ConnectionProfile> = {
weaviate: SCHEME_PROFILES.weaviate,
chromadb: SCHEME_PROFILES.chromadb,
victoriametrics: SCHEME_PROFILES.victoriametrics,
+ salesforce: SCHEME_PROFILES.salesforce,
consul: SCHEME_PROFILES.consul,
"nacos-v2": SCHEME_PROFILES["nacos-v2"],
"nacos-v3": SCHEME_PROFILES["nacos-v3"],
diff --git a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts b/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
index b44115c539..9aa38cfa01 100644
--- a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
+++ b/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
@@ -76,7 +76,7 @@ const STANDARD_URL_SCHEMES: Partial<Record<DatabaseType, string>> = {
};
/** Schemes that are plain HTTP(S) endpoints. */
-const HTTP_URL_DB_TYPES = new Set<DatabaseType>(["elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "rqlite", "consul", "victoriametrics", "influxdb", "influxdb3", "dynamodb"]);
+const HTTP_URL_DB_TYPES = new Set<DatabaseType>(["elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "rqlite", "consul", "victoriametrics", "influxdb", "influxdb3", "dynamodb", "salesforce"]);
/**
* Generic `prefix://host:port/db` JDBC dialects. Dialects with a different URL
diff --git a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
index 93eebbcd72..56fedc0599 100644
--- a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
+++ b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
@@ -5,7 +5,7 @@ const DRAFT_VISIBLE_DATABASES_PREFIX = "__visible_draft_";
// Turso and Cloudflare D1 target one fixed SQLite-compatible `main` namespace;
// non-database services expose their own root objects rather than database namespaces.
-const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul", "plugin"]);
+const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul", "plugin", "salesforce"]);
type VisibleDatabaseConnectionFields = Pick<
ConnectionConfig,
diff --git a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
index fe9d9f244a..850a2c6741 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
@@ -25,7 +25,7 @@ export function isColumnNameCopySeparator(value: unknown): value is ColumnNameCo
}
// SQL 执行能力是产品能力,不代表数据库支持 SQL 标识符引用。
-const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "victoriametrics"]);
+const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "victoriametrics", "salesforce"]);
// quoteTableIdentifier 对 jdbc/iotdb 原样返回(无引用字符可用)。
const UNQUOTABLE_DATABASE_TYPES = new Set<DatabaseType>(["jdbc", "iotdb"]);
diff --git a/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts b/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
index a8e39cef8a..653520d1ef 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
@@ -1,6 +1,6 @@
import type { DatabaseType } from "@/types/database";
-const NON_SQL_PREVIEW_DATABASE_TYPES: ReadonlySet<DatabaseType> = new Set<DatabaseType>(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr"]);
+const NON_SQL_PREVIEW_DATABASE_TYPES: ReadonlySet<DatabaseType> = new Set<DatabaseType>(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "salesforce"]);
export function dataGridPreviewLabelKey(databaseType?: DatabaseType): "toolbar.previewQuery" | "toolbar.previewSql" {
return databaseType && NON_SQL_PREVIEW_DATABASE_TYPES.has(databaseType) ? "toolbar.previewQuery" : "toolbar.previewSql";
diff --git a/apps/desktop/src/lib/database/databaseFeatureSupport.ts b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
index fb669bbd17..e32bc41640 100644
--- a/apps/desktop/src/lib/database/databaseFeatureSupport.ts
+++ b/apps/desktop/src/lib/database/databaseFeatureSupport.ts
@@ -128,7 +128,7 @@ export function supportsClearableQuerySchema(dbType?: DatabaseType): boolean {
* hidden there as well (issue #9609).
*/
export function supportsConnectionQueryActions(dbType?: DatabaseType): boolean {
- return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "plugin" && dbType !== "mq" && dbType !== "mqtt" && dbType !== "meilisearch";
+ return dbType !== "nacos" && dbType !== "consul" && dbType !== "hbase" && dbType !== "zookeeper" && dbType !== "plugin" && dbType !== "mq" && dbType !== "mqtt" && dbType !== "meilisearch" && dbType !== "salesforce";
}
/**
@@ -250,7 +250,9 @@ export function supportsObjectBrowserTreeNode(dbType: DatabaseType | undefined,
}
export function supportsTableTruncate(dbType?: DatabaseType): boolean {
- return !!dbType && dbType !== "impala" && dbType !== "sqlite" && dbType !== "rqlite" && dbType !== "turso" && dbType !== "cloudflare-d1" && dbType !== "duckdb" && dbType !== "influxdb" && dbType !== "influxdb3" && dbType !== "victoriametrics" && dbType !== "manticoresearch";
+ return (
+ !!dbType && dbType !== "impala" && dbType !== "sqlite" && dbType !== "rqlite" && dbType !== "turso" && dbType !== "cloudflare-d1" && dbType !== "duckdb" && dbType !== "influxdb" && dbType !== "influxdb3" && dbType !== "victoriametrics" && dbType !== "manticoresearch" && dbType !== "salesforce"
+ );
}
export function supportsTableVacuum(dbType?: DatabaseType): boolean {
diff --git a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
index f8208cdc58..91b55bd6b0 100644
--- a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
+++ b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
@@ -32,6 +32,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
elasticsearch: { deferred: "index creation is not modeled as database creation" },
easysearch: { deferred: "index creation is not modeled as database creation" },
meilisearch: { deferred: "index creation is not modeled as database creation" },
+ salesforce: { deferred: "Salesforce orgs do not expose database creation through SOQL" },
solr: { deferred: "core creation is not modeled as database creation" },
hbase: { deferred: "namespace creation needs dedicated HBase namespace options" },
qdrant: { deferred: "collection creation is separate from database creation" },
diff --git a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts
index e634abd7f2..9e31ffae2a 100644
--- a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts
+++ b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts
@@ -100,6 +100,7 @@ const DATABASE_TYPE_OBJECTS = new Map<DatabaseType, SidebarObjectKind[]>([
["influxdb3", ["TABLE"]],
["victoriametrics", ["TABLE"]],
["hbase", ["TABLE"]],
+ ["salesforce", ["TABLE"]],
["questdb", ["TABLE", "VIEW", "MATERIALIZED_VIEW"]],
["manticoresearch", ["TABLE", "FUNCTION"]],
["databend", ["TABLE", "VIEW", "PROCEDURE"]],
diff --git a/apps/desktop/src/lib/database/databasePropertyEditing.ts b/apps/desktop/src/lib/database/databasePropertyEditing.ts
index 0f3a92331a..4b67ac337e 100644
--- a/apps/desktop/src/lib/database/databasePropertyEditing.ts
+++ b/apps/desktop/src/lib/database/databasePropertyEditing.ts
@@ -33,6 +33,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
elasticsearch: { deferred: "index settings are not database properties" },
easysearch: { deferred: "index settings are not database properties" },
meilisearch: { deferred: "index settings are not database properties" },
+ salesforce: { deferred: "sObject metadata is managed in Salesforce Setup" },
solr: { deferred: "core settings are not database properties" },
hbase: { deferred: "namespace and table properties need a dedicated HBase workflow" },
qdrant: { deferred: "collection settings are not database properties" },
diff --git a/apps/desktop/src/lib/database/databaseTableDataCapabilities.ts b/apps/desktop/src/lib/database/databaseTableDataCapabilities.ts
index 860262c6f1..4c2ebb3473 100644
--- a/apps/desktop/src/lib/database/databaseTableDataCapabilities.ts
+++ b/apps/desktop/src/lib/database/databaseTableDataCapabilities.ts
@@ -235,6 +235,25 @@ const DATABASE_CAPABILITY_OVERRIDES: Partial<Record<DatabaseType, Partial<Databa
readonly: true,
},
},
+ salesforce: {
+ // SOQL has no DML. A grid save becomes one `DBX SALESFORCE DML` pseudo-command
+ // per record (built by dbx-sql) which the driver turns into a REST call:
+ // PATCH /sobjects/{object}/{id}, POST /sobjects/{object}, DELETE /sobjects/{object}/{id}.
+ // Row identity is the `Id` column (the driver marks it is_primary_key), so both
+ // update and delete require it. REST has no transactions: records are written
+ // one by one, a failure leaves the earlier records applied, and nothing can be
+ // rolled back — the grid therefore asks for confirmation before saving.
+ tableData: {
+ insert: true,
+ updateRequiresPrimaryKey: true,
+ deleteRequiresPrimaryKey: true,
+ keylessRowPredicate: false,
+ requiresTransactionalTableForExistingRows: false,
+ existingRowsReadonly: false,
+ transaction: false,
+ readonly: false,
+ },
+ },
};
function defaultTableDataCapability(dbType?: DatabaseType): TableDataCapability {
diff --git a/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts b/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
index 6832b1a78c..f750ecec95 100644
--- a/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
+++ b/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
@@ -117,6 +117,7 @@ const SQL_EXECUTION_TARGET_REGISTRY: Partial<Record<DatabaseType, SqlExecutionTa
chromadb: { scope: "connection" },
etcd: { scope: "connection" },
zookeeper: { scope: "connection" },
+ salesforce: { scope: "connection" },
doris: { supportsCatalog: true },
starrocks: { supportsCatalog: true },
"cloudflare-d1": { defaultDatabase: () => "main", allowDefaultWhenDatabaseListEmpty: true },
diff --git a/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts b/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
index d146cc58f3..719e56b61d 100644
--- a/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
+++ b/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
@@ -70,7 +70,7 @@ function decorationsForHints(hints: readonly InsertValueHint[]): DecorationSet {
* keep this list in sync instead of re-inlining it at call sites.
*/
export function supportsInsertValueHints(databaseType: string | undefined | null): boolean {
- return databaseType !== "redis" && databaseType !== "mongodb" && databaseType !== "elasticsearch" && databaseType !== "easysearch" && databaseType !== "meilisearch" && databaseType !== "solr" && databaseType !== "victoriametrics";
+ return databaseType !== "redis" && databaseType !== "mongodb" && databaseType !== "elasticsearch" && databaseType !== "easysearch" && databaseType !== "meilisearch" && databaseType !== "solr" && databaseType !== "victoriametrics" && databaseType !== "salesforce";
}
export function buildInsertValueHintDecorations(hints: readonly InsertValueHint[]): DecorationSet {
diff --git a/apps/desktop/src/lib/editor/codemirrorSqlDialect.ts b/apps/desktop/src/lib/editor/codemirrorSqlDialect.ts
index 4174525780..7b0f6cea6c 100644
--- a/apps/desktop/src/lib/editor/codemirrorSqlDialect.ts
+++ b/apps/desktop/src/lib/editor/codemirrorSqlDialect.ts
@@ -2,7 +2,7 @@ import type { SQLDialect } from "@codemirror/lang-sql";
import type { DatabaseType } from "@/types/database";
import { driverProfileSqlBuiltinTerms } from "@/lib/database/driverProfileExtensions";
-export type CodeMirrorSqlDialectName = "mysql" | "postgres" | "sqlserver" | "clickhouse";
+export type CodeMirrorSqlDialectName = "mysql" | "postgres" | "sqlserver" | "clickhouse" | "soql";
type CodeMirrorSqlLanguageModule = Pick<typeof import("@codemirror/lang-sql"), "Cassandra" | "MSSQL" | "MySQL" | "PLSQL" | "PostgreSQL" | "SQLite" | "SQLDialect" | "StandardSQL">;
@@ -162,7 +162,132 @@ const CLICKHOUSE_TYPES = [
.join(" ")
.toLowerCase();
-const CLICKHOUSE_BUILTINS = ["now", "today", "toDate", "toDateTime", "toDateTime64", "toYYYYMM", "count", "sum", "avg", "min", "max", "uniq", "uniqExact", "argMin", "argMax", "groupArray", "arrayJoin", "mapKeys", "mapValues", "JSONExtract", "JSONExtractString"].join(" ").toLowerCase();
+const CLICKHOUSE_BUILTINS = ["now", "today", "toDate", "toDateTime", "toDateTime64", "toYYYYMM", "count", "sum", "avg", "min", "max", "uniq", "uniqExact", "argMin", "argMax", "groupArray", "arrayJoin", "mapKeys", "mapValues", "JSONExtract", "JSONExtractString", "mapFilter", "mapContains"]
+ .join(" ")
+ .toLowerCase();
+
+// Salesforce SOQL is a distinct query language: no JOINs, no DDL/DML keywords, no
+// identifier quoting, single-quoted strings only, and its own clause/operator set.
+// CodeMirror's tokenizer lowercases each word before lookup (lang-sql keywords()),
+// so every entry below is stored lowercase to guarantee a match. true/false/null are
+// omitted on purpose — lang-sql pre-registers them as Bool/Null tokens.
+const SOQL_KEYWORDS = [
+ // Clauses & query structure
+ "select",
+ "from",
+ "where",
+ "and",
+ "or",
+ "not",
+ "in",
+ "like",
+ "includes",
+ "excludes",
+ "order",
+ "by",
+ "group",
+ "having",
+ "limit",
+ "offset",
+ "asc",
+ "desc",
+ "nulls",
+ "first",
+ "last",
+ "all",
+ "distinct",
+ // TYPEOF (polymorphic field selection)
+ "typeof",
+ "when",
+ "then",
+ "else",
+ "end",
+ // WITH clauses
+ "with",
+ "security_enforced",
+ "user_mode",
+ "system_mode",
+ "fields",
+ "standard",
+ "custom",
+ "data",
+ "category",
+ "using",
+ "scope",
+ "above",
+ "below",
+ "above_or_below",
+ // FOR clauses (tracking / viewstat)
+ "for",
+ "view",
+ "reference",
+ "update",
+ "tracking",
+ "viewstat",
+ // Date literals (the non-parameterized forms; :n variants highlight the stem)
+ "yesterday",
+ "today",
+ "tomorrow",
+ "last_week",
+ "this_week",
+ "next_week",
+ "last_month",
+ "this_month",
+ "next_month",
+ "last_90_days",
+ "next_90_days",
+ "last_n_days",
+ "next_n_days",
+ "last_quarter",
+ "this_quarter",
+ "next_quarter",
+ "last_n_quarters",
+ "next_n_quarters",
+ "last_year",
+ "this_year",
+ "next_year",
+ "last_n_years",
+ "next_n_years",
+ "last_fiscal_quarter",
+ "this_fiscal_quarter",
+ "next_fiscal_quarter",
+ "last_n_fiscal_quarters",
+ "next_n_fiscal_quarters",
+ "last_fiscal_year",
+ "this_fiscal_year",
+ "next_fiscal_year",
+ "last_n_fiscal_years",
+ "next_n_fiscal_years",
+].join(" ");
+
+// SOQL aggregate + date/convert functions. Highlighted as builtins (callable names).
+const SOQL_BUILTINS = [
+ "count",
+ "count_distinct",
+ "sum",
+ "avg",
+ "min",
+ "max",
+ "grouping",
+ "convertcurrency",
+ "converttimezone",
+ "tolabel",
+ "format",
+ "calendar_month",
+ "calendar_quarter",
+ "calendar_year",
+ "day_in_month",
+ "day_in_week",
+ "day_in_year",
+ "day_only",
+ "fiscal_month",
+ "fiscal_quarter",
+ "fiscal_year",
+ "hour_in_day",
+ "week_in_month",
+ "week_only",
+ "month_in_year",
+].join(" ");
// COUNT is stripped from Postgres keywords by postgresKeywordSyntaxTerms() (it's a
// valid Postgres identifier name), so it's re-added here as a builtin function instead.
@@ -228,6 +353,19 @@ function codeMirrorBaseDialect(langSql: CodeMirrorSqlLanguageModule, dialectName
}
export function createDbxCodeMirrorSqlDialect(langSql: CodeMirrorSqlLanguageModule, dialectName: CodeMirrorSqlDialectName = "mysql", databaseType?: DatabaseType, driverProfile?: string): SQLDialect {
+ // SOQL is its own language, not a SQL superset: define it from a precise keyword
+ // set with no identifier quoting, single-quoted strings, and backslash escapes.
+ if (databaseType === "salesforce" || dialectName === "soql") {
+ return langSql.SQLDialect.define({
+ keywords: SOQL_KEYWORDS,
+ builtin: [SOQL_BUILTINS, driverProfileSqlBuiltinTerms(driverProfile)].filter(Boolean).join(" ") || undefined,
+ backslashEscapes: true,
+ doubleQuotedStrings: false,
+ caseInsensitiveIdentifiers: true,
+ identifierQuotes: "",
+ doubleDollarQuotedStrings: false,
+ });
+ }
const baseDialect = codeMirrorBaseDialect(langSql, dialectName, databaseType);
const isPostgres = baseDialect === langSql.PostgreSQL;
const isMysql = baseDialect === langSql.MySQL;
diff --git a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
index e6dcc75c89..4f87d054ea 100644
--- a/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
+++ b/apps/desktop/src/lib/mcp/mcpPolicySelection.ts
@@ -37,6 +37,9 @@ export const MCP_TOOL_OPTIONS = [
{ name: "dbx_rollback_transaction", labelKey: "settings.mcpToolRollbackTransaction" },
{ name: "dbx_close_session", labelKey: "settings.mcpToolCloseSession" },
{ name: "dbx_execute_redis_command", labelKey: "settings.mcpToolExecuteRedisCommand" },
+ { name: "dbx_salesforce_current_user", labelKey: "settings.mcpToolSalesforceCurrentUser" },
+ { name: "dbx_salesforce_prepare_write", labelKey: "settings.mcpToolSalesforcePrepareWrite" },
+ { name: "dbx_salesforce_apply_write", labelKey: "settings.mcpToolSalesforceApplyWrite" },
{ name: "dbx_peek_messages", labelKey: "settings.mcpToolPeekMessages" },
{ name: "dbx_send_message", labelKey: "settings.mcpToolSendMessage" },
{ name: "dbx_add_connection", labelKey: "settings.mcpToolAddConnection" },
diff --git a/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts b/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
index 5e59140b0b..912c1e42c6 100644
--- a/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
@@ -71,7 +71,18 @@ function orderSidebarTreeChildrenForParent(parent: Pick<TreeNode, "type">, child
const regularChildren = normalized.filter((child) => child.type !== "user-admin" && child.type !== "dameng-users" && child.type !== "dameng-roles" && child.type !== "saved-sql-root");
const withConnectionUtilityOrder = (children: TreeNode[]) => [...savedSqlNodes, ...children, ...userAdminNodes];
- if (databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "solr" || databaseType === "qdrant" || databaseType === "milvus" || databaseType === "weaviate" || databaseType === "chromadb") {
+ if (
+ databaseType === "mongodb" ||
+ databaseType === "elasticsearch" ||
+ databaseType === "easysearch" ||
+ databaseType === "meilisearch" ||
+ databaseType === "solr" ||
+ databaseType === "qdrant" ||
+ databaseType === "milvus" ||
+ databaseType === "weaviate" ||
+ databaseType === "chromadb" ||
+ databaseType === "salesforce"
+ ) {
const meilisearchSystem = regularChildren.filter((child) => child.type === "meilisearch-system");
const databaseObjects = regularChildren.filter((child) => child.type !== "meilisearch-system");
return withConnectionUtilityOrder([...sortByLabel(databaseObjects), ...meilisearchSystem]);
diff --git a/apps/desktop/src/lib/soql/__tests__/soqlCompletion.spec.ts b/apps/desktop/src/lib/soql/__tests__/soqlCompletion.spec.ts
new file mode 100644
index 0000000000..f98699d987
--- /dev/null
+++ b/apps/desktop/src/lib/soql/__tests__/soqlCompletion.spec.ts
@@ -0,0 +1,319 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildSoqlCompletionItems,
+ getSoqlCompletionContext,
+ getSoqlCompletionResultValidFor,
+ resolveSoqlFieldCandidates,
+ resolveSoqlValueField,
+ shouldAutoOpenSoqlCompletion,
+ soqlCompletionNeedsFields,
+ soqlCompletionNeedsObjects,
+ type SoqlCompletionField,
+ type SoqlCompletionObject,
+} from "@/lib/soql/soqlCompletion";
+
+const ACCOUNT_FIELDS: SoqlCompletionField[] = [
+ { name: "Id", label: "Account ID", type: "id" },
+ { name: "Name", label: "Account Name", type: "string" },
+ { name: "OwnerId", label: "Owner ID", type: "reference", relationshipName: "Owner", referenceTo: ["User"] },
+ { name: "ParentId", label: "Parent Account ID", type: "reference", relationshipName: "Parent", referenceTo: ["Account"] },
+ { name: "Industry", label: "Industry", type: "picklist", picklistValues: ["Agriculture", "Banking", "Technology"] },
+ { name: "IsActive", label: "Active", type: "boolean" },
+ { name: "CreatedDate", label: "Created Date", type: "datetime" },
+ { name: "AnnualRevenue", label: "Annual Revenue", type: "currency" },
+];
+
+const USER_FIELDS: SoqlCompletionField[] = [
+ { name: "Id", type: "id" },
+ { name: "Name", label: "Full Name", type: "string" },
+ { name: "Email", label: "Email", type: "email" },
+ { name: "ManagerId", type: "reference", relationshipName: "Manager", referenceTo: ["User"] },
+];
+
+const OBJECTS: SoqlCompletionObject[] = [
+ { name: "Account", label: "Account" },
+ { name: "Contact", label: "Contact" },
+ { name: "Opportunity", label: "Opportunity" },
+ { name: "MyObj__c", label: "My Object" },
+];
+
+function loader(map: Record<string, SoqlCompletionField[]>) {
+ return async (objectName: string) => map[objectName] ?? [];
+}
+
+describe("getSoqlCompletionContext", () => {
+ it("returns keyword mode for an empty statement", () => {
+ const ctx = getSoqlCompletionContext("", 0);
+ expect(ctx.mode).toBe("keyword");
+ expect(ctx.clause).toBeNull();
+ });
+
+ it("classifies a partial leading keyword as keyword mode", () => {
+ const text = "SEL";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("keyword");
+ expect(ctx.prefix).toBe("SEL");
+ });
+
+ it("resolves the FROM object and reports object mode after FROM", () => {
+ const text = "SELECT Id FROM Acc";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("object");
+ expect(ctx.prefix).toBe("Acc");
+ expect(ctx.clause).toBe("from");
+ });
+
+ it("reports field mode in SELECT and finds a FROM object written later", () => {
+ const text = "SELECT Na FROM Account";
+ const cursor = "SELECT Na".length;
+ const ctx = getSoqlCompletionContext(text, cursor);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.clause).toBe("select");
+ expect(ctx.prefix).toBe("Na");
+ expect(ctx.fromObject).toBe("Account");
+ expect(ctx.relationshipPath).toEqual([]);
+ });
+
+ it("splits a relationship path into path + prefix", () => {
+ const text = "SELECT Owner.Na FROM Account";
+ const ctx = getSoqlCompletionContext(text, "SELECT Owner.Na".length);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.relationshipPath).toEqual(["Owner"]);
+ expect(ctx.prefix).toBe("Na");
+ expect(ctx.from).toBe("SELECT Owner.".length);
+ });
+
+ it("detects value mode inside an open single-quoted string", () => {
+ const text = "SELECT Id FROM Account WHERE Industry = 'Ban";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("value");
+ expect(ctx.insideString).toBe(true);
+ expect(ctx.valueField).toEqual({ path: [], name: "Industry" });
+ expect(ctx.prefix).toBe("Ban");
+ });
+
+ it("detects value mode after an operator without a quote yet", () => {
+ const text = "SELECT Id FROM Account WHERE IsActive = ";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("value");
+ expect(ctx.insideString).toBeFalsy();
+ expect(ctx.valueField).toEqual({ path: [], name: "IsActive" });
+ });
+
+ it("detects value mode on a relationship field path", () => {
+ const text = "SELECT Id FROM Account WHERE Owner.Name = ";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("value");
+ expect(ctx.valueField).toEqual({ path: ["Owner"], name: "Name" });
+ });
+
+ it("does not treat a bare field in WHERE as a value", () => {
+ const text = "SELECT Id FROM Account WHERE Ind";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.clause).toBe("where");
+ expect(ctx.prefix).toBe("Ind");
+ });
+
+ it("reports orderby clause", () => {
+ const text = "SELECT Id FROM Account ORDER BY Na";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.clause).toBe("orderby");
+ });
+});
+
+describe("getSoqlCompletionContext statement boundaries", () => {
+ it("does not inherit a value context from a completed statement", () => {
+ // The previous statement's `> 1000` (unquoted literal) must not make the new
+ // statement's `SELECT F|` a value context.
+ const text = "SELECT Id FROM Account WHERE AnnualRevenue > 1000; SELECT F FROM Account";
+ const cursor = "SELECT Id FROM Account WHERE AnnualRevenue > 1000; SELECT F".length;
+ const ctx = getSoqlCompletionContext(text, cursor);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.clause).toBe("select");
+ expect(ctx.prefix).toBe("F");
+ expect(ctx.fromObject).toBe("Account");
+ expect(ctx.from).toBe(cursor - 1);
+ });
+
+ it("starts a fresh keyword context right after a semicolon", () => {
+ const text = "SELECT Id FROM Account; SEL";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("keyword");
+ expect(ctx.prefix).toBe("SEL");
+ expect(ctx.from).toBe("SELECT Id FROM Account; ".length);
+ });
+
+ it("scopes FROM detection to the current statement", () => {
+ const text = "SELECT Id FROM Contact; SELECT Na FROM Account";
+ const cursor = "SELECT Id FROM Contact; SELECT Na".length;
+ const ctx = getSoqlCompletionContext(text, cursor);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.fromObject).toBe("Account");
+ });
+
+ it("does not borrow the previous statement's FROM when the current one has none yet", () => {
+ const text = "SELECT Id FROM Contact; SELECT Na";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("field");
+ expect(ctx.fromObject).toBeUndefined();
+ });
+
+ it("keeps absolute from positions for value mode inside a later statement's string", () => {
+ const text = "SELECT Id FROM Account; SELECT Id FROM Opportunity WHERE StageName = 'Clo";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ expect(ctx.mode).toBe("value");
+ expect(ctx.insideString).toBe(true);
+ expect(ctx.from).toBe(text.indexOf("'Clo") + 1);
+ expect(ctx.valueField).toEqual({ path: [], name: "StageName" });
+ expect(ctx.fromObject).toBe("Opportunity");
+ });
+});
+
+describe("resolveSoqlFieldCandidates", () => {
+ const load = loader({ Account: ACCOUNT_FIELDS, User: USER_FIELDS });
+
+ it("returns base object fields with no relationship path", async () => {
+ const ctx = getSoqlCompletionContext("SELECT FROM Account", "SELECT ".length);
+ const fields = await resolveSoqlFieldCandidates(ctx, load);
+ expect(fields).toEqual(ACCOUNT_FIELDS);
+ });
+
+ it("traverses a single relationship segment", async () => {
+ const ctx = getSoqlCompletionContext("SELECT Owner. FROM Account", "SELECT Owner.".length);
+ const fields = await resolveSoqlFieldCandidates(ctx, load);
+ expect(fields).toEqual(USER_FIELDS);
+ });
+
+ it("traverses a multi-segment relationship path", async () => {
+ const ctx = getSoqlCompletionContext("SELECT Owner.Manager. FROM Account", "SELECT Owner.Manager.".length);
+ const fields = await resolveSoqlFieldCandidates(ctx, load);
+ expect(fields).toEqual(USER_FIELDS);
+ });
+
+ it("returns empty when a path segment is not a relationship", async () => {
+ const ctx = getSoqlCompletionContext("SELECT Name. FROM Account", "SELECT Name.".length);
+ const fields = await resolveSoqlFieldCandidates(ctx, load);
+ expect(fields).toEqual([]);
+ });
+
+ it("returns empty when there is no FROM object", async () => {
+ const ctx = getSoqlCompletionContext("SELECT ", "SELECT ".length);
+ const fields = await resolveSoqlFieldCandidates(ctx, load);
+ expect(fields).toEqual([]);
+ });
+});
+
+describe("resolveSoqlValueField", () => {
+ const load = loader({ Account: ACCOUNT_FIELDS, User: USER_FIELDS });
+
+ it("resolves a direct field for value completion", async () => {
+ const ctx = getSoqlCompletionContext("SELECT Id FROM Account WHERE Industry = '", "SELECT Id FROM Account WHERE Industry = '".length);
+ const field = await resolveSoqlValueField(ctx, load);
+ expect(field?.name).toBe("Industry");
+ expect(field?.picklistValues).toContain("Banking");
+ });
+
+ it("resolves a field across a relationship path", async () => {
+ const ctx = getSoqlCompletionContext("SELECT Id FROM Account WHERE Owner.Email = '", "SELECT Id FROM Account WHERE Owner.Email = '".length);
+ const field = await resolveSoqlValueField(ctx, load);
+ expect(field?.name).toBe("Email");
+ });
+});
+
+describe("buildSoqlCompletionItems", () => {
+ it("offers clause keywords in keyword mode", () => {
+ const ctx = getSoqlCompletionContext("SEL", 3);
+ const items = buildSoqlCompletionItems(ctx, {});
+ expect(items.map((i) => i.label)).toContain("SELECT");
+ });
+
+ it("offers objects in object mode, standard before custom", () => {
+ const ctx = getSoqlCompletionContext("SELECT Id FROM ", "SELECT Id FROM ".length);
+ const items = buildSoqlCompletionItems(ctx, { objects: OBJECTS });
+ expect(items.map((i) => i.label)).toEqual(["Account", "Contact", "Opportunity", "MyObj__c"]);
+ expect(items[0].type).toBe("table");
+ });
+
+ it("offers fields and marks reference fields as traversal with a trailing dot", () => {
+ const ctx = getSoqlCompletionContext("SELECT FROM Account", "SELECT ".length);
+ const items = buildSoqlCompletionItems(ctx, { fields: ACCOUNT_FIELDS });
+ const owner = items.find((i) => i.label === "OwnerId");
+ expect(owner?.type).toBe("property");
+ expect(owner?.apply).toBe("Owner.");
+ const name = items.find((i) => i.label === "Name");
+ expect(name?.type).toBe("column");
+ expect(name?.apply).toBe("Name");
+ });
+
+ it("offers aggregate functions and FIELDS selectors in SELECT", () => {
+ const ctx = getSoqlCompletionContext("SELECT FROM Account", "SELECT ".length);
+ const items = buildSoqlCompletionItems(ctx, { fields: ACCOUNT_FIELDS });
+ const labels = items.map((i) => i.label);
+ expect(labels).toContain("COUNT");
+ expect(labels).toContain("FIELDS(ALL)");
+ });
+
+ it("offers picklist values (quoted) for a picklist value context outside a string", () => {
+ const ctx = getSoqlCompletionContext("SELECT Id FROM Account WHERE Industry = ", "SELECT Id FROM Account WHERE Industry = ".length);
+ const field = ACCOUNT_FIELDS.find((f) => f.name === "Industry")!;
+ const items = buildSoqlCompletionItems(ctx, { valueField: field });
+ const banking = items.find((i) => i.label === "Banking");
+ expect(banking?.apply).toBe("'Banking'");
+ });
+
+ it("inserts bare picklist values and consumes the closing quote inside a string", () => {
+ const text = "SELECT Id FROM Account WHERE Industry = '";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ const field = ACCOUNT_FIELDS.find((f) => f.name === "Industry")!;
+ const items = buildSoqlCompletionItems(ctx, { valueField: field });
+ const banking = items.find((i) => i.label === "Banking");
+ expect(banking?.apply).toBe("Banking");
+ expect(banking?.replaceClosingQuote).toBe("'");
+ });
+
+ it("offers TRUE/FALSE for a boolean field and date literals for datetime", () => {
+ const boolCtx = getSoqlCompletionContext("SELECT Id FROM Account WHERE IsActive = ", "SELECT Id FROM Account WHERE IsActive = ".length);
+ const boolField = ACCOUNT_FIELDS.find((f) => f.name === "IsActive")!;
+ expect(buildSoqlCompletionItems(boolCtx, { valueField: boolField }).map((i) => i.label)).toContain("TRUE");
+
+ const dateCtx = getSoqlCompletionContext("SELECT Id FROM Account WHERE CreatedDate > ", "SELECT Id FROM Account WHERE CreatedDate > ".length);
+ const dateField = ACCOUNT_FIELDS.find((f) => f.name === "CreatedDate")!;
+ const dateLabels = buildSoqlCompletionItems(dateCtx, { valueField: dateField }).map((i) => i.label);
+ expect(dateLabels).toContain("TODAY");
+ expect(dateLabels).toContain("LAST_N_DAYS:n");
+ });
+
+ it("filters by prefix case-insensitively on name and label", () => {
+ const ctx = getSoqlCompletionContext("SELECT ann FROM Account", "SELECT ann".length);
+ const items = buildSoqlCompletionItems(ctx, { fields: ACCOUNT_FIELDS });
+ // "ann" matches AnnualRevenue by name prefix (case-insensitive)
+ expect(items.map((i) => i.label)).toContain("AnnualRevenue");
+ });
+});
+
+describe("mode predicates and helpers", () => {
+ it("routes object vs field metadata needs", () => {
+ expect(soqlCompletionNeedsObjects("object")).toBe(true);
+ expect(soqlCompletionNeedsObjects("field")).toBe(false);
+ expect(soqlCompletionNeedsFields("field")).toBe(true);
+ expect(soqlCompletionNeedsFields("value")).toBe(true);
+ expect(soqlCompletionNeedsFields("keyword")).toBe(false);
+ });
+
+ it("auto-opens on relationship dot, quote, and identifier typing", () => {
+ expect(shouldAutoOpenSoqlCompletion("SELECT Owner.", "SELECT Owner.".length)).toBe(true);
+ expect(shouldAutoOpenSoqlCompletion("SELECT Id FROM Account WHERE Industry = '", "SELECT Id FROM Account WHERE Industry = '".length)).toBe(true);
+ expect(shouldAutoOpenSoqlCompletion("SELECT Na", "SELECT Na".length)).toBe(true);
+ expect(shouldAutoOpenSoqlCompletion("", 0)).toBe(false);
+ });
+
+ it("gives a value-mode validFor that stops at a quote", () => {
+ const text = "SELECT Id FROM Account WHERE Industry = 'Ban";
+ const ctx = getSoqlCompletionContext(text, text.length);
+ const re = getSoqlCompletionResultValidFor(ctx);
+ expect(re.test("Ban")).toBe(true);
+ expect(re.test("Ban'")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/soql/soqlCompletion.ts b/apps/desktop/src/lib/soql/soqlCompletion.ts
new file mode 100644
index 0000000000..5337d22b04
--- /dev/null
+++ b/apps/desktop/src/lib/soql/soqlCompletion.ts
@@ -0,0 +1,541 @@
+// Salesforce SOQL completion engine.
+//
+// SOQL is SQL-like but narrower: a single object per query (FROM), relationship
+// traversal via `Relationship.Field` paths, no JOINs, no DDL/DML. This module is a
+// PURE function library mirroring lib/mongo/mongoCompletion.ts: a context scanner
+// reads the text under the cursor, a builder turns resolved metadata into
+// completion items, and an async resolver walks relationship paths using a
+// caller-supplied field loader. QueryEditor.vue supplies the store-backed loader
+// (which reads the backend describe cache), so nothing here touches I/O directly.
+
+export interface SoqlCompletionObject {
+ /** sObject API name, e.g. "Account". */
+ name: string;
+ /** Human label, e.g. "Account" or a custom object's label. */
+ label?: string;
+}
+
+export interface SoqlCompletionField {
+ /** Field API name, e.g. "StageName". */
+ name: string;
+ /** Field label, e.g. "Stage". */
+ label?: string;
+ /** Salesforce describe type: picklist, reference, string, boolean, date, datetime, currency, … */
+ type?: string;
+ /** Active picklist values (from describe enum_values). */
+ picklistValues?: string[];
+ /** Relationship name used to traverse a reference field, e.g. "Owner". */
+ relationshipName?: string;
+ /** Referenced sObject API names, e.g. ["User"]. */
+ referenceTo?: string[];
+}
+
+export type SoqlCompletionItemType = "column" | "property" | "table" | "function" | "keyword" | "snippet" | "text";
+
+export interface SoqlCompletionItem {
+ label: string;
+ type: SoqlCompletionItemType;
+ detail?: string;
+ info?: string;
+ apply?: string;
+ filterText?: string;
+ boost: number;
+ /** When completing inside an open string, consume the matching closing quote. */
+ replaceClosingQuote?: "'";
+}
+
+export type SoqlCompletionMode = "none" | "keyword" | "object" | "field" | "value";
+
+export type SoqlClause = "select" | "from" | "where" | "orderby" | "groupby" | "having" | null;
+
+export interface SoqlValueTarget {
+ /** Relationship path segments before the field, e.g. ["Owner"] for `Owner.Name = '…'`. */
+ path: string[];
+ /** The field being compared, e.g. "StageName". */
+ name: string;
+}
+
+export interface SoqlCompletionContext {
+ mode: SoqlCompletionMode;
+ /** Partial identifier immediately before the cursor (last dot segment). */
+ prefix: string;
+ /** Document position where the completion replacement starts. */
+ from: number;
+ /** Resolved FROM object API name for the current statement, if any. */
+ fromObject?: string;
+ /** Relationship path segments before `prefix` (field mode), e.g. ["Owner"] for `Owner.Na|`. */
+ relationshipPath?: string[];
+ /** Clause the cursor sits in. */
+ clause?: SoqlClause;
+ /** Value-mode target field (path + name). */
+ valueField?: SoqlValueTarget;
+ /** Cursor is inside an open single-quoted string (value already being typed). */
+ insideString?: boolean;
+}
+
+export interface SoqlCompletionInput {
+ objects?: SoqlCompletionObject[];
+ /** Fields of the object the cursor resolves to (after relationship traversal). */
+ fields?: SoqlCompletionField[];
+ /** For value mode: the specific field being compared (carries picklistValues/type). */
+ valueField?: SoqlCompletionField | null;
+}
+
+/** SOQL clause keywords offered at statement start / after a completed clause. */
+const SOQL_CLAUSE_KEYWORDS: Array<{ label: string; detail: string; boost: number }> = [
+ { label: "SELECT", detail: "Projection clause", boost: 100 },
+ { label: "FROM", detail: "Object clause", boost: 98 },
+ { label: "WHERE", detail: "Filter clause", boost: 96 },
+ { label: "ORDER BY", detail: "Sort clause", boost: 90 },
+ { label: "GROUP BY", detail: "Grouping clause", boost: 88 },
+ { label: "HAVING", detail: "Aggregate filter", boost: 84 },
+ { label: "LIMIT", detail: "Row limit", boost: 80 },
+ { label: "OFFSET", detail: "Row offset", boost: 78 },
+ { label: "WITH SECURITY_ENFORCED", detail: "Enforce CRUD/FLS", boost: 70 },
+ { label: "NULLS FIRST", detail: "Sort nulls first", boost: 60 },
+ { label: "NULLS LAST", detail: "Sort nulls last", boost: 60 },
+ { label: "ASC", detail: "Ascending", boost: 58 },
+ { label: "DESC", detail: "Descending", boost: 58 },
+ { label: "AND", detail: "Logical AND", boost: 66 },
+ { label: "OR", detail: "Logical OR", boost: 64 },
+ { label: "NOT", detail: "Logical NOT", boost: 62 },
+ { label: "IN", detail: "Set membership", boost: 60 },
+ { label: "LIKE", detail: "Pattern match", boost: 60 },
+ { label: "INCLUDES", detail: "Multi-picklist includes", boost: 58 },
+ { label: "EXCLUDES", detail: "Multi-picklist excludes", boost: 58 },
+];
+
+/** Aggregate / conversion functions valid in SELECT, GROUP BY, HAVING. */
+const SOQL_FUNCTIONS: Array<{ label: string; detail: string; apply?: string }> = [
+ { label: "COUNT", detail: "Row count", apply: "COUNT()" },
+ { label: "COUNT_DISTINCT", detail: "Distinct count", apply: "COUNT_DISTINCT()" },
+ { label: "SUM", detail: "Sum", apply: "SUM()" },
+ { label: "AVG", detail: "Average", apply: "AVG()" },
+ { label: "MIN", detail: "Minimum", apply: "MIN()" },
+ { label: "MAX", detail: "Maximum", apply: "MAX()" },
+ { label: "GROUPING", detail: "Grouping indicator", apply: "GROUPING()" },
+ { label: "convertCurrency", detail: "Convert to user currency", apply: "convertCurrency()" },
+ { label: "convertTimezone", detail: "Convert datetime to user TZ", apply: "convertTimezone()" },
+ { label: "toLabel", detail: "Return picklist/reference label", apply: "toLabel()" },
+ { label: "CALENDAR_YEAR", detail: "Year from date", apply: "CALENDAR_YEAR()" },
+ { label: "CALENDAR_MONTH", detail: "Month from date", apply: "CALENDAR_MONTH()" },
+ { label: "CALENDAR_QUARTER", detail: "Quarter from date", apply: "CALENDAR_QUARTER()" },
+ { label: "DAY_ONLY", detail: "Date portion of datetime", apply: "DAY_ONLY()" },
+ { label: "FISCAL_YEAR", detail: "Fiscal year from date", apply: "FISCAL_YEAR()" },
+ { label: "FISCAL_QUARTER", detail: "Fiscal quarter from date", apply: "FISCAL_QUARTER()" },
+];
+
+/** FIELDS() selectors — SOQL's "expand all fields" (LIMIT ≤ 200; the driver auto-appends LIMIT 200 when missing). */
+const SOQL_FIELDS_SELECTORS: Array<{ label: string; detail: string }> = [
+ { label: "FIELDS(ALL)", detail: "All fields (LIMIT 200 auto-added if missing)" },
+ { label: "FIELDS(STANDARD)", detail: "All standard fields" },
+ { label: "FIELDS(CUSTOM)", detail: "All custom fields (LIMIT 200 auto-added if missing)" },
+];
+
+/** SOQL date literals offered in value position for date/datetime fields. */
+const SOQL_DATE_LITERALS: string[] = [
+ "YESTERDAY",
+ "TODAY",
+ "TOMORROW",
+ "LAST_WEEK",
+ "THIS_WEEK",
+ "NEXT_WEEK",
+ "LAST_MONTH",
+ "THIS_MONTH",
+ "NEXT_MONTH",
+ "LAST_90_DAYS",
+ "NEXT_90_DAYS",
+ "LAST_N_DAYS:n",
+ "NEXT_N_DAYS:n",
+ "LAST_QUARTER",
+ "THIS_QUARTER",
+ "NEXT_QUARTER",
+ "LAST_N_QUARTERS:n",
+ "NEXT_N_QUARTERS:n",
+ "LAST_YEAR",
+ "THIS_YEAR",
+ "NEXT_YEAR",
+ "LAST_N_YEARS:n",
+ "NEXT_N_YEARS:n",
+ "LAST_FISCAL_QUARTER",
+ "THIS_FISCAL_QUARTER",
+ "NEXT_FISCAL_QUARTER",
+ "LAST_FISCAL_YEAR",
+ "THIS_FISCAL_YEAR",
+ "NEXT_FISCAL_YEAR",
+];
+
+const SOQL_AGGREGATE_CLAUSES = new Set<SoqlClause>(["select", "groupby", "having"]);
+
+const WORD_CHAR = /[A-Za-z0-9_]/;
+
+/**
+ * Scan the text under the cursor and classify the SOQL completion context.
+ * Pure and synchronous — metadata resolution happens in the provider.
+ *
+ * All backward scanning is scoped to the CURRENT statement (text after the last
+ * `;`): a completed statement's `WHERE x > 1` must not make the next statement's
+ * `SELECT F|` look like a value context, and its FROM/clauses must not leak in.
+ * Returned `from` positions are always absolute document offsets.
+ */
+export function getSoqlCompletionContext(text: string, cursor: number): SoqlCompletionContext {
+ const safeCursor = Math.max(0, Math.min(cursor, text.length));
+ const beforeCursor = text.slice(0, safeCursor);
+ const statementStart = beforeCursor.lastIndexOf(";") + 1;
+ const statement = beforeCursor.slice(statementStart);
+
+ const fromObject = findFromObject(text, safeCursor);
+ const clause = findClause(statement);
+
+ // Value context: cursor sits inside an open single-quoted string, or right after
+ // a comparison operator (optionally a just-opened quote). `stringStart` is
+ // statement-relative; convert to an absolute offset before returning.
+ const stringStart = openSingleQuoteStart(statement);
+ const valueTarget = parseValueTarget(statement, stringStart);
+ if (valueTarget) {
+ const insideString = stringStart != null;
+ const trailing = readTrailingPrefix(statement);
+ return {
+ mode: "value",
+ prefix: insideString ? statement.slice(stringStart + 1) : trailing.prefix,
+ from: insideString ? statementStart + stringStart + 1 : safeCursor - trailing.prefix.length,
+ fromObject,
+ clause,
+ valueField: { path: valueTarget.path, name: valueTarget.name },
+ insideString,
+ };
+ }
+
+ // Object context: the cursor is in the FROM clause completing an sObject name.
+ if (clause === "from") {
+ const { prefix, from } = readTrailingPrefix(statement);
+ return { mode: "object", prefix, from: statementStart + from, fromObject, clause };
+ }
+
+ // Field context: SELECT / WHERE / ORDER BY / GROUP BY / HAVING (clause === "from"
+ // already returned above, so any remaining clause is a field clause).
+ if (clause) {
+ const { prefix, from, path } = readTrailingPrefix(statement);
+ return { mode: "field", prefix, from: statementStart + from, fromObject, relationshipPath: path, clause };
+ }
+
+ // No clause yet (empty/fresh statement, or only whitespace typed): offer clauses.
+ const { prefix, from } = readTrailingPrefix(statement);
+ if (prefix || statement.trim().length === 0) {
+ return { mode: "keyword", prefix, from: statementStart + from, fromObject, clause: null };
+ }
+ return { mode: "none", prefix: "", from: safeCursor, fromObject, clause };
+}
+
+/**
+ * Find the FROM object of the statement containing the cursor. Scoped to the
+ * current statement (`;`-separated) so a neighbouring query's FROM never leaks
+ * field candidates into this one; within the statement prefer the nearest FROM
+ * before the cursor, else the first one after it (the user is often still
+ * typing the projection when FROM exists only ahead of the cursor).
+ */
+function findFromObject(text: string, cursor: number): string | undefined {
+ const statementStart = text.lastIndexOf(";", cursor - 1) + 1;
+ const semicolonAfter = text.indexOf(";", cursor);
+ const statementEnd = semicolonAfter === -1 ? text.length : semicolonAfter;
+ const statement = text.slice(statementStart, statementEnd);
+ const re = /\bfrom\s+([A-Za-z_][A-Za-z0-9_]*)/gi;
+ let lastBefore: string | undefined;
+ let firstAfter: string | undefined;
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(statement)) !== null) {
+ const name = match[1];
+ if (statementStart + match.index < cursor) lastBefore = name;
+ else if (firstAfter == null) firstAfter = name;
+ }
+ return lastBefore ?? firstAfter;
+}
+
+/** Identify the clause the cursor is in from the last clause keyword before it. */
+function findClause(beforeCursor: string): SoqlClause {
+ const upper = beforeCursor.toUpperCase();
+ const markers: Array<{ kw: RegExp; clause: SoqlClause }> = [
+ { kw: /\bORDER\s+BY\b/g, clause: "orderby" },
+ { kw: /\bGROUP\s+BY\b/g, clause: "groupby" },
+ { kw: /\bHAVING\b/g, clause: "having" },
+ { kw: /\bWHERE\b/g, clause: "where" },
+ { kw: /\bFROM\b/g, clause: "from" },
+ { kw: /\bSELECT\b/g, clause: "select" },
+ ];
+ let best: { index: number; clause: SoqlClause } | null = null;
+ for (const { kw, clause } of markers) {
+ kw.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = kw.exec(upper)) !== null) {
+ if (!best || m.index > best.index) best = { index: m.index, clause };
+ if (m.index === kw.lastIndex) kw.lastIndex++;
+ }
+ }
+ return best ? best.clause : null;
+}
+
+/**
+ * If the cursor is inside an unterminated single-quoted string, return the index of
+ * the opening quote; otherwise null. Handles backslash escapes.
+ */
+function openSingleQuoteStart(beforeCursor: string): number | null {
+ let open: number | null = null;
+ for (let i = 0; i < beforeCursor.length; i++) {
+ const ch = beforeCursor[i];
+ if (ch === "\\") {
+ i++;
+ continue;
+ }
+ if (ch === "'") {
+ if (open == null) open = i;
+ else open = null;
+ }
+ }
+ return open;
+}
+
+/**
+ * Parse `<fieldPath> <op> ['…]` immediately before the cursor. Returns the field path
+ * and name when the cursor is in a value position, else null.
+ */
+function parseValueTarget(beforeCursor: string, stringStart: number | null): { path: string[]; name: string } | null {
+ // Text up to (and excluding) the operator, dropping any partial string content.
+ const head = stringStart != null ? beforeCursor.slice(0, stringStart) : beforeCursor;
+ const m = /([A-Za-z_][A-Za-z0-9_]*(?:\s*\.\s*[A-Za-z_][A-Za-z0-9_]*)*)\s*(?:=|!=|<>|<=|>=|<|>|\bLIKE\b|\bIN\b|\bINCLUDES\b|\bEXCLUDES\b)\s*'?[^']*$/i.exec(head);
+ if (!m) return null;
+ // When not inside a string, only treat as a value context if the operator is complete
+ // and followed by optional whitespace/quote (avoid matching `Name` in SELECT).
+ const segments = m[1].split(/\s*\.\s*/).filter(Boolean);
+ if (segments.length === 0) return null;
+ const name = segments[segments.length - 1];
+ return { path: segments.slice(0, -1), name };
+}
+
+/**
+ * Read the trailing dotted identifier under the cursor. Returns the last segment as
+ * `prefix`, the replacement start `from`, and preceding segments as `path`.
+ */
+function readTrailingPrefix(beforeCursor: string): { prefix: string; from: number; path: string[] } {
+ let i = beforeCursor.length;
+ while (i > 0 && (WORD_CHAR.test(beforeCursor[i - 1]) || beforeCursor[i - 1] === ".")) i--;
+ const span = beforeCursor.slice(i);
+ if (!span) return { prefix: "", from: beforeCursor.length, path: [] };
+ const segments = span.split(".");
+ const prefix = segments[segments.length - 1] ?? "";
+ const path = segments.slice(0, -1).filter((seg) => seg.length > 0);
+ const from = beforeCursor.length - prefix.length;
+ return { prefix, from, path };
+}
+
+/**
+ * Walk a relationship path from the FROM object, returning the fields of the final
+ * object. `loadFields` reads the (cached) describe metadata for one sObject.
+ */
+export async function resolveSoqlFieldCandidates(context: SoqlCompletionContext, loadFields: (objectName: string) => Promise<SoqlCompletionField[]>): Promise<SoqlCompletionField[]> {
+ if (!context.fromObject) return [];
+ let fields = await loadFields(context.fromObject);
+ for (const segment of context.relationshipPath ?? []) {
+ const rel = fields.find((f) => (f.relationshipName ?? "").toLowerCase() === segment.toLowerCase() || f.name.toLowerCase() === segment.toLowerCase());
+ const next = rel?.referenceTo?.[0];
+ if (!next) return [];
+ fields = await loadFields(next);
+ }
+ return fields;
+}
+
+/**
+ * Resolve the specific field a value-mode cursor compares against (walking its
+ * relationship path), so the builder can offer its picklist values / type-aware literals.
+ */
+export async function resolveSoqlValueField(context: SoqlCompletionContext, loadFields: (objectName: string) => Promise<SoqlCompletionField[]>): Promise<SoqlCompletionField | null> {
+ if (!context.fromObject || !context.valueField) return null;
+ let fields = await loadFields(context.fromObject);
+ for (const segment of context.valueField.path) {
+ const rel = fields.find((f) => (f.relationshipName ?? "").toLowerCase() === segment.toLowerCase() || f.name.toLowerCase() === segment.toLowerCase());
+ const next = rel?.referenceTo?.[0];
+ if (!next) return null;
+ fields = await loadFields(next);
+ }
+ return fields.find((f) => f.name.toLowerCase() === context.valueField!.name.toLowerCase()) ?? null;
+}
+
+/** True when the given mode's items come from the object list. */
+export function soqlCompletionNeedsObjects(mode: SoqlCompletionMode): boolean {
+ return mode === "object";
+}
+
+/** True when the given mode's items come from field metadata. */
+export function soqlCompletionNeedsFields(mode: SoqlCompletionMode): boolean {
+ return mode === "field" || mode === "value";
+}
+
+/**
+ * Build completion items for a resolved context. `input.fields` must already be the
+ * fields of the object the cursor resolves to (see resolveSoqlFieldCandidates);
+ * `input.valueField` is the compared field for value mode.
+ */
+export function buildSoqlCompletionItems(context: SoqlCompletionContext, input: SoqlCompletionInput = {}): SoqlCompletionItem[] {
+ const { prefix } = context;
+ switch (context.mode) {
+ case "none":
+ return [];
+ case "keyword":
+ return keywordItems(prefix);
+ case "object":
+ return objectItems(prefix, input.objects ?? []);
+ case "value":
+ return valueItems(prefix, input.valueField ?? null, context.insideString === true);
+ case "field":
+ return fieldItems(prefix, context, input.fields ?? []);
+ default:
+ return [];
+ }
+}
+
+function keywordItems(prefix: string): SoqlCompletionItem[] {
+ const lower = prefix.toLowerCase();
+ return SOQL_CLAUSE_KEYWORDS.filter((k) => matchesPrefix(k.label, lower)).map((k) => ({
+ label: k.label,
+ type: "keyword" as const,
+ detail: k.detail,
+ boost: k.boost,
+ filterText: k.label.replace(/\s+/g, ""),
+ }));
+}
+
+function objectItems(prefix: string, objects: SoqlCompletionObject[]): SoqlCompletionItem[] {
+ const lower = prefix.toLowerCase();
+ return objects
+ .filter((o) => matchesPrefix(o.name, lower) || matchesPrefix(o.label ?? "", lower))
+ .map((o) => ({
+ label: o.name,
+ type: "table" as const,
+ detail: o.label && o.label !== o.name ? o.label : "sObject",
+ filterText: o.name,
+ // Rank standard objects (no __c/__kav suffix) slightly above custom for a tidy list.
+ boost: o.name.endsWith("__c") ? 90 : 100,
+ }));
+}
+
+function fieldItems(prefix: string, context: SoqlCompletionContext, fields: SoqlCompletionField[]): SoqlCompletionItem[] {
+ const lower = prefix.toLowerCase();
+ const items: SoqlCompletionItem[] = [];
+
+ for (const field of fields) {
+ if (!matchesPrefix(field.name, lower) && !matchesPrefix(field.label ?? "", lower)) continue;
+ const isRelationship = !!field.relationshipName && (field.referenceTo?.length ?? 0) > 0;
+ items.push({
+ label: field.name,
+ type: isRelationship ? "property" : "column",
+ detail: describeField(field),
+ info: field.label && field.label !== field.name ? field.label : undefined,
+ filterText: field.name,
+ // Offer `Relationship.` traversal by appending a dot when accepted.
+ apply: isRelationship ? `${field.relationshipName}.` : field.name,
+ boost: 100,
+ });
+ }
+
+ // Relationship-name traversal is already covered above (reference fields apply as
+ // `Relationship.`). In aggregate-capable clauses, also offer functions and selectors.
+ if (SOQL_AGGREGATE_CLAUSES.has(context.clause ?? null)) {
+ for (const fn of SOQL_FUNCTIONS) {
+ if (!matchesPrefix(fn.label, lower)) continue;
+ items.push({ label: fn.label, type: "function", detail: fn.detail, apply: fn.apply, filterText: fn.label, boost: 78 });
+ }
+ }
+ if ((context.clause ?? null) === "select" && !context.relationshipPath?.length) {
+ for (const sel of SOQL_FIELDS_SELECTORS) {
+ if (!matchesPrefix(sel.label, lower) && !matchesPrefix("fields", lower)) continue;
+ items.push({ label: sel.label, type: "snippet", detail: sel.detail, apply: sel.label, filterText: sel.label.replace(/\W/g, ""), boost: 72 });
+ }
+ }
+ return items;
+}
+
+function valueItems(prefix: string, field: SoqlCompletionField | null, insideString: boolean): SoqlCompletionItem[] {
+ const lower = prefix.toLowerCase();
+ const items: SoqlCompletionItem[] = [];
+ const type = (field?.type ?? "").toLowerCase();
+
+ // `quoted` literals (picklist/string values) need surrounding single quotes. When the
+ // cursor is already inside an open string we insert the bare value and consume the
+ // closing quote; otherwise we insert a fully quoted literal. Unquoted literals
+ // (NULL / TRUE / FALSE / date literals) are inserted bare either way.
+ const addValues = (values: string[], detail: string, boost: number, quoted: boolean) => {
+ for (const value of values) {
+ if (!matchesPrefix(value, lower)) continue;
+ if (quoted && !insideString) {
+ items.push({ label: value, type: "text", detail, boost, apply: `'${value}'`, filterText: value });
+ } else {
+ items.push({
+ label: value,
+ type: "text",
+ detail,
+ boost,
+ apply: value,
+ filterText: value,
+ ...(quoted && insideString ? { replaceClosingQuote: "'" as const } : {}),
+ });
+ }
+ }
+ };
+
+ if (field?.picklistValues?.length) {
+ addValues(field.picklistValues, "Picklist value", 100, true);
+ }
+ if (type === "boolean") {
+ addValues(["TRUE", "FALSE"], "Boolean", 96, false);
+ }
+ if (type === "date" || type === "datetime") {
+ addValues(SOQL_DATE_LITERALS, "Date literal", 92, false);
+ }
+ // Universally valid literals.
+ addValues(["NULL"], "Null literal", 70, false);
+ if (!field || type === "string" || type === "textarea" || type === "email" || type === "phone" || type === "url") {
+ addValues(["TRUE", "FALSE"], "Boolean", 40, false);
+ }
+ return items;
+}
+
+function describeField(field: SoqlCompletionField): string {
+ const parts: string[] = [];
+ if (field.type) parts.push(field.type);
+ if (field.relationshipName && field.referenceTo?.length) parts.push(`→ ${field.referenceTo.join(", ")}`);
+ return parts.join(" ");
+}
+
+function matchesPrefix(candidate: string, lowerPrefix: string): boolean {
+ if (!lowerPrefix) return true;
+ return candidate.toLowerCase().startsWith(lowerPrefix);
+}
+
+/**
+ * Whether typing at this cursor should auto-open the completion popup. Mirrors the
+ * mongo/redis providers: open on relationship dots, after clause keywords + space,
+ * inside a just-opened quote, and while typing an identifier.
+ */
+export function shouldAutoOpenSoqlCompletion(text: string, cursor: number): boolean {
+ const safeCursor = Math.max(0, Math.min(cursor, text.length));
+ const before = text.slice(0, safeCursor);
+ const prevChar = before[before.length - 1];
+ if (!prevChar) return false;
+ if (prevChar === ".") return true;
+ if (prevChar === "'") return true;
+ if (/\s$/.test(before)) {
+ const ctx = getSoqlCompletionContext(text, safeCursor);
+ return ctx.mode !== "none";
+ }
+ if (WORD_CHAR.test(prevChar)) return true;
+ return false;
+}
+
+/**
+ * validFor predicate source: completions stay valid while the user keeps typing the
+ * identifier/value characters. Returned as a RegExp like the mongo/redis providers.
+ */
+export function getSoqlCompletionResultValidFor(context: SoqlCompletionContext): RegExp {
+ // In value mode inside a string, valid while the typed slice has no closing quote.
+ if (context.mode === "value" && context.insideString) return /^[^']*$/;
+ return /^[A-Za-z0-9_.]*$/;
+}
diff --git a/apps/desktop/src/lib/sql/semantic/dialect.ts b/apps/desktop/src/lib/sql/semantic/dialect.ts
index d4db2aa6b4..a1fe2cd01d 100644
--- a/apps/desktop/src/lib/sql/semantic/dialect.ts
+++ b/apps/desktop/src/lib/sql/semantic/dialect.ts
@@ -165,6 +165,21 @@ export const SQL_SEMANTIC_DIALECTS: Record<string, SqlSemanticDialectAdapter> =
return parts.length >= 1 ? "schema" : "unknown";
},
},
+ // SOQL: identifiers are never quoted, field names are case-insensitive, there are
+ // no table aliases or projection aliases, and a qualifier is a relationship path
+ // segment (Account.Owner) that always resolves to a related sObject ("table").
+ soql: {
+ id: "soql",
+ identifierQuotes: [],
+ supportsAsForTableAlias: false,
+ projectionAliasVisibility: { where: false, groupBy: false, having: false, orderBy: false },
+ normalizeIdentifier: (identifier) => identifier.toLowerCase(),
+ quoteIdentifier: (identifier) => identifier,
+ qualifierRole(_parts, context) {
+ if (context === "column") return "table";
+ return "unknown";
+ },
+ },
};
export function sqlReferenceAnalysisDialectFor(options: { databaseType?: DatabaseType; identifierQuote?: string; fallbackDialect: string }): string {
@@ -174,7 +189,8 @@ export function sqlReferenceAnalysisDialectFor(options: { databaseType?: Databas
return options.fallbackDialect;
}
-export function sqlSemanticDialectFor(options: { databaseType?: DatabaseType; dialect?: "mysql" | "postgres" | "sqlserver" | "clickhouse" | "doris" }): SqlSemanticDialectAdapter {
+export function sqlSemanticDialectFor(options: { databaseType?: DatabaseType; dialect?: "mysql" | "postgres" | "sqlserver" | "clickhouse" | "doris" | "soql" }): SqlSemanticDialectAdapter {
+ if (options.databaseType === "salesforce") return SQL_SEMANTIC_DIALECTS.soql;
if (options.databaseType === "clickhouse") return SQL_SEMANTIC_DIALECTS.clickhouse;
// Doris/StarRocks connections ride the editor's MySQL fallback dialect (codeMirrorSqlDialect maps
// them to "mysql"), so the explicit-dialect branch below would otherwise mask the doris adapter
@@ -222,6 +238,6 @@ export function sqlSemanticDialectFor(options: { databaseType?: DatabaseType; di
* "generic" default), matching tokenizeSqlSemantic's default and preserving the behavior callers
* had before dialect-aware scanning existed.
*/
-export function resolveSqlDialectId(options: { databaseType?: DatabaseType; dialect?: "mysql" | "postgres" | "sqlserver" | "clickhouse" | "doris" }): string {
+export function resolveSqlDialectId(options: { databaseType?: DatabaseType; dialect?: "mysql" | "postgres" | "sqlserver" | "clickhouse" | "doris" | "soql" }): string {
return options.databaseType || options.dialect ? sqlSemanticDialectFor(options).id : "mysql";
}
diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
index 38ceb78f94..65de407ed9 100644
--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts
+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
@@ -27,7 +27,7 @@ export function elasticsearchRestRequestRanges(sql: string, databaseType?: Datab
return requests.length > 0 && requests.every((request) => ELASTICSEARCH_REST_REQUEST.test(request.sql)) ? requests : [];
}
-const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "neo4j", "victoriametrics"]);
+const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "neo4j", "victoriametrics", "salesforce"]);
export function supportsExecutionTargetPicker(databaseType?: DatabaseType): boolean {
return !!databaseType && (databaseType === "redis" || isHttpJsonRestDatabaseType(databaseType) || !NON_SQL_EXECUTION_TARGET_TYPES.has(databaseType));
diff --git a/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts b/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts
index d044a681bd..72471a3143 100644
--- a/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts
+++ b/apps/desktop/src/lib/table/__tests__/tableMetadataCapabilities.spec.ts
@@ -14,6 +14,21 @@ describe("tableMetadataCapabilities", () => {
});
});
+ it("exposes only describe fields for Salesforce objects", () => {
+ // An SObject has no index, foreign key, trigger or DDL metadata; only the
+ // describe payload (fields) is real, so every other structure tab stays off
+ // instead of rendering permanently empty.
+ expect(getTableMetadataCapabilities("salesforce")).toEqual({
+ columns: true,
+ indexes: false,
+ foreignKeys: false,
+ constraints: false,
+ triggers: false,
+ partitions: false,
+ ddl: false,
+ });
+ });
+
it("exposes structured constraints only for dialects that implement list_constraints", () => {
expect(getTableMetadataCapabilities("oracle").constraints).toBe(true);
expect(getTableMetadataCapabilities("postgres").constraints).toBe(true);
diff --git a/apps/desktop/src/lib/table/tableEditing.ts b/apps/desktop/src/lib/table/tableEditing.ts
index 2b27eb6b7d..c7e7767e08 100644
--- a/apps/desktop/src/lib/table/tableEditing.ts
+++ b/apps/desktop/src/lib/table/tableEditing.ts
@@ -143,3 +143,49 @@ export function isClickHouseExistingRowReadonlyColumn(databaseType: DatabaseType
const columnInfo = columns.find((info) => info.name.toLowerCase() === column.toLowerCase());
return /\bpartition_key\b/i.test(columnInfo?.extra ?? "");
}
+
+/**
+ * Describe flags the Salesforce driver packs into `ColumnInfo.extra`
+ * (see `parse_describe_columns` in crates/dbx-drivers/src/db/salesforce_driver.rs).
+ * `relationshipName` / `referenceTo` also live there but are consumed by SOQL
+ * completion instead (`soqlFieldFromColumnInfo`).
+ */
+export interface SalesforceColumnFlags {
+ updateable?: boolean;
+ createable?: boolean;
+ custom?: boolean;
+ label?: string;
+}
+
+export function parseSalesforceColumnExtra(extra?: string | null): SalesforceColumnFlags | null {
+ if (!extra) return null;
+ try {
+ const parsed: unknown = JSON.parse(extra);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as SalesforceColumnFlags) : null;
+ } catch {
+ return null;
+ }
+}
+
+function findColumnInfoByName(columns: ColumnInfo[], column: string): ColumnInfo | undefined {
+ return columns.find((info) => info.name.toLowerCase() === column.toLowerCase());
+}
+
+/**
+ * Existing Salesforce rows: the record `Id` is the identity and never a write
+ * target, and describe reports `updateable: false` for formula, rollup summary,
+ * auto-number and system fields (CreatedDate, CreatedById, LastModifiedDate…).
+ * Missing/unparseable metadata fails open — Salesforce enforces the real rules
+ * server-side and returns a per-record error we surface on the row.
+ */
+export function isSalesforceExistingRowReadonlyColumn(databaseType: DatabaseType | undefined, column: string, primaryKeys: readonly string[], columns: ColumnInfo[] = []): boolean {
+ if (databaseType !== "salesforce") return false;
+ if (primaryKeys.some((key) => key.toLowerCase() === column.toLowerCase())) return true;
+ return parseSalesforceColumnExtra(findColumnInfoByName(columns, column)?.extra)?.updateable === false;
+}
+
+/** New Salesforce rows: fields describe reports as `createable: false` (Id, CreatedDate, …) cannot be set on insert. */
+export function isSalesforceNewRowReadonlyColumn(databaseType: DatabaseType | undefined, column: string, columns: ColumnInfo[] = []): boolean {
+ if (databaseType !== "salesforce") return false;
+ return parseSalesforceColumnExtra(findColumnInfoByName(columns, column)?.extra)?.createable === false;
+}
diff --git a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts b/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
index e81956fb7b..119236c2ad 100644
--- a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
+++ b/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
@@ -90,6 +90,15 @@ const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabi
triggers: false,
ddl: false,
},
+ // A Salesforce object only has describe metadata: the driver lists fields, and
+ // there is no index, foreign key, trigger or DDL surface behind an SObject, so
+ // those structure tabs would render permanently empty.
+ salesforce: {
+ indexes: false,
+ foreignKeys: false,
+ triggers: false,
+ ddl: false,
+ },
hbase: {
indexes: false,
foreignKeys: false,
diff --git a/apps/desktop/src/lib/table/tableSelectSql.ts b/apps/desktop/src/lib/table/tableSelectSql.ts
index 6aa03e55ef..304b95dfc0 100644
--- a/apps/desktop/src/lib/table/tableSelectSql.ts
+++ b/apps/desktop/src/lib/table/tableSelectSql.ts
@@ -89,6 +89,10 @@ function sqlStatementSpans(sql: string, dialectId: string): Array<{ start: numbe
export function quoteTableIdentifier(databaseType: DatabaseType | undefined, name: string): string {
if ((databaseType === "gaussdb" || databaseType === "opengauss") && isExplicitlyQuotedSqlIdentifier(name)) return name;
if (databaseType === "iotdb") return name;
+ // SOQL has no delimited identifiers — `"Account"` is a string literal there and
+ // `SELECT * FROM "Account"` fails with MALFORMED_QUERY. Mirrors the Rust
+ // `quote_table_identifier` so a grid ORDER BY / filter matches what the backend builds.
+ if (databaseType === "salesforce") return name;
// JDBC connections use the driver-reported identifier quote string
// (DatabaseMetaData.getIdentifierQuoteString()) — pass through unquoted.
if (databaseType === "jdbc") return name;
@@ -427,6 +431,21 @@ export function normalizeWhereInput(whereInput?: string): string {
return withoutSemicolon.replace(/^where\b/i, "").trim();
}
+/**
+ * Database types whose data-preview SQL cannot be built without a column list,
+ * so the columns must be awaited before the statement is generated rather than
+ * refreshed in the background.
+ *
+ * * MySQL / PostgreSQL: the large-value preview projection is derived from the
+ * column types and primary keys.
+ * * Salesforce: SOQL has no `SELECT *`. With no known fields the backend builder
+ * falls back to the `FIELDS(ALL)` selector, which the org only accepts with
+ * `LIMIT 200` or less — awaiting the describe keeps every page size working.
+ */
+export function requiresEagerTableMetadataForDataOpen(databaseType: DatabaseType | undefined): boolean {
+ return databaseType === "mysql" || databaseType === "postgres" || databaseType === "salesforce";
+}
+
export async function buildTableSelectSql(options: BuildTableSelectSqlOptions): Promise<string> {
if (options.databaseType === "victoriametrics") return metricRangeQuery(options.tableName);
return api.buildTableSelectSql(options);
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.salesforceIdentity.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.salesforceIdentity.spec.ts
new file mode 100644
index 0000000000..b0cba8d141
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/connectionStore.salesforceIdentity.spec.ts
@@ -0,0 +1,131 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ConnectionConfig } from "@/types/database";
+import type { SalesforceCurrentUser } from "@/types/salesforce";
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function salesforceConnection(): ConnectionConfig {
+ return {
+ id: "sf-1",
+ name: "Salesforce",
+ db_type: "salesforce",
+ host: "acme--qas1.sandbox.my.salesforce.com",
+ port: 443,
+ username: "[email protected]",
+ password: "",
+ database: "",
+ read_only: false,
+ } as ConnectionConfig;
+}
+
+const identity: SalesforceCurrentUser = {
+ userId: "005xx000001Swag",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ organizationId: "00Dxx0000001gEQ",
+ username: "[email protected]",
+ profileName: "System Administrator",
+ isAdmin: true,
+ orgName: "Acme QA Sandbox",
+};
+
+async function createStore(salesforceCurrentUser: ReturnType<typeof vi.fn>) {
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ connectionDatabaseInfo: vi.fn().mockResolvedValue(null),
+ connectionIdentifierQuote: vi.fn().mockResolvedValue(undefined),
+ salesforceCurrentUser,
+ }));
+
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const store = useConnectionStore();
+ store.connections = [salesforceConnection()];
+ // Already connected: the identity lookup must never trigger a connect of its own.
+ store.connectedIds.add("sf-1");
+ return store;
+}
+
+describe("connectionStore salesforce identity", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.unstubAllGlobals();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ });
+
+ it("resolves the identity once per connection and serves it from cache afterwards", async () => {
+ const api = vi.fn().mockResolvedValue(identity);
+ const store = await createStore(api);
+
+ expect(store.salesforceCurrentUser("sf-1")).toBeNull();
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toEqual(identity);
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toEqual(identity);
+
+ expect(store.salesforceCurrentUser("sf-1")).toEqual(identity);
+ expect(api).toHaveBeenCalledTimes(1);
+ expect(api).toHaveBeenCalledWith("sf-1");
+ });
+
+ it("deduplicates concurrent lookups into one request", async () => {
+ const api = vi.fn().mockResolvedValue(identity);
+ const store = await createStore(api);
+
+ const [first, second] = await Promise.all([store.loadSalesforceCurrentUser("sf-1"), store.loadSalesforceCurrentUser("sf-1")]);
+
+ expect(first).toEqual(identity);
+ expect(second).toEqual(identity);
+ expect(api).toHaveBeenCalledTimes(1);
+ });
+
+ it("hides the badge on failure without caching it, so a later lookup can recover", async () => {
+ const api = vi.fn().mockRejectedValueOnce(new Error("Connection not found")).mockResolvedValueOnce(identity);
+ const store = await createStore(api);
+
+ // The badge and the save-confirmation warning are advisory: a failed probe
+ // must resolve quietly instead of throwing into the caller.
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toBeNull();
+ expect(store.salesforceCurrentUser("sf-1")).toBeNull();
+
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toEqual(identity);
+ expect(api).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not cache a response that carries no identity", async () => {
+ const api = vi
+ .fn()
+ .mockResolvedValueOnce({ ...identity, userId: "", username: "", name: "" })
+ .mockResolvedValueOnce(identity);
+ const store = await createStore(api);
+
+ await store.loadSalesforceCurrentUser("sf-1");
+ expect(store.salesforceCurrentUser("sf-1")).toBeNull();
+
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toEqual(identity);
+ expect(api).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps an identity whose admin probe did not resolve", async () => {
+ const api = vi.fn().mockResolvedValue({ ...identity, isAdmin: null, profileName: undefined });
+ const store = await createStore(api);
+
+ await expect(store.loadSalesforceCurrentUser("sf-1")).resolves.toMatchObject({ username: "[email protected]", isAdmin: null });
+ expect(store.salesforceCurrentUser("sf-1")?.profileName).toBeUndefined();
+ });
+
+ it("resolves quietly without a connection id", async () => {
+ const api = vi.fn().mockResolvedValue(identity);
+ const store = await createStore(api);
+
+ await expect(store.loadSalesforceCurrentUser("")).resolves.toBeNull();
+ expect(api).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
index ba9574e7e3..66aebc9139 100644
--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts
@@ -697,6 +697,17 @@ describe("normalizeMcpGlobalPolicy", () => {
expect(policy.connectionPolicies[0].executionModePolicyVersion).toBeNull();
});
+ it("defaults the Salesforce DML opt-in to off and revokes it under read-only", () => {
+ // Policies saved before the switch existed carry no field at all.
+ expect(normalizeMcpGlobalPolicy({ connectionPolicies: [{ connectionId: "sfdc", databaseScope: "all" } as any] }).connectionPolicies[0].allowSalesforceDml).toBe(false);
+
+ expect(normalizeMcpGlobalPolicy({ connectionPolicies: [{ connectionId: "sfdc", allowSalesforceDml: true } as any] }).connectionPolicies[0].allowSalesforceDml).toBe(true);
+
+ expect(normalizeMcpGlobalPolicy({ connectionPolicies: [{ connectionId: "sfdc", readOnly: true, allowSalesforceDml: true } as any] }).connectionPolicies[0].allowSalesforceDml).toBe(false);
+
+ expect(normalizeMcpGlobalPolicy({ connectionPolicies: [{ connectionId: "sfdc", allowSalesforceDml: "yes" } as any] }).connectionPolicies[0].allowSalesforceDml).toBe(false);
+ });
+
it("round-trips queryTimeoutSecs null, undefined and positive numbers", () => {
expect(normalizeMcpGlobalPolicy({ queryTimeoutSecs: null }).queryTimeoutSecs).toBeNull();
expect(normalizeMcpGlobalPolicy({ queryTimeoutSecs: undefined } as any).queryTimeoutSecs).toBeNull();
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 98eba5fce8..408cb425ee 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -165,6 +165,8 @@ import { useSavedSqlStore } from "@/stores/savedSqlStore";
import { decorateDatabaseSavedSqlTreeNodes, indexSavedSqlFilesByDatabase, stripDatabaseSavedSqlTreeNodes, withDatabaseSavedSqlRoot } from "@/lib/savedSql/savedSqlDatabaseTree";
import { encodeSqlServerLinkedSchema, parseSqlServerLinkedSchema } from "@/lib/database/sqlServerLinkedServers";
import { inferMongoCompletionFields, type MongoCompletionField } from "@/lib/mongo/mongoCompletion";
+import type { SoqlCompletionField, SoqlCompletionObject } from "@/lib/soql/soqlCompletion";
+import type { SalesforceCurrentUser } from "@/types/salesforce";
import { flattenElasticsearchMappingFields, type ElasticsearchCompletionField } from "@/lib/elasticsearch/elasticsearchCompletion";
import { isMongoLegacyDriverProfile } from "@/lib/mongo/mongoCapabilities";
import { mongoCollectionKindFromNode, toMongoCollectionKind, visibleMongoCollections } from "@/lib/sidebar/mongoCollectionMutation";
@@ -532,6 +534,11 @@ export const useConnectionStore = defineStore("connection", () => {
const redisCommandDocsCacheGeneration = new Map<string, number>();
const mongoCompletionCollectionsCache = ref<Record<string, string[]>>({});
const mongoCompletionFieldsCache = ref<Record<string, MongoCompletionField[]>>({});
+ const soqlCompletionObjectsCache = ref<Record<string, SoqlCompletionObject[]>>({});
+ const soqlCompletionFieldsCache = ref<Record<string, SoqlCompletionField[]>>({});
+ // One entry per connection: the authenticated Salesforce user never changes for
+ // the life of a connection (token refreshes reuse the same identity).
+ const salesforceCurrentUserCache = ref<Record<string, SalesforceCurrentUser>>({});
const schemaListCache = ref<Record<string, string[]>>({});
const sidebarSearchQuery = ref("");
const sidebarTableSearchQueries = ref<Record<string, string>>({});
@@ -1666,6 +1673,7 @@ export const useConnectionStore = defineStore("connection", () => {
oscar: "神通 OSCAR",
influxdb: "InfluxDB",
victoriametrics: "VictoriaMetrics",
+ salesforce: "Salesforce",
};
const profile = config.driver_profile || config.db_type;
@@ -3805,6 +3813,12 @@ export const useConnectionStore = defineStore("connection", () => {
for (const key of Object.keys(mongoCompletionFieldsCache.value)) {
if (key === exactCacheKey || key.startsWith(cachePrefix)) delete mongoCompletionFieldsCache.value[key];
}
+ for (const key of Object.keys(soqlCompletionObjectsCache.value)) {
+ if (key === exactCacheKey || key.startsWith(cachePrefix)) delete soqlCompletionObjectsCache.value[key];
+ }
+ for (const key of Object.keys(soqlCompletionFieldsCache.value)) {
+ if (key === exactCacheKey || key.startsWith(cachePrefix)) delete soqlCompletionFieldsCache.value[key];
+ }
for (const key of completionTableIndex.keys()) {
if (key.startsWith(cachePrefix)) completionTableIndex.delete(key);
}
@@ -5182,7 +5196,7 @@ export const useConnectionStore = defineStore("connection", () => {
}
if (!connectedIds.value.has(connectionId)) return;
const config = getConfig(connectionId);
- if (!config || ["redis", "etcd", "zookeeper", "consul", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos"].includes(config.db_type)) return;
+ if (!config || ["redis", "etcd", "zookeeper", "consul", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos", "salesforce"].includes(config.db_type)) return;
const node = findConnectionNode(connectionId);
if (!node || node.type !== "connection" || hasConnectionMetadataChildren(node.children)) return;
const scope = { kind: "connection-databases" as const, connectionId, driverProfile: metadataDriverProfile(config) };
@@ -8511,6 +8525,105 @@ export const useConnectionStore = defineStore("connection", () => {
});
}
+ // Map a Salesforce describe column to a SOQL completion field. The backend packs
+ // relationshipName / referenceTo / label into ColumnInfo.extra (JSON) and active
+ // picklist values into enum_values; parse defensively since extra may be absent.
+ function soqlFieldFromColumnInfo(column: ColumnInfo): SoqlCompletionField {
+ let extra: { relationshipName?: string; referenceTo?: string[]; label?: string } | null = null;
+ if (column.extra) {
+ try {
+ extra = JSON.parse(column.extra);
+ } catch {
+ extra = null;
+ }
+ }
+ return {
+ name: column.name,
+ type: column.data_type || undefined,
+ label: extra?.label ?? column.comment ?? undefined,
+ picklistValues: column.enum_values?.length ? column.enum_values : undefined,
+ relationshipName: extra?.relationshipName ?? undefined,
+ referenceTo: extra?.referenceTo?.length ? extra.referenceTo : undefined,
+ };
+ }
+
+ async function listSoqlCompletionObjects(connectionId: string, database: string): Promise<SoqlCompletionObject[]> {
+ // No `database` guard: the Salesforce backend ignores the database parameter
+ // (the whole org is one synthesized database), and a restored query tab can
+ // legitimately carry an empty database while the connection still works.
+ const cacheKey = `${connectionId}:${database}`;
+ const cached = soqlCompletionObjectsCache.value[cacheKey];
+ if (cached) return cached;
+ return withCompletionInFlight(`${cacheKey}:soql-objects`, async () => {
+ await ensureConnected(connectionId);
+ const tables = await api.listTables(connectionId, database, "");
+ const labelByName = new Map(tables.map((t) => [t.name, t.comment ?? undefined]));
+ const objects = sortSidebarNames(tables.map((t) => t.name)).map((name) => ({ name, label: labelByName.get(name) }));
+ // Never cache an empty list: a transient failure would otherwise stick for the
+ // whole session and silently degrade SOQL completion to keywords-only.
+ if (objects.length > 0) {
+ soqlCompletionObjectsCache.value[cacheKey] = objects;
+ evictOldestCacheEntries(soqlCompletionObjectsCache.value, COMPLETION_CACHE_MAX);
+ }
+ return objects;
+ });
+ }
+
+ async function listSoqlCompletionFields(connectionId: string, database: string, objectName: string): Promise<SoqlCompletionField[]> {
+ if (!objectName) return [];
+ const cacheKey = `${connectionId}:${database}:${objectName}`;
+ const cached = soqlCompletionFieldsCache.value[cacheKey];
+ if (cached) return cached;
+ return withCompletionInFlight(`${cacheKey}:soql-fields`, async () => {
+ await ensureConnected(connectionId);
+ // Backed by the driver's in-memory describe cache, so repeated loads (e.g. one
+ // per keystroke while traversing a relationship) do not re-hit the Salesforce API.
+ const columns = await api.getColumns(connectionId, database, "", objectName);
+ const fields = columns.map(soqlFieldFromColumnInfo);
+ // Never cache an empty list: a transient describe failure would otherwise stick
+ // and make field completion silently vanish for this object all session.
+ if (fields.length > 0) {
+ soqlCompletionFieldsCache.value[cacheKey] = fields;
+ evictOldestCacheEntries(soqlCompletionFieldsCache.value, COMPLETION_CACHE_MAX);
+ }
+ return fields;
+ });
+ }
+
+ /**
+ * Identity behind a Salesforce connection (`GET /services/oauth2/userinfo` plus an
+ * admin probe), resolved at most once per connection and cached for the session.
+ * Deliberately failure-tolerant: the toolbar badge and the non-admin hint on the
+ * DML confirmation are advisory, so a failed lookup returns null instead of
+ * surfacing an error or blocking an edit.
+ */
+ async function loadSalesforceCurrentUser(connectionId: string): Promise<SalesforceCurrentUser | null> {
+ if (!connectionId) return null;
+ const cached = salesforceCurrentUserCache.value[connectionId];
+ if (cached) return cached;
+ try {
+ return await withCompletionInFlight(`${connectionId}:salesforce-current-user`, async () => {
+ await ensureConnected(connectionId);
+ const user = await api.salesforceCurrentUser(connectionId);
+ // Never cache an identity-less result: a partial failure would otherwise
+ // stick for the session and keep the badge blank.
+ if (user && (user.userId || user.username)) {
+ salesforceCurrentUserCache.value[connectionId] = user;
+ evictOldestCacheEntries(salesforceCurrentUserCache.value, COMPLETION_CACHE_MAX);
+ }
+ return user ?? null;
+ });
+ } catch (error) {
+ console.debug("[salesforce] current user lookup failed", error);
+ return null;
+ }
+ }
+
+ /** Last known Salesforce identity for a connection, or null before it resolves. */
+ function salesforceCurrentUser(connectionId: string): SalesforceCurrentUser | null {
+ return salesforceCurrentUserCache.value[connectionId] ?? null;
+ }
+
function listCompletionTableMetadata(connectionId: string, database: string, schema: string, filter?: string, limit?: number, catalog?: string): Promise<TableInfo[]> {
if (catalog) return api.listTables(connectionId, database, schema, filter, limit, undefined, undefined, catalog);
return api.listTables(connectionId, database, schema, filter, limit);
@@ -9946,6 +10059,10 @@ export const useConnectionStore = defineStore("connection", () => {
listRedisCompletionCommandDocs,
listMongoCompletionCollections,
listMongoCompletionFields,
+ listSoqlCompletionObjects,
+ listSoqlCompletionFields,
+ loadSalesforceCurrentUser,
+ salesforceCurrentUser,
invalidateCompletionCache,
invalidateCompletionTableCache,
completionCacheRevision,
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index 9aed9e0659..ac8d727c55 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -86,6 +86,13 @@ export interface McpConnectionPolicy {
databaseScope: "all" | "selected" | "none";
allowedDatabases: string[];
databasePolicies: McpDatabasePolicy[];
+ /**
+ * Per-connection opt-in for AI-agent writes to a Salesforce org. Off by default and
+ * forced off by `readOnly`: SOQL reads need nothing beyond the execution mode, but
+ * Salesforce DML has no transaction and no rollback, so it also requires the
+ * two-step prepare/apply confirmation on every single write.
+ */
+ allowSalesforceDml: boolean;
}
export interface McpDatabasePolicy {
@@ -174,6 +181,9 @@ export function normalizeMcpGlobalPolicy(policy: Partial<McpGlobalPolicy> | null
databaseScope,
allowedDatabases,
databasePolicies,
+ // Same fail-closed shape as allowDangerousSql: read-only wins, and a policy
+ // saved before the switch existed (field absent) normalizes to off.
+ allowSalesforceDml: rule.readOnly !== true && rule.allowSalesforceDml === true,
};
return rules;
}, {}),
diff --git a/apps/desktop/src/types/generated/connectionProfiles.ts b/apps/desktop/src/types/generated/connectionProfiles.ts
index 2c73d1ca17..77b6b6461b 100644
--- a/apps/desktop/src/types/generated/connectionProfiles.ts
+++ b/apps/desktop/src/types/generated/connectionProfiles.ts
@@ -122,6 +122,7 @@ export const CONNECTION_PROFILES = {
influxdb: { type: "influxdb", port: 8086, user: "", label: "InfluxDB", icon: "InfluxDB" },
influxdb3: { type: "influxdb3", port: 8181, user: "", label: "InfluxDB 3.x", icon: "InfluxDB" },
victoriametrics: { type: "victoriametrics", port: 8428, user: "", label: "VictoriaMetrics", icon: "victoriametrics" },
+ salesforce: { type: "salesforce", port: 443, user: "", label: "Salesforce", icon: "salesforce" },
custom_mysql: { type: "mysql", port: 3306, user: "root", label: "Custom", icon: "mysql", urlParams: "" },
dolt: { type: "mysql", port: 3306, user: "root", label: "Dolt", icon: "dolt", urlParams: "" },
custom_postgres: { type: "postgres", port: 5432, user: "postgres", label: "Custom", icon: "postgres", urlParams: "" },
@@ -230,6 +231,7 @@ export const CONNECTION_PROFILE_ICONS = {
influxdb: "influxdb",
influxdb3: "influxdb",
victoriametrics: "victoriametrics",
+ salesforce: "salesforce",
custom_mysql: "mysql",
dolt: "dolt",
custom_postgres: "postgres",
@@ -331,6 +333,7 @@ export const CONNECTION_PICKER_OPTIONS = [
{ value: "influxdb", label: "InfluxDB", category: "timeseries" },
{ value: "influxdb3", label: "InfluxDB 3.x", category: "timeseries" },
{ value: "victoriametrics", label: "VictoriaMetrics", category: "timeseries" },
+ { value: "salesforce", label: "Salesforce", category: "analytics" },
{ value: "custom_mysql", label: "Custom (MySQL)", category: "sql" },
{ value: "dolt", label: "Dolt", category: "sql" },
{ value: "custom_postgres", label: "Custom (PostgreSQL)", category: "sql" },
diff --git a/apps/desktop/src/types/generated/databaseTypes.ts b/apps/desktop/src/types/generated/databaseTypes.ts
index 170e1839f7..711fd02fad 100644
--- a/apps/desktop/src/types/generated/databaseTypes.ts
+++ b/apps/desktop/src/types/generated/databaseTypes.ts
@@ -82,6 +82,7 @@ export const DATABASE_TYPES = [
"jdbc",
"spark",
"plugin",
+ "salesforce",
] as const;
export type DatabaseType = (typeof DATABASE_TYPES)[number] | "plugin";
diff --git a/apps/desktop/src/types/salesforce.ts b/apps/desktop/src/types/salesforce.ts
new file mode 100644
index 0000000000..1bfdf53938
--- /dev/null
+++ b/apps/desktop/src/types/salesforce.ts
@@ -0,0 +1,80 @@
+// Salesforce OAuth metadata persisted on `ConnectionConfig.external_config.auth`.
+// The backend owns encryption/storage of refreshToken; the frontend only keeps
+// enough state to re-render the connection card and re-authorize when needed.
+
+export type SalesforceAuthMode = "token" | "oauth" | "device" | "password";
+
+export type SalesforceEnvironment = "production" | "sandbox" | "custom";
+
+export interface SalesforceOAuthToken {
+ accessToken: string;
+ refreshToken?: string;
+ instanceUrl: string;
+}
+
+// Backend `SfRefreshedToken`: instanceUrl is absent when Salesforce did not
+// echo it on the refresh grant (callers keep their known instance URL).
+export interface SalesforceOAuthRefreshResult {
+ accessToken: string;
+ refreshToken?: string;
+ instanceUrl?: string;
+}
+
+export interface SalesforceOAuthAuthorizeParams {
+ environment: SalesforceEnvironment;
+ loginUrl?: string;
+ clientId: string;
+ clientSecret?: string;
+}
+
+export interface SalesforceOAuthDeviceStartResult {
+ deviceCode: string;
+ userCode: string;
+ verificationUri: string;
+ intervalSecs: number;
+ expiresInSecs: number;
+}
+
+export type SalesforceOAuthDevicePollResult = { status: "pending"; intervalSecs: number } | { status: "success"; token: SalesforceOAuthToken } | { status: "expired" } | { status: "denied"; reason?: string };
+
+export interface SalesforceAuthContext {
+ mode: SalesforceAuthMode;
+ environment?: SalesforceEnvironment;
+ loginUrl?: string;
+ clientId?: string;
+ clientSecret?: string;
+ refreshToken?: string;
+ // Username-password (ROPC) mode. The password is scrubbed into the backend
+ // secret store (key salesforce.auth.password) and never rendered back.
+ username?: string;
+ password?: string;
+ authorizedAt?: string;
+}
+
+export interface SalesforceExternalConfig {
+ auth?: SalesforceAuthContext;
+}
+
+/**
+ * Identity of the user a Salesforce connection is authenticated as, resolved from
+ * `GET /services/oauth2/userinfo` plus a `Profile.PermissionsModifyAllData` probe.
+ * Returned by the `salesforce_current_user` command / `GET /api/salesforce/current-user`.
+ *
+ * `isAdmin` is advisory only (a permission set can grant fine-grained rights), so it
+ * drives a UI hint and never a security decision — Salesforce enforces the real rules.
+ * The backend omits `isAdmin` / `profileName` when the probe did not resolve, so both
+ * are optional; fields Salesforce did not return come back as empty strings.
+ */
+export interface SalesforceCurrentUser {
+ userId: string;
+ name: string;
+ email: string;
+ organizationId: string;
+ username: string;
+ profileName?: string;
+ isAdmin?: boolean | null;
+ /** Org display name (`SELECT Name FROM Organization`), falling back to the instance host. */
+ orgName: string;
+}
+
+export const SALESFORCE_OAUTH_CALLBACK_URL = "http://localhost:27098/callback";
diff --git a/crates/dbx-ai-provider/src/ai_cli_agent.rs b/crates/dbx-ai-provider/src/ai_cli_agent.rs
index f4c762cfb9..efa9242774 100644
--- a/crates/dbx-ai-provider/src/ai_cli_agent.rs
+++ b/crates/dbx-ai-provider/src/ai_cli_agent.rs
@@ -68,6 +68,14 @@ pub fn dbx_mcp_enabled_tools(agent_mode: bool) -> Vec<&'static str> {
if agent_mode {
tools.push("dbx_execute_query");
tools.push("dbx_execute_redis_command");
+ // Read-only Salesforce identity, so an agent working against an org can tell the
+ // user who a change would be attributed to. The `dbx_salesforce_prepare_write` /
+ // `dbx_salesforce_apply_write` pair is deliberately absent: DBX spawns these CLI
+ // agents with `--permission-mode dontAsk`, so a tool listed here runs with no
+ // interactive gate, and a Salesforce write cannot be rolled back. The two-step
+ // confirmation belongs to MCP clients that do put the summary in front of a
+ // person; the connection-level DML switch alone is not a substitute.
+ tools.push("dbx_salesforce_current_user");
}
tools
}
diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.json
index f25462b452..3050684650 100644
--- a/crates/dbx-core/assets/database-drivers.manifest.json
+++ b/crates/dbx-core/assets/database-drivers.manifest.json
@@ -2908,6 +2908,39 @@
"userAdmin": false,
"driverManagement": false
}
+ },
+ {
+ "dbType": "salesforce",
+ "label": "Salesforce",
+ "dialect": "SOQL",
+ "runtimeMode": "native",
+ "mcpMode": "bridge",
+ "singleConnectionPool": true,
+ "metadataConnectionScoped": false,
+ "skipTcpProbe": true,
+ "defaultPort": 443,
+ "traits": {
+ "singleDatabase": true
+ },
+ "supportLevel": "operate",
+ "capabilities": {
+ "queryExecution": true,
+ "metadataBrowse": true,
+ "objectBrowser": true,
+ "objectSource": false,
+ "schemaSearch": true,
+ "diagram": false,
+ "tableDataEdit": true,
+ "tableStructureEdit": false,
+ "tableImport": false,
+ "dataTransfer": false,
+ "sqlFileExecution": false,
+ "databaseCreate": false,
+ "fieldLineage": false,
+ "sqlExplain": false,
+ "userAdmin": false,
+ "driverManagement": false
+ }
}
]
}
diff --git a/crates/dbx-core/src/ai/mcp_policy.rs b/crates/dbx-core/src/ai/mcp_policy.rs
index 32a0d495c8..24286b9ac5 100644
--- a/crates/dbx-core/src/ai/mcp_policy.rs
+++ b/crates/dbx-core/src/ai/mcp_policy.rs
@@ -166,6 +166,21 @@ fn apply_ceiling(current: (bool, bool), ceiling: (bool, bool)) -> (bool, bool) {
(read_only, !read_only && current.1 && ceiling.1)
}
+/// Whether an AI agent may write to this Salesforce connection through MCP.
+///
+/// A pure per-connection opt-in: no global or group setting can turn it on, and
+/// a connection without a saved rule stays off. Callers still run every write
+/// through the ordinary execution policy, so the global/connection read-only
+/// modes, connection read-only protection and production protection all remain
+/// upper bounds on top of this switch.
+pub fn connection_allows_salesforce_dml(policy: &McpGlobalPolicy, connection_id: &str) -> bool {
+ policy
+ .connection_policies
+ .iter()
+ .find(|rule| rule.connection_id == connection_id)
+ .is_some_and(|rule| rule.allow_salesforce_dml && !rule.read_only)
+}
+
/// Reject qualified SQL references when database-specific execution rules are
/// present and individual referenced databases have not been evaluated.
pub fn ensure_sql_database_execution_scope(
@@ -251,7 +266,10 @@ pub fn ensure_mongo_database_execution_scope(
#[cfg(test)]
mod tests {
- use super::{effective_database_execution_policy, resolve_database, MCP_EXECUTION_POLICY_VERSION};
+ use super::{
+ connection_allows_salesforce_dml, effective_database_execution_policy, resolve_database,
+ MCP_EXECUTION_POLICY_VERSION,
+ };
use crate::storage::{McpConnectionPolicy, McpDatabasePolicy, McpGlobalPolicy};
fn policy(version: Option<u8>) -> McpGlobalPolicy {
@@ -270,6 +288,7 @@ mod tests {
read_only: false,
allow_dangerous_sql: true,
}],
+ allow_salesforce_dml: false,
}],
..Default::default()
}
@@ -316,4 +335,26 @@ mod tests {
assert_eq!(resolve_database(" ", Some("sample")), "sample");
assert_eq!(resolve_database("analytics", Some("sample")), "analytics");
}
+
+ #[test]
+ fn salesforce_dml_needs_an_explicit_connection_opt_in() {
+ // No rule for the connection at all → off, whatever the global mode says.
+ let mut open = policy(Some(MCP_EXECUTION_POLICY_VERSION));
+ open.read_only = false;
+ assert!(!connection_allows_salesforce_dml(&open, "other"));
+ assert!(!connection_allows_salesforce_dml(&open, "conn"));
+
+ open.connection_policies[0].allow_salesforce_dml = true;
+ assert!(connection_allows_salesforce_dml(&open, "conn"));
+ }
+
+ #[test]
+ fn salesforce_dml_opt_in_is_void_on_a_read_only_connection_rule() {
+ let mut policy = policy(Some(MCP_EXECUTION_POLICY_VERSION));
+ policy.connection_policies[0].allow_salesforce_dml = true;
+ policy.connection_policies[0].read_only = true;
+ // `normalized()` already clears the flag for read-only rules; this keeps a
+ // hand-built or legacy policy from sneaking a write through.
+ assert!(!connection_allows_salesforce_dml(&policy, "conn"));
+ }
}
diff --git a/crates/dbx-core/src/connection/connection_secrets.rs b/crates/dbx-core/src/connection/connection_secrets.rs
index 26de9af744..3b5c1af87b 100644
--- a/crates/dbx-core/src/connection/connection_secrets.rs
+++ b/crates/dbx-core/src/connection/connection_secrets.rs
@@ -27,6 +27,10 @@ pub const MQTT_AUTH_PASSWORD_KEY: &str = "mqtt.auth.password";
pub const CASSANDRA_TLS_SECRET_PREFIX: &str = "cassandra.tls.";
pub const CASSANDRA_TRUSTSTORE_PASSWORD_KEY: &str = "cassandra.tls.truststore_password";
pub const CASSANDRA_KEYSTORE_PASSWORD_KEY: &str = "cassandra.tls.keystore_password";
+pub const SALESFORCE_AUTH_SECRET_PREFIX: &str = "salesforce.auth.";
+pub const SALESFORCE_AUTH_CLIENT_SECRET_KEY: &str = "salesforce.auth.client_secret";
+pub const SALESFORCE_AUTH_REFRESH_TOKEN_KEY: &str = "salesforce.auth.refresh_token";
+pub const SALESFORCE_AUTH_PASSWORD_KEY: &str = "salesforce.auth.password";
pub const PLUGIN_CONNECTION_SECRET_PREFIX: &str = "plugin_connection.";
/// Storage-level secret key for one plugin connection field: namespaced under
@@ -127,6 +131,7 @@ pub fn save_connections_to_file(
persist_mq_token_signing_secret(store, config)?;
persist_mqtt_auth_secrets(store, config)?;
persist_cassandra_tls_secrets(store, config)?;
+ persist_salesforce_auth_secrets(store, config)?;
delete_secret_prefix(store, &config.id, PLUGIN_CONNECTION_SECRET_PREFIX)?;
for (key, secret) in &config.connection_secrets {
persist_secret(store, &config.id, &plugin_connection_secret_key(key)?, secret)?;
@@ -201,6 +206,7 @@ pub fn load_connections_from_file(
hydrate_mq_token_signing_secret(store, config, &mut needs_rewrite)?;
hydrate_mqtt_auth_secrets(store, config, &mut needs_rewrite)?;
hydrate_cassandra_tls_secrets(store, config, &mut needs_rewrite)?;
+ hydrate_salesforce_auth_secrets(store, config, &mut needs_rewrite)?;
let plugin_secret_keys = config.connection_secrets.keys().cloned().collect::<Vec<_>>();
for key in plugin_secret_keys {
let storage_key = plugin_connection_secret_key(&key)?;
@@ -394,6 +400,7 @@ fn delete_removed_connection_secrets(
delete_secret_prefix(store, &config.id, MQ_TOKEN_SIGNING_SECRET_PREFIX)?;
delete_secret_prefix(store, &config.id, MQTT_AUTH_SECRET_PREFIX)?;
delete_secret_prefix(store, &config.id, CASSANDRA_TLS_SECRET_PREFIX)?;
+ delete_secret_prefix(store, &config.id, SALESFORCE_AUTH_SECRET_PREFIX)?;
}
Ok(())
}
@@ -653,6 +660,96 @@ fn cassandra_tls_object_mut(
value?.get_mut("tls")?.as_object_mut()
}
+// ── Salesforce OAuth 密钥持久化 ─────────────────────────────────
+//
+// Persist semantics (mirrors MQ's replace_mq_auth_secret):
+// 1. Incoming empty/missing + secret already stored → preserve existing secret.
+// 2. Incoming non-empty → overwrite.
+// 3. external_config.auth block absent (user switched off OAuth) → delete both secrets.
+// This is required because the frontend edits an existing connection with the
+// sensitive fields blanked out — an empty value must not clobber the stored secret.
+
+fn persist_salesforce_auth_secrets(store: &dyn ConnectionSecretStore, config: &ConnectionConfig) -> Result<(), String> {
+ if config.db_type != DatabaseType::Salesforce {
+ delete_secret_prefix(store, &config.id, SALESFORCE_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ }
+
+ let Some(auth) = salesforce_auth_object(config.external_config.as_ref()) else {
+ delete_secret_prefix(store, &config.id, SALESFORCE_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ };
+
+ replace_salesforce_auth_secret(store, &config.id, SALESFORCE_AUTH_CLIENT_SECRET_KEY, auth, "clientSecret")?;
+ replace_salesforce_auth_secret(store, &config.id, SALESFORCE_AUTH_REFRESH_TOKEN_KEY, auth, "refreshToken")?;
+ replace_salesforce_auth_secret(store, &config.id, SALESFORCE_AUTH_PASSWORD_KEY, auth, "password")?;
+
+ Ok(())
+}
+
+fn replace_salesforce_auth_secret(
+ store: &dyn ConnectionSecretStore,
+ connection_id: &str,
+ key: &str,
+ auth: &serde_json::Map<String, serde_json::Value>,
+ field: &str,
+) -> Result<(), String> {
+ let current = auth.get(field).and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty());
+ let existing = if current.is_none() { store.get_secret(connection_id, key)? } else { None };
+ // Per-key delete: we only manage the exact key we own, so two parallel
+ // replace calls don't wipe each other out.
+ store.delete_secret(connection_id, key)?;
+ match current {
+ Some(secret) => store.set_secret(connection_id, key, secret),
+ None => match existing {
+ Some(secret) => store.set_secret(connection_id, key, &secret),
+ None => Ok(()),
+ },
+ }
+}
+
+fn hydrate_salesforce_auth_secrets(
+ store: &dyn ConnectionSecretStore,
+ config: &mut ConnectionConfig,
+ needs_rewrite: &mut bool,
+) -> Result<(), String> {
+ if config.db_type != DatabaseType::Salesforce {
+ return Ok(());
+ }
+
+ let Some(auth) = salesforce_auth_object_mut(config.external_config.as_mut()) else {
+ return Ok(());
+ };
+
+ hydrate_json_secret(store, &config.id, SALESFORCE_AUTH_CLIENT_SECRET_KEY, auth, "clientSecret", needs_rewrite)?;
+ hydrate_json_secret(store, &config.id, SALESFORCE_AUTH_REFRESH_TOKEN_KEY, auth, "refreshToken", needs_rewrite)?;
+ hydrate_json_secret(store, &config.id, SALESFORCE_AUTH_PASSWORD_KEY, auth, "password", needs_rewrite)?;
+
+ Ok(())
+}
+
+fn scrub_salesforce_auth_secrets(config: &mut ConnectionConfig) {
+ if config.db_type != DatabaseType::Salesforce {
+ return;
+ }
+ let Some(auth) = salesforce_auth_object_mut(config.external_config.as_mut()) else {
+ return;
+ };
+ scrub_json_secret(auth, "clientSecret");
+ scrub_json_secret(auth, "refreshToken");
+ scrub_json_secret(auth, "password");
+}
+
+fn salesforce_auth_object(value: Option<&serde_json::Value>) -> Option<&serde_json::Map<String, serde_json::Value>> {
+ value?.get("auth")?.as_object()
+}
+
+fn salesforce_auth_object_mut(
+ value: Option<&mut serde_json::Value>,
+) -> Option<&mut serde_json::Map<String, serde_json::Value>> {
+ value?.get_mut("auth")?.as_object_mut()
+}
+
// ── MQTT 密钥持久化 ──────────────────────────────────────────────
fn persist_mqtt_auth_secrets(store: &dyn ConnectionSecretStore, config: &ConnectionConfig) -> Result<(), String> {
@@ -845,6 +942,7 @@ fn sanitize_connections(configs: &[ConnectionConfig]) -> Vec<ConnectionConfig> {
scrub_mq_token_signing_secret(&mut config);
scrub_mqtt_auth_secrets(&mut config);
scrub_cassandra_tls_secrets(&mut config);
+ scrub_salesforce_auth_secrets(&mut config);
scrub_plugin_connection_secrets(&mut config);
config
})
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index fdf5d1a9ef..150279ace1 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -43,6 +43,7 @@ use crate::plugins::{
PluginRuntimeEnv, PluginRuntimeProxy,
};
use crate::query_cancel::RunningQueries;
+use crate::salesforce_oauth::SfBrowserOpener;
use crate::session_credentials::SessionCredentialStore;
use crate::storage::{normalize_duckdb_worker_max_processes, Storage, DUCKDB_WORKER_MAX_PROCESSES_DEFAULT};
use crate::task_supervisor::TaskSupervisor;
@@ -118,6 +119,7 @@ pub enum PoolKind {
Easysearch(db::easysearch_driver::EasysearchClient),
Solr(db::solr_driver::SolrClient),
Meilisearch(db::meilisearch_driver::MeilisearchClient),
+ Salesforce(db::salesforce_driver::SfClient),
HBase(db::hbase_driver::HBaseClient),
VectorDb(db::vector_driver::VectorClient),
InfluxDb(db::influxdb_driver::InfluxdbClient),
@@ -367,6 +369,24 @@ struct SharedResourceBudget {
semaphore: Arc<Semaphore>,
}
+/// Cached Salesforce connected-user identity + org display name, serialized
+/// with camelCase field names for the frontend. `Deserialize` is derived too so
+/// the Web-mode MCP backend can decode the same JSON the desktop route emits.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SalesforceCurrentUser {
+ pub user_id: String,
+ pub name: String,
+ pub email: String,
+ pub organization_id: String,
+ pub username: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub profile_name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub is_admin: Option<bool>,
+ pub org_name: String,
+}
+
pub struct AppState {
connections: Arc<RwLock<ConnectionPoolRegistry>>,
task_supervisor: TaskSupervisor,
@@ -407,6 +427,7 @@ pub struct AppState {
pub write_unlock_windows: crate::write_unlock::WriteUnlockWindows,
metadata_gates: Arc<Mutex<HashMap<String, Arc<Semaphore>>>>,
mongo_oidc_browser_opener: std::sync::RwLock<Option<MongoOidcBrowserOpener>>,
+ salesforce_browser_opener: std::sync::RwLock<Option<SfBrowserOpener>>,
#[cfg(feature = "mq-admin")]
pub mq_registry: crate::mq::MqAdminRegistry,
}
@@ -1601,6 +1622,7 @@ impl AppState {
write_unlock_windows: crate::write_unlock::WriteUnlockWindows::default(),
metadata_gates: Arc::new(Mutex::new(HashMap::new())),
mongo_oidc_browser_opener: std::sync::RwLock::new(None),
+ salesforce_browser_opener: std::sync::RwLock::new(None),
#[cfg(feature = "mq-admin")]
mq_registry: crate::mq::MqAdminRegistry::new(),
}
@@ -1614,6 +1636,14 @@ impl AppState {
self.mongo_oidc_browser_opener.read().expect("MongoDB OIDC browser opener lock poisoned").clone()
}
+ pub fn set_salesforce_browser_opener(&self, opener: SfBrowserOpener) {
+ *self.salesforce_browser_opener.write().expect("Salesforce browser opener lock poisoned") = Some(opener);
+ }
+
+ pub fn salesforce_browser_opener(&self) -> Option<SfBrowserOpener> {
+ self.salesforce_browser_opener.read().expect("Salesforce browser opener lock poisoned").clone()
+ }
+
pub(crate) async fn acquire_metadata_permit(
&self,
connection_id: &str,
@@ -2844,6 +2874,16 @@ impl AppState {
db::meilisearch_driver::test_connection(&client, connect_timeout).await?;
PoolKind::Meilisearch(client)
}
+ DatabaseType::Salesforce => {
+ let client = db::salesforce_driver::SfClient::from_config(
+ &url,
+ Some(&db_config.password),
+ db_config.external_config.as_ref(),
+ connect_timeout,
+ )?;
+ db::salesforce_driver::SfClient::test_connection(&client, connect_timeout).await?;
+ PoolKind::Salesforce(client)
+ }
DatabaseType::Hbase => {
let client = db::hbase_driver::HBaseClient::new(
&url,
@@ -4214,6 +4254,17 @@ impl AppState {
}
}
}
+ PoolKind::Salesforce(client) => {
+ let client = client.clone();
+ let timeout = crate::db::connection_timeout();
+ match db::salesforce_driver::SfClient::test_connection(&client, timeout).await {
+ Ok(()) => false,
+ Err(err) => {
+ log::warn!("Salesforce connection pool '{pool_key}' is stale: {err}");
+ true
+ }
+ }
+ }
PoolKind::HBase(client) => {
let client = client.clone();
let timeout = crate::db::connection_timeout();
@@ -5249,6 +5300,38 @@ impl AppState {
Ok(())
}
+ /// Cached connected-user identity for a Salesforce connection. Returns a
+ /// camelCase-serializable struct for the frontend (identity badge, admin
+ /// warning). Errors when the connection is not Salesforce or has no pool.
+ pub async fn salesforce_current_user(&self, connection_id: &str) -> Result<SalesforceCurrentUser, String> {
+ let db_type = {
+ let configs = self.configs.read().await;
+ configs.get(connection_id).map(|c| c.db_type)
+ };
+ if db_type != Some(DatabaseType::Salesforce) {
+ return Err("Not a Salesforce connection".to_string());
+ }
+ let pool_key = base_pool_key_for(db_type, connection_id, None, false);
+ let pool = self.pool_handle(&pool_key).await.ok_or_else(|| "Connection not found".to_string())?;
+ match pool {
+ PoolKind::Salesforce(client) => {
+ let user = client.cached_current_user().await?;
+ let org_name = client.org_display_name().await;
+ Ok(SalesforceCurrentUser {
+ user_id: user.user_id,
+ name: user.name,
+ email: user.email,
+ organization_id: user.organization_id,
+ username: user.username,
+ profile_name: user.profile_name,
+ is_admin: user.is_admin,
+ org_name,
+ })
+ }
+ _ => Err("Not a Salesforce connection".to_string()),
+ }
+ }
+
/// Warm the driver/pool a tab is about to use, off the user's critical path.
///
/// The first statement of a session pays costs that the user perceives as
@@ -5405,6 +5488,16 @@ impl AppState {
}
}
}
+ PoolKind::Salesforce(client) => {
+ let client = client.clone();
+ match db::salesforce_driver::SfClient::test_connection(&client, timeout).await {
+ Ok(()) => true,
+ Err(e) => {
+ log::warn!("Salesforce connection pool '{key}' is unhealthy: {e}");
+ false
+ }
+ }
+ }
PoolKind::HBase(client) => match db::hbase_driver::test_connection(client, timeout).await {
Ok(_) => true,
Err(e) => {
@@ -5796,6 +5889,7 @@ enum KeepaliveTarget {
SqlServer(Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
Elasticsearch(db::elasticsearch_driver::EsClient),
Easysearch(db::easysearch_driver::EasysearchClient),
+ Salesforce(db::salesforce_driver::SfClient),
Solr(db::solr_driver::SolrClient),
HBase(db::hbase_driver::HBaseClient),
VectorDb(db::vector_driver::VectorClient),
@@ -5898,6 +5992,7 @@ fn keepalive_target_from_pool(pool: &PoolKind, config: &ConnectionConfig) -> Opt
PoolKind::SqlServer(client) => Some(KeepaliveTarget::SqlServer(client.clone())),
PoolKind::Elasticsearch(client) => Some(KeepaliveTarget::Elasticsearch(client.clone())),
PoolKind::Easysearch(client) => Some(KeepaliveTarget::Easysearch(client.clone())),
+ PoolKind::Salesforce(client) => Some(KeepaliveTarget::Salesforce(client.clone())),
PoolKind::Solr(client) => Some(KeepaliveTarget::Solr(client.clone())),
PoolKind::HBase(client) => Some(KeepaliveTarget::HBase(client.clone())),
PoolKind::VectorDb(client) => Some(KeepaliveTarget::VectorDb(client.clone())),
@@ -5947,6 +6042,9 @@ async fn ping_keepalive_target(target: &mut KeepaliveTarget, timeout: Duration)
KeepaliveTarget::Easysearch(client) => {
db::easysearch_driver::test_connection(client, timeout).await.map_err(Into::into)
}
+ KeepaliveTarget::Salesforce(client) => {
+ db::salesforce_driver::SfClient::test_connection(client, timeout).await.map_err(Into::into)
+ }
KeepaliveTarget::Solr(client) => db::solr_driver::test_connection(client, timeout).await.map_err(Into::into),
KeepaliveTarget::HBase(client) => {
db::hbase_driver::test_connection(client, timeout).await.map(|_| ()).map_err(Into::into)
@@ -6370,6 +6468,7 @@ fn clone_pool_kind(pool: &PoolKind) -> PoolKind {
PoolKind::Easysearch(client) => PoolKind::Easysearch(client.clone()),
PoolKind::Solr(client) => PoolKind::Solr(client.clone()),
PoolKind::Meilisearch(client) => PoolKind::Meilisearch(client.clone()),
+ PoolKind::Salesforce(client) => PoolKind::Salesforce(client.clone()),
PoolKind::HBase(client) => PoolKind::HBase(client.clone()),
PoolKind::VectorDb(client) => PoolKind::VectorDb(client.clone()),
PoolKind::InfluxDb(client) => PoolKind::InfluxDb(client.clone()),
@@ -6434,6 +6533,9 @@ async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
PoolKind::Meilisearch(client) => {
drop(client);
}
+ PoolKind::Salesforce(client) => {
+ drop(client);
+ }
PoolKind::HBase(client) => {
drop(client);
}
@@ -6534,6 +6636,7 @@ fn base_pool_key_for_with_catalog(
| DatabaseType::Milvus
| DatabaseType::Weaviate
| DatabaseType::ChromaDb
+ | DatabaseType::Salesforce
));
is_single && (!database_capabilities::is_agent_type(db_type) || shares_database_pool_with_connection(db_type))
});
@@ -8997,6 +9100,20 @@ mod tests {
}
}
+ #[test]
+ fn salesforce_connections_never_use_a_tcp_probe() {
+ // Salesforce reaches a cloud HTTPS endpoint through one pooled client, so the
+ // manifest sets skipTcpProbe: a raw TCP pre-flight is meaningless even for a
+ // forwarded local endpoint.
+ let mut config = mysql_config(Some("app"));
+ config.db_type = DatabaseType::Salesforce;
+ config.host = "acme.my.salesforce.com".to_string();
+ config.port = 443;
+
+ assert!(!uses_tcp_probe(&config, "acme.my.salesforce.com", 443), "instance url");
+ assert!(!uses_tcp_probe(&config, "127.0.0.1", 54000), "forwarded");
+ }
+
#[test]
fn h2_agent_connections_skip_tcp_probe_for_file_and_tcp_modes() {
let mut file_config = mysql_config(None);
diff --git a/crates/dbx-core/src/data/csv_export.rs b/crates/dbx-core/src/data/csv_export.rs
index cdb79bd3b4..4c623b770a 100644
--- a/crates/dbx-core/src/data/csv_export.rs
+++ b/crates/dbx-core/src/data/csv_export.rs
@@ -42,6 +42,16 @@ async fn connection_database_type(state: &AppState, connection_id: &str) -> Resu
pub async fn export_table_data_csv_core(state: &AppState, options: TableCsvExportOptions) -> Result<u64, String> {
let database_type = connection_database_type(state, &options.connection_id).await?;
+ // This loop pages with `LIMIT <page_size> OFFSET <n>` and stops at the first
+ // short page. Neither half holds for SOQL: a `/query` response carries at most
+ // 2000 rows and hands the rest back as a QueryLocator (`has_more` +
+ // `session_id`), and OFFSET is capped at 2000, so the first page always looks
+ // short and the export would stop there — a CSV silently missing the rest of
+ // the object. Refuse instead of truncating; a Salesforce export has to follow
+ // the QueryLocator (`fetch_more`) the way the grid's "load more" does.
+ if database_type == DatabaseType::Salesforce {
+ return Err("Exporting a Salesforce object to CSV is not supported yet: SOQL pages through a QueryLocator, not LIMIT/OFFSET. Run a SOQL query and export its result instead.".to_string());
+ }
let page_size = options.page_size.unwrap_or(TABLE_DATA_EXPORT_PAGE_SIZE).max(1);
let mut writer =
BufWriter::new(File::create(&options.file_path).map_err(|err| format!("Failed to write CSV file: {err}"))?);
@@ -109,3 +119,59 @@ pub async fn export_table_data_csv_core(state: &AppState, options: TableCsvExpor
writer.flush().map_err(|err| err.to_string())?;
Ok(rows_exported)
}
+
+#[cfg(test)]
+mod tests {
+ use super::{export_table_data_csv_core, CsvQuoteMode, TableCsvExportOptions};
+ use crate::connection::AppState;
+ use crate::models::connection::{ConnectionConfig, DatabaseType};
+ use crate::storage::Storage;
+
+ fn salesforce_config(id: &str) -> ConnectionConfig {
+ let mut config = serde_json::from_value::<ConnectionConfig>(serde_json::json!({
+ "id": id,
+ "name": "SFDC QA",
+ "db_type": "postgres",
+ "host": "example.my.salesforce.com",
+ "port": 443,
+ "username": "[email protected]",
+ "password": "",
+ "database": ""
+ }))
+ .unwrap();
+ config.db_type = DatabaseType::Salesforce;
+ config
+ }
+
+ /// The refusal has to land before `File::create`, otherwise the user is left
+ /// holding a header-only CSV that looks like an object with no records.
+ #[tokio::test]
+ async fn salesforce_table_csv_export_is_refused_before_a_file_is_created() {
+ let directory = tempfile::tempdir().unwrap();
+ let storage = Storage::open(&directory.path().join("storage.db")).await.unwrap();
+ let state = AppState::new(storage);
+ let config = salesforce_config("sfdc-csv");
+ state.configs.write().await.insert(config.id.clone(), config);
+
+ let csv_path = directory.path().join("Account.csv");
+ let error = export_table_data_csv_core(
+ &state,
+ TableCsvExportOptions {
+ file_path: csv_path.to_string_lossy().into_owned(),
+ connection_id: "sfdc-csv".to_string(),
+ database: String::new(),
+ schema: None,
+ table_name: "Account".to_string(),
+ columns: vec!["Id".to_string(), "Name".to_string()],
+ page_size: None,
+ timeout_secs: None,
+ csv_quote_mode: CsvQuoteMode::default(),
+ },
+ )
+ .await
+ .expect_err("SOQL cannot page an export with LIMIT/OFFSET");
+
+ assert!(error.contains("QueryLocator"), "unexpected error: {error}");
+ assert!(!csv_path.exists(), "a refused export must not leave a truncated CSV behind");
+ }
+}
diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rs
index 4337f46350..59076fbbea 100644
--- a/crates/dbx-core/src/lib.rs
+++ b/crates/dbx-core/src/lib.rs
@@ -56,6 +56,7 @@ pub use data::mongodb_dump;
pub use data::mongodb_import_export;
pub use dbx_drivers::mongo_oidc;
pub use dbx_drivers::mongo_shell;
+pub use dbx_drivers::salesforce_oauth;
pub use dbx_formats::export_split_zip;
pub use dbx_plugin_runtime::plugins;
pub use dbx_sql::db_admin_sql;
diff --git a/crates/dbx-core/src/persistence/secret_codec.rs b/crates/dbx-core/src/persistence/secret_codec.rs
index ac9283dd1d..c0cc85d038 100644
--- a/crates/dbx-core/src/persistence/secret_codec.rs
+++ b/crates/dbx-core/src/persistence/secret_codec.rs
@@ -93,12 +93,30 @@ impl SecretCodec {
data_dir: &std::path::Path,
allow_create: bool,
) -> Result<SecretKeyResolution, String> {
- if let Some(path) = std::env::var_os("DBX_SECRET_KEY_FILE") {
+ Self::resolve_with_env(policy, data_dir, allow_create, |name| std::env::var_os(name))
+ }
+
+ /// [`Self::resolve`] with the environment lookup injected. `DBX_SECRET_KEY`
+ /// and `DBX_SECRET_KEY_FILE` are process global, so tests drive the explicit
+ /// key branches through here instead of mutating the environment: a mutation
+ /// in flight would silently change the key every other test in the same
+ /// binary resolves, and the tests that encrypt with one key would fail to
+ /// decrypt once it is restored.
+ fn resolve_with_env<F>(
+ policy: SecretKeyPolicy,
+ data_dir: &std::path::Path,
+ allow_create: bool,
+ env_lookup: F,
+ ) -> Result<SecretKeyResolution, String>
+ where
+ F: Fn(&str) -> Option<std::ffi::OsString>,
+ {
+ if let Some(path) = env_lookup("DBX_SECRET_KEY_FILE") {
let path = std::path::PathBuf::from(path);
let codec = Self::read_key_file(&path, false)?;
return Ok(SecretKeyResolution { codec, source: SecretKeySource::ExplicitFile });
}
- if let Some(value) = std::env::var_os("DBX_SECRET_KEY") {
+ if let Some(value) = env_lookup("DBX_SECRET_KEY") {
let value = value.to_str().ok_or_else(|| "SECRET_KEY_INVALID".to_string())?;
let codec = Self::from_key_material(value.trim()).map_err(|_| "SECRET_KEY_INVALID".to_string())?;
return Ok(SecretKeyResolution { codec, source: SecretKeySource::ExplicitEnv });
@@ -142,7 +160,9 @@ impl SecretCodec {
F: FnOnce(bool) -> Result<Option<SecretCodec>, String>,
{
let compatibility_error = if let Some(path) = compatibility_path.as_ref().filter(|path| path.exists()) {
- match Self::read_key_file(path, false) {
+ // Another process may have just created this file and not finished
+ // writing it yet; retry briefly before treating it as corrupt.
+ match read_key_file_with_retry(path, false) {
Ok(codec) => return Ok(SecretKeyResolution { codec, source: SecretKeySource::ManagedDataDir }),
Err(error) => Some(error),
}
@@ -417,13 +437,9 @@ fn create_key_file(path: &std::path::Path, managed: bool) -> Result<SecretCodec,
}
match path.symlink_metadata() {
Ok(metadata) if managed && metadata.file_type().is_symlink() => Err("KEY_FILE_UNAVAILABLE".to_string()),
- Ok(_) => {
- if managed {
- read_key_file_with_retry(path, managed)
- } else {
- SecretCodec::read_key_file(path, managed)
- }
- }
+ // The winner of the `create_new` race may still be mid-write, so read
+ // through the same retry loop the managed key path uses.
+ Ok(_) => read_key_file_with_retry(path, managed),
Err(_) => Err("KEY_FILE_UNAVAILABLE".to_string()),
}
}
@@ -433,16 +449,24 @@ pub fn managed_key_path(data_dir: &std::path::Path) -> std::path::PathBuf {
}
fn read_key_file_with_retry(path: &std::path::Path, reject_symlink: bool) -> Result<SecretCodec, String> {
+ let mut last_error = "KEY_FILE_UNAVAILABLE".to_string();
for attempt in 0..20 {
match SecretCodec::read_key_file(path, reject_symlink) {
Ok(codec) => return Ok(codec),
- Err(error) if attempt < 19 && error == "SECRET_KEY_INVALID" && path.metadata().is_ok() => {
+ Err(error) => {
+ let retryable = attempt < 19 && error == "SECRET_KEY_INVALID" && path.metadata().is_ok();
+ last_error = error;
+ if !retryable {
+ break;
+ }
std::thread::sleep(std::time::Duration::from_millis(5));
}
- Err(error) => return Err(error),
}
}
- Err("KEY_FILE_UNAVAILABLE".to_string())
+ // Surface what the file actually said: callers tell a corrupt key
+ // (SECRET_KEY_INVALID) apart from an unreadable one, and retrying must not
+ // blur that distinction once the retries are exhausted.
+ Err(last_error)
}
fn default_key_path() -> Option<std::path::PathBuf> {
@@ -470,7 +494,7 @@ fn aad(namespace: &str, key: &str) -> String {
#[cfg(test)]
mod tests {
- use super::{managed_key_path, SecretCodec, SecretKeyPolicy, SecretKeySource};
+ use super::{managed_key_path, read_key_file_with_retry, SecretCodec, SecretKeyPolicy, SecretKeySource};
use base64::Engine as _;
use std::sync::{Mutex, OnceLock};
@@ -555,6 +579,46 @@ mod tests {
}
}
+ #[test]
+ fn compatibility_key_still_being_written_by_a_concurrent_starter_is_retried() {
+ // The shared compatibility path (`~/.config/dbx/secret.key`) is global, so
+ // two starters can race: the `create_new` winner leaves an empty file on
+ // disk for a moment. A reader that gives up immediately reports
+ // SECRET_KEY_INVALID for a key that is fine a millisecond later.
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("secret.key");
+ std::fs::write(&path, "").unwrap();
+ let writer_path = path.clone();
+ let writer = std::thread::spawn(move || {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ let material = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([7u8; 32]);
+ std::fs::write(&writer_path, material).unwrap();
+ });
+
+ // allow_create=false covers the read-only probe every write goes through;
+ // allow_create=true covers the losing side of the create_new race.
+ for allow_create in [false, true] {
+ let resolved =
+ SecretCodec::resolve_platform_default(Some(path.clone()), allow_create, |_| Ok(None)).unwrap();
+ assert_eq!(resolved.source, SecretKeySource::ManagedDataDir);
+ let expected = SecretCodec::new([7u8; 32]);
+ let envelope = expected.encrypt("n", "k", "value").unwrap();
+ assert_eq!(resolved.codec.decrypt("n", "k", &envelope).unwrap(), "value");
+ }
+ writer.join().unwrap();
+ }
+
+ #[test]
+ fn exhausted_key_file_retries_keep_the_original_error_code() {
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("secret.key");
+ std::fs::write(&path, "\n").unwrap();
+ // A key file that stays corrupt must not be laundered into the generic
+ // "unavailable" code: the migration preflight reports Invalid vs
+ // Unavailable differently.
+ assert!(matches!(read_key_file_with_retry(&path, false), Err(error) if error == "SECRET_KEY_INVALID"));
+ }
+
#[cfg(unix)]
#[test]
fn managed_key_symlink_is_rejected() {
@@ -576,39 +640,37 @@ mod tests {
#[test]
fn explicit_key_file_symlink_is_allowed() {
use std::os::unix::fs::symlink;
- let _guard = env_lock().lock().unwrap();
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real.key");
let link = dir.path().join("external.key");
std::fs::write(&real, base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([5u8; 32])).unwrap();
symlink(&real, &link).unwrap();
- let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
- let previous_env = std::env::var_os("DBX_SECRET_KEY");
- std::env::set_var("DBX_SECRET_KEY_FILE", &link);
- std::env::remove_var("DBX_SECRET_KEY");
- let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
+ let resolved = SecretCodec::resolve_with_env(
+ SecretKeyPolicy::ManagedDataDir,
+ dir.path(),
+ false,
+ explicit_env(&[("DBX_SECRET_KEY_FILE", std::ffi::OsString::from(&link))]),
+ )
+ .unwrap();
assert_eq!(resolved.source, SecretKeySource::ExplicitFile);
- restore_env("DBX_SECRET_KEY_FILE", previous_file);
- restore_env("DBX_SECRET_KEY", previous_env);
}
#[cfg(unix)]
#[test]
fn invalid_non_utf8_explicit_environment_key_does_not_fallback() {
use std::os::unix::ffi::OsStringExt;
- let _guard = env_lock().lock().unwrap();
let dir = tempfile::tempdir().unwrap();
- let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
- let previous_env = std::env::var_os("DBX_SECRET_KEY");
- std::env::remove_var("DBX_SECRET_KEY_FILE");
- std::env::set_var("DBX_SECRET_KEY", std::ffi::OsString::from_vec(vec![0xff, 0xfe]));
+ let invalid = std::ffi::OsString::from_vec(vec![0xff, 0xfe]);
assert!(matches!(
- SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true),
+ SecretCodec::resolve_with_env(
+ SecretKeyPolicy::ManagedDataDir,
+ dir.path(),
+ true,
+ explicit_env(&[("DBX_SECRET_KEY", invalid)])
+ ),
Err(error) if error == "SECRET_KEY_INVALID"
));
- restore_env("DBX_SECRET_KEY_FILE", previous_file);
- restore_env("DBX_SECRET_KEY", previous_env);
}
#[test]
@@ -673,40 +735,38 @@ mod tests {
#[test]
fn explicit_sources_follow_precedence_without_fallback() {
- let _guard = env_lock().lock().unwrap();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("external.key");
- let previous_file = std::env::var_os("DBX_SECRET_KEY_FILE");
- let previous_env = std::env::var("DBX_SECRET_KEY").ok();
- std::env::remove_var("DBX_SECRET_KEY_FILE");
- std::env::remove_var("DBX_SECRET_KEY");
- SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), true).unwrap();
+ let env_key = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([2u8; 32]);
+ let resolve = |allow_create: bool, entries: &[(&str, std::ffi::OsString)]| {
+ let env = explicit_env(entries);
+ SecretCodec::resolve_with_env(SecretKeyPolicy::ManagedDataDir, dir.path(), allow_create, env)
+ };
+
+ // Nothing explicit is configured, so the managed data-dir key is provisioned.
+ resolve(true, &[]).unwrap();
+ // A corrupt explicit file outranks a valid explicit key and must not fall back.
std::fs::write(&file, "\n").unwrap();
- std::env::set_var("DBX_SECRET_KEY_FILE", &file);
- std::env::set_var("DBX_SECRET_KEY", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([2u8; 32]));
- assert!(matches!(
- SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false),
- Err(error) if error == "SECRET_KEY_INVALID"
- ));
+ let both = [
+ ("DBX_SECRET_KEY_FILE", std::ffi::OsString::from(&file)),
+ ("DBX_SECRET_KEY", std::ffi::OsString::from(env_key.as_str())),
+ ];
+ assert!(matches!(resolve(false, &both), Err(error) if error == "SECRET_KEY_INVALID"));
std::fs::write(&file, base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([1u8; 32])).unwrap();
- let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
- assert_eq!(resolved.source, SecretKeySource::ExplicitFile);
-
- std::env::remove_var("DBX_SECRET_KEY_FILE");
- let resolved = SecretCodec::resolve(SecretKeyPolicy::ManagedDataDir, dir.path(), false).unwrap();
- assert_eq!(resolved.source, SecretKeySource::ExplicitEnv);
+ assert_eq!(resolve(false, &both).unwrap().source, SecretKeySource::ExplicitFile);
- restore_env("DBX_SECRET_KEY_FILE", previous_file);
- restore_env("DBX_SECRET_KEY", previous_env.map(std::ffi::OsString::from));
+ let key_only = [("DBX_SECRET_KEY", std::ffi::OsString::from(env_key.as_str()))];
+ assert_eq!(resolve(false, &key_only).unwrap().source, SecretKeySource::ExplicitEnv);
}
- fn restore_env(name: &str, value: Option<std::ffi::OsString>) {
- if let Some(value) = value {
- std::env::set_var(name, value);
- } else {
- std::env::remove_var(name);
- }
+ /// Environment lookup for [`SecretCodec::resolve_with_env`] that never
+ /// touches the process environment, so these tests cannot change the key
+ /// another test in the same binary resolves while they run.
+ fn explicit_env<'a>(
+ entries: &'a [(&'a str, std::ffi::OsString)],
+ ) -> impl Fn(&str) -> Option<std::ffi::OsString> + 'a {
+ move |name| entries.iter().find(|(key, _)| *key == name).map(|(_, value)| value.clone())
}
}
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index 7b310aabd4..5b6ca777e5 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -25,7 +25,8 @@ use crate::connection_secrets::{
CASSANDRA_TRUSTSTORE_PASSWORD_KEY, MQTT_AUTH_PASSWORD_KEY, MQTT_AUTH_SECRET_PREFIX, MQ_AUTH_API_KEY_VALUE_KEY,
MQ_AUTH_CLIENT_SECRET_KEY, MQ_AUTH_PASSWORD_KEY, MQ_AUTH_SECRET_PREFIX, MQ_AUTH_TOKEN_KEY, MQ_TOKEN_SIGNING_KEY,
MQ_TOKEN_SIGNING_SECRET_PREFIX, NACOS_AUTH_PASSWORD_KEY, NACOS_AUTH_SECRET_PREFIX,
- NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX,
+ NACOS_RNACOS_CONSOLE_PASSWORD_KEY, PLUGIN_CONNECTION_SECRET_PREFIX, SALESFORCE_AUTH_CLIENT_SECRET_KEY,
+ SALESFORCE_AUTH_PASSWORD_KEY, SALESFORCE_AUTH_REFRESH_TOKEN_KEY, SALESFORCE_AUTH_SECRET_PREFIX,
};
use crate::db::sqlite::{connect_path_create_if_missing, SqliteHandle};
use crate::history::{
@@ -471,6 +472,15 @@ pub struct McpConnectionPolicy {
/// connection default, while a present entry takes priority over it.
#[serde(default)]
pub database_policies: Vec<McpDatabasePolicy>,
+ /// Opt-in switch letting an AI agent write to this Salesforce org through
+ /// MCP. Absent on every policy saved before the switch existed, and `false`
+ /// by default: SOQL reads need no permission beyond the execution mode, but
+ /// Salesforce DML has no transaction and no rollback, so an agent may only
+ /// reach it after a person turns this on for the connection and confirms
+ /// each write (`dbx_salesforce_prepare_write` → `dbx_salesforce_apply_write`).
+ /// Forced back to false whenever `read_only` is set.
+ #[serde(default)]
+ pub allow_salesforce_dml: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -646,6 +656,9 @@ impl McpGlobalPolicy {
current.allowed_databases = databases;
current.database_policies =
merge_mcp_database_policies(&current.database_policies, &rule.database_policies);
+ // Same conjunction as high-risk SQL: every duplicate rule has
+ // to opt in before an agent may write to the org.
+ current.allow_salesforce_dml &= rule.allow_salesforce_dml;
})
.or_insert_with(|| McpConnectionPolicy {
connection_id: connection_id.to_string(),
@@ -656,6 +669,7 @@ impl McpGlobalPolicy {
database_scope: rule.database_scope,
allowed_databases: normalize_mcp_database_names(&rule.allowed_databases),
database_policies: normalize_mcp_database_policies(&rule.database_policies),
+ allow_salesforce_dml: rule.allow_salesforce_dml,
});
}
let mut connection_policies = policies.into_values().collect::<Vec<_>>();
@@ -663,6 +677,9 @@ impl McpGlobalPolicy {
for rule in &mut connection_policies {
if rule.read_only {
rule.allow_dangerous_sql = false;
+ // A read-only connection cannot carry a Salesforce write opt-in,
+ // however the saved rules were merged.
+ rule.allow_salesforce_dml = false;
}
rule.allowed_databases = normalize_mcp_database_names(&rule.allowed_databases);
if rule.database_scope != McpDatabaseScope::Selected {
@@ -2947,6 +2964,18 @@ fn scrub_cassandra_tls_secrets(config: &mut ConnectionConfig) {
scrub_json_secret(tls, "keystore_password");
}
+fn scrub_salesforce_auth_secrets(config: &mut ConnectionConfig) {
+ if config.db_type != DatabaseType::Salesforce {
+ return;
+ }
+ let Some(auth) = salesforce_auth_object_mut(config.external_config.as_mut()) else {
+ return;
+ };
+ scrub_json_secret(auth, "clientSecret");
+ scrub_json_secret(auth, "refreshToken");
+ scrub_json_secret(auth, "password");
+}
+
fn delete_secret_prefix_in_tx(
tx: &rusqlite::Transaction<'_>,
connection_id: &str,
@@ -5209,6 +5238,7 @@ fn sanitized_connection_config(config: &ConnectionConfig) -> ConnectionConfig {
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
+ scrub_salesforce_auth_secrets(&mut sanitized);
sanitized.connection_secrets.clear();
sanitized
}
@@ -5306,6 +5336,7 @@ fn persist_connection_in_tx(
persist_mq_token_signing_secret_in_tx(tx, codec, &config)?;
persist_nacos_auth_secrets_in_tx(tx, codec, &config)?;
persist_cassandra_tls_secrets_in_tx(tx, codec, &config)?;
+ persist_salesforce_auth_secrets_in_tx(tx, codec, &config)?;
delete_secret_prefix_in_tx(tx, &config.id, PLUGIN_CONNECTION_SECRET_PREFIX)?;
for (key, secret) in &config.connection_secrets {
if !key.is_empty() {
@@ -5576,6 +5607,7 @@ impl Storage {
scrub_mq_token_signing_secret(&mut sanitized);
scrub_nacos_auth_secrets(&mut sanitized);
scrub_cassandra_tls_secrets(&mut sanitized);
+ scrub_salesforce_auth_secrets(&mut sanitized);
sanitized.connection_secrets.clear();
let json = serde_json::to_string(&sanitized).map_err(|e| e.to_string())?;
@@ -5964,6 +5996,7 @@ impl Storage {
let needs_mq_token_signing_rewrite = self.hydrate_mq_token_signing_secret(&id, &mut config).await?;
let needs_nacos_auth_rewrite = self.hydrate_nacos_auth_secret(&id, &mut config).await?;
let needs_cassandra_tls_rewrite = self.hydrate_cassandra_tls_secrets(&id, &mut config).await?;
+ let needs_salesforce_auth_rewrite = self.hydrate_salesforce_auth_secrets(&id, &mut config).await?;
let mut needs_plugin_secret_rewrite = false;
let plugin_secret_keys = config.connection_secrets.keys().cloned().collect::<Vec<_>>();
for key in plugin_secret_keys {
@@ -5983,6 +6016,7 @@ impl Storage {
|| needs_mq_token_signing_rewrite
|| needs_nacos_auth_rewrite
|| needs_cassandra_tls_rewrite
+ || needs_salesforce_auth_rewrite
|| needs_plugin_secret_rewrite;
if needs_external_secret_rewrite {
// `config` is hydrated above, so always use the canonical
@@ -6140,6 +6174,28 @@ impl Storage {
.await?;
Ok(truststore_rewrite || keystore_rewrite)
}
+
+ async fn hydrate_salesforce_auth_secrets(
+ &self,
+ connection_id: &str,
+ config: &mut ConnectionConfig,
+ ) -> Result<bool, String> {
+ if config.db_type != DatabaseType::Salesforce {
+ return Ok(false);
+ }
+ let Some(auth) = salesforce_auth_object_mut(config.external_config.as_mut()) else {
+ return Ok(false);
+ };
+ let client_secret_rewrite =
+ hydrate_mq_json_secret(self, connection_id, SALESFORCE_AUTH_CLIENT_SECRET_KEY, auth, "clientSecret")
+ .await?;
+ let refresh_token_rewrite =
+ hydrate_mq_json_secret(self, connection_id, SALESFORCE_AUTH_REFRESH_TOKEN_KEY, auth, "refreshToken")
+ .await?;
+ let password_rewrite =
+ hydrate_mq_json_secret(self, connection_id, SALESFORCE_AUTH_PASSWORD_KEY, auth, "password").await?;
+ Ok(client_secret_rewrite || refresh_token_rewrite || password_rewrite)
+ }
}
// Saved SQL
@@ -7862,6 +7918,60 @@ fn persist_cassandra_tls_secrets_in_tx(
)
}
+fn persist_salesforce_auth_secrets_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ config: &ConnectionConfig,
+) -> Result<(), String> {
+ if config.db_type != DatabaseType::Salesforce {
+ delete_secret_prefix_in_tx(tx, &config.id, SALESFORCE_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ }
+ let Some(auth) = salesforce_auth_object(config.external_config.as_ref()) else {
+ delete_secret_prefix_in_tx(tx, &config.id, SALESFORCE_AUTH_SECRET_PREFIX)?;
+ return Ok(());
+ };
+ replace_salesforce_auth_secret_in_tx(
+ tx,
+ codec,
+ &config.id,
+ SALESFORCE_AUTH_CLIENT_SECRET_KEY,
+ auth,
+ "clientSecret",
+ )?;
+ replace_salesforce_auth_secret_in_tx(
+ tx,
+ codec,
+ &config.id,
+ SALESFORCE_AUTH_REFRESH_TOKEN_KEY,
+ auth,
+ "refreshToken",
+ )?;
+ replace_salesforce_auth_secret_in_tx(tx, codec, &config.id, SALESFORCE_AUTH_PASSWORD_KEY, auth, "password")?;
+ Ok(())
+}
+
+fn replace_salesforce_auth_secret_in_tx(
+ tx: &rusqlite::Transaction<'_>,
+ codec: &SecretCodec,
+ connection_id: &str,
+ key: &str,
+ auth: &serde_json::Map<String, serde_json::Value>,
+ field: &str,
+) -> Result<(), String> {
+ let current = auth.get(field).and_then(serde_json::Value::as_str).filter(|secret| !secret.is_empty());
+ let existing = if current.is_none() { get_secret_in_tx(tx, codec, connection_id, key)? } else { None };
+ tx.execute("DELETE FROM connection_secrets WHERE connection_id = ?1 AND key = ?2", params![connection_id, key])
+ .map_err(|e| e.to_string())?;
+ match current {
+ Some(secret) => persist_secret_in_tx(tx, codec, connection_id, key, secret),
+ None => match existing {
+ Some(secret) => persist_secret_in_tx(tx, codec, connection_id, key, &secret),
+ None => Ok(()),
+ },
+ }
+}
+
fn persist_json_secret_if_present_in_tx(
tx: &rusqlite::Transaction<'_>,
codec: &SecretCodec,
@@ -7934,6 +8044,16 @@ fn cassandra_tls_object_mut(
value?.get_mut("tls")?.as_object_mut()
}
+fn salesforce_auth_object(value: Option<&serde_json::Value>) -> Option<&serde_json::Map<String, serde_json::Value>> {
+ value?.get("auth")?.as_object()
+}
+
+fn salesforce_auth_object_mut(
+ value: Option<&mut serde_json::Value>,
+) -> Option<&mut serde_json::Map<String, serde_json::Value>> {
+ value?.get_mut("auth")?.as_object_mut()
+}
+
fn nacos_auth_object(value: Option<&serde_json::Value>) -> Option<&serde_json::Map<String, serde_json::Value>> {
value?.get("auth")?.as_object()
}
diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rs
index 1f21dba027..29423155cc 100644
--- a/crates/dbx-core/src/query/mod.rs
+++ b/crates/dbx-core/src/query/mod.rs
@@ -2078,6 +2078,23 @@ async fn do_execute_typed(
}
result
}
+ PoolKind::Salesforce(client) => {
+ let client = client.clone();
+ let sql = sql.to_string();
+ let max_rows = options.max_rows;
+ let result = wait_for_query_opt(cancel_token, query_timeout, async move {
+ if let Some(cursor) = options.result_session_id.as_deref() {
+ client.fetch_more(cursor).await
+ } else {
+ client.execute_query(&sql, max_rows).await
+ }
+ })
+ .await;
+ if matches!(result.as_ref(), Err(err) if should_discard_pool_after_error(pool_db_type, err)) {
+ state.remove_pool_by_key(pool_key).await;
+ }
+ result
+ }
PoolKind::VectorDb(client) => {
let client = client.clone();
let sql = sql.to_string();
@@ -4704,6 +4721,7 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
| PoolKind::Easysearch(_)
| PoolKind::Solr(_)
| PoolKind::Meilisearch(_)
+ | PoolKind::Salesforce(_)
| PoolKind::VectorDb(_)
| PoolKind::InfluxDb(_)
| PoolKind::InfluxDb3(_)
@@ -5108,6 +5126,7 @@ fn batch_transaction_path(pool: &PoolKind) -> BatchTransactionPath {
| PoolKind::Easysearch(_)
| PoolKind::Solr(_)
| PoolKind::Meilisearch(_)
+ | PoolKind::Salesforce(_)
| PoolKind::VectorDb(_)
| PoolKind::InfluxDb(_)
| PoolKind::InfluxDb3(_)
diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rs
index b3b6ef64bd..85837e60f9 100644
--- a/crates/dbx-core/src/schema/mod.rs
+++ b/crates/dbx-core/src/schema/mod.rs
@@ -676,6 +676,12 @@ async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Ve
if let Some(client) = extract_pool!(pool_handle.as_ref(), VictoriaMetrics) {
return db::victoriametrics_driver::list_databases(&client).await;
}
+ if let Some(client) = extract_pool!(pool_handle.as_ref(), Salesforce) {
+ // singleDatabase trait: the whole org is one synthesized database
+ // node; sObjects are listed as its tables.
+ let name = client.org_display_name().await;
+ return Ok(vec![db::DatabaseInfo { name, ..Default::default() }]);
+ }
try_sqlserver!(pool_handle, list_databases);
if let Some(client) = extract_pool!(pool_handle.as_ref(), Agent) {
let is_mongo = db_config.as_ref().is_some_and(|config| config.db_type == DatabaseType::MongoDb);
@@ -2683,6 +2689,10 @@ async fn list_tables_once(
.await
.map(|names| collection_names_to_tables(names, "INDEX"))
.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter)),
+ PoolKind::Salesforce(client) => db::salesforce_driver::SfClient::list_tables(client)
+ .await
+ .map(|names| collection_names_to_tables(names, "SOBJECT"))
+ .map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter)),
PoolKind::HBase(client) => db::hbase_driver::list_tables(client, database)
.await
.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter)),
@@ -7456,6 +7466,9 @@ async fn get_columns_core_for_session_inner_with_pool(
PoolKind::Meilisearch(client) => {
db::meilisearch_driver::get_columns(client, table).await.map(deduplicate_column_infos)
}
+ PoolKind::Salesforce(client) => {
+ db::salesforce_driver::SfClient::get_columns(client, table).await.map(deduplicate_column_infos)
+ }
PoolKind::HBase(client) => {
db::hbase_driver::get_columns(client, database, table).await.map(deduplicate_column_infos)
}
diff --git a/crates/dbx-core/tests/database_capabilities.rs b/crates/dbx-core/tests/database_capabilities.rs
index 6b716791ff..0211a5f438 100644
--- a/crates/dbx-core/tests/database_capabilities.rs
+++ b/crates/dbx-core/tests/database_capabilities.rs
@@ -364,6 +364,18 @@ fn driver_manifest_declares_expected_product_capabilities() {
assert!(!uxdb.capabilities.data_transfer);
assert!(!uxdb.capabilities.user_admin);
+ let salesforce = find_driver(DatabaseType::Salesforce);
+ assert_eq!(salesforce.label, "Salesforce");
+ assert_eq!(salesforce.support_level, "operate");
+ assert!(salesforce.capabilities.query_execution);
+ assert!(salesforce.capabilities.metadata_browse);
+ assert!(salesforce.capabilities.object_browser);
+ assert!(salesforce.capabilities.schema_search);
+ assert!(salesforce.capabilities.table_data_edit);
+ assert!(!salesforce.capabilities.table_structure_edit);
+ assert!(!salesforce.capabilities.object_source);
+ assert!(!salesforce.capabilities.diagram);
+
let spanner = find_driver(DatabaseType::Spanner);
assert_eq!(spanner.label, "Google Cloud Spanner");
assert_eq!(spanner.runtime_mode, "agent");
diff --git a/crates/dbx-drivers/src/db/mod.rs b/crates/dbx-drivers/src/db/mod.rs
index e9ed1e3f21..4dc7a9e510 100644
--- a/crates/dbx-drivers/src/db/mod.rs
+++ b/crates/dbx-drivers/src/db/mod.rs
@@ -39,6 +39,7 @@ pub mod proxy_tunnel;
pub mod questdb;
pub mod redis_driver;
pub mod rqlite_driver;
+pub mod salesforce_driver;
pub mod solr_driver;
pub mod sqlite;
pub mod sqlite_worker;
diff --git a/crates/dbx-drivers/src/db/salesforce_driver.rs b/crates/dbx-drivers/src/db/salesforce_driver.rs
new file mode 100644
index 0000000000..5ea44560db
--- /dev/null
+++ b/crates/dbx-drivers/src/db/salesforce_driver.rs
@@ -0,0 +1,1722 @@
+//! Salesforce (SOQL) driver.
+//!
+//! Talks to the Salesforce REST API over HTTPS. The connection's `host` field
+//! carries the org instance URL (e.g. `https://acme.my.salesforce.com`) and the
+//! `password` field carries the OAuth access token / session id.
+//!
+//! Mapping to DBX abstractions (see docs/salesforce-soql-integration-spec.md):
+//! - org -> single database (`singleDatabase` trait)
+//! - sObject -> table
+//! - field -> column (label + apiName + type + picklist values)
+//! - SOQL query -> `QueryResult` (rows/columns), pagination via QueryLocator
+//!
+//! DML and SOQL completion metadata are layered on top in later milestones.
+//! OAuth lives in `crate::salesforce_oauth`; this module consumes it for
+//! transparent token refresh — every request funnels through `api_send` /
+//! `api_get_conditional`, both of which retry once after a refresh on 401.
+
+use reqwest::{Client as HttpClient, Method, StatusCode, Url};
+use serde::Serialize;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use super::{http_client_builder, json_value_for_js, with_connection_timeout};
+use crate::db::ColumnInfo;
+use crate::salesforce_oauth::{
+ oauth_params_from_external_config, password_grant_token, refresh_access_token, SfOauthParams, SfRefreshMethod,
+};
+use crate::types::QueryResult;
+
+/// API version pinned by default. Salesforce keeps every version alive for
+/// 3+ years; bump deliberately (spec §4.1), users can override via
+/// `external_config.apiVersion`.
+pub const SALESFORCE_DEFAULT_API_VERSION: &str = "v62.0";
+
+/// Hard cap on rows materialized per query batch. Salesforce itself pages
+/// SOQL results at 2000 rows and hands out a QueryLocator for the rest.
+const SALESFORCE_MAX_ROWS_PER_BATCH: usize = 2_000;
+
+/// Cells larger than this are shipped as a JSON string instead of being
+/// flattened, to keep the grid payload bounded (subqueries, rich text, ...).
+const SALESFORCE_MAX_NESTED_JSON_CHARS: usize = 64 * 1024;
+
+#[derive(Clone)]
+pub struct SfClient {
+ http: HttpClient,
+ /// Normalized org instance base URL, no trailing slash.
+ instance_url: String,
+ /// Live access token. Mutable because it is transparently replaced by the
+ /// refresh flow (spec §2.4); readers clone it under the lock, never hold
+ /// the guard across an await.
+ access_token: Arc<Mutex<String>>,
+ /// Refresh context parsed from `external_config.auth` (OAuth connections
+ /// only). `None` for pasted-token connections.
+ refresh: Arc<tokio::sync::Mutex<Option<SfRefreshContext>>>,
+ /// e.g. `v62.0` (no leading path component).
+ api_version: String,
+ timeout: Duration,
+ /// `/sobjects/` listing, cached with its ETag (Salesforce supports
+ /// conditional requests here; spec §6.1 — quota friendly).
+ sobject_cache: Arc<Mutex<Option<CachedSObjectList>>>,
+ /// Per-sObject describe bodies, cached in memory for the connection's
+ /// lifetime. Describes are large and rarely change within a session.
+ describe_cache: Arc<Mutex<HashMap<String, Value>>>,
+ /// Resolved organization display name (one SOQL call, cached; falls back
+ /// to the instance host label without caching on failure).
+ org_name_cache: Arc<Mutex<Option<String>>>,
+ /// Cached connected-user identity (one `current_user()` call, cached for
+ /// the connection's lifetime so repeated metadata requests don't burn API
+ /// quota).
+ current_user_cache: Arc<Mutex<Option<SfUserInfo>>>,
+}
+
+/// Re-auth material held for the connection's lifetime (refresh token for
+/// OAuth connections, stored credentials for username-password connections).
+struct SfRefreshContext {
+ params: SfOauthParams,
+ method: SfRefreshMethod,
+}
+
+/// Distinguishes 401s (retryable via refresh) from everything else so the two
+/// HTTP surfaces share one retry policy.
+enum ApiFailure {
+ Unauthorized(String),
+ Other(String),
+}
+
+impl ApiFailure {
+ fn into_error(self) -> String {
+ match self {
+ Self::Unauthorized(message) | Self::Other(message) => message,
+ }
+ }
+}
+
+impl std::fmt::Debug for SfClient {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let refresh_configured = self.refresh.try_lock().map(|guard| guard.is_some()).unwrap_or(true);
+ f.debug_struct("SfClient")
+ .field("instance_url", &self.instance_url)
+ .field("api_version", &self.api_version)
+ .field("access_token", &"<redacted>")
+ .field("refresh_configured", &refresh_configured)
+ .finish()
+ }
+}
+
+struct CachedSObjectList {
+ etag: Option<String>,
+ entries: Vec<SfSObjectEntry>,
+}
+
+/// One entry of the `/sobjects/` listing.
+#[derive(Debug, Clone, Serialize)]
+pub struct SfSObjectEntry {
+ pub name: String,
+ pub label: String,
+ pub custom: bool,
+ pub queryable: bool,
+}
+
+/// Identity + coarse admin flag for the connected user (spec §3).
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct SfUserInfo {
+ pub user_id: String,
+ pub name: String,
+ pub email: String,
+ pub organization_id: String,
+ pub username: String,
+ pub profile_name: Option<String>,
+ /// `Profile.PermissionsModifyAllData` — advisory only, NOT a security
+ /// boundary (server-side sharing/FLS always wins).
+ pub is_admin: Option<bool>,
+}
+
+impl SfClient {
+ /// Build a client from the stored connection config.
+ ///
+ /// - `instance_url`: org instance (`host` field of the connection; scheme
+ /// defaults to https when missing).
+ /// - `access_token`: OAuth access token / session id (`password` field).
+ /// May be empty when `external_config.auth` carries a refresh token —
+ /// the first request then refreshes before hitting the API.
+ /// - `external_config`: optional overrides —
+ /// `{ "apiVersion": "v62.0", "auth": { "environment", "loginUrl",
+ /// "clientId", "clientSecret", "refreshToken" } }`. The auth values are
+ /// hydrated from the secret store by dbx-core for saved connections.
+ pub fn from_config(
+ instance_url: &str,
+ access_token: Option<&str>,
+ external_config: Option<&Value>,
+ timeout: Duration,
+ ) -> Result<Self, String> {
+ let instance_url = normalize_instance_url(instance_url)?;
+ let access_token = access_token.unwrap_or("").trim().to_string();
+ let refresh_context = oauth_params_from_external_config(external_config)
+ .map(|(params, method)| SfRefreshContext { params, method });
+ if access_token.is_empty() && refresh_context.is_none() {
+ return Err("Salesforce access token is required. Paste a session/access token, or sign in via OAuth (desktop app).".to_string());
+ }
+ let api_version = salesforce_api_version(external_config)?;
+ let http = http_client_builder(timeout)
+ .build()
+ .map_err(|error| format!("Failed to initialize Salesforce HTTP client: {error}"))?;
+ Ok(Self {
+ http,
+ instance_url,
+ access_token: Arc::new(Mutex::new(access_token)),
+ refresh: Arc::new(tokio::sync::Mutex::new(refresh_context)),
+ api_version,
+ timeout,
+ sobject_cache: Arc::new(Mutex::new(None)),
+ describe_cache: Arc::new(Mutex::new(HashMap::new())),
+ org_name_cache: Arc::new(Mutex::new(None)),
+ current_user_cache: Arc::new(Mutex::new(None)),
+ })
+ }
+
+ /// Whether this client can transparently refresh its access token.
+ pub fn has_refresh_token(&self) -> bool {
+ self.refresh.try_lock().map(|guard| guard.is_some()).unwrap_or(true)
+ }
+
+ fn current_token(&self) -> String {
+ self.access_token.lock().map(|token| token.clone()).unwrap_or_default()
+ }
+
+ /// Re-authenticate in place (refresh-token exchange, or replaying the
+ /// username-password login for ROPC connections). Returns true when a
+ /// fresh token was installed; serialized by the async mutex so concurrent
+ /// 401s trigger a single re-auth.
+ async fn try_refresh_token(&self) -> bool {
+ let mut guard = self.refresh.lock().await;
+ let Some(context) = guard.as_mut() else { return false };
+ let outcome = match &context.method {
+ SfRefreshMethod::RefreshToken(refresh_token) => refresh_access_token(&context.params, refresh_token)
+ .await
+ .map(|tokens| (tokens.access_token, tokens.refresh_token)),
+ SfRefreshMethod::Password { username, password } => {
+ password_grant_token(&context.params, username, password)
+ .await
+ .map(|tokens| (tokens.access_token, None))
+ }
+ };
+ match outcome {
+ Ok((access_token, rotated)) => {
+ if let (Some(rotated), SfRefreshMethod::RefreshToken(current)) = (rotated, &mut context.method) {
+ *current = rotated;
+ }
+ if let Ok(mut current) = self.access_token.lock() {
+ *current = access_token;
+ }
+ true
+ }
+ Err(_) => false,
+ }
+ }
+
+ /// Run one HTTP surface with a single refresh retry: when the first
+ /// attempt fails with 401 and a refresh token is configured, refresh and
+ /// replay once.
+ async fn with_refresh_retry<T, F, Fut>(&self, attempt: F) -> Result<T, String>
+ where
+ F: Fn() -> Fut,
+ Fut: std::future::Future<Output = Result<T, ApiFailure>>,
+ {
+ // No token yet (expired paste cleared, or OAuth connection whose
+ // access token was never persisted): refresh proactively.
+ if self.current_token().is_empty() && self.has_refresh_token() {
+ let _ = self.try_refresh_token().await;
+ }
+ match attempt().await {
+ Ok(value) => Ok(value),
+ Err(ApiFailure::Unauthorized(message)) => {
+ if self.try_refresh_token().await {
+ match attempt().await {
+ Ok(value) => Ok(value),
+ Err(failure) => Err(failure.into_error()),
+ }
+ } else {
+ Err(message)
+ }
+ }
+ Err(failure) => Err(failure.into_error()),
+ }
+ }
+
+ pub fn instance_url(&self) -> &str {
+ &self.instance_url
+ }
+
+ pub fn api_version(&self) -> &str {
+ &self.api_version
+ }
+
+ /// `{instance}/services/data/{apiVersion}`
+ fn api_base(&self) -> String {
+ format!("{}/services/data/{}", self.instance_url, self.api_version)
+ }
+
+ async fn api_send(&self, method: Method, url: &str, body: Option<Value>) -> Result<Value, String> {
+ let method = method.clone();
+ let url = url.to_string();
+ self.with_refresh_retry(|| {
+ let method = method.clone();
+ let url = url.clone();
+ let body = body.clone();
+ async move { self.api_send_once(method, &url, body).await }
+ })
+ .await
+ }
+
+ async fn api_send_once(&self, method: Method, url: &str, body: Option<Value>) -> Result<Value, ApiFailure> {
+ let label = format!("Salesforce {} {}", method, url);
+ let request =
+ self.http.request(method, url).bearer_auth(self.current_token()).header("Accept", "application/json");
+ let request = match body {
+ Some(value) => request.json(&value),
+ None => request,
+ };
+ let response = with_connection_timeout(&label, self.timeout, async {
+ request.send().await.map_err(|error| format!("Salesforce request failed: {error}"))
+ })
+ .await
+ .map_err(ApiFailure::Other)?;
+ let status = response.status();
+ let text = response
+ .text()
+ .await
+ .map_err(|error| ApiFailure::Other(format!("Failed to read Salesforce response: {error}")))?;
+ if status == StatusCode::UNAUTHORIZED {
+ return Err(ApiFailure::Unauthorized(map_salesforce_error(status, &text)));
+ }
+ if status == StatusCode::NO_CONTENT || text.trim().is_empty() {
+ if status.is_success() {
+ return Ok(Value::Null);
+ }
+ return Err(ApiFailure::Other(map_salesforce_error(status, "")));
+ }
+ let value: Value = serde_json::from_str(&text)
+ .map_err(|error| ApiFailure::Other(format!("Invalid Salesforce JSON response ({status}): {error}")))?;
+ if status.is_success() {
+ return Ok(value);
+ }
+ Err(ApiFailure::Other(salesforce_error_message(status, &value)))
+ }
+
+ async fn api_get(&self, url: &str) -> Result<Value, String> {
+ self.api_send(Method::GET, url, None).await
+ }
+
+ async fn api_post(&self, url: &str, body: Value) -> Result<Value, String> {
+ self.api_send(Method::POST, url, Some(body)).await
+ }
+
+ async fn api_patch(&self, url: &str, body: Value) -> Result<Value, String> {
+ self.api_send(Method::PATCH, url, Some(body)).await
+ }
+
+ async fn api_delete(&self, url: &str) -> Result<Value, String> {
+ self.api_send(Method::DELETE, url, None).await
+ }
+
+ /// GET with conditional-request headers; returns `Ok(None)` on 304.
+ async fn api_get_conditional(
+ &self,
+ url: &str,
+ etag: Option<&str>,
+ ) -> Result<Option<(Value, Option<String>)>, String> {
+ let url = url.to_string();
+ let etag = etag.map(str::to_string);
+ self.with_refresh_retry(|| {
+ let url = url.clone();
+ let etag = etag.clone();
+ async move { self.api_get_conditional_once(&url, etag.as_deref()).await }
+ })
+ .await
+ }
+
+ async fn api_get_conditional_once(
+ &self,
+ url: &str,
+ etag: Option<&str>,
+ ) -> Result<Option<(Value, Option<String>)>, ApiFailure> {
+ let label = format!("Salesforce GET {url}");
+ let mut request = self.http.get(url).bearer_auth(self.current_token()).header("Accept", "application/json");
+ if let Some(etag) = etag {
+ request = request.header("If-None-Match", etag);
+ }
+ let response = with_connection_timeout(&label, self.timeout, async {
+ request.send().await.map_err(|error| format!("Salesforce request failed: {error}"))
+ })
+ .await
+ .map_err(ApiFailure::Other)?;
+ let status = response.status();
+ if status == StatusCode::UNAUTHORIZED {
+ let text = response.text().await.unwrap_or_default();
+ return Err(ApiFailure::Unauthorized(map_salesforce_error(status, &text)));
+ }
+ if status == StatusCode::NOT_MODIFIED {
+ return Ok(None);
+ }
+ let new_etag =
+ response.headers().get(reqwest::header::ETAG).and_then(|value| value.to_str().ok()).map(str::to_string);
+ let text = response
+ .text()
+ .await
+ .map_err(|error| ApiFailure::Other(format!("Failed to read Salesforce response: {error}")))?;
+ if !status.is_success() {
+ let value: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
+ return Err(ApiFailure::Other(salesforce_error_message(status, &value)));
+ }
+ let value: Value = serde_json::from_str(&text)
+ .map_err(|error| ApiFailure::Other(format!("Invalid Salesforce JSON response ({status}): {error}")))?;
+ Ok(Some((value, new_etag)))
+ }
+
+ /// Connectivity/auth check: list API versions (cheap, unauthenticated-ish
+ /// endpoint that still surfaces instance URL problems, then hit userinfo
+ /// so an expired token fails fast with a clear message).
+ pub async fn test_connection(client: &SfClient, timeout: Duration) -> Result<(), String> {
+ let label = "Salesforce connectivity check";
+ let versions_url = format!("{}/services/data", client.instance_url);
+ let versions = with_connection_timeout(label, timeout, async {
+ client
+ .http
+ .get(&versions_url)
+ .header("Accept", "application/json")
+ .send()
+ .await
+ .map_err(|error| format!("Cannot reach Salesforce instance '{versions_url}': {error}"))
+ })
+ .await?;
+ let status = versions.status();
+ if !status.is_success() {
+ return Err(format!("Salesforce instance returned HTTP {status} for {versions_url}"));
+ }
+ // Validate the token itself.
+ client.api_get(&format!("{}/sobjects/", client.api_base())).await.map(|_| ())
+ }
+
+ /// Execute a SOQL query or a `DBX SALESFORCE DML` pseudo-command. `max_rows`
+ /// caps materialized rows; remaining rows stay behind `has_more` +
+ /// QueryLocator (`session_id`).
+ pub async fn execute_query(&self, soql: &str, max_rows: Option<usize>) -> Result<QueryResult, String> {
+ // Route DBX SALESFORCE pseudo-commands before the SOQL path so they
+ // never get `apply_fields_function_limit` treatment.
+ if starts_with_salesforce_header(soql) {
+ let statement = parse_salesforce_statement(soql)?;
+ return self.execute_dml(&statement).await;
+ }
+ let started = Instant::now();
+ let soql = apply_fields_function_limit(soql);
+ let url = format!("{}/query?q={}", self.api_base(), urlencoded(&soql));
+ let value = self.api_get(&url).await?;
+ let limit = max_rows.unwrap_or(SALESFORCE_MAX_ROWS_PER_BATCH).max(1);
+ Ok(parse_soql_response(value, started.elapsed().as_millis(), limit))
+ }
+
+ /// Fetch the next page using a QueryLocator URL returned as `session_id`.
+ pub async fn fetch_more(&self, cursor: &str) -> Result<QueryResult, String> {
+ let started = Instant::now();
+ let url = self.resolve_cursor_url(cursor)?;
+ let value = self.api_get(&url).await?;
+ Ok(parse_soql_response(value, started.elapsed().as_millis(), SALESFORCE_MAX_ROWS_PER_BATCH))
+ }
+
+ /// Resolve a QueryLocator cursor to a request URL. Salesforce returns
+ /// `nextRecordsUrl` as an absolute URL on the org's own host; relative
+ /// cursors are resolved against the instance. An absolute cursor pointing
+ /// at any other origin would receive this connection's bearer token, so it
+ /// is refused instead of followed.
+ fn resolve_cursor_url(&self, cursor: &str) -> Result<String, String> {
+ let trimmed = cursor.trim();
+ if !(trimmed.starts_with("http://") || trimmed.starts_with("https://")) {
+ return Ok(format!("{}{}", self.instance_url, trimmed));
+ }
+ let instance =
+ Url::parse(&self.instance_url).map_err(|error| format!("Salesforce instance URL is invalid: {error}"))?;
+ let absolute =
+ Url::parse(trimmed).map_err(|error| format!("Salesforce query cursor is not a valid URL: {error}"))?;
+ if absolute.origin() != instance.origin() {
+ return Err(format!(
+ "Salesforce query cursor points outside the connected org ({}) and was not followed",
+ absolute.host_str().unwrap_or_default()
+ ));
+ }
+ Ok(trimmed.to_string())
+ }
+
+ /// sObject listing (queryable ones are the "tables" of the org).
+ pub async fn list_sobjects(&self) -> Result<Vec<SfSObjectEntry>, String> {
+ let url = format!("{}/sobjects/", self.api_base());
+ let cached_etag =
+ self.sobject_cache.lock().ok().and_then(|guard| guard.as_ref().and_then(|cached| cached.etag.clone()));
+ match self.api_get_conditional(&url, cached_etag.as_deref()).await? {
+ None => {
+ // 304 — serve from cache.
+ let entries = self
+ .sobject_cache
+ .lock()
+ .ok()
+ .and_then(|guard| guard.as_ref().map(|cached| cached.entries.clone()))
+ .unwrap_or_default();
+ Ok(entries)
+ }
+ Some((value, etag)) => {
+ let entries = parse_sobject_list(&value);
+ if let Ok(mut guard) = self.sobject_cache.lock() {
+ *guard = Some(CachedSObjectList { etag, entries: entries.clone() });
+ }
+ Ok(entries)
+ }
+ }
+ }
+
+ /// Table names for the schema browser / completion metadata.
+ pub async fn list_tables(&self) -> Result<Vec<String>, String> {
+ Ok(self.list_sobjects().await?.into_iter().filter(|entry| entry.queryable).map(|entry| entry.name).collect())
+ }
+
+ /// Raw describe body for one sObject (cached per connection).
+ pub async fn describe_sobject(&self, name: &str) -> Result<Value, String> {
+ if let Some(cached) = self.describe_cache.lock().ok().and_then(|guard| guard.get(name).cloned()) {
+ return Ok(cached);
+ }
+ let url = format!("{}/sobjects/{}/describe", self.api_base(), urlencoded(name));
+ let value = self.api_get(&url).await?;
+ if let Ok(mut guard) = self.describe_cache.lock() {
+ guard.insert(name.to_string(), value.clone());
+ }
+ Ok(value)
+ }
+
+ /// Field metadata for one sObject, mapped onto `ColumnInfo`
+ /// (label → comment, picklist values → enum_values, Id → primary key).
+ pub async fn get_columns(&self, sobject: &str) -> Result<Vec<ColumnInfo>, String> {
+ let describe = self.describe_sobject(sobject).await?;
+ Ok(parse_describe_columns(&describe))
+ }
+
+ /// Connected-user identity + coarse admin flag (spec §3).
+ pub async fn current_user(&self) -> Result<SfUserInfo, String> {
+ let userinfo = self.api_get(&format!("{}/services/oauth2/userinfo", self.instance_url)).await?;
+ let mut info = SfUserInfo {
+ user_id: string_field(&userinfo, "user_id"),
+ name: string_field(&userinfo, "name"),
+ email: string_field(&userinfo, "email"),
+ organization_id: string_field(&userinfo, "organization_id"),
+ ..Default::default()
+ };
+ // Coarse admin detection via Profile permission flags. The user id from
+ // userinfo is a 15/18-char alphanumeric Salesforce id; refuse anything
+ // else instead of interpolating it into SOQL.
+ if !info.user_id.is_empty() && info.user_id.chars().all(|c| c.is_ascii_alphanumeric()) {
+ let soql = format!(
+ "SELECT Username, Profile.Name, Profile.PermissionsModifyAllData FROM User WHERE Id = '{}'",
+ info.user_id
+ );
+ let url = format!("{}/query?q={}", self.api_base(), urlencoded(&soql));
+ if let Ok(value) = self.api_get(&url).await {
+ if let Some(record) = value.get("records").and_then(Value::as_array).and_then(|rows| rows.first()) {
+ info.username = string_field(record, "Username");
+ info.profile_name =
+ record.get("Profile").and_then(|p| p.get("Name")).and_then(Value::as_str).map(str::to_string);
+ info.is_admin =
+ record.get("Profile").and_then(|p| p.get("PermissionsModifyAllData")).and_then(Value::as_bool);
+ }
+ }
+ }
+ Ok(info)
+ }
+
+ /// Cached variant of `current_user()`: returns the resolved identity from
+ /// the in-memory cache when available, falling back to a fresh call on
+ /// the first invocation (or after the cache is cleared). Repeated UI
+ /// polls don't burn Salesforce API quota.
+ pub async fn cached_current_user(&self) -> Result<SfUserInfo, String> {
+ if let Some(cached) = self.current_user_cache.lock().ok().and_then(|guard| guard.clone()) {
+ return Ok(cached);
+ }
+ let info = self.current_user().await?;
+ if let Ok(mut guard) = self.current_user_cache.lock() {
+ *guard = Some(info.clone());
+ }
+ Ok(info)
+ }
+
+ /// Display name of the org for the synthesized single database node
+ /// (`singleDatabase` trait). One cached `SELECT Name FROM Organization`;
+ /// falls back to the instance host's first label (e.g. `acme--qas1`)
+ /// when that query is unavailable. Fallbacks are NOT cached so a transient
+ /// failure does not stick.
+ pub async fn org_display_name(&self) -> String {
+ if let Some(name) = self.org_name_cache.lock().ok().and_then(|guard| guard.clone()) {
+ return name;
+ }
+ let url = format!("{}/query?q={}", self.api_base(), urlencoded("SELECT Name FROM Organization LIMIT 1"));
+ if let Ok(value) = self.api_get(&url).await {
+ let name =
+ value.pointer("/records/0/Name").and_then(Value::as_str).map(str::trim).filter(|name| !name.is_empty());
+ if let Some(name) = name {
+ if let Ok(mut guard) = self.org_name_cache.lock() {
+ *guard = Some(name.to_string());
+ }
+ return name.to_string();
+ }
+ }
+ self.instance_host_fallback_name()
+ }
+
+ fn instance_host_fallback_name(&self) -> String {
+ let host = self.instance_url.split_once("://").map(|(_, rest)| rest).unwrap_or(self.instance_url.as_str());
+ let label = host.split(['/', ':']).next().unwrap_or("");
+ label.split('.').next().filter(|part| !part.is_empty()).unwrap_or("Salesforce").to_string()
+ }
+}
+
+fn normalize_instance_url(raw: &str) -> Result<String, String> {
+ let trimmed = raw.trim().trim_end_matches('/');
+ if trimmed.is_empty() {
+ return Err("Salesforce instance URL is required (e.g. https://acme.my.salesforce.com).".to_string());
+ }
+ if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
+ return Ok(trimmed.to_string());
+ }
+ if trimmed.contains("://") {
+ return Err(format!("Unsupported Salesforce instance URL scheme: {trimmed}"));
+ }
+ Ok(format!("https://{trimmed}"))
+}
+
+fn salesforce_api_version(external_config: Option<&Value>) -> Result<String, String> {
+ let raw = external_config
+ .and_then(|config| config.get("apiVersion"))
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .unwrap_or(SALESFORCE_DEFAULT_API_VERSION);
+ let normalized = if let Some(stripped) = raw.strip_prefix('v') { stripped } else { raw };
+ if normalized.is_empty()
+ || !normalized.split_once('.').is_some_and(|(major, minor)| {
+ !major.is_empty() && major.chars().all(|c| c.is_ascii_digit()) && !minor.is_empty()
+ })
+ {
+ return Err(format!("Invalid Salesforce API version '{raw}' (expected e.g. v62.0)."));
+ }
+ Ok(format!("v{normalized}"))
+}
+
+fn urlencoded(value: &str) -> String {
+ percent_encoding::utf8_percent_encode(value, percent_encoding::NON_ALPHANUMERIC).to_string()
+}
+
+fn string_field(value: &Value, key: &str) -> String {
+ value.get(key).and_then(Value::as_str).unwrap_or("").to_string()
+}
+
+/// Largest `&s[..n]` that ends on a UTF-8 char boundary (`str::floor_char_boundary`
+/// is still unstable).
+fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
+ if s.len() <= max {
+ return s;
+ }
+ let mut end = max;
+ while end > 0 && !s.is_char_boundary(end) {
+ end -= 1;
+ }
+ &s[..end]
+}
+
+/// Parse a `/query` (or QueryLocator page) response into a `QueryResult`.
+///
+/// Column layout: record keys in first-seen order, minus `attributes`.
+/// Nested objects (compound fields like `BillingAddress`) are flattened one
+/// level with dotted names; anything deeper (relationship subqueries, arrays)
+/// is serialized to a JSON string cell so the grid stays tabular.
+fn parse_soql_response(value: Value, elapsed_ms: u128, max_rows: usize) -> QueryResult {
+ let mut columns: Vec<String> = Vec::new();
+ let mut seen: HashMap<String, usize> = HashMap::new();
+ let mut rows: Vec<Vec<Value>> = Vec::new();
+ let mut truncated = false;
+
+ let records = value.get("records").and_then(Value::as_array).cloned().unwrap_or_default();
+ let total_size = value.get("totalSize").and_then(Value::as_u64).unwrap_or(records.len() as u64);
+
+ for record in records.iter() {
+ if rows.len() >= max_rows {
+ truncated = true;
+ break;
+ }
+ let mut cells: Vec<(String, Value)> = Vec::new();
+ flatten_record(record, "", &mut cells, 0);
+ let mut row: Vec<Value> = vec![Value::Null; columns.len()];
+ for (key, cell) in cells {
+ let index = match seen.get(&key) {
+ Some(index) => *index,
+ None => {
+ let index = columns.len();
+ columns.push(key.clone());
+ seen.insert(key.clone(), index);
+ row.push(Value::Null);
+ index
+ }
+ };
+ row[index] = json_value_for_js(cell);
+ }
+ rows.push(row);
+ }
+
+ let column_types = infer_column_types(&columns, &rows);
+ let done = value.get("done").and_then(Value::as_bool).unwrap_or(true);
+ let next_url = value.get("nextRecordsUrl").and_then(Value::as_str).map(str::to_string).filter(|_| !done);
+
+ QueryResult {
+ columns,
+ column_types,
+ column_sortables: Vec::new(),
+ spatial_columns: Vec::new(),
+ spatial_values: Vec::new(),
+ rows,
+ affected_rows: total_size,
+ execution_time_ms: elapsed_ms,
+ server_execute_time_us: None,
+ truncated,
+ session_id: next_url,
+ has_more: !done || truncated,
+ elasticsearch_raw_body: None,
+ messages: Vec::new(),
+ }
+}
+
+fn flatten_record(value: &Value, prefix: &str, out: &mut Vec<(String, Value)>, depth: u8) {
+ let Some(map) = value.as_object() else {
+ out.push((prefix.to_string(), value.clone()));
+ return;
+ };
+ // A nested query locator / subquery result — keep it as a JSON string.
+ if map.contains_key("records") || depth >= 2 {
+ let encoded = serde_json::to_string(value).unwrap_or_default();
+ let cell = if encoded.len() > SALESFORCE_MAX_NESTED_JSON_CHARS {
+ let cut = truncate_at_char_boundary(&encoded, SALESFORCE_MAX_NESTED_JSON_CHARS);
+ Value::String(format!("{cut}…(truncated)"))
+ } else {
+ Value::String(encoded)
+ };
+ out.push((prefix.to_string(), cell));
+ return;
+ }
+ for (key, child) in map {
+ if key == "attributes" && prefix.is_empty() {
+ continue;
+ }
+ let path = if prefix.is_empty() { key.clone() } else { format!("{prefix}.{key}") };
+ match child {
+ // Recurse for every object so the rule above decides the shape: a
+ // compound field flattens (BillingAddress.city) while a subquery
+ // locator — or anything already two levels deep — stays one JSON
+ // string cell.
+ Value::Object(_) => flatten_record(child, &path, out, depth + 1),
+ _ => out.push((path, child.clone())),
+ }
+ }
+}
+
+fn infer_column_types(columns: &[String], rows: &[Vec<Value>]) -> Vec<String> {
+ columns
+ .iter()
+ .enumerate()
+ .map(|(index, _)| {
+ for row in rows {
+ if let Some(cell) = row.get(index) {
+ match cell {
+ Value::Null => continue,
+ Value::Bool(_) => return "boolean".to_string(),
+ Value::Number(_) => return "double".to_string(),
+ Value::String(_) => return "string".to_string(),
+ _ => return "json".to_string(),
+ }
+ }
+ }
+ String::new()
+ })
+ .collect()
+}
+
+fn parse_sobject_list(value: &Value) -> Vec<SfSObjectEntry> {
+ value
+ .get("sobjects")
+ .and_then(Value::as_array)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(|entry| {
+ let name = string_field(entry, "name");
+ if name.is_empty() {
+ return None;
+ }
+ Some(SfSObjectEntry {
+ label: string_field(entry, "label"),
+ custom: entry.get("custom").and_then(Value::as_bool).unwrap_or(false),
+ queryable: entry.get("queryable").and_then(Value::as_bool).unwrap_or(false),
+ name,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Whether a describe field entry can be named in a SOQL `SELECT` list.
+///
+/// Two kinds of describe entry cannot, and Salesforce rejects the *whole* query
+/// for either one:
+///
+/// * Compound `address` / `location` fields (`BillingAddress`, `Location__c`) are
+/// metadata containers. SOQL projects their sub-fields instead — `BillingStreet`,
+/// `BillingLatitude`, … — which describe already returns as separate entries, so
+/// flattening to the sub-fields (spec §7) loses nothing.
+/// * Fields the running user has no FLS read access to (`accessible: false`) are
+/// invisible to SOQL, which answers `INVALID_FIELD`. `FIELDS(ALL)` skips them for
+/// the same reason, so an explicit projection has to match. A missing flag means
+/// the org did not report FLS at all: keep the field.
+fn is_soql_projectable_field(field: &Value) -> bool {
+ let field_type = string_field(field, "type").to_ascii_lowercase();
+ if matches!(field_type.as_str(), "address" | "location") {
+ return false;
+ }
+ field.get("accessible").and_then(Value::as_bool).unwrap_or(true)
+}
+
+fn parse_describe_columns(describe: &Value) -> Vec<ColumnInfo> {
+ describe
+ .get("fields")
+ .and_then(Value::as_array)
+ .map(|fields| {
+ fields
+ .iter()
+ // This list feeds the data grid's explicit SOQL projection and the
+ // editor's field completion, so a name SOQL cannot project must not
+ // appear: one bad field fails the whole query rather than one column.
+ .filter(|field| is_soql_projectable_field(field))
+ .map(|field| {
+ let name = string_field(field, "name");
+ let label = string_field(field, "label");
+ let data_type = string_field(field, "type");
+ let picklist_values = field
+ .get("picklistValues")
+ .and_then(Value::as_array)
+ .map(|values| {
+ values
+ .iter()
+ .filter(|value| value.get("active").and_then(Value::as_bool).unwrap_or(true))
+ .map(|value| string_field(value, "value"))
+ .filter(|value| !value.is_empty())
+ .collect::<Vec<_>>()
+ })
+ .filter(|values: &Vec<String>| !values.is_empty());
+ let length = field.get("length").and_then(Value::as_i64).filter(|length| *length > 0);
+ let mut extra = serde_json::json!({
+ "updateable": field.get("updateable").and_then(Value::as_bool).unwrap_or(false),
+ "createable": field.get("createable").and_then(Value::as_bool).unwrap_or(false),
+ "custom": field.get("custom").and_then(Value::as_bool).unwrap_or(false),
+ "label": label,
+ });
+ if let Some(rel_name) = field.get("relationshipName").and_then(Value::as_str) {
+ if !rel_name.is_empty() {
+ extra["relationshipName"] = serde_json::json!(rel_name);
+ }
+ }
+ if let Some(refs) = field.get("referenceTo").and_then(Value::as_array) {
+ let ref_strings: Vec<String> =
+ refs.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(String::from).collect();
+ if !ref_strings.is_empty() {
+ extra["referenceTo"] = serde_json::json!(ref_strings);
+ }
+ }
+ ColumnInfo {
+ is_primary_key: name.eq_ignore_ascii_case("Id"),
+ is_nullable: field.get("nillable").and_then(Value::as_bool).unwrap_or(true),
+ column_default: field.get("defaultValue").filter(|value| !value.is_null()).map(|value| {
+ match value {
+ Value::String(text) => text.clone(),
+ other => other.to_string(),
+ }
+ }),
+ is_unique: false,
+ // describe flags the grid/DML layer needs later (M4):
+ // formula/rollup/auto-number fields come back with
+ // updateable=false and must render read-only.
+ extra: Some(extra.to_string()),
+ comment: if label.is_empty() || label == name { None } else { Some(label) },
+ numeric_precision: field
+ .get("precision")
+ .and_then(Value::as_i64)
+ .and_then(|p| i32::try_from(p).ok())
+ .filter(|p| *p > 0),
+ numeric_scale: field
+ .get("scale")
+ .and_then(Value::as_i64)
+ .and_then(|s| i32::try_from(s).ok())
+ .filter(|s| *s > 0),
+ character_maximum_length: length.and_then(|l| i32::try_from(l).ok()),
+ enum_values: picklist_values,
+ resolved_schema: None,
+ // Plugin-provided column metadata capabilities do not apply:
+ // the describe payload is parsed here, not by a plugin driver.
+ metadata_capabilities: None,
+ character_set: None,
+ collation: None,
+ name,
+ data_type,
+ }
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// SOQL's `FIELDS(ALL)` / `FIELDS(STANDARD)` / `FIELDS(CUSTOM)` selectors require the
+/// query to carry `LIMIT n` with n ≤ 200 (a Salesforce REST rule). Users writing
+/// `SELECT FIELDS(ALL) FROM Account` hit `MALFORMED_QUERY` otherwise. When the query
+/// uses a FIELDS function and has no LIMIT clause yet, append `LIMIT 200` so the common
+/// "select everything" intent just works. If a LIMIT is already present we never touch
+/// it (Salesforce's own error explains a too-large limit better than we could).
+///
+/// Detection is a lightweight case-insensitive scan; it intentionally skips content
+/// inside single-quoted string literals so a `WHERE Name = 'LIMIT'` does not suppress
+/// the append, and so `FIELDS(ALL)` inside a literal does not trigger it.
+fn apply_fields_function_limit(soql: &str) -> std::borrow::Cow<'_, str> {
+ fn scan(outside_literals: &str) -> (bool, bool) {
+ let upper = outside_literals.to_ascii_uppercase();
+ // Compact away whitespace so both `FIELDS(ALL)` and `FIELDS ( ALL )` match.
+ let compact: String = upper.chars().filter(|c| !c.is_whitespace()).collect();
+ let has_fields = ["FIELDS(ALL)", "FIELDS(STANDARD)", "FIELDS(CUSTOM)"].iter().any(|n| compact.contains(n));
+ // Word-boundary LIMIT search on the original (spacing-preserving) masked text.
+ let bytes = upper.as_bytes();
+ let mut has_limit = false;
+ for (i, _) in upper.match_indices("LIMIT") {
+ let before_ok = i == 0 || (!bytes[i - 1].is_ascii_alphanumeric() && bytes[i - 1] != b'_');
+ let after = i + "LIMIT".len();
+ let after_ok = after >= bytes.len() || (!bytes[after].is_ascii_alphanumeric() && bytes[after] != b'_');
+ if before_ok && after_ok {
+ has_limit = true;
+ break;
+ }
+ }
+ (has_fields, has_limit)
+ }
+
+ // Build a copy of the query with single-quoted literal bodies blanked out, so the
+ // keyword scan ignores them. SOQL escapes a quote inside a literal by backslash.
+ let mut masked = String::with_capacity(soql.len());
+ let chars: Vec<char> = soql.chars().collect();
+ let mut i = 0;
+ let mut in_literal = false;
+ while i < chars.len() {
+ let c = chars[i];
+ if in_literal {
+ if c == '\\' {
+ masked.push(' ');
+ if i + 1 < chars.len() {
+ masked.push(' ');
+ }
+ i += 2;
+ continue;
+ }
+ if c == '\'' {
+ in_literal = false;
+ masked.push(' ');
+ } else {
+ masked.push(' ');
+ }
+ i += 1;
+ continue;
+ }
+ if c == '\'' {
+ in_literal = true;
+ masked.push(' ');
+ i += 1;
+ continue;
+ }
+ masked.push(c);
+ i += 1;
+ }
+
+ let (has_fields, has_limit) = scan(&masked);
+ if !has_fields || has_limit {
+ return std::borrow::Cow::Borrowed(soql);
+ }
+ let trimmed = soql.trim_end_matches(|c: char| c.is_whitespace() || c == ';');
+ std::borrow::Cow::Owned(format!("{trimmed} LIMIT 200"))
+}
+
+fn map_salesforce_error(status: StatusCode, body: &str) -> String {
+ let mut message = format!("Salesforce API error (HTTP {status})");
+ if !body.is_empty() {
+ message.push_str(": ");
+ message.push_str(body);
+ }
+ message
+}
+
+/// Turn a Salesforce REST error body (`[{errorCode, message, fields}]`) into a
+/// user-readable message with the common codes explained (spec §7).
+fn salesforce_error_message(status: StatusCode, body: &Value) -> String {
+ let first = body.as_array().and_then(|entries| entries.first());
+ let entry = first.unwrap_or(body);
+ let code = entry.get("errorCode").and_then(Value::as_str).unwrap_or("");
+ let message = entry.get("message").and_then(Value::as_str).unwrap_or("");
+ let hint = match code {
+ "INVALID_SESSION_ID" | "INVALID_AUTH_HEADER" => {
+ Some("Access token is invalid or expired — reconnect or paste a fresh token.")
+ }
+ "MALFORMED_QUERY" => {
+ if message.contains("FIELDS function must have a LIMIT") {
+ Some("FIELDS(ALL/STANDARD/CUSTOM) requires LIMIT 200 or less — lower the explicit LIMIT value (DBX auto-appends LIMIT 200 only when the query has no LIMIT at all).")
+ } else {
+ Some("SOQL syntax error — check the query near the position Salesforce reports.")
+ }
+ }
+ "INVALID_FIELD" | "INVALID_TYPE" | "INVALID_COLUMN" => {
+ Some("Unknown object/field, or it is not visible to your user (field-level security).")
+ }
+ "INSUFFICIENT_ACCESS" | "INSUFFICIENT_ACCESS_OR_READONLY" => {
+ Some("Your Salesforce user lacks access to this operation.")
+ }
+ "REQUEST_LIMIT_EXCEEDED" | "TOTAL_API_REQUESTS_LIMIT_EXCEEDED" => Some(
+ "Salesforce daily API request limit exhausted for this org — this is a Salesforce-side quota, not a DBX limit.",
+ ),
+ "NOT_MODIFIED" => None,
+ _ => None,
+ };
+ let mut result = if status == StatusCode::UNAUTHORIZED && code.is_empty() {
+ "Salesforce authentication failed (HTTP 401): access token is invalid or expired.".to_string()
+ } else if code.is_empty() && message.is_empty() {
+ map_salesforce_error(status, "")
+ } else {
+ format!("Salesforce error [{code}]: {message}")
+ };
+ if let Some(hint) = hint {
+ result.push_str("\n\nHint: ");
+ result.push_str(hint);
+ }
+ result
+}
+
+// ---------------------------------------------------------------------------
+// DBX SALESFORCE DML pseudo-command (spec §8)
+// ---------------------------------------------------------------------------
+
+/// Pseudo-command header the grid save path emits. Case-insensitive after
+/// trim; everything after it (trimmed) is one JSON object.
+const SALESFORCE_DML_HEADER: &str = "DBX SALESFORCE DML";
+
+/// DML operation parsed from the JSON body's `op` field.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SfDmlOp {
+ Insert,
+ Update,
+ Delete,
+}
+
+impl SfDmlOp {
+ /// Lowercase wire name, as it appears in the statement's `op` field. Public
+ /// so callers that render a statement back to a human (MCP write
+ /// confirmations) cannot drift from what the parser accepts.
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::Insert => "insert",
+ Self::Update => "update",
+ Self::Delete => "delete",
+ }
+ }
+}
+
+/// Parsed `DBX SALESFORCE DML` statement ready for execution.
+#[derive(Debug, Clone)]
+pub struct SfDmlStatement {
+ pub op: SfDmlOp,
+ pub object: String,
+ /// Required for `update`/`delete`; ignored for `insert`.
+ pub id: Option<String>,
+ /// Field API name → JSON value. Required and non-empty for `insert`/
+ /// `update`; absent for `delete`.
+ pub fields: Option<serde_json::Map<String, Value>>,
+}
+
+/// True when the source's first non-empty trimmed line begins with
+/// `DBX SALESFORCE` (case-insensitive). Used by `execute_query` to route
+/// pseudo-commands away from the SOQL path without eagerly parsing the JSON
+/// body — a non-DBX SOQL query never reaches this check.
+fn starts_with_salesforce_header(source: &str) -> bool {
+ let header = source.lines().find(|line| !line.trim().is_empty()).map(str::trim).unwrap_or("");
+ header.to_ascii_uppercase().starts_with("DBX SALESFORCE")
+}
+
+/// Parse a `DBX SALESFORCE DML` statement from its textual form.
+///
+/// Shape (header line + JSON body, DynamoDB-precedent):
+/// ```text
+/// DBX SALESFORCE DML
+/// {"op":"update","object":"Account","id":"001xx…","fields":{"Name":"Acme"}}
+/// ```
+///
+/// The header is compared case-insensitively after trim; the remainder is
+/// trimmed and parsed as one JSON object. Unknown `DBX SALESFORCE …` headers,
+/// malformed JSON, unknown ops, and missing required fields all produce
+/// `Err(String)` — never a panic.
+pub fn parse_salesforce_statement(source: &str) -> Result<SfDmlStatement, String> {
+ let trimmed = source.trim();
+ if trimmed.is_empty() {
+ return Err("Salesforce statement is empty.".to_string());
+ }
+ let (header, rest) = match trimmed.split_once('\n') {
+ Some((h, r)) => (h.trim(), r),
+ None => (trimmed, ""),
+ };
+ if !header.eq_ignore_ascii_case(SALESFORCE_DML_HEADER) {
+ return Err(
+ "Unsupported DBX SALESFORCE statement. Use DBX SALESFORCE DML with a JSON body (op, object, id, fields)."
+ .to_string(),
+ );
+ }
+ let body = rest.trim();
+ if body.is_empty() {
+ return Err("DBX SALESFORCE DML statement is missing its JSON body.".to_string());
+ }
+ let json: Value =
+ serde_json::from_str(body).map_err(|error| format!("Invalid DBX SALESFORCE DML JSON body: {error}"))?;
+ let obj = json.as_object().ok_or_else(|| "DBX SALESFORCE DML body must be a JSON object.".to_string())?;
+
+ let op_str = obj
+ .get("op")
+ .and_then(Value::as_str)
+ .ok_or_else(|| "DBX SALESFORCE DML body requires an 'op' field (insert | update | delete).".to_string())?;
+ let op = match op_str {
+ "insert" => SfDmlOp::Insert,
+ "update" => SfDmlOp::Update,
+ "delete" => SfDmlOp::Delete,
+ _ => return Err(format!("Unknown DBX SALESFORCE DML op: '{op_str}'. Expected insert, update, or delete.")),
+ };
+
+ let object = obj
+ .get("object")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| "DBX SALESFORCE DML body requires a non-empty 'object' field.".to_string())?
+ .to_string();
+
+ let id = obj.get("id").and_then(Value::as_str).map(str::to_string);
+
+ match op {
+ SfDmlOp::Update | SfDmlOp::Delete => {
+ if id.as_deref().unwrap_or("").is_empty() {
+ return Err(format!("DBX SALESFORCE DML {} requires a non-empty 'id' field.", op.as_str()));
+ }
+ }
+ SfDmlOp::Insert => {}
+ }
+
+ let fields = obj.get("fields").and_then(Value::as_object).cloned();
+ match op {
+ SfDmlOp::Insert | SfDmlOp::Update => {
+ if fields.as_ref().is_none_or(|map| map.is_empty()) {
+ return Err(format!("DBX SALESFORCE DML {} requires a non-empty 'fields' object.", op.as_str()));
+ }
+ }
+ SfDmlOp::Delete => {}
+ }
+
+ Ok(SfDmlStatement { op, object, id, fields })
+}
+
+impl SfClient {
+ /// Execute a parsed `DBX SALESFORCE DML` statement against the REST API.
+ ///
+ /// - `insert` → `POST {apiBase}/sobjects/{object}` (body = fields)
+ /// - `update` → `PATCH {apiBase}/sobjects/{object}/{id}` (body = fields)
+ /// - `delete` → `DELETE {apiBase}/sobjects/{object}/{id}` (no body)
+ ///
+ /// Insert returns the new Id in the result rows; update/delete return
+ /// `affected_rows = 1` with no rows. Errors are prefixed with the
+ /// operation context so a failed row is identifiable in a batch.
+ async fn execute_dml(&self, statement: &SfDmlStatement) -> Result<QueryResult, String> {
+ let started = Instant::now();
+ let api_base = self.api_base();
+ let context = match statement.op {
+ SfDmlOp::Insert => format!("insert on {}", statement.object),
+ SfDmlOp::Update => format!("update on {} (Id {})", statement.object, statement.id.as_deref().unwrap_or("")),
+ SfDmlOp::Delete => format!("delete on {} (Id {})", statement.object, statement.id.as_deref().unwrap_or("")),
+ };
+
+ match statement.op {
+ SfDmlOp::Insert => {
+ let url = format!("{api_base}/sobjects/{}", urlencoded(&statement.object));
+ let body = Value::Object(statement.fields.clone().unwrap_or_default());
+ let value =
+ self.api_post(&url, body).await.map_err(|error| format!("Salesforce {context} failed: {error}"))?;
+ let success = value.get("success").and_then(Value::as_bool).unwrap_or(false);
+ if !success {
+ let errors = value.get("errors").cloned().unwrap_or(Value::Null);
+ let detail = if errors.is_null() {
+ "Salesforce reported success=false without error details.".to_string()
+ } else {
+ format!("{errors}")
+ };
+ return Err(format!("Salesforce {context} failed: {detail}"));
+ }
+ let new_id = value.get("id").and_then(Value::as_str).unwrap_or("").to_string();
+ Ok(QueryResult {
+ columns: vec!["Id".to_string()],
+ column_types: vec!["String".to_string()],
+ column_sortables: vec![false],
+ spatial_columns: Vec::new(),
+ spatial_values: Vec::new(),
+ rows: vec![vec![Value::String(new_id)]],
+ affected_rows: 1,
+ execution_time_ms: started.elapsed().as_millis(),
+ server_execute_time_us: None,
+ truncated: false,
+ session_id: None,
+ has_more: false,
+ elasticsearch_raw_body: None,
+ messages: Vec::new(),
+ })
+ }
+ SfDmlOp::Update => {
+ let id = statement.id.as_deref().unwrap_or("");
+ let url = format!("{api_base}/sobjects/{}/{}", urlencoded(&statement.object), urlencoded(id));
+ let body = Value::Object(statement.fields.clone().unwrap_or_default());
+ self.api_patch(&url, body).await.map_err(|error| format!("Salesforce {context} failed: {error}"))?;
+ Ok(salesforce_affected_query_result(1, started))
+ }
+ SfDmlOp::Delete => {
+ let id = statement.id.as_deref().unwrap_or("");
+ let url = format!("{api_base}/sobjects/{}/{}", urlencoded(&statement.object), urlencoded(id));
+ self.api_delete(&url).await.map_err(|error| format!("Salesforce {context} failed: {error}"))?;
+ Ok(salesforce_affected_query_result(1, started))
+ }
+ }
+ }
+}
+
+fn salesforce_affected_query_result(affected_rows: u64, started: Instant) -> QueryResult {
+ QueryResult {
+ columns: Vec::new(),
+ column_types: Vec::new(),
+ column_sortables: Vec::new(),
+ spatial_columns: Vec::new(),
+ spatial_values: Vec::new(),
+ rows: Vec::new(),
+ affected_rows,
+ execution_time_ms: started.elapsed().as_millis(),
+ server_execute_time_us: None,
+ truncated: false,
+ session_id: None,
+ has_more: false,
+ elasticsearch_raw_body: None,
+ messages: Vec::new(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_instance_url_defaults_to_https_and_strips_slash() {
+ assert_eq!(normalize_instance_url("acme.my.salesforce.com/").unwrap(), "https://acme.my.salesforce.com");
+ assert_eq!(normalize_instance_url("https://login.salesforce.com").unwrap(), "https://login.salesforce.com");
+ assert!(normalize_instance_url("ftp://x").is_err());
+ assert!(normalize_instance_url(" ").is_err());
+ }
+
+ #[test]
+ fn org_name_fallback_uses_first_host_label() {
+ let client = SfClient::from_config(
+ "https://acme--qas1.sandbox.my.salesforce.com",
+ Some("tok"),
+ None,
+ Duration::from_secs(5),
+ )
+ .unwrap();
+ assert_eq!(client.instance_host_fallback_name(), "acme--qas1");
+ let plain = SfClient::from_config("na1.salesforce.com", Some("tok"), None, Duration::from_secs(5)).unwrap();
+ assert_eq!(plain.instance_host_fallback_name(), "na1");
+ }
+
+ #[test]
+ fn api_version_validation() {
+ assert_eq!(salesforce_api_version(None).unwrap(), SALESFORCE_DEFAULT_API_VERSION);
+ let config = serde_json::json!({ "apiVersion": "61.0" });
+ assert_eq!(salesforce_api_version(Some(&config)).unwrap(), "v61.0");
+ let bad = serde_json::json!({ "apiVersion": "abc" });
+ assert!(salesforce_api_version(Some(&bad)).is_err());
+ }
+
+ #[test]
+ fn parse_soql_response_maps_rows_and_pagination() {
+ let body = serde_json::json!({
+ "totalSize": 3,
+ "done": false,
+ "nextRecordsUrl": "/services/data/v62.0/query/01gxx00000-2000",
+ "records": [
+ {"attributes": {"type": "Account"}, "Id": "001x1", "Name": "Acme", "BillingAddress": {"city": "SF", "street": "Market St"}},
+ {"attributes": {"type": "Account"}, "Id": "001x2", "Name": "Globex", "AnnualRevenue": 12345.67}
+ ]
+ });
+ let result = parse_soql_response(body, 12, SALESFORCE_MAX_ROWS_PER_BATCH);
+ assert_eq!(result.columns, vec!["Id", "Name", "BillingAddress.city", "BillingAddress.street", "AnnualRevenue"]);
+ assert_eq!(result.rows.len(), 2);
+ assert_eq!(result.rows[0][2], serde_json::json!("SF"));
+ assert_eq!(result.rows[1][4], serde_json::json!(12345.67));
+ assert!(result.has_more);
+ assert_eq!(result.session_id.as_deref(), Some("/services/data/v62.0/query/01gxx00000-2000"));
+ assert_eq!(result.column_types[4], "double");
+ assert!(!result.truncated);
+ }
+
+ #[test]
+ fn parse_soql_response_truncates_at_max_rows() {
+ let records: Vec<Value> = (0..5).map(|i| serde_json::json!({"Id": format!("001{i}")})).collect();
+ let body = serde_json::json!({ "totalSize": 5, "done": true, "records": records });
+ let result = parse_soql_response(body, 1, 3);
+ assert_eq!(result.rows.len(), 3);
+ assert!(result.truncated);
+ assert!(result.has_more);
+ }
+
+ #[test]
+ fn parse_soql_response_keeps_subqueries_as_json_strings() {
+ let body = serde_json::json!({
+ "totalSize": 1,
+ "done": true,
+ "records": [{
+ "attributes": {"type": "Account"},
+ "Id": "001x1",
+ "Contacts": {"totalSize": 1, "done": true, "records": [{"Id": "003x1", "Name": "Ann"}]}
+ }]
+ });
+ let result = parse_soql_response(body, 1, 100);
+ assert_eq!(result.columns, vec!["Id", "Contacts"]);
+ let cell = result.rows[0][1].as_str().unwrap();
+ assert!(cell.contains("003x1"));
+ }
+
+ #[test]
+ fn describe_columns_map_picklists_and_flags() {
+ let describe = serde_json::json!({
+ "fields": [
+ {"name": "Id", "label": "Record ID", "type": "id", "nillable": false, "updateable": false, "createable": false, "length": 18},
+ {"name": "StageName", "label": "Stage", "type": "picklist", "nillable": false, "updateable": true, "createable": true,
+ "picklistValues": [{"value": "Prospecting", "active": true}, {"value": "Closed", "active": true}, {"value": "Old", "active": false}]},
+ {"name": "Amount", "label": "Amount", "type": "currency", "nillable": true, "updateable": true, "createable": true, "precision": 18, "scale": 2}
+ ]
+ });
+ let columns = parse_describe_columns(&describe);
+ assert_eq!(columns.len(), 3);
+ assert!(columns[0].is_primary_key);
+ assert_eq!(columns[1].enum_values.as_ref().unwrap(), &vec!["Prospecting".to_string(), "Closed".to_string()]);
+ assert_eq!(columns[1].comment.as_deref(), Some("Stage"));
+ assert_eq!(columns[2].numeric_precision, Some(18));
+ assert_eq!(columns[2].numeric_scale, Some(2));
+ let extra: Value = serde_json::from_str(columns[1].extra.as_ref().unwrap()).unwrap();
+ assert_eq!(extra["updateable"], serde_json::json!(true));
+ }
+
+ #[test]
+ fn describe_columns_omit_fields_soql_cannot_project() {
+ // The grid projects describe fields by name, and SOQL fails the whole query
+ // on a field it cannot select. Compound address/location fields and
+ // FLS-hidden fields are both invisible to a SELECT list; their sub-fields
+ // (`BillingStreet`, …) arrive as separate describe entries and are kept.
+ let describe = serde_json::json!({
+ "fields": [
+ {"name": "Id", "type": "id", "accessible": true},
+ {"name": "BillingAddress", "type": "address", "accessible": true},
+ {"name": "BillingStreet", "type": "textarea", "compoundFieldName": "BillingAddress", "accessible": true},
+ {"name": "Site", "type": "location", "accessible": true},
+ {"name": "Secret__c", "type": "string", "accessible": false},
+ // No `accessible` flag at all: the org did not report FLS, keep it.
+ {"name": "Legacy__c", "type": "string"}
+ ]
+ });
+ let names: Vec<String> = parse_describe_columns(&describe).iter().map(|column| column.name.clone()).collect();
+ assert_eq!(names, vec!["Id", "BillingStreet", "Legacy__c"]);
+ }
+
+ #[test]
+ fn describe_columns_extra_has_label_relationship_and_reference() {
+ let describe = serde_json::json!({
+ "fields": [
+ {
+ "name": "StageName",
+ "label": "Stage",
+ "type": "picklist",
+ "nillable": false,
+ "updateable": true,
+ "createable": true,
+ "picklistValues": [
+ {"value": "Prospecting", "active": true},
+ {"value": "Closed", "active": true},
+ {"value": "Old", "active": false}
+ ]
+ },
+ {
+ "name": "OwnerId",
+ "label": "Owner ID",
+ "type": "reference",
+ "nillable": false,
+ "updateable": true,
+ "createable": true,
+ "relationshipName": "Owner",
+ "referenceTo": ["User"]
+ },
+ {
+ "name": "Name",
+ "label": "Account Name",
+ "type": "string",
+ "nillable": false,
+ "updateable": true,
+ "createable": true,
+ "length": 255
+ }
+ ]
+ });
+ let columns = parse_describe_columns(&describe);
+ assert_eq!(columns.len(), 3);
+
+ // (a) picklist: enum_values only includes active values; extra has label
+ let picklist_extra: Value = serde_json::from_str(columns[0].extra.as_ref().unwrap()).unwrap();
+ assert_eq!(picklist_extra["label"], serde_json::json!("Stage"));
+ assert_eq!(picklist_extra["updateable"], serde_json::json!(true));
+ assert!(picklist_extra.get("relationshipName").is_none());
+ assert!(picklist_extra.get("referenceTo").is_none());
+ assert_eq!(columns[0].enum_values.as_ref().unwrap(), &vec!["Prospecting".to_string(), "Closed".to_string()]);
+
+ // (b) reference: relationshipName and referenceTo present in extra
+ let ref_extra: Value = serde_json::from_str(columns[1].extra.as_ref().unwrap()).unwrap();
+ assert_eq!(ref_extra["label"], serde_json::json!("Owner ID"));
+ assert_eq!(ref_extra["relationshipName"], serde_json::json!("Owner"));
+ assert_eq!(ref_extra["referenceTo"], serde_json::json!(["User"]));
+ assert!(columns[1].enum_values.is_none());
+
+ // (c) plain string: label present, no relationship/reference
+ let str_extra: Value = serde_json::from_str(columns[2].extra.as_ref().unwrap()).unwrap();
+ assert_eq!(str_extra["label"], serde_json::json!("Account Name"));
+ assert!(str_extra.get("relationshipName").is_none());
+ assert!(str_extra.get("referenceTo").is_none());
+ }
+
+ #[test]
+ fn describe_columns_reference_empty_array_omitted() {
+ let describe = serde_json::json!({
+ "fields": [{
+ "name": "LookupId",
+ "label": "Lookup",
+ "type": "reference",
+ "nillable": true,
+ "referenceTo": [],
+ "relationshipName": null
+ }]
+ });
+ let columns = parse_describe_columns(&describe);
+ assert_eq!(columns.len(), 1);
+ let extra: Value = serde_json::from_str(columns[0].extra.as_ref().unwrap()).unwrap();
+ assert!(extra.get("referenceTo").is_none(), "empty referenceTo must be omitted");
+ assert!(extra.get("relationshipName").is_none(), "null relationshipName must be omitted");
+ }
+
+ #[test]
+ fn error_message_hints_known_codes() {
+ let body = serde_json::json!([{ "errorCode": "MALFORMED_QUERY", "message": "unexpected token: FROMM" }]);
+ let message = salesforce_error_message(StatusCode::BAD_REQUEST, &body);
+ assert!(message.contains("MALFORMED_QUERY"));
+ assert!(message.contains("SOQL syntax error"));
+ }
+
+ #[test]
+ fn error_message_hints_fields_limit_rule() {
+ let body = serde_json::json!([{
+ "errorCode": "MALFORMED_QUERY",
+ "message": "The SOQL FIELDS function must have a LIMIT of at most 200"
+ }]);
+ let message = salesforce_error_message(StatusCode::BAD_REQUEST, &body);
+ assert!(message.contains("requires LIMIT 200 or less"));
+ }
+
+ #[test]
+ fn fields_function_appends_limit_when_missing() {
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account"),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 200"
+ );
+ assert_eq!(
+ apply_fields_function_limit("select fields(standard) from Contact"),
+ "select fields(standard) from Contact LIMIT 200"
+ );
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS ( CUSTOM ) FROM Account"),
+ "SELECT FIELDS ( CUSTOM ) FROM Account LIMIT 200"
+ );
+ // Trailing semicolon/whitespace is trimmed before appending.
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account; "),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 200"
+ );
+ }
+
+ #[test]
+ fn fields_function_keeps_existing_limit_untouched() {
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account LIMIT 5"),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 5"
+ );
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account LIMIT 5000"),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 5000"
+ );
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account limit 10"),
+ "SELECT FIELDS(ALL) FROM Account limit 10"
+ );
+ }
+
+ #[test]
+ fn non_fields_queries_are_untouched() {
+ assert_eq!(apply_fields_function_limit("SELECT Id, Name FROM Account"), "SELECT Id, Name FROM Account");
+ // `LIMIT` inside a string literal must not suppress the append.
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account WHERE Name = 'LIMIT'"),
+ "SELECT FIELDS(ALL) FROM Account WHERE Name = 'LIMIT' LIMIT 200"
+ );
+ // `FIELDS(ALL)` inside a string literal must not trigger the append.
+ assert_eq!(
+ apply_fields_function_limit("SELECT Id FROM Account WHERE Name = 'FIELDS(ALL)'"),
+ "SELECT Id FROM Account WHERE Name = 'FIELDS(ALL)'"
+ );
+ // A word containing LIMIT (e.g. a custom field) is not a LIMIT clause.
+ assert_eq!(
+ apply_fields_function_limit("SELECT FIELDS(ALL) FROM Account ORDER BY LIMIT__c"),
+ "SELECT FIELDS(ALL) FROM Account ORDER BY LIMIT__c LIMIT 200"
+ );
+ }
+
+ #[test]
+ fn from_config_requires_token_and_valid_version() {
+ assert!(SfClient::from_config("acme.my.salesforce.com", None, None, Duration::from_secs(5)).is_err());
+ let bad_version = serde_json::json!({ "apiVersion": "nope" });
+ assert!(SfClient::from_config(
+ "acme.my.salesforce.com",
+ Some("tok"),
+ Some(&bad_version),
+ Duration::from_secs(5)
+ )
+ .is_err());
+ let client =
+ SfClient::from_config("acme.my.salesforce.com", Some("tok"), None, Duration::from_secs(5)).unwrap();
+ assert_eq!(client.instance_url(), "https://acme.my.salesforce.com");
+ assert_eq!(client.api_base(), "https://acme.my.salesforce.com/services/data/v62.0");
+ }
+
+ #[test]
+ fn query_cursors_resolve_only_against_the_connected_org() {
+ let client =
+ SfClient::from_config("acme--qas1.sandbox.my.salesforce.com", Some("tok"), None, Duration::from_secs(5))
+ .unwrap();
+
+ // Relative cursors (and Salesforce's own absolute nextRecordsUrl) resolve as before.
+ assert_eq!(
+ client.resolve_cursor_url("/services/data/v62.0/query/01g-2000").unwrap(),
+ "https://acme--qas1.sandbox.my.salesforce.com/services/data/v62.0/query/01g-2000"
+ );
+ assert_eq!(
+ client
+ .resolve_cursor_url("https://acme--qas1.sandbox.my.salesforce.com/services/data/v62.0/query/01g-2000")
+ .unwrap(),
+ "https://acme--qas1.sandbox.my.salesforce.com/services/data/v62.0/query/01g-2000"
+ );
+ // Host casing and the explicit default port are still the same origin.
+ assert_eq!(
+ client
+ .resolve_cursor_url(
+ "https://ACME--qas1.sandbox.my.salesforce.com:443/services/data/v62.0/query/01g-2000"
+ )
+ .unwrap(),
+ "https://ACME--qas1.sandbox.my.salesforce.com:443/services/data/v62.0/query/01g-2000"
+ );
+
+ // A cursor pointing anywhere else would carry the bearer token with it.
+ let foreign = client.resolve_cursor_url("https://collector.example.com/records");
+ assert!(foreign.is_err(), "foreign-origin cursor must be refused");
+ assert!(foreign.unwrap_err().contains("outside the connected org"));
+ // Plain HTTP is never the same origin as the HTTPS instance URL.
+ assert!(client
+ .resolve_cursor_url("http://acme--qas1.sandbox.my.salesforce.com/services/data/v62.0/query/01g-2000")
+ .is_err());
+ // A same-host cursor on a different port is a different origin.
+ assert!(client.resolve_cursor_url("https://acme--qas1.sandbox.my.salesforce.com:8443/query/01g-2000").is_err());
+ }
+
+ #[test]
+ fn from_config_accepts_empty_token_when_oauth_refresh_is_configured() {
+ let oauth_config = serde_json::json!({
+ "apiVersion": "v62.0",
+ "auth": {
+ "environment": "sandbox",
+ "clientId": "3MVG9xxx",
+ "refreshToken": "refresh-abc"
+ }
+ });
+ // empty access token + refresh context is allowed (first request refreshes)
+ let client = SfClient::from_config(
+ "acme--qas1.sandbox.my.salesforce.com",
+ Some(""),
+ Some(&oauth_config),
+ Duration::from_secs(5),
+ )
+ .unwrap();
+ assert!(client.has_refresh_token());
+ assert_eq!(client.current_token(), "");
+ // debug output must never leak token material
+ let debug = format!("{client:?}");
+ assert!(!debug.contains("refresh-abc"));
+ assert!(!debug.contains("3MVG9xxx"));
+ assert!(debug.contains("<redacted>"));
+ // token-only connections have no refresh context
+ let manual =
+ SfClient::from_config("acme.my.salesforce.com", Some("tok"), None, Duration::from_secs(5)).unwrap();
+ assert!(!manual.has_refresh_token());
+ // auth block without refreshToken keeps the strict token requirement
+ let incomplete = serde_json::json!({ "auth": { "clientId": "x" } });
+ assert!(
+ SfClient::from_config("acme.my.salesforce.com", None, Some(&incomplete), Duration::from_secs(5)).is_err()
+ );
+ // username-password mode: stored credentials also satisfy the empty-token rule
+ let ropc = serde_json::json!({
+ "auth": {
+ "mode": "password",
+ "environment": "sandbox",
+ "clientId": "3MVG9xxx",
+ "clientSecret": "secret",
+ "username": "[email protected]",
+ "password": "pw"
+ }
+ });
+ let ropc_client = SfClient::from_config(
+ "acme--qas1.sandbox.my.salesforce.com",
+ Some(""),
+ Some(&ropc),
+ Duration::from_secs(5),
+ )
+ .unwrap();
+ assert!(ropc_client.has_refresh_token());
+ let ropc_debug = format!("{ropc_client:?}");
+ assert!(!ropc_debug.contains("[email protected]"), "{ropc_debug}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_insert() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"insert\",\"object\":\"Account\",\"fields\":{\"Name\":\"Acme\"}}";
+ let stmt = parse_salesforce_statement(source).unwrap();
+ assert_eq!(stmt.op, SfDmlOp::Insert);
+ assert_eq!(stmt.object, "Account");
+ assert!(stmt.id.is_none());
+ let fields = stmt.fields.unwrap();
+ assert_eq!(fields.get("Name").and_then(Value::as_str), Some("Acme"));
+ }
+
+ #[test]
+ fn parse_salesforce_statement_update() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001xx000003DGbY\",\"fields\":{\"Name\":\"Acme\"}}";
+ let stmt = parse_salesforce_statement(source).unwrap();
+ assert_eq!(stmt.op, SfDmlOp::Update);
+ assert_eq!(stmt.object, "Account");
+ assert_eq!(stmt.id.as_deref(), Some("001xx000003DGbY"));
+ }
+
+ #[test]
+ fn parse_salesforce_statement_delete() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\",\"id\":\"001xx000003DGbY\"}";
+ let stmt = parse_salesforce_statement(source).unwrap();
+ assert_eq!(stmt.op, SfDmlOp::Delete);
+ assert_eq!(stmt.id.as_deref(), Some("001xx000003DGbY"));
+ assert!(stmt.fields.is_none());
+ }
+
+ #[test]
+ fn parse_salesforce_statement_case_insensitive_header() {
+ let source = "dbx salesforce dml\n{\"op\":\"delete\",\"object\":\"Lead\",\"id\":\"abc\"}";
+ let stmt = parse_salesforce_statement(source).unwrap();
+ assert_eq!(stmt.op, SfDmlOp::Delete);
+ }
+
+ #[test]
+ fn parse_salesforce_statement_malformed_json() {
+ let source = "DBX SALESFORCE DML\n{not json";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("Invalid DBX SALESFORCE DML JSON body"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_unknown_op() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"upsert\",\"object\":\"Account\",\"id\":\"x\"}";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("Unknown DBX SALESFORCE DML op"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_missing_id_for_update() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"fields\":{\"Name\":\"x\"}}";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("requires a non-empty 'id'"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_missing_id_for_delete() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\"}";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("requires a non-empty 'id'"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_empty_fields_for_insert() {
+ let source = "DBX SALESFORCE DML\n{\"op\":\"insert\",\"object\":\"Account\",\"fields\":{}}";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("non-empty 'fields'"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_non_dbx_soql_is_not_matched() {
+ // Plain SOQL never enters the parser — but if it somehow did, the
+ // header check catches it.
+ let source = "SELECT Id FROM Account";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("Unsupported DBX SALESFORCE statement"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_unknown_header() {
+ let source = "DBX SALESFORCE SOMETHING\n{}";
+ let err = parse_salesforce_statement(source).unwrap_err();
+ assert!(err.contains("Unsupported DBX SALESFORCE statement"), "{err}");
+ }
+
+ #[test]
+ fn parse_salesforce_statement_empty_input() {
+ let err = parse_salesforce_statement("").unwrap_err();
+ assert!(err.contains("empty"), "{err}");
+ }
+
+ #[test]
+ fn starts_with_salesforce_header_detects_dml() {
+ assert!(starts_with_salesforce_header("DBX SALESFORCE DML\n{}"));
+ assert!(starts_with_salesforce_header(" dbx salesforce dml\n{}"));
+ assert!(!starts_with_salesforce_header("SELECT Id FROM Account"));
+ assert!(!starts_with_salesforce_header(""));
+ }
+}
diff --git a/crates/dbx-drivers/src/lib.rs b/crates/dbx-drivers/src/lib.rs
index f6b4f602c8..12671f95b6 100644
--- a/crates/dbx-drivers/src/lib.rs
+++ b/crates/dbx-drivers/src/lib.rs
@@ -22,4 +22,5 @@ pub mod metadata;
pub mod mongo_oidc;
pub mod mongo_shell;
pub mod runtime_config;
+pub mod salesforce_oauth;
pub mod ssh_config;
diff --git a/crates/dbx-drivers/src/salesforce_oauth.rs b/crates/dbx-drivers/src/salesforce_oauth.rs
new file mode 100644
index 0000000000..afebd14e91
--- /dev/null
+++ b/crates/dbx-drivers/src/salesforce_oauth.rs
@@ -0,0 +1,1122 @@
+//! Salesforce OAuth flows (spec §2, milestone M2).
+//!
+//! Three grant paths, all against `{loginBase}/services/oauth2/*`:
+//! - **Authorization Code + PKCE** ([`authorize_with_browser`]) — desktop app;
+//! opens the system browser, catches the redirect on a fixed localhost port
+//! (same shape as `mongo_oidc.rs`, own port so both flows can coexist).
+//! - **Device Flow** ([`device_authorization_request`] + [`device_poll`]) —
+//! works in web mode too: the backend never opens a browser, the frontend
+//! shows the user code and drives the polling loop.
+//! - **Refresh** ([`refresh_access_token`]) — used by the driver on 401 and
+//! available for explicit re-auth without a browser.
+//! - **Username-password (ROPC)** ([`password_grant_token`]) — deprecated by
+//! Salesforce but common in corporate orgs; no refresh token is issued, so
+//! the driver replays the login on 401 ([`SfRefreshMethod`]).
+//!
+//! The Connected App is bring-your-own for now (decision D1): users register
+//! one in their org with callback URL [`SALESFORCE_OAUTH_REDIRECT_URI`] and
+//! PKCE enabled. A bundled client id can be slotted into the defaults later
+//! without changing any of this module's API.
+
+use std::{
+ sync::{Arc, OnceLock},
+ time::{Duration, Instant},
+};
+
+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
+use reqwest::Url;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::TcpListener,
+ sync::Mutex,
+};
+
+/// Redirect URI users must register in their Salesforce Connected App.
+pub const SALESFORCE_OAUTH_REDIRECT_URI: &str = "http://localhost:27098/callback";
+const OAUTH_CALLBACK_ADDRESS: &str = "127.0.0.1:27098";
+const OAUTH_CALLBACK_PATH: &str = "/callback";
+/// Browser flows block the calling command until the user finishes login;
+/// keep the same budget as the MongoDB OIDC precedent.
+pub const SALESFORCE_OAUTH_BROWSER_TIMEOUT: Duration = Duration::from_secs(5 * 60);
+const HTTP_TIMEOUT: Duration = Duration::from_secs(20);
+const MAX_CALLBACK_REQUEST_BYTES: usize = 16 * 1024;
+/// `refresh_token` = offline access (survives session expiry), `api` = data
+/// access. Users can narrow permissions per Connected App policy.
+const OAUTH_SCOPES: &str = "refresh_token api";
+/// Salesforce's device-flow grant type (it predates RFC 8628 and uses its own
+/// string for both the initial request and the poll).
+const DEVICE_GRANT_TYPE: &str = "device_code";
+/// Poll floor; Salesforce recommends 5s and answers `slow_down` otherwise.
+const MIN_DEVICE_POLL_INTERVAL_SECS: u64 = 5;
+
+pub type SfBrowserOpener = Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;
+
+/// Which Salesforce login host to authorize against.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum SfLoginEnvironment {
+ #[default]
+ Production,
+ Sandbox,
+ /// Custom My Domain / proxy host supplied via [`SfOauthParams::login_url`].
+ Custom,
+}
+
+/// Everything needed to run any of the three flows. Mirrors the
+/// `external_config.auth` object persisted with the connection (camelCase).
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SfOauthParams {
+ pub environment: SfLoginEnvironment,
+ /// Only for [`SfLoginEnvironment::Custom`].
+ pub login_url: Option<String>,
+ pub client_id: String,
+ /// Optional: only confidential Connected Apps need it (PKCE public apps
+ /// must leave it empty).
+ pub client_secret: Option<String>,
+}
+
+/// Token bundle returned to the caller. `instance_url` is what the connection
+/// `host` field should be set to (org-specific, e.g. My Domain).
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SfTokenSet {
+ pub access_token: String,
+ pub refresh_token: Option<String>,
+ pub instance_url: String,
+}
+
+/// Result of [`refresh_access_token`]. Salesforce echoes `instance_url` on
+/// refresh; when it does not (older behavior) callers keep their known URL.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SfRefreshedToken {
+ pub access_token: String,
+ /// Present only when Salesforce rotated it; otherwise keep the old one.
+ pub refresh_token: Option<String>,
+ pub instance_url: Option<String>,
+}
+
+/// Device-flow kickoff response; the frontend shows `user_code` +
+/// `verification_uri` and polls every `interval_secs`.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SfDeviceAuthorization {
+ pub device_code: String,
+ pub user_code: String,
+ pub verification_uri: String,
+ pub interval_secs: u64,
+ pub expires_in_secs: u64,
+}
+
+/// One device-flow poll result (frontend drives the loop so it can cancel).
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase", tag = "status")]
+pub enum SfDevicePoll {
+ /// Not decided yet; wait `interval_secs` (already includes `slow_down`
+ /// backoff) and poll again.
+ Pending {
+ interval_secs: u64,
+ },
+ Success {
+ token: SfTokenSet,
+ },
+ Expired,
+ Denied {
+ reason: Option<String>,
+ },
+}
+
+#[derive(Clone, Copy)]
+enum EndpointPolicy {
+ HttpsOnly,
+ #[cfg(test)]
+ AllowLoopbackHttp,
+}
+
+impl EndpointPolicy {
+ fn parse_url(self, value: &str, description: &str) -> Result<Url, String> {
+ let url = Url::parse(value).map_err(|err| oauth_error(format!("invalid {description}: {err}")))?;
+ if url.scheme() == "https" {
+ return Ok(url);
+ }
+ #[cfg(test)]
+ if matches!(self, Self::AllowLoopbackHttp)
+ && url.scheme() == "http"
+ && url.host_str().is_some_and(|host| {
+ host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
+ })
+ {
+ return Ok(url);
+ }
+ Err(oauth_error(format!("{description} must use HTTPS")))
+ }
+}
+
+/// Distinct from a transport error: OAuth-protocol refusals (device polling
+/// especially) are expected states, not failures.
+#[derive(Debug)]
+enum TokenEndpointError {
+ Oauth { error: String, description: Option<String> },
+ Other(String),
+}
+
+fn oauth_error(message: impl Into<String>) -> String {
+ format!("Salesforce OAuth failed: {}", message.into())
+}
+
+fn browser_flow_lock() -> &'static Mutex<()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+}
+
+/// Resolve the login host for the flow. Custom hosts must be https and are
+/// normalized (no trailing slash, no path/query).
+pub fn login_base_url(params: &SfOauthParams) -> Result<String, String> {
+ login_base_url_with_policy(params, EndpointPolicy::HttpsOnly)
+}
+
+/// Same as [`login_base_url`], but the caller's endpoint policy decides whether a
+/// custom login URL may be loopback HTTP — test builds only, so the mock OAuth
+/// server the tests run is reachable while production stays HTTPS-only.
+fn login_base_url_with_policy(params: &SfOauthParams, policy: EndpointPolicy) -> Result<String, String> {
+ let base = match params.environment {
+ SfLoginEnvironment::Production => "https://login.salesforce.com".to_string(),
+ SfLoginEnvironment::Sandbox => "https://test.salesforce.com".to_string(),
+ SfLoginEnvironment::Custom => {
+ let raw = params.login_url.as_deref().unwrap_or("").trim().trim_end_matches('/');
+ if raw.is_empty() {
+ return Err(oauth_error("custom login URL is required for the 'custom' environment"));
+ }
+ let url = if raw.starts_with("http://") || raw.starts_with("https://") {
+ raw.to_string()
+ } else {
+ format!("https://{raw}")
+ };
+ let parsed = policy.parse_url(&url, "custom login URL")?;
+ format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or_default())
+ + &parsed.port().map(|port| format!(":{port}")).unwrap_or_default()
+ }
+ };
+ if params.client_id.trim().is_empty() {
+ return Err(oauth_error("client ID is required (create a Connected App with PKCE enabled)"));
+ }
+ Ok(base)
+}
+
+fn random_url_safe_value() -> String {
+ let first = uuid::Uuid::new_v4();
+ let second = uuid::Uuid::new_v4();
+ let mut bytes = [0_u8; 32];
+ bytes[..16].copy_from_slice(first.as_bytes());
+ bytes[16..].copy_from_slice(second.as_bytes());
+ URL_SAFE_NO_PAD.encode(bytes)
+}
+
+fn s256_challenge(verifier: &str) -> String {
+ URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
+}
+
+fn token_endpoint(base: &str) -> String {
+ format!("{base}/services/oauth2/token")
+}
+
+fn authorize_endpoint(base: &str) -> String {
+ format!("{base}/services/oauth2/authorize")
+}
+
+fn build_authorize_url(
+ params: &SfOauthParams,
+ state: &str,
+ code_challenge: &str,
+ policy: EndpointPolicy,
+) -> Result<Url, String> {
+ let base = login_base_url_with_policy(params, policy)?;
+ let mut url = policy.parse_url(&authorize_endpoint(&base), "authorization endpoint")?;
+ url.query_pairs_mut()
+ .append_pair("response_type", "code")
+ .append_pair("client_id", params.client_id.trim())
+ .append_pair("redirect_uri", SALESFORCE_OAUTH_REDIRECT_URI)
+ .append_pair("scope", OAUTH_SCOPES)
+ .append_pair("state", state)
+ .append_pair("code_challenge", code_challenge)
+ .append_pair("code_challenge_method", "S256");
+ Ok(url)
+}
+
+async fn write_callback_response(stream: &mut tokio::net::TcpStream, success: bool) {
+ let (status, title, body) = if success {
+ (
+ "200 OK",
+ "Salesforce authorization received",
+ "DBX received the authorization response. Return to DBX to finish saving the connection.",
+ )
+ } else {
+ (
+ "400 Bad Request",
+ "Authorization failed",
+ "DBX could not complete the Salesforce authorization. Return to DBX for details.",
+ )
+ };
+ let html = format!(
+ "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>{title}</title><style>body{{font-family:system-ui,sans-serif;margin:48px;color:#202124}}h1{{font-size:22px}}</style></head><body><h1>{title}</h1><p>{body}</p></body></html>"
+ );
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Security-Policy: default-src 'none'; style-src 'unsafe-inline'\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{html}",
+ html.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.shutdown().await;
+}
+
+#[derive(Debug)]
+struct AuthorizationCallback {
+ code: String,
+ state: String,
+}
+
+fn parse_callback_target(target: &str) -> Result<AuthorizationCallback, String> {
+ let url = Url::parse(&format!("http://localhost{target}")).map_err(|err| format!("invalid callback URL: {err}"))?;
+ if url.path() != OAUTH_CALLBACK_PATH {
+ return Err("unexpected callback path".to_string());
+ }
+ let mut code = None;
+ let mut state = None;
+ let mut provider_error = None;
+ let mut provider_error_description = None;
+ for (key, value) in url.query_pairs() {
+ match key.as_ref() {
+ "code" => code = Some(value.into_owned()),
+ "state" => state = Some(value.into_owned()),
+ "error" => provider_error = Some(value.into_owned()),
+ "error_description" => provider_error_description = Some(value.into_owned()),
+ _ => {}
+ }
+ }
+ if let Some(error) = provider_error {
+ let detail = provider_error_description.map(|description| format!(": {description}")).unwrap_or_default();
+ return Err(format!("Salesforce returned {error}{detail}"));
+ }
+ Ok(AuthorizationCallback {
+ code: code.ok_or_else(|| "callback did not include an authorization code".to_string())?,
+ state: state.ok_or_else(|| "callback did not include state".to_string())?,
+ })
+}
+
+async fn wait_for_callback(listener: TcpListener, expected_state: &str) -> Result<String, String> {
+ 'requests: loop {
+ let (mut stream, _) =
+ listener.accept().await.map_err(|err| oauth_error(format!("callback listener failed: {err}")))?;
+ let mut buffer = Vec::with_capacity(1024);
+ loop {
+ if buffer.len() == MAX_CALLBACK_REQUEST_BYTES {
+ write_callback_response(&mut stream, false).await;
+ continue 'requests;
+ }
+ let mut chunk = [0_u8; 1024];
+ let remaining = MAX_CALLBACK_REQUEST_BYTES - buffer.len();
+ let read_len = remaining.min(chunk.len());
+ let bytes_read = match stream.read(&mut chunk[..read_len]).await {
+ Ok(bytes_read) => bytes_read,
+ Err(_) => {
+ write_callback_response(&mut stream, false).await;
+ continue 'requests;
+ }
+ };
+ if bytes_read == 0 {
+ break;
+ }
+ buffer.extend_from_slice(&chunk[..bytes_read]);
+ if buffer.windows(4).any(|window| window == b"\r\n\r\n") {
+ break;
+ }
+ }
+ let request = String::from_utf8_lossy(&buffer);
+ let target = request.lines().next().and_then(|line| line.split_whitespace().nth(1)).map(str::to_owned);
+ let Some(target) = target else {
+ write_callback_response(&mut stream, false).await;
+ continue;
+ };
+ let callback = match parse_callback_target(&target) {
+ Ok(callback) => callback,
+ Err(_) => {
+ write_callback_response(&mut stream, false).await;
+ continue;
+ }
+ };
+ if callback.state != expected_state {
+ write_callback_response(&mut stream, false).await;
+ continue;
+ }
+ write_callback_response(&mut stream, true).await;
+ return Ok(callback.code);
+ }
+}
+
+/// POST the token endpoint and split transport failures from OAuth refusals.
+async fn post_token_form(
+ params: &SfOauthParams,
+ form: &[(&str, &str)],
+ policy: EndpointPolicy,
+) -> Result<Value, TokenEndpointError> {
+ let base = login_base_url_with_policy(params, policy).map_err(TokenEndpointError::Other)?;
+ let endpoint = policy.parse_url(&token_endpoint(&base), "token endpoint").map_err(TokenEndpointError::Other)?;
+ let client = reqwest::Client::builder()
+ .timeout(HTTP_TIMEOUT)
+ .build()
+ .map_err(|err| TokenEndpointError::Other(oauth_error(format!("failed to create HTTP client: {err}"))))?;
+ let response = client
+ .post(endpoint)
+ .form(form)
+ .send()
+ .await
+ .map_err(|err| TokenEndpointError::Other(oauth_error(format!("token request failed: {err}"))))?;
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ let value: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
+ if status.is_success() {
+ return Ok(value);
+ }
+ let error = value.get("error").and_then(Value::as_str).unwrap_or_default().to_string();
+ if !error.is_empty() {
+ return Err(TokenEndpointError::Oauth {
+ description: value.get("error_description").and_then(Value::as_str).map(str::to_string),
+ error,
+ });
+ }
+ let detail = body.chars().take(300).collect::<String>();
+ Err(TokenEndpointError::Other(oauth_error(format!("token endpoint returned HTTP {status}: {detail}"))))
+}
+
+fn token_set_from_value(value: &Value, require_instance_url: bool) -> Result<SfTokenSet, String> {
+ let access_token = value.get("access_token").and_then(Value::as_str).unwrap_or_default().to_string();
+ if access_token.is_empty() {
+ return Err(oauth_error("token response did not include an access token"));
+ }
+ let instance_url =
+ value.get("instance_url").and_then(Value::as_str).unwrap_or_default().trim().trim_end_matches('/').to_string();
+ if require_instance_url && instance_url.is_empty() {
+ return Err(oauth_error("token response did not include an instance URL"));
+ }
+ Ok(SfTokenSet {
+ access_token,
+ refresh_token: value
+ .get("refresh_token")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|token| !token.is_empty())
+ .map(str::to_string),
+ instance_url,
+ })
+}
+
+fn client_secret_pair(params: &SfOauthParams) -> Option<String> {
+ params.client_secret.as_deref().map(str::trim).filter(|secret| !secret.is_empty()).map(str::to_string)
+}
+
+/// Authorization Code + PKCE via the system browser (desktop only).
+///
+/// Blocks until the user completes login, denies it, or 5 minutes pass. Only
+/// one browser flow may run at a time (shared lock with nothing else — Mongo
+/// OIDC keeps its own).
+pub async fn authorize_with_browser(params: &SfOauthParams, opener: &SfBrowserOpener) -> Result<SfTokenSet, String> {
+ authorize_with_browser_policy(params, opener, EndpointPolicy::HttpsOnly).await
+}
+
+async fn authorize_with_browser_policy(
+ params: &SfOauthParams,
+ opener: &SfBrowserOpener,
+ policy: EndpointPolicy,
+) -> Result<SfTokenSet, String> {
+ let deadline = Instant::now() + SALESFORCE_OAUTH_BROWSER_TIMEOUT;
+ let remaining = || {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return Err(oauth_error("browser authorization timed out"));
+ }
+ Ok(remaining)
+ };
+
+ let _flow_guard = tokio::time::timeout(remaining()?, browser_flow_lock().lock())
+ .await
+ .map_err(|_| oauth_error("browser authorization timed out"))?;
+ let listener = TcpListener::bind(OAUTH_CALLBACK_ADDRESS)
+ .await
+ .map_err(|err| oauth_error(format!("cannot listen on {SALESFORCE_OAUTH_REDIRECT_URI}: {err}")))?;
+
+ let state = random_url_safe_value();
+ let verifier = random_url_safe_value();
+ let authorize_url = build_authorize_url(params, &state, &s256_challenge(&verifier), policy)?;
+ opener(authorize_url.as_str())?;
+
+ let code = tokio::time::timeout(remaining()?, wait_for_callback(listener, &state))
+ .await
+ .map_err(|_| oauth_error("browser authorization timed out"))??;
+
+ let mut form: Vec<(&str, &str)> = vec![
+ ("grant_type", "authorization_code"),
+ ("client_id", params.client_id.trim()),
+ ("code", code.as_str()),
+ ("redirect_uri", SALESFORCE_OAUTH_REDIRECT_URI),
+ ("code_verifier", verifier.as_str()),
+ ];
+ let client_secret = client_secret_pair(params);
+ if let Some(secret) = client_secret.as_deref() {
+ form.push(("client_secret", secret));
+ }
+ let value = post_token_form(params, &form, policy).await.map_err(token_error_to_string)?;
+ token_set_from_value(&value, true)
+}
+
+/// Kick off the device flow. Salesforce returns a short `user_code` the user
+/// enters at `verification_uri` on any device.
+pub async fn device_authorization_request(params: &SfOauthParams) -> Result<SfDeviceAuthorization, String> {
+ device_authorization_request_policy(params, EndpointPolicy::HttpsOnly).await
+}
+
+async fn device_authorization_request_policy(
+ params: &SfOauthParams,
+ policy: EndpointPolicy,
+) -> Result<SfDeviceAuthorization, String> {
+ let form = [("grant_type", DEVICE_GRANT_TYPE), ("client_id", params.client_id.trim()), ("scope", OAUTH_SCOPES)];
+ let value = post_token_form(params, &form, policy).await.map_err(token_error_to_string)?;
+ let required = |key: &str| {
+ value
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|text| !text.trim().is_empty())
+ .map(str::to_string)
+ .ok_or_else(|| oauth_error(format!("device authorization response missing '{key}'")))
+ };
+ let interval = value.get("interval").and_then(Value::as_u64).unwrap_or(MIN_DEVICE_POLL_INTERVAL_SECS);
+ Ok(SfDeviceAuthorization {
+ device_code: required("device_code")?,
+ user_code: required("user_code")?,
+ verification_uri: required("verification_uri")?,
+ interval_secs: interval.max(MIN_DEVICE_POLL_INTERVAL_SECS),
+ expires_in_secs: value.get("expires_in").and_then(Value::as_u64).unwrap_or(600),
+ })
+}
+
+/// One device-flow poll. Never returns `Pending` errors for
+/// `authorization_pending` / `slow_down` — those are normal states.
+pub async fn device_poll(
+ params: &SfOauthParams,
+ device_code: &str,
+ interval_secs: u64,
+) -> Result<SfDevicePoll, String> {
+ device_poll_policy(params, device_code, interval_secs, EndpointPolicy::HttpsOnly).await
+}
+
+async fn device_poll_policy(
+ params: &SfOauthParams,
+ device_code: &str,
+ interval_secs: u64,
+ policy: EndpointPolicy,
+) -> Result<SfDevicePoll, String> {
+ let current_interval = interval_secs.max(MIN_DEVICE_POLL_INTERVAL_SECS);
+ let form = [("grant_type", DEVICE_GRANT_TYPE), ("client_id", params.client_id.trim()), ("code", device_code)];
+ match post_token_form(params, &form, policy).await {
+ Ok(value) => {
+ let token = token_set_from_value(&value, true)?;
+ Ok(SfDevicePoll::Success { token })
+ }
+ Err(TokenEndpointError::Oauth { error, description }) => match error.as_str() {
+ "authorization_pending" => Ok(SfDevicePoll::Pending { interval_secs: current_interval }),
+ "slow_down" => Ok(SfDevicePoll::Pending { interval_secs: current_interval + 5 }),
+ "expired_token" | "expired_device_code" => Ok(SfDevicePoll::Expired),
+ "access_denied" => Ok(SfDevicePoll::Denied { reason: description }),
+ other => Err(oauth_error(format!(
+ "device authorization refused ({other}){}",
+ description.map(|detail| format!(": {detail}")).unwrap_or_default()
+ ))),
+ },
+ Err(TokenEndpointError::Other(message)) => Err(message),
+ }
+}
+
+/// Exchange a stored refresh token for a fresh access token. Used by the
+/// driver on 401 and by the UI for explicit re-auth.
+pub async fn refresh_access_token(params: &SfOauthParams, refresh_token: &str) -> Result<SfRefreshedToken, String> {
+ refresh_access_token_policy(params, refresh_token, EndpointPolicy::HttpsOnly).await
+}
+
+async fn refresh_access_token_policy(
+ params: &SfOauthParams,
+ refresh_token: &str,
+ policy: EndpointPolicy,
+) -> Result<SfRefreshedToken, String> {
+ if refresh_token.trim().is_empty() {
+ return Err(oauth_error("refresh token is empty"));
+ }
+ let mut form: Vec<(&str, &str)> = vec![
+ ("grant_type", "refresh_token"),
+ ("client_id", params.client_id.trim()),
+ ("refresh_token", refresh_token.trim()),
+ ];
+ let client_secret = client_secret_pair(params);
+ if let Some(secret) = client_secret.as_deref() {
+ form.push(("client_secret", secret));
+ }
+ let value = post_token_form(params, &form, policy).await.map_err(token_error_to_string)?;
+ let access_token = value.get("access_token").and_then(Value::as_str).unwrap_or_default().to_string();
+ if access_token.is_empty() {
+ return Err(oauth_error("refresh response did not include an access token"));
+ }
+ Ok(SfRefreshedToken {
+ access_token,
+ refresh_token: value
+ .get("refresh_token")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|token| !token.is_empty() && *token != refresh_token.trim())
+ .map(str::to_string),
+ instance_url: value
+ .get("instance_url")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|url| !url.is_empty())
+ .map(|url| url.trim_end_matches('/').to_string()),
+ })
+}
+
+fn token_error_to_string(error: TokenEndpointError) -> String {
+ match error {
+ TokenEndpointError::Oauth { error, description } => {
+ oauth_error(format!("{error}{}", description.map(|detail| format!(" ({detail})")).unwrap_or_default()))
+ }
+ TokenEndpointError::Other(message) => message,
+ }
+}
+
+/// Username-password flow (ROPC). Deprecated by Salesforce but still enabled
+/// on many orgs via Session Settings → "Permit users to exchange
+/// username–password credentials for an access token", and the grant many
+/// corporate integrations already rely on. Issues **no refresh token** — the
+/// driver re-runs this grant with the stored credentials when the session
+/// expires instead.
+pub async fn password_grant_token(
+ params: &SfOauthParams,
+ username: &str,
+ password: &str,
+) -> Result<SfTokenSet, String> {
+ password_grant_token_policy(params, username, password, EndpointPolicy::HttpsOnly).await
+}
+
+async fn password_grant_token_policy(
+ params: &SfOauthParams,
+ username: &str,
+ password: &str,
+ policy: EndpointPolicy,
+) -> Result<SfTokenSet, String> {
+ if username.trim().is_empty() || password.is_empty() {
+ return Err(oauth_error("username and password are required"));
+ }
+ let mut form: Vec<(&str, &str)> = vec![
+ ("grant_type", "password"),
+ ("client_id", params.client_id.trim()),
+ ("username", username.trim()),
+ ("password", password),
+ ("format", "json"),
+ ];
+ let client_secret = client_secret_pair(params);
+ if let Some(secret) = client_secret.as_deref() {
+ form.push(("client_secret", secret));
+ }
+ let value = post_token_form(params, &form, policy).await.map_err(|error| match error {
+ TokenEndpointError::Oauth { error, description } => oauth_error(format!(
+ "{error}{} — check the username (sandbox users end with the sandbox name, e.g. [email protected]), \
+ the password (append your security token if your IP is not trusted), and that the org permits the \
+ username-password flow (Session Settings). MFA-enforced users cannot use this grant.",
+ description.map(|detail| format!(" ({detail})")).unwrap_or_default()
+ )),
+ TokenEndpointError::Other(message) => message,
+ })?;
+ token_set_from_value(&value, true)
+}
+
+/// How a saved connection re-authenticates when its access token expires.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SfRefreshMethod {
+ /// OAuth flows: exchange the stored refresh token.
+ RefreshToken(String),
+ /// Username-password flow: Salesforce issues no refresh token, so the
+ /// driver replays the login with the stored credentials.
+ Password { username: String, password: String },
+}
+
+/// Parse the `external_config.auth` object a saved Salesforce connection
+/// carries (values hydrated from the secret store by dbx-core). Returns
+/// `None` when no automatic re-auth is configured (pasted-token mode).
+pub fn oauth_params_from_external_config(external_config: Option<&Value>) -> Option<(SfOauthParams, SfRefreshMethod)> {
+ let auth = external_config?.get("auth")?;
+ let client_id = auth.get("clientId").and_then(Value::as_str).unwrap_or_default().trim().to_string();
+ if client_id.is_empty() {
+ return None;
+ }
+ let text = |key: &str| auth.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_string();
+ let mode = text("mode");
+ let refresh_token = text("refreshToken");
+ let method = if mode == "password" {
+ let username = text("username");
+ let password = auth.get("password").and_then(Value::as_str).unwrap_or_default().to_string();
+ if username.is_empty() || password.is_empty() {
+ return None;
+ }
+ SfRefreshMethod::Password { username, password }
+ } else if !refresh_token.is_empty() {
+ SfRefreshMethod::RefreshToken(refresh_token)
+ } else {
+ return None;
+ };
+ let environment = match text("environment").as_str() {
+ "sandbox" => SfLoginEnvironment::Sandbox,
+ "custom" => SfLoginEnvironment::Custom,
+ _ => SfLoginEnvironment::Production,
+ };
+ let login_url = text("loginUrl");
+ let client_secret = text("clientSecret");
+ let params = SfOauthParams {
+ environment,
+ login_url: (!login_url.is_empty()).then_some(login_url),
+ client_id,
+ client_secret: (!client_secret.is_empty()).then_some(client_secret),
+ };
+ Some((params, method))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ io::{Read, Write},
+ sync::{Arc, Mutex as StdMutex},
+ time::Duration,
+ };
+
+ use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+ task::JoinHandle,
+ };
+
+ use super::*;
+
+ fn params(login_base: &str) -> SfOauthParams {
+ SfOauthParams {
+ environment: SfLoginEnvironment::Custom,
+ login_url: Some(login_base.to_string()),
+ client_id: "dbx-connected-app".to_string(),
+ client_secret: None,
+ }
+ }
+
+ async fn read_http_request(stream: &mut tokio::net::TcpStream) -> String {
+ let mut request = Vec::new();
+ loop {
+ let mut chunk = [0_u8; 1024];
+ let read = AsyncReadExt::read(stream, &mut chunk).await.unwrap();
+ if read == 0 {
+ break;
+ }
+ request.extend_from_slice(&chunk[..read]);
+ if request.windows(4).any(|window| window == b"\r\n\r\n") {
+ break;
+ }
+ }
+ String::from_utf8(request).unwrap()
+ }
+
+ async fn write_json_response(stream: &mut tokio::net::TcpStream, body: &str) {
+ // Salesforce answers OAuth refusals (`invalid_grant`, `authorization_pending`, …)
+ // with HTTP 400 plus an `error` body, and `post_token_form` branches on the
+ // status — so the mock has to reproduce that instead of always saying 200.
+ let is_oauth_error = serde_json::from_str::<Value>(body)
+ .ok()
+ .and_then(|value| value.get("error").and_then(Value::as_str).map(|error| !error.is_empty()))
+ .unwrap_or(false);
+ let status = if is_oauth_error { "400 Bad Request" } else { "200 OK" };
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ stream.write_all(response.as_bytes()).await.unwrap();
+ }
+
+ /// Mock OAuth server: every POST to /services/oauth2/token is recorded and
+ /// answered by the shared queue of JSON bodies (or the default token body).
+ async fn start_mock_oauth_server(responses: Vec<String>) -> (String, Arc<StdMutex<Vec<String>>>, JoinHandle<()>) {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let requests = Arc::new(StdMutex::new(Vec::new()));
+ let server_requests = requests.clone();
+ let task = tokio::spawn(async move {
+ let mut responses = responses;
+ loop {
+ let Ok((mut stream, _)) = listener.accept().await else { break };
+ let request = read_http_request(&mut stream).await;
+ server_requests.lock().unwrap().push(request.clone());
+ let body = if responses.is_empty() {
+ r#"{"access_token":"token","refresh_token":"refresh","instance_url":"https://acme.my.salesforce.com/"}"#
+ .to_string()
+ } else {
+ responses.remove(0)
+ };
+ write_json_response(&mut stream, &body).await;
+ }
+ });
+ (base, requests, task)
+ }
+
+ #[test]
+ fn login_base_url_resolves_environments() {
+ let production = SfOauthParams { client_id: "c".into(), ..Default::default() };
+ assert_eq!(login_base_url(&production).unwrap(), "https://login.salesforce.com");
+ let sandbox =
+ SfOauthParams { environment: SfLoginEnvironment::Sandbox, client_id: "c".into(), ..Default::default() };
+ assert_eq!(login_base_url(&sandbox).unwrap(), "https://test.salesforce.com");
+ let custom = params("https://acme.my.salesforce.com/");
+ assert_eq!(login_base_url(&custom).unwrap(), "https://acme.my.salesforce.com");
+ // missing client id
+ let missing = SfOauthParams::default();
+ assert!(login_base_url(&missing).unwrap_err().contains("client ID is required"));
+ // custom without url
+ let no_url =
+ SfOauthParams { environment: SfLoginEnvironment::Custom, client_id: "c".into(), ..Default::default() };
+ assert!(login_base_url(&no_url).is_err());
+ // non-https custom
+ let insecure = params("http://acme.my.salesforce.com");
+ assert!(login_base_url(&insecure).unwrap_err().contains("HTTPS"));
+ }
+
+ #[test]
+ fn authorize_url_carries_pkce_state_and_scopes() {
+ let url = build_authorize_url(
+ &params("https://acme.my.salesforce.com"),
+ "expected-state",
+ "challenge",
+ EndpointPolicy::HttpsOnly,
+ )
+ .unwrap();
+ assert_eq!(url.as_str().split('?').next().unwrap(), "https://acme.my.salesforce.com/services/oauth2/authorize");
+ let query = url.query_pairs().collect::<std::collections::HashMap<_, _>>();
+ let param = |key: &str| query.get(key).map(|value| value.as_ref());
+ assert_eq!(param("response_type"), Some("code"));
+ assert_eq!(param("redirect_uri"), Some(SALESFORCE_OAUTH_REDIRECT_URI));
+ assert_eq!(param("code_challenge_method"), Some("S256"));
+ assert_eq!(param("state"), Some("expected-state"));
+ assert_eq!(param("scope"), Some(OAUTH_SCOPES));
+ assert!(!query.get("client_id").unwrap().is_empty());
+ // production authorize url hits login.salesforce.com even when the org
+ // instance is a my-domain host
+ let production = SfOauthParams { client_id: "c".into(), ..Default::default() };
+ let url = build_authorize_url(&production, "s", "ch", EndpointPolicy::HttpsOnly).unwrap();
+ assert!(url.as_str().starts_with("https://login.salesforce.com/services/oauth2/authorize?"));
+ }
+
+ #[test]
+ fn s256_challenge_matches_rfc_example() {
+ // RFC 7636 Appendix B test vector.
+ let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
+ assert_eq!(s256_challenge(verifier), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
+ }
+
+ #[test]
+ fn callback_requires_code_and_state() {
+ let callback = parse_callback_target("/callback?code=abc&state=xyz").unwrap();
+ assert_eq!(callback.code, "abc");
+ assert_eq!(callback.state, "xyz");
+ assert!(parse_callback_target("/redirect?code=abc&state=xyz").is_err());
+ assert!(parse_callback_target("/callback?error=access_denied&error_description=user+cancelled")
+ .unwrap_err()
+ .contains("access_denied: user cancelled"));
+ }
+
+ #[tokio::test]
+ async fn callback_ignores_invalid_requests_until_matching_state() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let callback = tokio::spawn(wait_for_callback(listener, "expected-state"));
+
+ for target in ["/callback?code=wrong&state=wrong-state", "/callback?error=access_denied"] {
+ let mut stream = TcpStream::connect(address).await.unwrap();
+ stream
+ .write_all(format!("GET {target} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").as_bytes())
+ .await
+ .unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).await.unwrap();
+ assert!(response.starts_with("HTTP/1.1 400 Bad Request"));
+ }
+
+ let mut stream = TcpStream::connect(address).await.unwrap();
+ stream
+ .write_all(b"GET /callback?code=valid-code&state=expected-state HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
+ .await
+ .unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).await.unwrap();
+ assert!(response.starts_with("HTTP/1.1 200 OK"));
+ assert_eq!(callback.await.unwrap().unwrap(), "valid-code");
+ }
+
+ #[tokio::test]
+ async fn browser_flow_exchanges_pkce_code_for_tokens() {
+ let (base, requests, server) = start_mock_oauth_server(Vec::new()).await;
+ let opened = Arc::new(StdMutex::new(None));
+ let captured = opened.clone();
+ let opener: SfBrowserOpener = Arc::new(move |url| {
+ let parsed = Url::parse(url).unwrap();
+ let state = parsed.query_pairs().find_map(|(k, v)| (k == "state").then(|| v.into_owned())).unwrap();
+ *captured.lock().unwrap() = Some(parsed);
+ std::thread::spawn(move || {
+ let mut stream = std::net::TcpStream::connect("127.0.0.1:27098").unwrap();
+ write!(stream, "GET /callback?code=auth-code&state={state}").unwrap();
+ std::thread::sleep(Duration::from_millis(10));
+ write!(stream, " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
+ let mut response = String::new();
+ stream.read_to_string(&mut response).unwrap();
+ assert!(response.starts_with("HTTP/1.1 200 OK"));
+ });
+ Ok(())
+ });
+
+ let tokens =
+ authorize_with_browser_policy(&params(&base), &opener, EndpointPolicy::AllowLoopbackHttp).await.unwrap();
+ server.abort();
+
+ assert_eq!(tokens.access_token, "token");
+ assert_eq!(tokens.refresh_token.as_deref(), Some("refresh"));
+ assert_eq!(tokens.instance_url, "https://acme.my.salesforce.com");
+ let authorize_url = opened.lock().unwrap().clone().unwrap();
+ assert!(authorize_url.query_pairs().find(|(k, _)| k == "code_challenge").unwrap().1.len() > 20);
+ let recorded = requests.lock().unwrap();
+ assert!(recorded[0].contains("grant_type=authorization_code"));
+ assert!(recorded[0].contains("code=auth-code"));
+ assert!(recorded[0].contains("code_verifier="));
+ assert!(!recorded[0].contains("client_secret"));
+ }
+
+ #[tokio::test]
+ async fn confidential_app_sends_client_secret() {
+ let (base, requests, server) = start_mock_oauth_server(Vec::new()).await;
+ let opener: SfBrowserOpener = Arc::new(move |url| {
+ let parsed = Url::parse(url).unwrap();
+ let state = parsed.query_pairs().find_map(|(k, v)| (k == "state").then(|| v.into_owned())).unwrap();
+ std::thread::spawn(move || {
+ let mut stream = std::net::TcpStream::connect("127.0.0.1:27098").unwrap();
+ write!(
+ stream,
+ "GET /callback?code=c&state={state} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
+ )
+ .unwrap();
+ let mut response = String::new();
+ let _ = stream.read_to_string(&mut response);
+ });
+ Ok(())
+ });
+ let mut confidential = params(&base);
+ confidential.client_secret = Some("app-secret".to_string());
+ let _ = authorize_with_browser_policy(&confidential, &opener, EndpointPolicy::AllowLoopbackHttp).await.unwrap();
+ server.abort();
+ assert!(requests.lock().unwrap()[0].contains("client_secret=app-secret"));
+ }
+
+ #[tokio::test]
+ async fn device_flow_start_and_poll_states() {
+ let (base, requests, server) = start_mock_oauth_server(vec![
+ r#"{"device_code":"dev-code","user_code":"ABCD-1234","verification_uri":"https://login.salesforce.com/setup/connect","interval":5,"expires_in":600}"#.to_string(),
+ r#"{"error":"authorization_pending"}"#.to_string(),
+ r#"{"error":"slow_down"}"#.to_string(),
+ r#"{"error":"access_denied","error_description":"user said no"}"#.to_string(),
+ r#"{"error":"expired_token"}"#.to_string(),
+ r#"{"access_token":"device-token","refresh_token":"device-refresh","instance_url":"https://acme.my.salesforce.com"}"#.to_string(),
+ ])
+ .await;
+ let p = params(&base);
+ let policy = EndpointPolicy::AllowLoopbackHttp;
+
+ let auth = device_authorization_request_policy(&p, policy).await.unwrap();
+ assert_eq!(auth.user_code, "ABCD-1234");
+ assert_eq!(auth.device_code, "dev-code");
+ assert_eq!(auth.interval_secs, 5);
+ assert!(auth.verification_uri.starts_with("https://"));
+
+ assert!(matches!(
+ device_poll_policy(&p, "dev-code", 5, policy).await.unwrap(),
+ SfDevicePoll::Pending { interval_secs: 5 }
+ ));
+ assert!(matches!(
+ device_poll_policy(&p, "dev-code", 5, policy).await.unwrap(),
+ SfDevicePoll::Pending { interval_secs: 10 }
+ ));
+ match device_poll_policy(&p, "dev-code", 5, policy).await.unwrap() {
+ SfDevicePoll::Denied { reason } => assert_eq!(reason.as_deref(), Some("user said no")),
+ other => panic!("expected denied, got {other:?}"),
+ }
+ assert!(matches!(device_poll_policy(&p, "dev-code", 5, policy).await.unwrap(), SfDevicePoll::Expired));
+ match device_poll_policy(&p, "dev-code", 5, policy).await.unwrap() {
+ SfDevicePoll::Success { token } => {
+ assert_eq!(token.access_token, "device-token");
+ assert_eq!(token.refresh_token.as_deref(), Some("device-refresh"));
+ }
+ other => panic!("expected success, got {other:?}"),
+ }
+ server.abort();
+ // device grant uses Salesforce's own grant_type string on both calls
+ let recorded = requests.lock().unwrap();
+ assert!(recorded[0].contains("grant_type=device_code"));
+ assert!(recorded[1].contains("code=dev-code"));
+ }
+
+ #[tokio::test]
+ async fn refresh_returns_tokens_and_detects_rotation() {
+ let (base, requests, server) = start_mock_oauth_server(vec![
+ // unchanged refresh token + trailing-slash instance url
+ r#"{"access_token":"fresh","refresh_token":"old-refresh","instance_url":"https://acme.my.salesforce.com/"}"#.to_string(),
+ // rotated refresh token, no instance url
+ r#"{"access_token":"fresh2","refresh_token":"rotated"}"#.to_string(),
+ ])
+ .await;
+ let p = params(&base);
+ let policy = EndpointPolicy::AllowLoopbackHttp;
+
+ let first = refresh_access_token_policy(&p, "old-refresh", policy).await.unwrap();
+ assert_eq!(first.access_token, "fresh");
+ assert_eq!(first.refresh_token, None, "unchanged refresh token must not be reported as rotated");
+ assert_eq!(first.instance_url.as_deref(), Some("https://acme.my.salesforce.com"));
+
+ let second = refresh_access_token_policy(&p, "old-refresh", policy).await.unwrap();
+ assert_eq!(second.access_token, "fresh2");
+ assert_eq!(second.refresh_token.as_deref(), Some("rotated"));
+ assert_eq!(second.instance_url, None);
+
+ server.abort();
+ // Copy the recorded body out so the MutexGuard drops before the next await.
+ let first_request = requests.lock().unwrap()[0].clone();
+ assert!(first_request.contains("grant_type=refresh_token"));
+ assert!(first_request.contains("refresh_token=old-refresh"));
+
+ assert!(refresh_access_token_policy(&p, " ", policy).await.unwrap_err().contains("refresh token is empty"));
+ }
+
+ #[tokio::test]
+ async fn oauth_protocol_errors_surface_description() {
+ let (base, _requests, server) = start_mock_oauth_server(vec![
+ r#"{"error":"invalid_grant","error_description":"expired access/refresh user"}"#.to_string(),
+ ])
+ .await;
+ let err = refresh_access_token_policy(&params(&base), "whatever", EndpointPolicy::AllowLoopbackHttp)
+ .await
+ .unwrap_err();
+ server.abort();
+ assert!(err.contains("invalid_grant"), "{err}");
+ assert!(err.contains("expired access/refresh user"), "{err}");
+ }
+
+ #[test]
+ fn external_config_auth_round_trips_into_params() {
+ let config = serde_json::json!({
+ "apiVersion": "v62.0",
+ "auth": {
+ "environment": "sandbox",
+ "clientId": "3MVG9xxx",
+ "clientSecret": "secret",
+ "refreshToken": "refresh-abc"
+ }
+ });
+ let (params, method) = oauth_params_from_external_config(Some(&config)).unwrap();
+ assert_eq!(method, SfRefreshMethod::RefreshToken("refresh-abc".to_string()));
+ assert_eq!(params.environment, SfLoginEnvironment::Sandbox);
+ assert_eq!(params.client_id, "3MVG9xxx");
+ assert_eq!(params.client_secret.as_deref(), Some("secret"));
+ // missing refresh token => no oauth context (manual token connection)
+ let manual = serde_json::json!({ "auth": { "clientId": "x" } });
+ assert!(oauth_params_from_external_config(Some(&manual)).is_none());
+ assert!(oauth_params_from_external_config(None).is_none());
+ // custom environment keeps loginUrl
+ let custom = serde_json::json!({
+ "auth": { "environment": "custom", "loginUrl": "https://acme.my.salesforce.com", "clientId": "c", "refreshToken": "r" }
+ });
+ let (params, _) = oauth_params_from_external_config(Some(&custom)).unwrap();
+ assert_eq!(params.environment, SfLoginEnvironment::Custom);
+ assert_eq!(params.login_url.as_deref(), Some("https://acme.my.salesforce.com"));
+ }
+
+ #[test]
+ fn external_config_auth_parses_password_mode() {
+ let config = serde_json::json!({
+ "auth": {
+ "mode": "password",
+ "environment": "sandbox",
+ "clientId": "3MVG9xxx",
+ "clientSecret": "secret",
+ "username": "[email protected]",
+ "password": "pw+securitytoken"
+ }
+ });
+ let (params, method) = oauth_params_from_external_config(Some(&config)).unwrap();
+ assert_eq!(params.environment, SfLoginEnvironment::Sandbox);
+ assert_eq!(
+ method,
+ SfRefreshMethod::Password { username: "[email protected]".into(), password: "pw+securitytoken".into() }
+ );
+ // password mode without stored password (scrubbed, not yet hydrated) => no context
+ let missing_pw = serde_json::json!({
+ "auth": { "mode": "password", "clientId": "c", "username": "u" }
+ });
+ assert!(oauth_params_from_external_config(Some(&missing_pw)).is_none());
+ // explicit mode:password wins over a leftover refreshToken
+ let hybrid = serde_json::json!({
+ "auth": { "mode": "password", "clientId": "c", "username": "u", "password": "p", "refreshToken": "r" }
+ });
+ let (_, method) = oauth_params_from_external_config(Some(&hybrid)).unwrap();
+ assert!(matches!(method, SfRefreshMethod::Password { .. }));
+ }
+
+ #[tokio::test]
+ async fn password_grant_posts_ropc_form_and_returns_tokens() {
+ let (base, requests, server) = start_mock_oauth_server(vec![
+ r#"{"access_token":"ropc-token","instance_url":"https://acme--qas1.sandbox.my.salesforce.com/","id":"https://test.salesforce.com/id/00D/005"}"#.to_string(),
+ ])
+ .await;
+ let mut p = params(&base);
+ p.client_secret = Some("app-secret".to_string());
+ let tokens =
+ password_grant_token_policy(&p, "[email protected]", "pw+token", EndpointPolicy::AllowLoopbackHttp)
+ .await
+ .unwrap();
+ server.abort();
+ assert_eq!(tokens.access_token, "ropc-token");
+ assert_eq!(tokens.refresh_token, None, "ROPC issues no refresh token");
+ assert_eq!(tokens.instance_url, "https://acme--qas1.sandbox.my.salesforce.com");
+ // Copy the recorded body out so the MutexGuard drops before the next await.
+ let first_request = requests.lock().unwrap()[0].clone();
+ assert!(first_request.contains("grant_type=password"));
+ assert!(first_request.contains("client_secret=app-secret"));
+ assert!(first_request.contains("format=json"));
+ // password is form-encoded, '+' must not leak as a space separator
+ assert!(first_request.contains("pw%2Btoken"), "{first_request}");
+
+ assert!(password_grant_token_policy(&p, "", "x", EndpointPolicy::AllowLoopbackHttp)
+ .await
+ .unwrap_err()
+ .contains("username and password are required"));
+ }
+
+ #[tokio::test]
+ async fn password_grant_invalid_grant_error_lists_common_causes() {
+ let (base, _requests, server) = start_mock_oauth_server(vec![
+ r#"{"error":"invalid_grant","description":"authentication failure"}"#.to_string(),
+ ])
+ .await;
+ let err =
+ password_grant_token_policy(&params(&base), "u", "p", EndpointPolicy::AllowLoopbackHttp).await.unwrap_err();
+ server.abort();
+ assert!(err.contains("invalid_grant"), "{err}");
+ assert!(err.contains("security token"), "{err}");
+ assert!(err.contains("MFA"), "{err}");
+ }
+}
diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs
index d9624637c5..15993437d6 100644
--- a/crates/dbx-mcp/src/backend.rs
+++ b/crates/dbx-mcp/src/backend.rs
@@ -8,7 +8,7 @@ use async_trait::async_trait;
use dbx_core::{
agent_events::{ToolCall, ToolResult},
agent_tools::{self, format_query_result_as_text, AgentSqlPermissions, QueryCellWindow},
- connection::{connection_configs_pool_equivalent, AppState, ConnectionLifecycleSnapshot},
+ connection::{connection_configs_pool_equivalent, AppState, ConnectionLifecycleSnapshot, SalesforceCurrentUser},
db::{mongo_driver::MongoIndexSpec, redis_driver::RedisCommandResult, ColumnInfo, TableInfo},
history::HistoryEntry,
mcp_policy::{connection_group_paths, McpConnectionGroupPath},
@@ -87,6 +87,9 @@ fn effective_mcp_policy_with_legacy_allow_writes(
for rule in &mut policy.connection_policies {
rule.read_only = true;
rule.allow_dangerous_sql = false;
+ // An unconfirmed CLI run must not reach Salesforce DML either: the
+ // connection opt-in is a write permission like any other here.
+ rule.allow_salesforce_dml = false;
rule.execution_mode_configured = true;
rule.execution_mode_policy_version = Some(dbx_core::mcp_policy::MCP_EXECUTION_POLICY_VERSION);
for database_policy in &mut rule.database_policies {
@@ -390,6 +393,14 @@ pub trait DbxBackend: Send + Sync {
let _ = (connection, database, command);
Err("MongoDB shell commands are not supported by this backend.".to_string())
}
+ /// Connected-user identity for a Salesforce connection: who a write would be
+ /// attributed to, plus the profile's "Modify All Data" flag. Salesforce has
+ /// no session-scoped identity, so this reads the pool's cached user info and
+ /// creates the pool when the MCP process is still cold.
+ async fn salesforce_current_user(&self, connection: &ConnectionConfig) -> Result<SalesforceCurrentUser, String> {
+ let _ = connection;
+ Err("Salesforce identity is not supported by this backend.".to_string())
+ }
/// Release the connection pool pinned by an MCP session (`client_session_id`).
async fn close_client_session(
&self,
@@ -1253,6 +1264,19 @@ impl DbxBackend for LocalBackend {
dbx_core::mongo_ops::execute_mongo_command_core(&self.state, &connection.id, database, command, 100).await
}
+ async fn salesforce_current_user(&self, connection: &ConnectionConfig) -> Result<SalesforceCurrentUser, String> {
+ if connection.db_type != DatabaseType::Salesforce {
+ return Err("Not a Salesforce connection".to_string());
+ }
+ // The identity is the pool's cached connected-user record, so a cold MCP
+ // process has to establish the connection first — the same thing the
+ // metadata paths above do before reading pool state.
+ if self.state.pool_handle(&connection.id).await.is_none() {
+ self.state.get_or_create_pool(&connection.id, None).await?;
+ }
+ self.state.salesforce_current_user(&connection.id).await
+ }
+
async fn close_client_session(
&self,
connection_id: &str,
@@ -1838,6 +1862,19 @@ impl DbxBackend for WebBackend {
.map_err(|error| format!("Invalid Redis command response: {error}"))
}
+ async fn salesforce_current_user(&self, connection: &ConnectionConfig) -> Result<SalesforceCurrentUser, String> {
+ self.ensure_connected(connection).await?;
+ self.request(
+ reqwest::Method::GET,
+ &format!("/api/salesforce/current-user?connection_id={}", url_encode(&connection.id)),
+ None,
+ )
+ .await?
+ .json()
+ .await
+ .map_err(|error| format!("Invalid Salesforce identity response: {error}"))
+ }
+
async fn execute_mongo_command(
&self,
connection: &ConnectionConfig,
@@ -2684,6 +2721,35 @@ mod tests {
assert!(effective_mcp_policy_with_legacy_allow_writes(policy_state(true, true), None).read_only);
}
+ #[test]
+ fn legacy_read_only_also_revokes_the_salesforce_dml_opt_in() {
+ // DBX_MCP_ALLOW_WRITES=0 marks an unconfirmed CLI run. The Salesforce DML
+ // opt-in is a write permission like any other, so it must be withdrawn
+ // with the rest — an opted-in connection must not become writable just
+ // because the org speaks REST instead of SQL.
+ let mut state = policy_state(true, false);
+ state.connection_policies = vec![dbx_core::storage::McpConnectionPolicy {
+ connection_id: "sfdc".to_string(),
+ read_only: false,
+ allow_dangerous_sql: true,
+ execution_mode_configured: false,
+ execution_mode_policy_version: None,
+ database_scope: dbx_core::storage::McpDatabaseScope::All,
+ allowed_databases: Vec::new(),
+ database_policies: Vec::new(),
+ allow_salesforce_dml: true,
+ }];
+
+ let forced = effective_mcp_policy_with_legacy_allow_writes(state.clone(), Some(false));
+ assert!(forced.read_only);
+ assert!(!forced.connection_policies[0].allow_salesforce_dml);
+ assert!(!forced.connection_policies[0].allow_dangerous_sql);
+
+ // Without the env override the stored opt-in survives untouched.
+ let untouched = effective_mcp_policy_with_legacy_allow_writes(state, None);
+ assert!(untouched.connection_policies[0].allow_salesforce_dml);
+ }
+
#[test]
fn parses_database_type_using_dbx_protocol_names() {
assert_eq!(parse_database_type("Postgres").unwrap(), DatabaseType::Postgres);
diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs
index 93a5a1689e..9030d78e09 100644
--- a/crates/dbx-mcp/src/server.rs
+++ b/crates/dbx-mcp/src/server.rs
@@ -1,4 +1,4 @@
-use std::{collections::HashMap, sync::Arc, time::Instant};
+use std::{collections::HashMap, sync::Arc, time::Duration, time::Instant};
use rmcp::{
handler::server::{router::tool::ToolRouter, wrapper::Parameters},
@@ -17,16 +17,19 @@ use dbx_core::{
agent_tools::{
format_query_result_as_text, normalize_sql_for_confirmation, QueryCellWindow, MAX_EXECUTE_QUERY_ROWS,
},
+ connection::SalesforceCurrentUser,
database_manifest,
db::redis_driver::{classify_command, parse_command_argv, RedisCommandResult, RedisCommandSafety},
+ db::salesforce_driver::parse_salesforce_statement,
history::HistoryEntry,
+ mcp_policy::connection_allows_salesforce_dml,
models::connection::ConnectionConfig,
models::connection::DatabaseType,
production_safety::{
is_production_database, mongo_pipeline_targets_production_database, sql_references_disallowed_database,
targets_production_database,
},
- query_execution_sql::is_write_sql_for_database,
+ query_execution_sql::{classify_salesforce_statement_risk, is_write_sql_for_database, SalesforceStatementRisk},
sql_risk::{
classify_sql_risk_for_database, is_dangerous_sql_for_database, mcp_sql_has_forbidden_database_switch, SqlRisk,
},
@@ -369,11 +372,129 @@ pub struct ExecuteBatchQueryRequest {
pub use_transaction: Option<bool>,
}
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct SalesforceIdentityRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct SalesforcePrepareWriteRequest {
+ #[serde(flatten)]
+ pub selector: ConnectionSelector,
+ #[schemars(
+ description = "Database name. Salesforce has no databases, so omit this unless DBX MCP settings scope the connection."
+ )]
+ #[schemars(extend("type" = "string"))]
+ pub database: Option<String>,
+ #[schemars(description = "Write operation: \"insert\", \"update\" or \"delete\". One record per call.")]
+ pub op: String,
+ #[schemars(
+ description = "Salesforce object API name, e.g. \"Account\", \"Contact\" or a custom object such as \"Invoice__c\"."
+ )]
+ pub object: String,
+ #[schemars(
+ description = "Record Id of the row to change. Required for update and delete; omit for insert, where Salesforce assigns it."
+ )]
+ #[schemars(extend("type" = "string"))]
+ pub id: Option<String>,
+ #[schemars(
+ description = "Field API name to value map, e.g. {\"Name\": \"Acme\", \"AnnualRevenue\": 1200}. Required and non-empty for insert and update; omit for delete. Never include \"Id\"."
+ )]
+ #[schemars(extend("type" = "object"))]
+ pub fields: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct SalesforceApplyWriteRequest {
+ #[schemars(
+ description = "The confirm_token returned by dbx_salesforce_prepare_write. Single-use, and valid only for the exact write that was summarized."
+ )]
+ pub confirm_token: String,
+}
+
+/// How long a prepared Salesforce write stays applicable. Long enough for an
+/// agent to show the summary and for a human to answer, short enough that a
+/// token left in a transcript cannot be replayed much later against a changed
+/// org.
+const SALESFORCE_WRITE_CONFIRM_TTL: Duration = Duration::from_secs(300);
+/// Ceiling on simultaneously pending confirmations. Prepared writes live in
+/// process memory, so an agent that prepares in a loop must not be able to grow
+/// the map without bound.
+const SALESFORCE_WRITE_PENDING_LIMIT: usize = 64;
+/// Field rows shown in a confirmation summary before it collapses the rest into
+/// a count. The full statement is still in `structured_content`.
+const SALESFORCE_SUMMARY_MAX_FIELDS: usize = 40;
+/// Characters of one field value shown in the summary.
+const SALESFORCE_SUMMARY_MAX_VALUE_CHARS: usize = 200;
+/// Header the Salesforce driver routes to its REST DML endpoints. Mirrors
+/// `dbx-sql`'s grid save builder; the driver matches it case-insensitively.
+const SALESFORCE_DML_HEADER: &str = "DBX SALESFORCE DML";
+
+/// One write prepared by `dbx_salesforce_prepare_write` and waiting for its
+/// `dbx_salesforce_apply_write` call.
+///
+/// Salesforce has no transactions and no rollback, so this confirmation step is
+/// the only place a write can still be stopped. The statement text is captured
+/// here verbatim and re-sent verbatim: what the summary showed the user is
+/// exactly what the org receives, and an agent cannot widen it in between.
+#[derive(Debug, Clone)]
+struct PendingSalesforceWrite {
+ connection_id: String,
+ database: String,
+ statement: String,
+ created_at: Instant,
+}
+
+#[derive(Debug)]
+struct PendingSalesforceWrites {
+ ttl: Duration,
+ entries: tokio::sync::Mutex<HashMap<String, PendingSalesforceWrite>>,
+}
+
+impl PendingSalesforceWrites {
+ fn new(ttl: Duration) -> Arc<Self> {
+ Arc::new(Self { ttl, entries: tokio::sync::Mutex::new(HashMap::new()) })
+ }
+
+ fn ttl_secs(&self) -> u64 {
+ self.ttl.as_secs()
+ }
+
+ fn is_expired(&self, pending: &PendingSalesforceWrite) -> bool {
+ pending.created_at.elapsed() >= self.ttl
+ }
+
+ /// Store a prepared write under its token, dropping expired entries first
+ /// and then the oldest ones until the cap has room.
+ async fn insert(&self, token: String, pending: PendingSalesforceWrite) {
+ let mut entries = self.entries.lock().await;
+ entries.retain(|_, entry| !self.is_expired(entry));
+ while entries.len() >= SALESFORCE_WRITE_PENDING_LIMIT {
+ let Some(oldest) = entries.iter().min_by_key(|(_, entry)| entry.created_at).map(|(token, _)| token.clone())
+ else {
+ break;
+ };
+ entries.remove(&oldest);
+ }
+ entries.insert(token, pending);
+ }
+
+ /// Consume a token. Single-use by design: a failed apply, a retry, or a
+ /// second call with the same token all have to go back through prepare, so
+ /// every write that reaches Salesforce was summarized again first.
+ async fn take(&self, token: &str) -> Option<PendingSalesforceWrite> {
+ let entry = self.entries.lock().await.remove(token.trim())?;
+ (!self.is_expired(&entry)).then_some(entry)
+ }
+}
+
#[derive(Clone)]
pub struct DbxMcpServer {
backend: Arc<dyn DbxBackend>,
scope: McpScope,
sessions: Arc<McpSessionStore>,
+ pending_salesforce_writes: Arc<PendingSalesforceWrites>,
tool_router: ToolRouter<Self>,
}
@@ -462,7 +583,13 @@ impl DbxMcpServer {
tool_router.disable_route("dbx_send_message");
tool_router.disable_route("dbx_peek_messages");
}
- Self { backend, scope, sessions: McpSessionStore::new(), tool_router }
+ Self {
+ backend,
+ scope,
+ sessions: McpSessionStore::new(),
+ pending_salesforce_writes: PendingSalesforceWrites::new(SALESFORCE_WRITE_CONFIRM_TTL),
+ tool_router,
+ }
}
fn spawn_session_cleanup(&self, session: McpSession) -> tokio::sync::oneshot::Receiver<SessionCleanupResult> {
@@ -786,6 +913,22 @@ impl DbxMcpServer {
"Redis connections do not accept SQL through dbx_execute_query. Use dbx_execute_redis_command.",
);
}
+ if connection.db_type == DatabaseType::Salesforce
+ && !is_database_discovery_sql(&request.sql)
+ && is_write_sql_for_database(&request.sql, DatabaseType::Salesforce)
+ {
+ // SOQL has no write verbs, so anything the Salesforce classifier reads
+ // as a write here is a `DBX SALESFORCE DML` pseudo-command. Letting it
+ // ride along as a "query" would bypass both the connection's DML opt-in
+ // and the two-step confirmation, and Salesforce cannot roll it back.
+ // `SHOW DATABASES` is the one non-SOQL probe exempted: SOQL rules read
+ // every non-SELECT as opaque, and the discovery path below answers it
+ // with the "one org is one scope" explanation instead.
+ return tool_error(
+ "SALESFORCE_DML_REQUIRES_CONFIRMATION",
+ "Salesforce writes cannot run through dbx_execute_query. Call dbx_salesforce_prepare_write, show its summary to the user, then dbx_salesforce_apply_write with the confirm_token it returns.",
+ );
+ }
if sql_requires_batch_execution(&request.sql, connection.db_type) {
return self
.execute_batch_request(ExecuteBatchQueryRequest {
@@ -1072,6 +1215,12 @@ impl DbxMcpServer {
Err(error) => return error,
};
let connection = &resolved.connection;
+ if connection.db_type == DatabaseType::Salesforce {
+ return tool_error(
+ "DBX_BATCH_UNSUPPORTED",
+ "Salesforce has no batch execution: SOQL is read-only and every write touches exactly one record. Use dbx_execute_query for SOQL, and dbx_salesforce_prepare_write followed by dbx_salesforce_apply_write for a write.",
+ );
+ }
if matches!(connection.db_type, DatabaseType::Redis | DatabaseType::MongoDb) {
return tool_error(
"DBX_BATCH_UNSUPPORTED",
@@ -1434,6 +1583,12 @@ impl DbxMcpServer {
Err(error) => return error,
};
let connection = &resolved.connection;
+ if connection.db_type == DatabaseType::Salesforce {
+ return tool_error(
+ "SESSION_UNSUPPORTED",
+ "Salesforce connections are stateless REST calls: there is no session to pin, no USE, and no transaction. Use dbx_execute_query for SOQL, and dbx_salesforce_prepare_write followed by dbx_salesforce_apply_write for a write.",
+ );
+ }
if matches!(connection.db_type, DatabaseType::Redis | DatabaseType::MongoDb) {
return tool_error(
"SESSION_UNSUPPORTED",
@@ -2220,10 +2375,213 @@ impl DbxMcpServer {
Err(error) => backend_tool_error("DBX_NOT_RUNNING", error),
}
}
+
+ #[tool(
+ name = "dbx_salesforce_current_user",
+ description = "Show the Salesforce identity behind a DBX connection: the connected user, their profile, whether that profile holds \"Modify All Data\" (which bypasses field-level security and record sharing), and the org. Read-only. Call it before preparing a write so the user knows who the change will be attributed to, and to tell a permission failure apart from a bad record Id."
+ )]
+ async fn salesforce_current_user(
+ &self,
+ Parameters(request): Parameters<SalesforceIdentityRequest>,
+ ) -> CallToolResult {
+ if let Err(error) = self.ensure_tool_allowed("dbx_salesforce_current_user").await {
+ return error;
+ }
+ let resolved = match self.resolve_connection(&request.selector).await {
+ Ok(resolved) => resolved,
+ Err(error) => return error,
+ };
+ let connection = &resolved.connection;
+ if connection.db_type != DatabaseType::Salesforce {
+ return not_salesforce_error(connection);
+ }
+ match self.backend.salesforce_current_user(connection).await {
+ Ok(identity) => {
+ let mut result = text(format_salesforce_identity_block(connection, Some(&identity)));
+ result.structured_content = Some(salesforce_identity_json(&identity));
+ result
+ }
+ Err(error) => tool_error("SALESFORCE_IDENTITY_ERROR", error),
+ }
+ }
+
+ #[tool(
+ name = "dbx_salesforce_prepare_write",
+ description = "Step 1 of 2 for a Salesforce write: prepare an insert, update or delete of exactly ONE record. Nothing is sent to Salesforce. The call validates the request against DBX MCP policy and returns a human-readable summary plus a single-use confirm_token. Show that summary to the user and wait for their approval, then call dbx_salesforce_apply_write with the token. Salesforce has no transactions, so an applied write cannot be rolled back. Reads never need this: use dbx_execute_query with SOQL."
+ )]
+ async fn salesforce_prepare_write(
+ &self,
+ Parameters(request): Parameters<SalesforcePrepareWriteRequest>,
+ ) -> CallToolResult {
+ if let Err(error) = self.ensure_tool_allowed("dbx_salesforce_prepare_write").await {
+ return error;
+ }
+ let resolved = match self.resolve_connection(&request.selector).await {
+ Ok(resolved) => resolved,
+ Err(error) => return error,
+ };
+ let connection = &resolved.connection;
+ if connection.db_type != DatabaseType::Salesforce {
+ return not_salesforce_error(connection);
+ }
+ let database = match self.resolve_database(request.database, &resolved) {
+ Ok(database) => database,
+ Err(error) => return error,
+ };
+ if !connection_allows_salesforce_dml(&resolved.policy, &connection.id) {
+ return tool_error(
+ "SALESFORCE_DML_DISABLED",
+ format!(
+ "Salesforce writes are disabled for connection \"{}\". The user has to enable the \"Allow DML\" switch for this connection in DBX Settings → MCP, and the connection must not be read-only. Reads are unaffected: use dbx_execute_query with SOQL.",
+ connection.name
+ ),
+ );
+ }
+ let statement = match build_salesforce_dml_statement(
+ &request.op,
+ &request.object,
+ request.id.as_deref(),
+ request.fields.as_ref(),
+ ) {
+ Ok(statement) => statement,
+ Err(error) => return tool_error("SALESFORCE_DML_INVALID", error),
+ };
+ // The driver is the authority on what a statement means. Refusing here
+ // rather than at apply time means a token is never handed out for a write
+ // the org would reject.
+ if let Err(error) = parse_salesforce_statement(&statement) {
+ return tool_error("SALESFORCE_DML_INVALID", error);
+ }
+ let policy =
+ effective_policy_for_database_with_groups(&resolved.policy, &resolved.group_ids, connection, &database);
+ // The same envelope every other statement passes through: global and
+ // connection read-only rules, the high-risk tier for a write whose scope
+ // the classifier cannot pin down, and the production block. SOQL and the
+ // DML pseudo-command cannot name another database, so the SQL
+ // database-scope guards have nothing to add here.
+ if let Err(error) = validate_sql_policy(connection, &policy, &database, &statement, false) {
+ return error;
+ }
+ // Best effort: a failed identity lookup must not block the confirmation,
+ // it only leaves the "signed in as" line out of the summary.
+ let identity = self.backend.salesforce_current_user(connection).await.ok();
+ let token = format!("sfdml-{}", Uuid::new_v4());
+ let expires_in_secs = self.pending_salesforce_writes.ttl_secs();
+ self.pending_salesforce_writes
+ .insert(
+ token.clone(),
+ PendingSalesforceWrite {
+ connection_id: connection.id.clone(),
+ database: database.clone(),
+ statement: statement.clone(),
+ created_at: Instant::now(),
+ },
+ )
+ .await;
+ let summary =
+ format_salesforce_write_summary(&statement, connection, identity.as_ref(), &token, expires_in_secs);
+ let mut result = text(summary);
+ result.structured_content = Some(json!({
+ "confirm_token": token,
+ "expires_in_secs": expires_in_secs,
+ "connection_id": connection.id,
+ "statement": statement,
+ "identity": identity.as_ref().map(salesforce_identity_json),
+ }));
+ result
+ }
+
+ #[tool(
+ name = "dbx_salesforce_apply_write",
+ description = "Step 2 of 2 for a Salesforce write: execute exactly the write prepared by dbx_salesforce_prepare_write, identified by its confirm_token. The token is single-use, expires 5 minutes after it was issued, and is bound to that one statement — a changed write needs a new prepare. Call this only after the user has approved the summary they were shown. Returns the Salesforce result, or the org's own per-record error text."
+ )]
+ async fn salesforce_apply_write(
+ &self,
+ Parameters(request): Parameters<SalesforceApplyWriteRequest>,
+ ) -> CallToolResult {
+ if let Err(error) = self.ensure_tool_allowed("dbx_salesforce_apply_write").await {
+ return error;
+ }
+ let Some(pending) = self.pending_salesforce_writes.take(&request.confirm_token).await else {
+ return tool_error(
+ "CONFIRM_TOKEN_INVALID",
+ format!(
+ "No pending Salesforce write for confirm_token \"{}\". Tokens are single-use and expire {} seconds after they are issued; call dbx_salesforce_prepare_write again and show the new summary to the user.",
+ request.confirm_token.trim(),
+ self.pending_salesforce_writes.ttl_secs()
+ ),
+ );
+ };
+ // Re-read the connection and the whole policy envelope at apply time: the
+ // user may have flipped the connection to read-only, withdrawn the DML
+ // opt-in or narrowed the scope while the summary was on screen.
+ let resolved = match self
+ .resolve_connection(&ConnectionSelector {
+ connection_id: Some(pending.connection_id.clone()),
+ connection_name: None,
+ })
+ .await
+ {
+ Ok(resolved) => resolved,
+ Err(error) => return error,
+ };
+ let connection = &resolved.connection;
+ if connection.db_type != DatabaseType::Salesforce {
+ return not_salesforce_error(connection);
+ }
+ if !connection_allows_salesforce_dml(&resolved.policy, &connection.id) {
+ return tool_error(
+ "SALESFORCE_DML_DISABLED",
+ format!(
+ "Salesforce writes were disabled for connection \"{}\" after this write was prepared. Nothing was sent. Re-enable the \"Allow DML\" switch in DBX Settings → MCP and prepare the write again.",
+ connection.name
+ ),
+ );
+ }
+ let policy = effective_policy_for_database_with_groups(
+ &resolved.policy,
+ &resolved.group_ids,
+ connection,
+ &pending.database,
+ );
+ let permissions = match validate_sql_policy(connection, &policy, &pending.database, &pending.statement, false) {
+ Ok(permissions) => permissions,
+ Err(error) => return error,
+ };
+ let mut arguments = json!({ "sql": pending.statement, "limit": 1 });
+ if let Some(secs) = resolved.policy.query_timeout_secs {
+ arguments["timeout_secs"] = json!(secs);
+ }
+ let label = salesforce_write_label(&pending.statement);
+ let started_at = Instant::now();
+ let result = self
+ .backend
+ .execute_agent_tool(connection, &pending.database, "execute_query", arguments, permissions)
+ .await;
+ let success = !result.is_error;
+ let error = result.is_error.then(|| result.content.trim_start_matches("Error: ").to_string());
+ self.save_mcp_sql_history(connection, &pending.database, &pending.statement, started_at, success, error, None)
+ .await;
+ if !success {
+ return agent_result(result);
+ }
+ text(format!("Salesforce write applied: {label}.\n{}", result.content))
+ }
}
impl DbxMcpServer {
async fn list_databases_for_resolved(&self, resolved: &ResolvedConnection) -> CallToolResult {
+ if resolved.connection.db_type == DatabaseType::Salesforce
+ && !matches!(resolved.database_scope, DatabaseScope::None)
+ {
+ // An org has no database layer, so an empty list would read as a
+ // broken connection. Point at the surface that does exist instead.
+ return text(
+ "Salesforce has no databases: the whole org is one scope.\n\
+ List its objects with dbx_list_tables, then read them with dbx_execute_query using SOQL, e.g. SELECT Id, Name FROM Account LIMIT 10.\n\
+ Writes go through dbx_salesforce_prepare_write and dbx_salesforce_apply_write.",
+ );
+ }
match &resolved.database_scope {
DatabaseScope::None => tool_error(
"DATABASE_OUT_OF_SCOPE",
@@ -2595,6 +2953,17 @@ fn sql_requires_batch_execution(sql: &str, database_type: DatabaseType) -> bool
const BATCH_MAX_ROWS: usize = 100;
fn mcp_sql_activity_kind(sql: &str, database_type: DatabaseType) -> &'static str {
+ if database_type == DatabaseType::Salesforce {
+ // The generic path below derives the kind from SQL risk tiers, and the
+ // Salesforce tiers deliberately fail closed: an unscoped or unrecognized
+ // write lands in the DDL tier, which would file a record mutation under
+ // "schema_change". Every Salesforce statement is either a SOQL read or a
+ // DML write, so classify it as one unit instead.
+ return match classify_salesforce_statement_risk(sql) {
+ SalesforceStatementRisk::Read => "query",
+ SalesforceStatementRisk::ScopedWrite | SalesforceStatementRisk::OpaqueWrite => "data_change",
+ };
+ }
let risks = dbx_core::sql::sql_execution_plan_for_database(sql, database_type)
.statements
.into_iter()
@@ -2610,6 +2979,18 @@ fn mcp_sql_activity_kind(sql: &str, database_type: DatabaseType) -> &'static str
}
fn mcp_sql_operation(sql: &str, database_type: DatabaseType) -> String {
+ if database_type == DatabaseType::Salesforce {
+ // Naming the DML verb keeps history readable; "DBX" (the first word of
+ // the pseudo-command header) would say nothing about what changed.
+ return match classify_salesforce_statement_risk(sql) {
+ SalesforceStatementRisk::Read => "SELECT".to_string(),
+ SalesforceStatementRisk::ScopedWrite | SalesforceStatementRisk::OpaqueWrite => {
+ parse_salesforce_statement(sql)
+ .map(|parsed| parsed.op.as_str().to_ascii_uppercase())
+ .unwrap_or_else(|_| "DML".to_string())
+ }
+ };
+ }
dbx_core::sql::sql_execution_plan_for_database(sql, database_type)
.statements
.first()
@@ -3088,6 +3469,208 @@ fn validate_transaction_sql_shape(sql: &str) -> Result<(), String> {
Ok(())
}
+// CallToolResult is the transport-native error payload; boxing it would complicate every MCP call site.
+#[allow(clippy::result_large_err)]
+fn not_salesforce_error(connection: &ConnectionConfig) -> CallToolResult {
+ tool_error(
+ "NOT_SALESFORCE_CONNECTION",
+ format!(
+ "Connection \"{}\" is a {:?} connection, not Salesforce. The dbx_salesforce_* tools only work against a Salesforce org.",
+ connection.name, connection.db_type
+ ),
+ )
+}
+
+/// Build the exact `DBX SALESFORCE DML` pseudo-command the driver executes.
+///
+/// Validation lives here rather than in the driver so a rejected shape never
+/// receives a confirm token: the statement that gets summarized is the statement
+/// that gets sent, one record at a time. Upsert and bulk shapes are refused
+/// outright — the driver cannot express them, and a token must not promise what
+/// the org cannot do.
+fn build_salesforce_dml_statement(
+ op: &str,
+ object: &str,
+ id: Option<&str>,
+ fields: Option<&serde_json::Value>,
+) -> Result<String, String> {
+ let op = op.trim().to_ascii_lowercase();
+ let object = object.trim();
+ if object.is_empty() {
+ return Err("'object' must be a non-empty Salesforce object API name, e.g. \"Account\".".to_string());
+ }
+ let id = id.map(str::trim).filter(|id| !id.is_empty());
+ let fields = match fields {
+ None => None,
+ Some(serde_json::Value::Object(map)) => (!map.is_empty()).then_some(map),
+ Some(_) => return Err("'fields' must be a JSON object mapping field API names to values.".to_string()),
+ };
+ let body = match op.as_str() {
+ "insert" => {
+ if id.is_some() {
+ return Err("insert creates a new record: drop 'id' and let Salesforce assign it.".to_string());
+ }
+ let Some(fields) = fields else {
+ return Err("insert requires a non-empty 'fields' object.".to_string());
+ };
+ reject_salesforce_identity_field(fields)?;
+ json!({ "op": "insert", "object": object, "fields": fields })
+ }
+ "update" => {
+ let Some(id) = id else {
+ return Err("update requires the 'id' of the record to change.".to_string());
+ };
+ let Some(fields) = fields else {
+ return Err("update requires a non-empty 'fields' object.".to_string());
+ };
+ reject_salesforce_identity_field(fields)?;
+ json!({ "op": "update", "object": object, "id": id, "fields": fields })
+ }
+ "delete" => {
+ let Some(id) = id else {
+ return Err("delete requires the 'id' of the record to remove.".to_string());
+ };
+ if fields.is_some() {
+ return Err("delete takes no 'fields' — it removes the whole record.".to_string());
+ }
+ json!({ "op": "delete", "object": object, "id": id })
+ }
+ other => {
+ return Err(format!(
+ "Unknown op \"{other}\". Expected insert, update or delete — upsert, bulk and composite writes are not supported."
+ ));
+ }
+ };
+ Ok(format!("{SALESFORCE_DML_HEADER}\n{body}"))
+}
+
+/// `Id` is the record identity, never a write target: sending it would either be
+/// ignored (insert) or read as an attempt to re-key a record (update).
+fn reject_salesforce_identity_field(fields: &serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
+ if fields.keys().any(|name| name.eq_ignore_ascii_case("Id")) {
+ return Err(
+ "'fields' must not contain Id — the record identity is the 'id' parameter, and Salesforce assigns it on insert."
+ .to_string(),
+ );
+ }
+ if fields.keys().any(|name| name.trim().is_empty()) {
+ return Err("'fields' contains an empty field name.".to_string());
+ }
+ Ok(())
+}
+
+/// One-line description of a prepared statement, in the same words the driver
+/// uses in its own errors, so a summary and a failure line up.
+fn salesforce_write_label(statement: &str) -> String {
+ match parse_salesforce_statement(statement) {
+ Ok(parsed) => match parsed.id.as_deref().filter(|id| !id.is_empty()) {
+ Some(id) => format!("{} on {} (Id {id})", parsed.op.as_str(), parsed.object),
+ None => format!("{} on {}", parsed.op.as_str(), parsed.object),
+ },
+ // Unreachable for a token the server issued; keep the line honest anyway.
+ Err(_) => "Salesforce write".to_string(),
+ }
+}
+
+/// The confirmation an agent must show the user before applying a prepared
+/// write. It names the operation, the exact field values, and the identity the
+/// change will be attributed to, then states the two properties that make
+/// Salesforce different from SQL: no transaction and no rollback.
+fn format_salesforce_write_summary(
+ statement: &str,
+ connection: &ConnectionConfig,
+ identity: Option<&SalesforceCurrentUser>,
+ token: &str,
+ expires_in_secs: u64,
+) -> String {
+ let mut lines = vec!["Salesforce write prepared — nothing has been sent yet.".to_string(), String::new()];
+ match parse_salesforce_statement(statement) {
+ Ok(parsed) => {
+ lines.push(format!("Operation: {}", parsed.op.as_str()));
+ lines.push(format!("Object: {}", parsed.object));
+ if let Some(id) = parsed.id.as_deref().filter(|id| !id.is_empty()) {
+ lines.push(format!("Record Id: {id}"));
+ }
+ if let Some(fields) = parsed.fields.as_ref() {
+ lines.push(format!("Fields ({}):", fields.len()));
+ for (index, (name, value)) in fields.iter().enumerate() {
+ if index >= SALESFORCE_SUMMARY_MAX_FIELDS {
+ lines.push(format!(
+ " … and {} more (full statement in structured_content)",
+ fields.len() - index
+ ));
+ break;
+ }
+ lines.push(format!(" - {name} = {}", truncate_salesforce_value(value)));
+ }
+ }
+ }
+ Err(error) => lines.push(format!("Operation: unparseable ({error})")),
+ }
+ lines.push(String::new());
+ lines.push(format!("Connection: {} ({})", connection.name, connection.id));
+ lines.extend(format_salesforce_identity_lines(identity));
+ lines.push(String::new());
+ lines.push(
+ "Salesforce writes are not transactional: once applied, this cannot be rolled back. Field-level security, record sharing, validation rules and flows all still apply, and a refusal comes back as Salesforce's own error text."
+ .to_string(),
+ );
+ lines.push(String::new());
+ lines.push(format!(
+ "Show this summary to the user. Only if they approve, call dbx_salesforce_apply_write with confirm_token \"{token}\". The token is single-use and expires in {expires_in_secs} seconds; any change to the write needs a new dbx_salesforce_prepare_write."
+ ));
+ lines.join("\n")
+}
+
+/// The whole identity block, for `dbx_salesforce_current_user`.
+fn format_salesforce_identity_block(connection: &ConnectionConfig, identity: Option<&SalesforceCurrentUser>) -> String {
+ let mut lines = vec![format!("Salesforce identity for connection \"{}\" ({})", connection.name, connection.id)];
+ lines.extend(format_salesforce_identity_lines(identity));
+ lines.join("\n")
+}
+
+fn format_salesforce_identity_lines(identity: Option<&SalesforceCurrentUser>) -> Vec<String> {
+ let Some(identity) = identity else {
+ return vec![
+ "Signed in as: unknown — the identity lookup failed, so treat every permission as unverified. Salesforce still enforces its own rules on the write."
+ .to_string(),
+ ];
+ };
+ let profile = identity.profile_name.as_deref().map(str::trim).filter(|name| !name.is_empty()).unwrap_or("unknown");
+ let rights = match identity.is_admin {
+ Some(true) => "has \"Modify All Data\": it bypasses field-level security and record sharing",
+ Some(false) => "no \"Modify All Data\": field-level security and record sharing apply",
+ None => "\"Modify All Data\" could not be determined, so treat it as if it were granted",
+ };
+ vec![
+ format!("Signed in as: {} <{}> (user Id {})", identity.name, identity.email, identity.user_id),
+ format!("Organization: {} ({})", identity.org_name, identity.organization_id),
+ format!("Profile: \"{profile}\" — {rights}"),
+ ]
+}
+
+fn salesforce_identity_json(identity: &SalesforceCurrentUser) -> serde_json::Value {
+ json!({
+ "user_id": identity.user_id,
+ "name": identity.name,
+ "email": identity.email,
+ "username": identity.username,
+ "organization_id": identity.organization_id,
+ "org_name": identity.org_name,
+ "profile_name": identity.profile_name,
+ "is_admin": identity.is_admin,
+ })
+}
+
+fn truncate_salesforce_value(value: &serde_json::Value) -> String {
+ let rendered = value.to_string();
+ if rendered.chars().count() <= SALESFORCE_SUMMARY_MAX_VALUE_CHARS {
+ return rendered;
+ }
+ let kept: String = rendered.chars().take(SALESFORCE_SUMMARY_MAX_VALUE_CHARS).collect();
+ format!("{kept}…")
+}
+
// CallToolResult is the transport-native error payload; boxing it would complicate every MCP call site.
#[allow(clippy::result_large_err)]
fn validate_sql_policy(
@@ -3546,6 +4129,7 @@ mod tests {
transaction_open_after_owner: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>)>,
transaction_open_error: Option<String>,
policy_override: std::sync::Mutex<Option<McpGlobalPolicy>>,
+ salesforce_identity: Option<SalesforceCurrentUser>,
}
impl Default for FakeBackend {
@@ -3567,6 +4151,7 @@ mod tests {
transaction_open_after_owner: None,
transaction_open_error: None,
policy_override: std::sync::Mutex::new(None),
+ salesforce_identity: None,
}
}
}
@@ -3682,6 +4267,13 @@ mod tests {
}
}
+ async fn salesforce_current_user(
+ &self,
+ _connection: &ConnectionConfig,
+ ) -> Result<SalesforceCurrentUser, String> {
+ self.salesforce_identity.clone().ok_or_else(|| "no Salesforce pool".to_string())
+ }
+
#[cfg(feature = "mq-admin")]
async fn peek_messages(
&self,
@@ -3969,9 +4561,9 @@ mod tests {
let tools = server.tool_router.list_all();
let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
#[cfg(feature = "mq-admin")]
- assert_eq!(tools.len(), 22);
+ assert_eq!(tools.len(), 25);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(tools.len(), 20);
+ assert_eq!(tools.len(), 23);
#[cfg(feature = "mq-admin")]
assert!(names.contains(&"dbx_peek_messages"));
#[cfg(not(feature = "mq-admin"))]
@@ -3991,6 +4583,9 @@ mod tests {
assert!(names.contains(&"dbx_duplicate_connection"));
assert!(names.contains(&"dbx_remove_connection"));
assert!(names.contains(&"dbx_execute_redis_command"));
+ assert!(names.contains(&"dbx_salesforce_current_user"));
+ assert!(names.contains(&"dbx_salesforce_prepare_write"));
+ assert!(names.contains(&"dbx_salesforce_apply_write"));
assert!(names.contains(&"dbx_get_schema_context"));
assert!(names.contains(&"dbx_open_table"));
assert!(names.contains(&"dbx_execute_and_show"));
@@ -4238,9 +4833,9 @@ mod tests {
);
let names = server.tool_router.list_all().into_iter().map(|tool| tool.name).collect::<Vec<_>>();
#[cfg(feature = "mq-admin")]
- assert_eq!(names.len(), 17);
+ assert_eq!(names.len(), 20);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(names.len(), 15);
+ assert_eq!(names.len(), 18);
assert!(!names.iter().any(|name| name == "dbx_add_connection"));
assert!(!names.iter().any(|name| name == "dbx_duplicate_connection"));
assert!(!names.iter().any(|name| name == "dbx_remove_connection"));
@@ -4254,6 +4849,12 @@ mod tests {
assert!(names.iter().any(|name| name == "dbx_begin_transaction"));
assert!(names.iter().any(|name| name == "dbx_commit_transaction"));
assert!(names.iter().any(|name| name == "dbx_rollback_transaction"));
+ // The Salesforce tools act on the scoped connection itself, so connection
+ // scoping keeps them visible. What narrows them is the per-connection DML
+ // opt-in and the execution policy, both re-checked on every call.
+ assert!(names.iter().any(|name| name == "dbx_salesforce_current_user"));
+ assert!(names.iter().any(|name| name == "dbx_salesforce_prepare_write"));
+ assert!(names.iter().any(|name| name == "dbx_salesforce_apply_write"));
#[cfg(feature = "mq-admin")]
assert!(names.iter().any(|name| name == "dbx_send_message"));
}
@@ -4384,6 +4985,7 @@ mod tests {
allow_dangerous_sql: false,
},
],
+ allow_salesforce_dml: false,
}],
..Default::default()
};
@@ -4422,6 +5024,7 @@ mod tests {
database_policies: Vec::new(),
execution_mode_configured: false,
execution_mode_policy_version: None,
+ allow_salesforce_dml: false,
}],
..Default::default()
},
@@ -4598,6 +5201,7 @@ mod tests {
allow_dangerous_sql: false,
},
],
+ allow_salesforce_dml: false,
}],
..Default::default()
};
@@ -5912,6 +6516,31 @@ mod tests {
);
}
+ #[test]
+ fn mcp_history_metadata_reads_salesforce_statements_as_one_unit() {
+ let database_type = DatabaseType::Salesforce;
+ assert_eq!(mcp_sql_activity_kind("SELECT Id FROM Account", database_type), "query");
+ assert_eq!(mcp_sql_operation("SELECT Id FROM Account", database_type), "SELECT");
+
+ let update = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001x\",\"fields\":{\"Name\":\"Acme\"}}";
+ assert_eq!(mcp_sql_activity_kind(update, database_type), "data_change");
+ assert_eq!(mcp_sql_operation(update, database_type), "UPDATE");
+
+ // An unscoped write fails closed to the high-risk tier, which the generic
+ // tier-based path would file under "schema_change". It is still a record
+ // mutation; only the driver's own parser can say which verb it was.
+ let unscoped = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\"}";
+ assert_eq!(mcp_sql_activity_kind(unscoped, database_type), "data_change");
+ assert_eq!(mcp_sql_operation(unscoped, database_type), "DML");
+
+ // A field value that reads like another statement is data, not a second
+ // statement: the label must not change because of what it contains.
+ let literal =
+ "DBX SALESFORCE DML\n{\"op\":\"insert\",\"object\":\"Lead\",\"fields\":{\"Description\":\"a; CREATE TABLE t (id int)\"}}";
+ assert_eq!(mcp_sql_activity_kind(literal, database_type), "data_change");
+ assert_eq!(mcp_sql_operation(literal, database_type), "INSERT");
+ }
+
#[tokio::test]
async fn execute_batch_rejects_transaction_with_session() {
let postgres = connection("pg", "pg", "postgres", "app");
@@ -6406,4 +7035,496 @@ mod tests {
let structured = result.structured_content.as_ref().expect("structured content must be populated");
assert_eq!(structured["results"][0]["merged"], true);
}
+
+ fn salesforce_connection() -> ConnectionConfig {
+ connection("sfdc", "Acme QA org", "salesforce", "")
+ }
+
+ fn salesforce_dml_policy(allow_dml: bool, read_only: bool) -> McpGlobalPolicy {
+ McpGlobalPolicy {
+ read_only: false,
+ allow_dangerous_sql: false,
+ connection_policies: vec![dbx_core::storage::McpConnectionPolicy {
+ connection_id: "sfdc".to_string(),
+ read_only,
+ allow_dangerous_sql: false,
+ execution_mode_configured: false,
+ execution_mode_policy_version: None,
+ database_scope: McpDatabaseScope::All,
+ allowed_databases: Vec::new(),
+ database_policies: Vec::new(),
+ allow_salesforce_dml: allow_dml,
+ }],
+ ..Default::default()
+ }
+ }
+
+ fn salesforce_identity(is_admin: Option<bool>) -> SalesforceCurrentUser {
+ SalesforceCurrentUser {
+ user_id: "005000000000000001".to_string(),
+ name: "Jane Doe".to_string(),
+ email: "[email protected]".to_string(),
+ organization_id: "00D000000000000001".to_string(),
+ username: "[email protected]".to_string(),
+ profile_name: Some("System Administrator".to_string()),
+ is_admin,
+ org_name: "Acme".to_string(),
+ }
+ }
+
+ fn salesforce_server(policy: McpGlobalPolicy, identity: Option<SalesforceCurrentUser>) -> Arc<FakeBackend> {
+ Arc::new(FakeBackend {
+ connections: vec![salesforce_connection()],
+ policy,
+ salesforce_identity: identity,
+ ..Default::default()
+ })
+ }
+
+ fn prepare_request(
+ op: &str,
+ object: &str,
+ id: Option<&str>,
+ fields: Option<serde_json::Value>,
+ ) -> Parameters<SalesforcePrepareWriteRequest> {
+ Parameters(SalesforcePrepareWriteRequest {
+ selector: selector("sfdc"),
+ database: None,
+ op: op.to_string(),
+ object: object.to_string(),
+ id: id.map(str::to_string),
+ fields,
+ })
+ }
+
+ fn confirm_token(result: &CallToolResult) -> String {
+ result.structured_content.as_ref().expect("prepare returns structured content")["confirm_token"]
+ .as_str()
+ .expect("confirm_token")
+ .to_string()
+ }
+
+ #[test]
+ fn salesforce_dml_builder_accepts_only_single_scoped_records() {
+ let update =
+ build_salesforce_dml_statement("UPDATE", " Account ", Some(" 001x "), Some(&json!({"Name": "Acme"})))
+ .expect("a scoped update is the shape the driver executes");
+ assert!(update.starts_with("DBX SALESFORCE DML\n"), "missing pseudo-command header: {update}");
+ assert_eq!(
+ classify_salesforce_statement_risk(&update),
+ SalesforceStatementRisk::ScopedWrite,
+ "a prepared write must never land in the read tier"
+ );
+ let parsed = parse_salesforce_statement(&update).expect("the driver must accept what prepare handed out");
+ assert_eq!(parsed.op.as_str(), "update");
+ assert_eq!(parsed.object, "Account");
+ assert_eq!(parsed.id.as_deref(), Some("001x"));
+ assert_eq!(parsed.fields.expect("fields")["Name"], json!("Acme"));
+ assert_eq!(salesforce_write_label(&update), "update on Account (Id 001x)");
+
+ let insert = build_salesforce_dml_statement("insert", "Lead", None, Some(&json!({"Company": "Acme"}))).unwrap();
+ assert_eq!(salesforce_write_label(&insert), "insert on Lead");
+ let delete = build_salesforce_dml_statement("delete", "Lead", Some("00Qx"), None).unwrap();
+ assert_eq!(salesforce_write_label(&delete), "delete on Lead (Id 00Qx)");
+
+ let rejected: Vec<(&str, Result<String, String>)> = vec![
+ ("no object", build_salesforce_dml_statement("update", " ", Some("001x"), Some(&json!({"Name": "a"})))),
+ ("no fields on insert", build_salesforce_dml_statement("insert", "Lead", None, None)),
+ ("empty fields", build_salesforce_dml_statement("insert", "Lead", None, Some(&json!({})))),
+ ("fields not an object", build_salesforce_dml_statement("insert", "Lead", None, Some(&json!(["Name"])))),
+ (
+ "id on insert",
+ build_salesforce_dml_statement("insert", "Lead", Some("00Qx"), Some(&json!({"Company": "a"}))),
+ ),
+ ("no id on update", build_salesforce_dml_statement("update", "Lead", None, Some(&json!({"Company": "a"})))),
+ ("no id on delete", build_salesforce_dml_statement("delete", "Lead", None, None)),
+ (
+ "fields on delete",
+ build_salesforce_dml_statement("delete", "Lead", Some("00Qx"), Some(&json!({"Company": "a"}))),
+ ),
+ (
+ "Id inside fields",
+ build_salesforce_dml_statement("update", "Lead", Some("00Qx"), Some(&json!({"id": "00Qy"}))),
+ ),
+ (
+ "empty field name",
+ build_salesforce_dml_statement("update", "Lead", Some("00Qx"), Some(&json!({" ": "x"}))),
+ ),
+ ("upsert", build_salesforce_dml_statement("upsert", "Lead", Some("00Qx"), Some(&json!({"Company": "a"})))),
+ ("raw sql", build_salesforce_dml_statement("DELETE FROM Lead", "Lead", None, None)),
+ ];
+ for (label, result) in rejected {
+ assert!(result.is_err(), "{label} must be refused, got {:?}", result.ok());
+ }
+ }
+
+ #[tokio::test]
+ async fn pending_salesforce_writes_are_single_use_and_expire() {
+ let statement =
+ build_salesforce_dml_statement("update", "Account", Some("001x"), Some(&json!({"Name": "Acme"}))).unwrap();
+ let pending = || PendingSalesforceWrite {
+ connection_id: "sfdc".to_string(),
+ database: String::new(),
+ statement: statement.clone(),
+ created_at: Instant::now(),
+ };
+
+ let live = PendingSalesforceWrites::new(SALESFORCE_WRITE_CONFIRM_TTL);
+ live.insert("sfdml-a".to_string(), pending()).await;
+ assert!(live.take("sfdml-a").await.is_some(), "a fresh token must apply");
+ assert!(live.take("sfdml-a").await.is_none(), "a token is single-use: a replay must not execute twice");
+ assert!(live.take(" sfdml-missing ").await.is_none());
+
+ let expired = PendingSalesforceWrites::new(Duration::ZERO);
+ expired.insert("sfdml-b".to_string(), pending()).await;
+ assert!(expired.take("sfdml-b").await.is_none(), "an expired token must not execute");
+ }
+
+ #[tokio::test]
+ async fn pending_salesforce_writes_stay_bounded() {
+ let store = PendingSalesforceWrites::new(SALESFORCE_WRITE_CONFIRM_TTL);
+ for index in 0..(SALESFORCE_WRITE_PENDING_LIMIT + 10) {
+ store
+ .insert(
+ format!("sfdml-{index}"),
+ PendingSalesforceWrite {
+ connection_id: "sfdc".to_string(),
+ database: String::new(),
+ statement: "DBX SALESFORCE DML\n{}".to_string(),
+ created_at: Instant::now(),
+ },
+ )
+ .await;
+ }
+ assert_eq!(store.entries.lock().await.len(), SALESFORCE_WRITE_PENDING_LIMIT);
+ }
+
+ #[tokio::test]
+ async fn salesforce_prepare_write_needs_an_explicit_connection_opt_in() {
+ for (label, policy) in [
+ ("no connection rule", McpGlobalPolicy::default()),
+ ("opt-in off", salesforce_dml_policy(false, false)),
+ ("opt-in void on read-only", salesforce_dml_policy(true, true)),
+ ] {
+ let backend = salesforce_server(policy, None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let prepared = server
+ .salesforce_prepare_write(prepare_request(
+ "update",
+ "Account",
+ Some("001x"),
+ Some(json!({"Name": "Acme"})),
+ ))
+ .await;
+ assert!(result_text(&prepared).contains("SALESFORCE_DML_DISABLED"), "{label}: {prepared:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty(), "{label} must not reach the org");
+ }
+ }
+
+ #[tokio::test]
+ async fn salesforce_prepare_write_summarises_the_write_and_the_identity() {
+ let backend = salesforce_server(salesforce_dml_policy(true, false), Some(salesforce_identity(Some(true))));
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let prepared = server
+ .salesforce_prepare_write(prepare_request(
+ "update",
+ "Account",
+ Some("001x"),
+ Some(json!({"Name": "Acme", "AnnualRevenue": 1200})),
+ ))
+ .await;
+ let summary = result_text(&prepared);
+ assert_ne!(prepared.is_error, Some(true), "{prepared:?}");
+ for expected in [
+ "nothing has been sent yet",
+ "Operation: update",
+ "Object: Account",
+ "Record Id: 001x",
+ "Name = \"Acme\"",
+ "AnnualRevenue = 1200",
+ "Jane Doe",
+ "\"System Administrator\"",
+ "Modify All Data",
+ "cannot be rolled back",
+ "dbx_salesforce_apply_write",
+ ] {
+ assert!(summary.contains(expected), "summary is missing \"{expected}\":\n{summary}");
+ }
+ assert!(confirm_token(&prepared).starts_with("sfdml-"));
+ assert_eq!(
+ prepared.structured_content.as_ref().unwrap()["statement"].as_str().unwrap(),
+ build_salesforce_dml_statement(
+ "update",
+ "Account",
+ Some("001x"),
+ Some(&json!({"Name": "Acme", "AnnualRevenue": 1200}))
+ )
+ .unwrap()
+ );
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty(), "prepare must not write");
+ }
+
+ #[tokio::test]
+ async fn salesforce_prepare_write_survives_a_failed_identity_lookup() {
+ let backend = salesforce_server(salesforce_dml_policy(true, false), None);
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+ let prepared = server.salesforce_prepare_write(prepare_request("delete", "Lead", Some("00Qx"), None)).await;
+ assert_ne!(prepared.is_error, Some(true), "{prepared:?}");
+ assert!(result_text(&prepared).contains("identity lookup failed"), "{}", result_text(&prepared));
+ }
+
+ #[tokio::test]
+ async fn salesforce_apply_write_sends_the_prepared_statement_exactly_once() {
+ let backend = salesforce_server(salesforce_dml_policy(true, false), Some(salesforce_identity(Some(false))));
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let prepared = server
+ .salesforce_prepare_write(prepare_request("update", "Account", Some("001x"), Some(json!({"Name": "Acme"}))))
+ .await;
+ let token = confirm_token(&prepared);
+ let statement = prepared.structured_content.as_ref().unwrap()["statement"].as_str().unwrap().to_string();
+
+ let applied = server
+ .salesforce_apply_write(Parameters(SalesforceApplyWriteRequest { confirm_token: token.clone() }))
+ .await;
+ assert_ne!(applied.is_error, Some(true), "{applied:?}");
+ assert!(
+ result_text(&applied).starts_with("Salesforce write applied: update on Account (Id 001x)."),
+ "{}",
+ result_text(&applied)
+ );
+
+ let recorded = backend.recorded_arguments.lock().unwrap().clone();
+ assert_eq!(recorded.len(), 1, "exactly one write reached the backend: {recorded:?}");
+ assert_eq!(recorded[0].0, "execute_query");
+ assert_eq!(
+ recorded[0].1["sql"].as_str(),
+ Some(statement.as_str()),
+ "the applied statement must be the prepared one"
+ );
+ assert_eq!(recorded[0].1["limit"], json!(1));
+
+ let history = backend.history.lock().unwrap().clone();
+ assert_eq!(history.len(), 1);
+ assert_eq!(history[0].sql, statement);
+ assert_eq!(history[0].operation, "UPDATE");
+ assert_eq!(history[0].activity_kind, "data_change");
+ assert!(history[0].success);
+
+ let replayed =
+ server.salesforce_apply_write(Parameters(SalesforceApplyWriteRequest { confirm_token: token })).await;
+ assert!(result_text(&replayed).contains("CONFIRM_TOKEN_INVALID"), "{replayed:?}");
+ assert_eq!(backend.recorded_arguments.lock().unwrap().len(), 1, "a replayed token must not write again");
+ }
+
+ #[tokio::test]
+ async fn salesforce_apply_write_rejects_a_token_it_never_issued() {
+ let backend = salesforce_server(salesforce_dml_policy(true, false), None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let applied = server
+ .salesforce_apply_write(Parameters(SalesforceApplyWriteRequest {
+ confirm_token: "sfdml-forged".to_string(),
+ }))
+ .await;
+ assert!(result_text(&applied).contains("CONFIRM_TOKEN_INVALID"), "{applied:?}");
+ assert!(result_text(&applied).contains("dbx_salesforce_prepare_write"));
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn salesforce_prepare_write_honours_read_only_and_production_rules() {
+ let read_only = McpGlobalPolicy { read_only: true, ..salesforce_dml_policy(true, false) };
+ let backend = salesforce_server(read_only, None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let prepared = server
+ .salesforce_prepare_write(prepare_request("update", "Account", Some("001x"), Some(json!({"Name": "Acme"}))))
+ .await;
+ assert!(result_text(&prepared).contains("MCP_READ_ONLY"), "{prepared:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+
+ let mut production = salesforce_connection();
+ production.is_production = true;
+ let backend = Arc::new(FakeBackend {
+ connections: vec![production],
+ policy: salesforce_dml_policy(true, false),
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let prepared = server
+ .salesforce_prepare_write(prepare_request("update", "Account", Some("001x"), Some(json!({"Name": "Acme"}))))
+ .await;
+ assert!(result_text(&prepared).contains("PRODUCTION_WRITE_BLOCKED"), "{prepared:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn salesforce_write_pseudo_commands_cannot_sneak_through_execute_query() {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![salesforce_connection()],
+ policy: McpGlobalPolicy { read_only: false, allow_dangerous_sql: true, ..Default::default() },
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let statement = build_salesforce_dml_statement("delete", "Account", Some("001x"), None).unwrap();
+ let blocked = server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("sfdc"),
+ database: None,
+ sql: statement,
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await;
+ assert!(result_text(&blocked).contains("SALESFORCE_DML_REQUIRES_CONFIRMATION"), "{blocked:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty(), "the write must not reach the org");
+
+ // SOQL stays readable even when a literal or a custom field name looks
+ // like a write verb to a keyword scan.
+ for soql in ["SELECT Id FROM Case WHERE Subject = 'Delete request'", "SELECT Id, Update__c FROM Lead LIMIT 5"] {
+ let queried = server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("sfdc"),
+ database: None,
+ sql: soql.to_string(),
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await;
+ assert_ne!(queried.is_error, Some(true), "{soql}: {queried:?}");
+ }
+ let recorded = backend.recorded_arguments.lock().unwrap().clone();
+ assert_eq!(recorded.len(), 2, "{recorded:?}");
+ assert_eq!(recorded[0].1["sql"], json!("SELECT Id FROM Case WHERE Subject = 'Delete request'"));
+ }
+
+ #[tokio::test]
+ async fn salesforce_database_discovery_probe_is_not_read_as_a_write() {
+ // `SHOW DATABASES` is not SOQL, so the Salesforce classifier calls it an
+ // opaque write. Answering it with "writes need confirmation" would send an
+ // agent looking for a schema into the DML flow; the discovery path already
+ // has the right answer.
+ let backend = salesforce_server(McpGlobalPolicy::default(), None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ for probe in ["SHOW DATABASES", " show schemas; "] {
+ let probed = server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("sfdc"),
+ database: None,
+ sql: probe.to_string(),
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await;
+ assert_ne!(probed.is_error, Some(true), "{probe}: {probed:?}");
+ assert!(result_text(&probed).contains("Salesforce has no databases"), "{probe}: {probed:?}");
+ }
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty(), "a discovery probe must not reach the org");
+
+ // The exemption is exact-match, so a pseudo-command still cannot use it as
+ // a way past the confirmation guard.
+ let smuggled = server
+ .execute_query(Parameters(ExecuteQueryRequest {
+ selector: selector("sfdc"),
+ database: None,
+ sql: "show databases; DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\",\"id\":\"001x\"}"
+ .to_string(),
+ session_id: None,
+ cell_char_offset: None,
+ cell_char_limit: None,
+ max_rows: None,
+ }))
+ .await;
+ assert!(result_text(&smuggled).contains("SALESFORCE_DML_REQUIRES_CONFIRMATION"), "{smuggled:?}");
+ }
+
+ #[tokio::test]
+ async fn salesforce_has_no_batch_and_no_session() {
+ let backend = salesforce_server(McpGlobalPolicy::default(), None);
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let batch = server
+ .execute_batch(Parameters(ExecuteBatchQueryRequest {
+ selector: selector("sfdc"),
+ database: None,
+ sql: "SELECT Id FROM Account".to_string(),
+ session_id: None,
+ continue_on_error: None,
+ use_transaction: None,
+ cell_window: CellWindowArgs::default(),
+ }))
+ .await;
+ assert!(result_text(&batch).contains("DBX_BATCH_UNSUPPORTED"), "{batch:?}");
+ let session = server
+ .open_session(Parameters(OpenSessionRequest {
+ selector: selector("sfdc"),
+ database: None,
+ enable_transactions: false,
+ }))
+ .await;
+ assert!(result_text(&session).contains("SESSION_UNSUPPORTED"), "{session:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn salesforce_list_databases_points_at_objects_and_soql() {
+ let backend = salesforce_server(McpGlobalPolicy::default(), None);
+ let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
+ let listed = server.list_databases(Parameters(ListDatabasesRequest { selector: selector("sfdc") })).await;
+ assert_ne!(listed.is_error, Some(true), "{listed:?}");
+ let text = result_text(&listed);
+ assert!(text.contains("Salesforce has no databases"), "{text}");
+ assert!(text.contains("dbx_list_tables"), "{text}");
+ assert!(text.contains("SELECT Id, Name FROM Account LIMIT 10"), "{text}");
+ }
+
+ #[tokio::test]
+ async fn salesforce_current_user_names_the_profile_rights() {
+ for (is_admin, expected) in [
+ (Some(true), "bypasses field-level security"),
+ (Some(false), "field-level security and record sharing apply"),
+ (None, "could not be determined"),
+ ] {
+ let backend = salesforce_server(McpGlobalPolicy::default(), Some(salesforce_identity(is_admin)));
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let identity = server
+ .salesforce_current_user(Parameters(SalesforceIdentityRequest { selector: selector("sfdc") }))
+ .await;
+ assert_ne!(identity.is_error, Some(true), "{identity:?}");
+ let text = result_text(&identity);
+ assert!(text.contains("Jane Doe"), "{text}");
+ assert!(text.contains(expected), "{text}");
+ assert_eq!(identity.structured_content.as_ref().unwrap()["is_admin"], json!(is_admin));
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty(), "identity must not run a query");
+ }
+ }
+
+ #[tokio::test]
+ async fn salesforce_tools_refuse_other_database_types() {
+ let backend = Arc::new(FakeBackend {
+ connections: vec![connection("pg", "pg", "postgres", "app")],
+ ..Default::default()
+ });
+ let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false);
+ let postgres_selector = || ConnectionSelector { connection_id: Some("pg".to_string()), connection_name: None };
+ let identity = server
+ .salesforce_current_user(Parameters(SalesforceIdentityRequest { selector: postgres_selector() }))
+ .await;
+ assert!(result_text(&identity).contains("NOT_SALESFORCE_CONNECTION"), "{identity:?}");
+ let prepared = server
+ .salesforce_prepare_write(Parameters(SalesforcePrepareWriteRequest {
+ selector: postgres_selector(),
+ database: None,
+ op: "update".to_string(),
+ object: "Account".to_string(),
+ id: Some("001x".to_string()),
+ fields: Some(json!({"Name": "Acme"})),
+ }))
+ .await;
+ assert!(result_text(&prepared).contains("NOT_SALESFORCE_CONNECTION"), "{prepared:?}");
+ assert!(backend.recorded_arguments.lock().unwrap().is_empty());
+ }
}
diff --git a/crates/dbx-mcp/tests/mongodb_databases.rs b/crates/dbx-mcp/tests/mongodb_databases.rs
index f420c60cc5..5fea81701e 100644
--- a/crates/dbx-mcp/tests/mongodb_databases.rs
+++ b/crates/dbx-mcp/tests/mongodb_databases.rs
@@ -57,6 +57,7 @@ async fn list_databases(
database_scope,
allowed_databases,
database_policies: Vec::new(),
+ allow_salesforce_dml: false,
}],
..Default::default()
})
diff --git a/crates/dbx-mcp/tests/protocol.rs b/crates/dbx-mcp/tests/protocol.rs
index 83b03d905f..1186fab5c1 100644
--- a/crates/dbx-mcp/tests/protocol.rs
+++ b/crates/dbx-mcp/tests/protocol.rs
@@ -328,9 +328,9 @@ async fn initializes_lists_tools_and_calls_a_tool() {
let tools = client.peer().list_tools(None).await.expect("list tools");
let names = tools.tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
#[cfg(feature = "mq-admin")]
- assert_eq!(names.len(), 22);
+ assert_eq!(names.len(), 25);
#[cfg(not(feature = "mq-admin"))]
- assert_eq!(names.len(), 20);
+ assert_eq!(names.len(), 23);
#[cfg(feature = "mq-admin")]
assert!(names.contains(&"dbx_peek_messages"));
#[cfg(not(feature = "mq-admin"))]
@@ -339,6 +339,9 @@ async fn initializes_lists_tools_and_calls_a_tool() {
assert!(names.contains(&"dbx_list_databases"));
assert!(names.contains(&"dbx_duplicate_connection"));
assert!(names.contains(&"dbx_execute_redis_command"));
+ assert!(names.contains(&"dbx_salesforce_current_user"));
+ assert!(names.contains(&"dbx_salesforce_prepare_write"));
+ assert!(names.contains(&"dbx_salesforce_apply_write"));
assert!(names.contains(&"dbx_execute_and_show"));
assert!(names.contains(&"dbx_execute_batch"));
assert!(names.contains(&"dbx_list_routines"));
diff --git a/crates/dbx-sql/src/data_grid_salesforce_sql.rs b/crates/dbx-sql/src/data_grid_salesforce_sql.rs
new file mode 100644
index 0000000000..28b994eea5
--- /dev/null
+++ b/crates/dbx-sql/src/data_grid_salesforce_sql.rs
@@ -0,0 +1,459 @@
+use serde_json::{Map, Value};
+
+use super::*;
+use crate::models::connection::DatabaseType;
+
+/// Header line emitted before every JSON body. The driver's
+/// `parse_salesforce_statement` matches this case-insensitively.
+const SALESFORCE_DML_HEADER: &str = "DBX SALESFORCE DML";
+
+/// Build the save statements for a Salesforce grid save. Order matches the
+/// generic SQL builder: updates, deletes, inserts (see `build_data_grid_save_statements`).
+///
+/// Each statement is a `DBX SALESFORCE DML` pseudo-command carrying a JSON
+/// body. The driver routes them to the appropriate REST endpoint.
+pub(super) fn build_salesforce_data_grid_save_statements(options: &DataGridSaveStatementOptions) -> Vec<String> {
+ let object = &options.table_meta.table_name;
+ let columns = resolve_salesforce_columns(options);
+ let column_info = options.table_meta.columns.as_deref().unwrap_or(&[]);
+ let id_column_index = find_salesforce_id_column_index(&columns, &options.table_meta.primary_keys);
+ let mut statements = Vec::new();
+
+ // 1. Updates (dirty_rows): one statement per dirty row, fields = only the changed columns.
+ for (row_index, changes) in &options.dirty_rows {
+ let Some(row) = options.rows.get(*row_index) else { continue };
+ let Some(id_index) = id_column_index else { continue };
+ let Some(id_value) = row.get(id_index).and_then(Value::as_str).filter(|s| !s.is_empty()) else {
+ continue;
+ };
+
+ let mut fields = Map::new();
+ for (column_index, value) in changes {
+ let Some(field_name) = columns.get(*column_index).and_then(|c| c.as_deref()) else { continue };
+ // Id is the identity, never a write target.
+ if field_name.eq_ignore_ascii_case("Id") {
+ continue;
+ }
+ // Skip columns marked non-updateable in the describe metadata.
+ if !salesforce_column_is_updateable(column_info_for(column_info, field_name)) {
+ continue;
+ }
+ fields.insert(field_name.to_string(), value.clone());
+ }
+ if fields.is_empty() {
+ continue;
+ }
+
+ let body = serde_json::json!({
+ "op": "update",
+ "object": object,
+ "id": id_value,
+ "fields": fields
+ });
+ statements.push(format!("{SALESFORCE_DML_HEADER}\n{body}"));
+ }
+
+ // 2. Deletes (deleted_rows): one statement per deleted row index.
+ for row_index in &options.deleted_rows {
+ let Some(row) = options.rows.get(*row_index) else { continue };
+ let Some(id_index) = id_column_index else { continue };
+ let Some(id_value) = row.get(id_index).and_then(Value::as_str).filter(|s| !s.is_empty()) else {
+ continue;
+ };
+
+ let body = serde_json::json!({
+ "op": "delete",
+ "object": object,
+ "id": id_value
+ });
+ statements.push(format!("{SALESFORCE_DML_HEADER}\n{body}"));
+ }
+
+ // 3. Inserts (new_rows): one statement per new row, skipping null and empty-string cells.
+ for row in &options.new_rows {
+ let mut fields = Map::new();
+ for (index, field_name) in columns.iter().enumerate() {
+ let Some(field_name) = field_name.as_deref() else { continue };
+ // Id is server-generated for inserts; never send it.
+ if field_name.eq_ignore_ascii_case("Id") {
+ continue;
+ }
+ // Skip columns marked non-createable in the describe metadata.
+ if !salesforce_column_is_createable(column_info_for(column_info, field_name)) {
+ continue;
+ }
+ let value = row.get(index).unwrap_or(&Value::Null);
+ // Untouched cells must not be sent.
+ if value.is_null() {
+ continue;
+ }
+ if value.is_string() && value.as_str().unwrap_or("").is_empty() {
+ continue;
+ }
+ fields.insert(field_name.to_string(), value.clone());
+ }
+ if fields.is_empty() {
+ continue;
+ }
+
+ let body = serde_json::json!({
+ "op": "insert",
+ "object": object,
+ "fields": fields
+ });
+ statements.push(format!("{SALESFORCE_DML_HEADER}\n{body}"));
+ }
+
+ statements
+}
+
+/// Salesforce REST has no transactions — rollback statements are always empty.
+pub(super) fn build_salesforce_data_grid_rollback_statements(_options: &DataGridSaveStatementOptions) -> Vec<String> {
+ Vec::new()
+}
+
+/// Validate that the Salesforce sObject has a resolvable Id column. Called
+/// from `validate_data_grid_save` before the builder runs.
+pub(super) fn validate_salesforce_id_column(options: &DataGridSaveStatementOptions) -> Option<String> {
+ if options.database_type != Some(DatabaseType::Salesforce) {
+ return None;
+ }
+ // Only validate when there are updates, deletes, or inserts that would
+ // need an Id (updates/deletes need it from existing rows; inserts don't
+ // strictly need it, but the grid always has an Id column from the query).
+ if options.dirty_rows.is_empty() && options.deleted_rows.is_empty() && options.new_rows.is_empty() {
+ return None;
+ }
+ let columns = resolve_salesforce_columns(options);
+ if find_salesforce_id_column_index(&columns, &options.table_meta.primary_keys).is_none() {
+ return Some(format!(
+ "Cannot save Salesforce {}: no Id column found. The grid must include the record Id to enable editing.",
+ options.table_meta.table_name
+ ));
+ }
+ None
+}
+
+/// Resolve the field name for each display column: `source_columns[i]` when
+/// present, else `columns[i]`.
+fn resolve_salesforce_columns(options: &DataGridSaveStatementOptions) -> Vec<Option<String>> {
+ match &options.source_columns {
+ Some(source_columns) if source_columns.len() == options.columns.len() => source_columns.clone(),
+ _ => options.columns.iter().map(|column| Some(column.clone())).collect(),
+ }
+}
+
+/// Locate the Id column by matching `table_meta.primary_keys` (case-insensitive)
+/// against the resolved field names.
+fn find_salesforce_id_column_index(columns: &[Option<String>], primary_keys: &[String]) -> Option<usize> {
+ // Try primary keys first (case-insensitive).
+ for pk in primary_keys {
+ let pk_upper = pk.to_ascii_uppercase();
+ if let Some(index) =
+ columns.iter().position(|col| col.as_deref().is_some_and(|name| name.to_ascii_uppercase() == pk_upper))
+ {
+ return Some(index);
+ }
+ }
+ // Fallback: look for a column literally named "Id" (case-insensitive).
+ columns.iter().position(|col| col.as_deref().is_some_and(|name| name.eq_ignore_ascii_case("Id")))
+}
+
+/// Whether a column should be included in update payloads. Returns `true`
+/// unless the column's `extra` metadata explicitly marks `updateable: false`.
+/// Missing or unparseable `extra` → treat as writable (fail-open; Salesforce
+/// enforces the real rules server-side).
+fn salesforce_column_is_updateable(info: Option<&DataGridColumnInfo>) -> bool {
+ salesforce_extra_flag(info, "updateable").unwrap_or(true)
+}
+
+/// Whether a column should be included in insert payloads. Returns `true`
+/// unless the column's `extra` metadata explicitly marks `createable: false`.
+fn salesforce_column_is_createable(info: Option<&DataGridColumnInfo>) -> bool {
+ salesforce_extra_flag(info, "createable").unwrap_or(true)
+}
+
+/// Read a boolean flag from the `extra` JSON string on a `DataGridColumnInfo`.
+/// Returns `None` when `extra` is absent, unparseable, or lacks the key.
+fn salesforce_extra_flag(info: Option<&DataGridColumnInfo>, key: &str) -> Option<bool> {
+ let extra_str = info?.extra.as_deref()?;
+ let extra: Value = serde_json::from_str(extra_str).ok()?;
+ extra.get(key).and_then(Value::as_bool)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn make_options(
+ columns: Vec<&str>,
+ primary_keys: Vec<&str>,
+ dirty_rows: Vec<(usize, Vec<(usize, Value)>)>,
+ deleted_rows: Vec<usize>,
+ new_rows: Vec<Vec<Value>>,
+ rows: Vec<Vec<Value>>,
+ ) -> DataGridSaveStatementOptions {
+ DataGridSaveStatementOptions {
+ database_type: Some(DatabaseType::Salesforce),
+ identifier_quote: None,
+ table_meta: DataGridTableMeta {
+ database: None,
+ catalog: None,
+ schema: None,
+ table_name: "Account".to_string(),
+ primary_keys: primary_keys.into_iter().map(str::to_string).collect(),
+ columns: None,
+ },
+ columns: columns.into_iter().map(str::to_string).collect(),
+ source_columns: None,
+ rows,
+ dirty_rows,
+ deleted_rows,
+ new_rows,
+ include_database_name: false,
+ }
+ }
+
+ fn make_options_with_extra(
+ columns: Vec<&str>,
+ primary_keys: Vec<&str>,
+ extras: Vec<Option<&str>>,
+ ) -> DataGridSaveStatementOptions {
+ let cols: Vec<DataGridColumnInfo> = columns
+ .iter()
+ .zip(extras.iter())
+ .map(|(name, extra)| DataGridColumnInfo {
+ name: name.to_string(),
+ data_type: String::new(),
+ is_nullable: true,
+ is_primary_key: false,
+ column_default: None,
+ extra: extra.map(|s| s.to_string()),
+ })
+ .collect();
+ DataGridSaveStatementOptions {
+ database_type: Some(DatabaseType::Salesforce),
+ identifier_quote: None,
+ table_meta: DataGridTableMeta {
+ database: None,
+ catalog: None,
+ schema: None,
+ table_name: "Account".to_string(),
+ primary_keys: primary_keys.into_iter().map(str::to_string).collect(),
+ columns: Some(cols),
+ },
+ columns: columns.into_iter().map(str::to_string).collect(),
+ source_columns: None,
+ rows: Vec::new(),
+ dirty_rows: Vec::new(),
+ deleted_rows: Vec::new(),
+ new_rows: Vec::new(),
+ include_database_name: false,
+ }
+ }
+
+ #[test]
+ fn update_generates_dml_statement() {
+ let opts = make_options(
+ vec!["Id", "Name", "Industry"],
+ vec!["Id"],
+ vec![(0, vec![(1, Value::String("Acme".to_string()))])],
+ vec![],
+ vec![],
+ vec![vec![
+ Value::String("001xx000003DGbY".to_string()),
+ Value::String("Old Name".to_string()),
+ Value::String("Tech".to_string()),
+ ]],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ assert!(stmts[0].starts_with("DBX SALESFORCE DML\n"));
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert_eq!(body["op"], "update");
+ assert_eq!(body["object"], "Account");
+ assert_eq!(body["id"], "001xx000003DGbY");
+ assert_eq!(body["fields"]["Name"], "Acme");
+ // Industry was not changed → not in fields.
+ assert!(body["fields"].get("Industry").is_none());
+ // Id is never in fields.
+ assert!(body["fields"].get("Id").is_none());
+ }
+
+ #[test]
+ fn delete_generates_dml_statement() {
+ let opts = make_options(
+ vec!["Id", "Name"],
+ vec!["Id"],
+ vec![],
+ vec![0],
+ vec![],
+ vec![vec![Value::String("001xx000003DGbY".to_string()), Value::String("Acme".to_string())]],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert_eq!(body["op"], "delete");
+ assert_eq!(body["id"], "001xx000003DGbY");
+ }
+
+ #[test]
+ fn insert_generates_dml_statement_skipping_nulls_and_empties() {
+ let opts = make_options(
+ vec!["Id", "Name", "Phone", "Website"],
+ vec!["Id"],
+ vec![],
+ vec![],
+ vec![vec![
+ Value::Null,
+ Value::String("Acme".to_string()),
+ Value::String("".to_string()), // empty → skip
+ Value::Null, // null → skip
+ ]],
+ vec![],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert_eq!(body["op"], "insert");
+ assert_eq!(body["object"], "Account");
+ assert_eq!(body["fields"]["Name"], "Acme");
+ // Id, Phone, Website excluded.
+ assert!(body["fields"].get("Id").is_none());
+ assert!(body["fields"].get("Phone").is_none());
+ assert!(body["fields"].get("Website").is_none());
+ }
+
+ #[test]
+ fn id_excluded_from_update_fields() {
+ // Even if Id appears in the changes, it must not be in the fields payload.
+ let opts = make_options(
+ vec!["Id", "Name"],
+ vec!["Id"],
+ vec![(0, vec![(0, Value::String("new-id".to_string())), (1, Value::String("Acme".to_string()))])],
+ vec![],
+ vec![],
+ vec![vec![Value::String("001xx000003DGbY".to_string()), Value::String("Old".to_string())]],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert!(body["fields"].get("Id").is_none());
+ assert_eq!(body["fields"]["Name"], "Acme");
+ }
+
+ #[test]
+ fn updateable_false_columns_skipped_on_update() {
+ let opts = make_options_with_extra(
+ vec!["Id", "Name", "SystemField"],
+ vec!["Id"],
+ vec![
+ None,
+ Some(r#"{"updateable":true,"createable":true}"#),
+ Some(r#"{"updateable":false,"createable":true}"#),
+ ],
+ );
+ let mut opts = opts;
+ opts.rows = vec![vec![
+ Value::String("001xx000003DGbY".to_string()),
+ Value::String("Old".to_string()),
+ Value::String("system".to_string()),
+ ]];
+ opts.dirty_rows =
+ vec![(0, vec![(1, Value::String("New".to_string())), (2, Value::String("changed".to_string()))])];
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert_eq!(body["fields"]["Name"], "New");
+ assert!(body["fields"].get("SystemField").is_none());
+ }
+
+ #[test]
+ fn createable_false_columns_skipped_on_insert() {
+ let opts = make_options_with_extra(
+ vec!["Id", "Name", "AutoField"],
+ vec!["Id"],
+ vec![
+ None,
+ Some(r#"{"updateable":true,"createable":true}"#),
+ Some(r#"{"updateable":true,"createable":false}"#),
+ ],
+ );
+ let mut opts = opts;
+ opts.new_rows = vec![vec![Value::Null, Value::String("Acme".to_string()), Value::String("auto".to_string())]];
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 1);
+ let body: Value = serde_json::from_str(stmts[0].split_once('\n').unwrap().1).unwrap();
+ assert_eq!(body["fields"]["Name"], "Acme");
+ assert!(body["fields"].get("AutoField").is_none());
+ }
+
+ #[test]
+ fn missing_id_column_produces_validation_error() {
+ let opts = make_options(
+ vec!["Name", "Industry"],
+ vec![], // no primary keys
+ vec![(0, vec![(0, Value::String("Acme".to_string()))])],
+ vec![],
+ vec![],
+ vec![vec![Value::String("Old".to_string()), Value::String("Tech".to_string())]],
+ );
+ let error = validate_salesforce_id_column(&opts);
+ assert!(error.is_some());
+ assert!(error.unwrap().contains("no Id column found"));
+ }
+
+ #[test]
+ fn rollback_statements_are_empty() {
+ let opts = make_options(vec!["Id", "Name"], vec!["Id"], vec![], vec![], vec![], vec![]);
+ assert!(build_salesforce_data_grid_rollback_statements(&opts).is_empty());
+ }
+
+ #[test]
+ fn statement_order_is_updates_deletes_inserts() {
+ let opts = make_options(
+ vec!["Id", "Name"],
+ vec!["Id"],
+ vec![(0, vec![(1, Value::String("Updated".to_string()))])],
+ vec![1],
+ vec![vec![Value::Null, Value::String("New".to_string())]],
+ vec![
+ vec![Value::String("id1".to_string()), Value::String("Row1".to_string())],
+ vec![Value::String("id2".to_string()), Value::String("Row2".to_string())],
+ ],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert_eq!(stmts.len(), 3);
+ let ops: Vec<&str> = stmts
+ .iter()
+ .map(|s| {
+ let body: Value = serde_json::from_str(s.split_once('\n').unwrap().1).unwrap();
+ // Leak to get a &'static str — fine in tests.
+ Box::leak(body["op"].as_str().unwrap().to_string().into_boxed_str()) as &str
+ })
+ .collect();
+ assert_eq!(ops, vec!["update", "delete", "insert"]);
+ }
+
+ #[test]
+ fn empty_change_set_after_filtering_skips_row() {
+ let opts = make_options(
+ vec!["Id", "Name"],
+ vec!["Id"],
+ // Only change is to Id itself → filtered out → empty fields → skip.
+ vec![(0, vec![(0, Value::String("new-id".to_string()))])],
+ vec![],
+ vec![],
+ vec![vec![Value::String("001xx000003DGbY".to_string()), Value::String("Old".to_string())]],
+ );
+ let stmts = build_salesforce_data_grid_save_statements(&opts);
+ assert!(stmts.is_empty());
+ }
+
+ #[test]
+ fn non_salesforce_database_type_returns_no_validation_error() {
+ let mut opts = make_options(vec!["Id"], vec!["Id"], vec![], vec![], vec![], vec![]);
+ opts.database_type = Some(DatabaseType::Postgres);
+ assert!(validate_salesforce_id_column(&opts).is_none());
+ }
+}
diff --git a/crates/dbx-sql/src/data_grid_sql.rs b/crates/dbx-sql/src/data_grid_sql.rs
index 7c7bf7cf2b..1350e1cb32 100644
--- a/crates/dbx-sql/src/data_grid_sql.rs
+++ b/crates/dbx-sql/src/data_grid_sql.rs
@@ -21,6 +21,13 @@ use data_grid_tdengine_sql::{
validate_tdengine_existing_rows, validate_tdengine_inserted_rows,
};
+#[path = "data_grid_salesforce_sql.rs"]
+mod data_grid_salesforce_sql;
+use data_grid_salesforce_sql::{
+ build_salesforce_data_grid_rollback_statements, build_salesforce_data_grid_save_statements,
+ validate_salesforce_id_column,
+};
+
use crate::models::connection::DatabaseType;
use crate::sql_dialect::{
firebird_rows_clause, quote_table_identifier, table_pagination_strategy, uses_oracle_row_id,
@@ -1195,6 +1202,9 @@ fn build_neo4j_data_grid_column_distinct_values_sql(options: &DataGridColumnDist
}
fn validate_data_grid_save(options: &DataGridSaveStatementOptions) -> Option<String> {
+ if let Some(error) = validate_salesforce_id_column(options) {
+ return Some(error);
+ }
if let Some(error) = validate_iotdb_existing_rows(options) {
return Some(error);
}
@@ -1461,6 +1471,9 @@ fn build_data_grid_save_statements(
if options.database_type == Some(DatabaseType::Tdengine) {
return build_tdengine_data_grid_save_statements(options);
}
+ if options.database_type == Some(DatabaseType::Salesforce) {
+ return build_salesforce_data_grid_save_statements(options);
+ }
if uses_iotdb_table_model_save(options) {
return build_iotdb_data_grid_save_statements(options);
}
@@ -1656,6 +1669,9 @@ fn build_data_grid_rollback_statements(
if options.database_type == Some(DatabaseType::Tdengine) {
return build_tdengine_data_grid_rollback_statements(options);
}
+ if options.database_type == Some(DatabaseType::Salesforce) {
+ return build_salesforce_data_grid_rollback_statements(options);
+ }
if uses_iotdb_table_model_save(options) {
return build_iotdb_data_grid_rollback_statements(options);
}
diff --git a/crates/dbx-sql/src/query_execution_sql.rs b/crates/dbx-sql/src/query_execution_sql.rs
index 519a00a2ca..fa02ae813c 100644
--- a/crates/dbx-sql/src/query_execution_sql.rs
+++ b/crates/dbx-sql/src/query_execution_sql.rs
@@ -424,6 +424,13 @@ pub fn is_write_sql_for_database(sql: &str, database_type: DatabaseType) -> bool
return is_write;
}
}
+ if database_type == DatabaseType::Salesforce {
+ // SOQL has no write verbs — every write arrives as a DBX pseudo-command —
+ // so the keyword scan below would misread a string literal
+ // (`Subject = 'Delete request'`) or a custom field (`Update__c`) as a
+ // write and lock a read-only session out of an ordinary SELECT.
+ return classify_salesforce_statement_risk(sql) != SalesforceStatementRisk::Read;
+ }
if let Some(risk) = classify_search_engine_query_risk(sql, database_type) {
return risk != SearchEngineQueryRisk::ReadOnly;
}
@@ -440,6 +447,68 @@ fn classify_dynamodb_statement_write(source: &str) -> Option<bool> {
}
}
+/// How a Salesforce statement must be treated by write and risk classification.
+///
+/// `SfClient::execute_query` accepts exactly two shapes: a SOQL `SELECT`, which
+/// the REST query endpoint runs read-only, and a `DBX SALESFORCE <…>`
+/// pseudo-command carrying a JSON body. Anything else is rejected by Salesforce
+/// anyway, so it is classified as an opaque write and fails closed rather than
+/// being guessed at by the SQL keyword scan.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SalesforceStatementRisk {
+ /// SOQL `SELECT` — always a read, whatever its literals and field names say.
+ Read,
+ /// Single-record DML naming its object and, for update/delete, its record Id.
+ ScopedWrite,
+ /// Unscoped or unknown DML, unrecognized pseudo-commands, non-SOQL text.
+ OpaqueWrite,
+}
+
+pub fn classify_salesforce_statement_risk(source: &str) -> SalesforceStatementRisk {
+ use SalesforceStatementRisk::{OpaqueWrite, Read, ScopedWrite};
+
+ let header = source.lines().find(|line| !line.trim().is_empty()).unwrap_or("").trim();
+ if header.to_ascii_uppercase().starts_with("DBX SALESFORCE") {
+ return if salesforce_dml_is_scoped(source) { ScopedWrite } else { OpaqueWrite };
+ }
+ // Comments are stripped before the verb check, but the pseudo-command branch
+ // above deliberately reads the raw text: a `--` inside a JSON field value
+ // must not be mistaken for a line comment and truncate the payload.
+ let first_word = strip_sql_comments(source)
+ .split(|character: char| !character.is_alphanumeric() && character != '_')
+ .find(|token| !token.is_empty())
+ .unwrap_or("")
+ .to_ascii_uppercase();
+ if first_word == "SELECT" {
+ Read
+ } else {
+ OpaqueWrite
+ }
+}
+
+/// Whether a `DBX SALESFORCE DML` body targets exactly one identified record:
+/// an insert needs only its object, while an update or delete without an Id has
+/// nothing bounding it and stays opaque.
+fn salesforce_dml_is_scoped(source: &str) -> bool {
+ // The header line never contains a brace, so the JSON body starts at the first `{`.
+ let Some(start) = source.find('{') else { return false };
+ let Ok(body) = serde_json::from_str::<serde_json::Value>(&source[start..]) else {
+ return false;
+ };
+ let names_object =
+ body.get("object").and_then(|value| value.as_str()).is_some_and(|object| !object.trim().is_empty());
+ if !names_object {
+ return false;
+ }
+ match body.get("op").and_then(|value| value.as_str()).map(str::to_ascii_lowercase).as_deref() {
+ Some("insert") => true,
+ Some("update") | Some("delete") => {
+ body.get("id").and_then(|value| value.as_str()).is_some_and(|id| !id.trim().is_empty())
+ }
+ _ => false,
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchEngineQueryRisk {
ReadOnly,
@@ -2460,6 +2529,107 @@ mod tests {
);
}
+ #[test]
+ fn classify_salesforce_statement_risk_scoped_dml() {
+ let update = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001x\",\"fields\":{\"Name\":\"Acme\"}}";
+ assert_eq!(classify_salesforce_statement_risk(update), SalesforceStatementRisk::ScopedWrite);
+ let delete = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\",\"id\":\"001x\"}";
+ assert_eq!(classify_salesforce_statement_risk(delete), SalesforceStatementRisk::ScopedWrite);
+ let insert = "DBX SALESFORCE DML\n{\"op\":\"insert\",\"object\":\"Lead\",\"fields\":{\"Company\":\"Acme\"}}";
+ assert_eq!(classify_salesforce_statement_risk(insert), SalesforceStatementRisk::ScopedWrite);
+ }
+
+ #[test]
+ fn classify_salesforce_statement_risk_unscoped_dml_fails_closed() {
+ // No Id: nothing bounds the write, so it is not a safe write.
+ assert_eq!(
+ classify_salesforce_statement_risk(
+ "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"fields\":{}}"
+ ),
+ SalesforceStatementRisk::OpaqueWrite
+ );
+ // Unknown op / unknown header / unparseable body all fail closed.
+ assert_eq!(
+ classify_salesforce_statement_risk(
+ "DBX SALESFORCE DML\n{\"op\":\"upsert\",\"object\":\"Account\",\"id\":\"001x\"}"
+ ),
+ SalesforceStatementRisk::OpaqueWrite
+ );
+ assert_eq!(
+ classify_salesforce_statement_risk("DBX SALESFORCE FUTURE\n{}"),
+ SalesforceStatementRisk::OpaqueWrite
+ );
+ assert_eq!(
+ classify_salesforce_statement_risk("DBX SALESFORCE DML\n{not json"),
+ SalesforceStatementRisk::OpaqueWrite
+ );
+ }
+
+ #[test]
+ fn classify_salesforce_statement_risk_dml_body_survives_comment_lookalikes() {
+ // A `--` inside a field value must not be stripped as a line comment:
+ // the pseudo-command branch reads the raw text, so the body still parses
+ // and the write stays scoped.
+ let dml = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001x\",\"fields\":{\"Description\":\"a--b\"}}";
+ assert_eq!(classify_salesforce_statement_risk(dml), SalesforceStatementRisk::ScopedWrite);
+ }
+
+ #[test]
+ fn classify_salesforce_statement_risk_soql_is_read() {
+ assert_eq!(classify_salesforce_statement_risk("SELECT Id FROM Account"), SalesforceStatementRisk::Read);
+ assert_eq!(classify_salesforce_statement_risk(" select Name from Lead "), SalesforceStatementRisk::Read);
+ // SOQL forms sqlparser cannot parse must still read as reads.
+ assert_eq!(
+ classify_salesforce_statement_risk("SELECT FIELDS(ALL) FROM Account LIMIT 200"),
+ SalesforceStatementRisk::Read
+ );
+ assert_eq!(
+ classify_salesforce_statement_risk("SELECT Id FROM Opportunity WHERE CloseDate = LAST_N_DAYS:7"),
+ SalesforceStatementRisk::Read
+ );
+ assert_eq!(
+ classify_salesforce_statement_risk("SELECT Id, (SELECT Id FROM Contacts) FROM Account"),
+ SalesforceStatementRisk::Read
+ );
+ assert_eq!(
+ classify_salesforce_statement_risk("/* report */ SELECT Id FROM Account"),
+ SalesforceStatementRisk::Read
+ );
+ }
+
+ #[test]
+ fn classify_salesforce_statement_risk_non_soql_is_opaque_write() {
+ // The driver only accepts SELECT and DBX pseudo-commands; anything else
+ // is a client error, not something to classify as a harmless read.
+ assert_eq!(classify_salesforce_statement_risk("DELETE FROM Account"), SalesforceStatementRisk::OpaqueWrite);
+ assert_eq!(
+ classify_salesforce_statement_risk("FIND {Acme} IN ALL FIELDS"),
+ SalesforceStatementRisk::OpaqueWrite
+ );
+ assert_eq!(classify_salesforce_statement_risk(""), SalesforceStatementRisk::OpaqueWrite);
+ }
+
+ #[test]
+ fn is_write_sql_for_database_salesforce_soql_is_read() {
+ assert!(!is_write_sql_for_database("SELECT Id FROM Account", DatabaseType::Salesforce));
+ }
+
+ #[test]
+ fn is_write_sql_for_database_salesforce_literals_are_not_writes() {
+ // The generic keyword scan would see DELETE/UPDATE here; SOQL cannot write.
+ assert!(!is_write_sql_for_database(
+ "SELECT Id FROM Case WHERE Subject = 'Delete request'",
+ DatabaseType::Salesforce
+ ));
+ assert!(!is_write_sql_for_database("SELECT Update__c FROM Lead", DatabaseType::Salesforce));
+ }
+
+ #[test]
+ fn is_write_sql_for_database_salesforce_dml_is_write() {
+ let dml = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Account\",\"id\":\"x\"}";
+ assert!(is_write_sql_for_database(dml, DatabaseType::Salesforce));
+ }
+
#[test]
fn mysql_explicit_transaction_openers_are_recognized() {
for sql in [
diff --git a/crates/dbx-sql/src/query_result_sql.rs b/crates/dbx-sql/src/query_result_sql.rs
index 4a72827ba9..91107d193a 100644
--- a/crates/dbx-sql/src/query_result_sql.rs
+++ b/crates/dbx-sql/src/query_result_sql.rs
@@ -550,9 +550,17 @@ fn err(reason: &str) -> QuerySqlBuildResult {
}
fn unsupported_pagination_type(database_type: Option<DatabaseType>) -> bool {
+ // SOQL has no derived tables and no OFFSET wrapping; the Salesforce driver
+ // pages through QueryLocator cursors (session_id) instead.
matches!(
database_type,
- Some(DatabaseType::Neo4j | DatabaseType::MongoDb | DatabaseType::Redis | DatabaseType::Solr)
+ Some(
+ DatabaseType::Neo4j
+ | DatabaseType::MongoDb
+ | DatabaseType::Redis
+ | DatabaseType::Salesforce
+ | DatabaseType::Solr
+ )
)
}
diff --git a/crates/dbx-sql/src/sql_dialect/ddl_profile.rs b/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
index 62a430bec0..71f23e15d5 100644
--- a/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
+++ b/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
@@ -823,7 +823,7 @@ pub fn profile_for(db_type: DatabaseType) -> DdlDialectProfile {
// Non-tabular / not applicable for relational CREATE TABLE
Redis | MongoDb | DynamoDb | Elasticsearch | Easysearch | Solr | Meilisearch | Qdrant | Milvus | Weaviate
| ChromaDb | Neo4j | Cassandra | Etcd | ZooKeeper | Nacos | Consul | InfluxDb3 | VictoriaMetrics
- | MessageQueue | Mqtt | Hbase => conservative_ansi(db_type),
+ | MessageQueue | Mqtt | Hbase | Salesforce => conservative_ansi(db_type),
}
}
diff --git a/crates/dbx-sql/src/sql_dialect/descriptor.rs b/crates/dbx-sql/src/sql_dialect/descriptor.rs
index e4be68bd4e..0f20f8cb58 100644
--- a/crates/dbx-sql/src/sql_dialect/descriptor.rs
+++ b/crates/dbx-sql/src/sql_dialect/descriptor.rs
@@ -14,6 +14,7 @@ pub enum DialectKind {
ManticoreSearch,
Informix,
Questdb,
+ Soql,
Unsupported,
}
@@ -35,6 +36,7 @@ impl DialectKind {
DialectKind::ManticoreSearch => Some(DatabaseType::ManticoreSearch),
DialectKind::Informix => Some(DatabaseType::Informix),
DialectKind::Questdb => Some(DatabaseType::Questdb),
+ DialectKind::Soql => Some(DatabaseType::Salesforce),
DialectKind::Unsupported => None,
}
}
@@ -52,6 +54,7 @@ impl DialectKind {
DialectKind::ManticoreSearch => "manticoresearch",
DialectKind::Informix => "informix",
DialectKind::Questdb => "questdb",
+ DialectKind::Soql => "soql",
DialectKind::Unsupported => "unsupported",
}
}
@@ -79,6 +82,7 @@ impl DialectKind {
"manticoresearch" => Some(DialectKind::ManticoreSearch),
"informix" => Some(DialectKind::Informix),
"questdb" => Some(DialectKind::Questdb),
+ "soql" | "salesforce" => Some(DialectKind::Soql),
_ => None,
}
}
@@ -585,6 +589,14 @@ impl DialectCapabilityDescriptor {
supports_partitioning: true,
..Default::default()
},
+ DialectKind::Soql => Self {
+ dialect: DialectKind::Soql,
+ flags: 0,
+ max_identifier_length: 40,
+ max_columns_per_table: 500,
+ max_query_size_bytes: 20_000,
+ ..Default::default()
+ },
DialectKind::Unsupported => Self::default(),
}
}
@@ -941,10 +953,23 @@ impl DialectInfo {
pub fn all() -> Vec<Self> {
use DialectKind::*;
- vec![Mysql, Postgres, Sqlite, DuckDb, SqlServer, Oracle, H2, ClickHouse, ManticoreSearch, Informix, Questdb]
- .into_iter()
- .map(Self::for_kind)
- .collect()
+ vec![
+ Mysql,
+ Postgres,
+ Sqlite,
+ DuckDb,
+ SqlServer,
+ Oracle,
+ H2,
+ ClickHouse,
+ ManticoreSearch,
+ Informix,
+ Questdb,
+ Soql,
+ ]
+ .into_iter()
+ .map(Self::for_kind)
+ .collect()
}
}
@@ -974,6 +999,7 @@ mod tests {
(DatabaseType::ManticoreSearch, DialectKind::ManticoreSearch),
(DatabaseType::Informix, DialectKind::Informix),
(DatabaseType::Questdb, DialectKind::Questdb),
+ (DatabaseType::Salesforce, DialectKind::Soql),
(DatabaseType::Redis, DialectKind::Unsupported),
(DatabaseType::MongoDb, DialectKind::Unsupported),
];
@@ -1001,6 +1027,7 @@ mod tests {
DialectKind::ManticoreSearch,
DialectKind::Informix,
DialectKind::Questdb,
+ DialectKind::Soql,
] {
let db_type = kind.to_database_type().unwrap();
let back = DialectKind::from_database_type(db_type);
@@ -1023,6 +1050,7 @@ mod tests {
DialectKind::ManticoreSearch,
DialectKind::Informix,
DialectKind::Questdb,
+ DialectKind::Soql,
DialectKind::Unsupported,
] {
let desc = DialectCapabilityDescriptor::for_dialect(*kind);
diff --git a/crates/dbx-sql/src/sql_dialect/dialect_types.rs b/crates/dbx-sql/src/sql_dialect/dialect_types.rs
index 22b277f03b..147f584c25 100644
--- a/crates/dbx-sql/src/sql_dialect/dialect_types.rs
+++ b/crates/dbx-sql/src/sql_dialect/dialect_types.rs
@@ -39,6 +39,7 @@ fn core_catalog_name(kind: DialectKind) -> &'static str {
DialectKind::ManticoreSearch => "ManticoreSearch",
DialectKind::Informix => "Informix",
DialectKind::Questdb => "QuestDB",
+ DialectKind::Soql => "SOQL",
DialectKind::Unsupported => "Unsupported",
}
}
diff --git a/crates/dbx-sql/src/sql_dialect/dialect_yaml.rs b/crates/dbx-sql/src/sql_dialect/dialect_yaml.rs
index fa556b2966..398051cc59 100644
--- a/crates/dbx-sql/src/sql_dialect/dialect_yaml.rs
+++ b/crates/dbx-sql/src/sql_dialect/dialect_yaml.rs
@@ -959,6 +959,7 @@ fn kind_name(kind: DialectKind) -> String {
DialectKind::ManticoreSearch => "ManticoreSearch",
DialectKind::Informix => "Informix",
DialectKind::Questdb => "QuestDB",
+ DialectKind::Soql => "SOQL",
DialectKind::Unsupported => "Unsupported",
}
.to_string()
@@ -1333,6 +1334,7 @@ identifier_rules:
DialectKind::ManticoreSearch,
DialectKind::Informix,
DialectKind::Questdb,
+ DialectKind::Soql,
];
for kind in kinds {
let yaml = DialectYaml::from_descriptor(*kind);
diff --git a/crates/dbx-sql/src/sql_dialect/identifiers.rs b/crates/dbx-sql/src/sql_dialect/identifiers.rs
index eefd4b7a52..fc93d36959 100644
--- a/crates/dbx-sql/src/sql_dialect/identifiers.rs
+++ b/crates/dbx-sql/src/sql_dialect/identifiers.rs
@@ -117,6 +117,10 @@ pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -
}
match database_type {
Some(DatabaseType::Iotdb) => name.to_string(),
+ // SOQL has no delimited identifiers: `SELECT * FROM "Account"` fails with
+ // MALFORMED_QUERY, and double quotes are string literals there. Object and
+ // field API names are always sent bare.
+ Some(DatabaseType::Salesforce) => name.to_string(),
// JDBC connections use the driver-reported identifier quote string
// (DatabaseMetaData.getIdentifierQuoteString()) inside the JDBC agent,
// so the Rust layer passes identifiers through unquoted.
diff --git a/crates/dbx-sql/src/sql_dialect/snapshots/dbx_sql__sql_dialect__descriptor_snapshots__all_dialects_info.snap b/crates/dbx-sql/src/sql_dialect/snapshots/dbx_sql__sql_dialect__descriptor_snapshots__all_dialects_info.snap
index cdb189ccd7..e09b4dad2c 100644
--- a/crates/dbx-sql/src/sql_dialect/snapshots/dbx_sql__sql_dialect__descriptor_snapshots__all_dialects_info.snap
+++ b/crates/dbx-sql/src/sql_dialect/snapshots/dbx_sql__sql_dialect__descriptor_snapshots__all_dialects_info.snap
@@ -426,5 +426,25 @@ expression: all
"supports_full_text_index": false,
"supports_spatial_index": false,
"supports_transactional_ddl": false
+ },
+ {
+ "kind": "soql",
+ "label": "soql",
+ "capabilities": [],
+ "max_identifier_length": 40,
+ "supports_schemas": false,
+ "supports_catalogs": false,
+ "max_columns_per_table": 500,
+ "supports_json_type": true,
+ "supports_array_type": false,
+ "supports_enum_type": false,
+ "supports_uuid_type": false,
+ "supports_auto_increment": false,
+ "supports_identity_columns": false,
+ "supports_sequences": false,
+ "supports_partitioning": false,
+ "supports_full_text_index": false,
+ "supports_spatial_index": false,
+ "supports_transactional_ddl": false
}
]
diff --git a/crates/dbx-sql/src/sql_dialect/table_select.rs b/crates/dbx-sql/src/sql_dialect/table_select.rs
index ea96d0d740..3ace9d1072 100644
--- a/crates/dbx-sql/src/sql_dialect/table_select.rs
+++ b/crates/dbx-sql/src/sql_dialect/table_select.rs
@@ -200,6 +200,9 @@ pub fn build_table_data_select_sql_with_database(
if database_type == Some(DatabaseType::Neo4j) {
return build_neo4j_table_select_sql(&options, limit);
}
+ if database_type == Some(DatabaseType::Salesforce) {
+ return build_salesforce_table_select_sql(&options, limit);
+ }
if database_type == Some(DatabaseType::VictoriaMetrics) {
return format!("{}[1h]", victoriametrics_metric_selector(&options.table_name));
}
@@ -863,6 +866,47 @@ pub(super) fn build_neo4j_table_select_sql(options: &TableDataSelectSqlOptions,
format!("MATCH (n:{label}){where_clause} RETURN {returns}{order}{skip} LIMIT {limit};")
}
+/// Salesforce's `FIELDS(ALL)` selector is only legal with a LIMIT of 200 or less.
+const SALESFORCE_FIELDS_ALL_MAX_LIMIT: usize = 200;
+
+/// Builds the SOQL used by the data-table grid for a Salesforce sObject.
+///
+/// SOQL is not SQL in three ways that matter here: there is no `SELECT *`, there
+/// are no delimited identifiers (`FROM "Account"` is a `MALFORMED_QUERY`), and
+/// the "everything" projection is the `FIELDS(ALL)` selector, which Salesforce
+/// only accepts with `LIMIT 200` or less. Known fields are therefore projected
+/// by name — that keeps any page size working — and `FIELDS(ALL)` is the capped
+/// fallback for the callers that build SQL before the describe cache has loaded.
+///
+/// The statement carries no trailing semicolon: SOQL does not accept one.
+pub(super) fn build_salesforce_table_select_sql(options: &TableDataSelectSqlOptions, limit: usize) -> String {
+ let object = options.table_name.trim();
+ let columns: Vec<&str> = options
+ .columns
+ .iter()
+ .map(String::as_str)
+ .map(str::trim)
+ .filter(|column| !column.is_empty() && !column.eq_ignore_ascii_case(DBX_ROWID_COLUMN))
+ .collect();
+ let (projection, effective_limit) = if columns.is_empty() {
+ ("FIELDS(ALL)".to_string(), limit.min(SALESFORCE_FIELDS_ALL_MAX_LIMIT))
+ } else {
+ (columns.join(", "), limit)
+ };
+ // Passed through verbatim: a grid filter is the user's own predicate, and
+ // SOQL WHERE accepts the same parenthesised shape. Wrapping it in parentheses
+ // keeps a caller-supplied `OR` from binding outside the filter.
+ let predicate = normalize_where_input(options.where_input.as_deref());
+ let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
+ let order_by = options.order_by.as_deref().map(str::trim).filter(|order_by| !order_by.is_empty());
+ let order = order_by.map(|order_by| format!(" ORDER BY {order_by}")).unwrap_or_default();
+ // SOQL caps OFFSET at 2000 rows. Past that the org rejects the query, and
+ // surfacing its own error beats silently returning an earlier page.
+ let offset =
+ options.offset.filter(|offset| *offset > 0).map(|offset| format!(" OFFSET {offset}")).unwrap_or_default();
+ format!("SELECT {projection} FROM {object}{where_clause}{order} LIMIT {effective_limit}{offset}")
+}
+
pub(super) fn build_questdb_table_select_sql(
table: &str,
where_clause: &str,
@@ -1179,4 +1223,86 @@ mod tests {
assert_eq!(build_table_data_select_sql(options), "SELECT [id], [name] FROM [users] ORDER BY [id] ASC");
}
+
+ #[test]
+ fn salesforce_table_select_projects_described_fields_as_soql() {
+ // SOQL has no `SELECT *` and no delimited identifiers, so the ANSI shape the
+ // grid used to emit (`SELECT * FROM "Account" LIMIT 100`) fails twice over:
+ // the star is not a SOQL selector and the quote is read as a string literal,
+ // which Salesforce reports as MALFORMED_QUERY at column 14. Fields from the
+ // describe go out bare and by name. No trailing semicolon either — SOQL
+ // rejects one.
+ let mut options = opts(DatabaseType::Salesforce, Some("sales"), Some("org"), "Account");
+ options.columns = vec!["Id".to_string(), "Name".to_string(), "First_Name__c".to_string()];
+ options.limit = Some(100);
+
+ // A Salesforce org is a single scope: schema/database qualification has no
+ // SOQL spelling and would land in the FROM clause as a parse error.
+ assert_eq!(build_table_data_select_sql(options), "SELECT Id, Name, First_Name__c FROM Account LIMIT 100");
+ }
+
+ #[test]
+ fn salesforce_table_select_caps_the_fields_all_fallback() {
+ // Callers that build SQL before the describe cache has loaded have no field
+ // list. `FIELDS(ALL)` is the SOQL "everything" projection, but Salesforce
+ // only accepts it with LIMIT 200 or less, so a larger page size is clamped
+ // instead of being sent as a query the org would refuse outright.
+ assert_eq!(
+ build_table_data_select_sql(TableDataSelectSqlOptions {
+ database_type: Some(DatabaseType::Salesforce),
+ table_name: "Account".to_string(),
+ limit: Some(1000),
+ ..Default::default()
+ }),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 200"
+ );
+ assert_eq!(
+ build_table_data_select_sql(TableDataSelectSqlOptions {
+ database_type: Some(DatabaseType::Salesforce),
+ table_name: "Account".to_string(),
+ ..Default::default()
+ }),
+ "SELECT FIELDS(ALL) FROM Account LIMIT 100"
+ );
+ }
+
+ #[test]
+ fn salesforce_table_select_keeps_an_explicit_projection_at_any_page_size() {
+ // The 200-row clamp is a property of FIELDS(), not of SOQL: naming the
+ // fields keeps a 1000-row page legal.
+ let mut options = opts(DatabaseType::Salesforce, None, None, "Account");
+ options.columns = vec!["Id".to_string(), "Name".to_string()];
+ options.limit = Some(1000);
+
+ assert_eq!(build_table_data_select_sql(options), "SELECT Id, Name FROM Account LIMIT 1000");
+ }
+
+ #[test]
+ fn salesforce_table_select_composes_filter_order_and_offset() {
+ let mut options = opts(DatabaseType::Salesforce, None, None, "Account");
+ options.columns = vec!["Id".to_string(), "Name".to_string()];
+ options.where_input = Some("WHERE Industry = 'Energy' OR AnnualRevenue > 0".to_string());
+ options.order_by = Some("Name ASC".to_string());
+ options.limit = Some(50);
+ options.offset = Some(150);
+
+ // The leading WHERE is stripped and the predicate is parenthesised so a
+ // caller-supplied OR cannot bind outside the grid filter.
+ assert_eq!(
+ build_table_data_select_sql(options),
+ "SELECT Id, Name FROM Account WHERE (Industry = 'Energy' OR AnnualRevenue > 0) ORDER BY Name ASC LIMIT 50 OFFSET 150"
+ );
+ }
+
+ #[test]
+ fn salesforce_table_select_drops_the_synthetic_row_id() {
+ // The grid's synthetic row-id column is a DBX artifact for drivers without a
+ // primary key; it is not an sObject field, so projecting it would be an
+ // invalid field name in SOQL.
+ let mut options = opts(DatabaseType::Salesforce, None, None, "Account");
+ options.columns = vec!["Id".to_string(), DBX_ROWID_COLUMN.to_string()];
+ options.include_row_id = true;
+
+ assert_eq!(build_table_data_select_sql(options), "SELECT Id FROM Account LIMIT 10");
+ }
}
diff --git a/crates/dbx-sql/src/sql_dialect/tests.rs b/crates/dbx-sql/src/sql_dialect/tests.rs
index 5974fc73e8..7adb6d1fec 100644
--- a/crates/dbx-sql/src/sql_dialect/tests.rs
+++ b/crates/dbx-sql/src/sql_dialect/tests.rs
@@ -34,6 +34,13 @@ fn quotes_identifiers_by_database_type() {
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "users_1"), "users_1");
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "user name"), "user name");
assert_eq!(quote_table_identifier(Some(DatabaseType::Iotdb), "root.test.device2"), "root.test.device2");
+ // SOQL has no delimited identifiers and reads `"` as a string literal, so
+ // `SELECT * FROM "Account"` fails with MALFORMED_QUERY. Object and field API
+ // names always go out bare, and an org is a single scope: no schema qualifier.
+ assert_eq!(quote_table_identifier(Some(DatabaseType::Salesforce), "Account"), "Account");
+ assert_eq!(quote_table_identifier(Some(DatabaseType::Salesforce), "First_Name__c"), "First_Name__c");
+ assert_eq!(quote_table_data_identifier(Some(DatabaseType::Salesforce), "Account", None), "Account");
+ assert_eq!(qualified_table_name(Some(DatabaseType::Salesforce), Some("sales"), "Account"), "Account");
assert_eq!(quote_table_identifier(Some(DatabaseType::Spanner), "user`name"), "`user``name`");
// ArgoDB shares the Hive-family dialect: backticks quote identifiers and
// double quotes are string literals, and schemas qualify table names.
diff --git a/crates/dbx-sql/src/sql_risk.rs b/crates/dbx-sql/src/sql_risk.rs
index f23ec65b0e..8347d77ef7 100644
--- a/crates/dbx-sql/src/sql_risk.rs
+++ b/crates/dbx-sql/src/sql_risk.rs
@@ -695,6 +695,13 @@ pub fn classify_sql_risk(sql: &str, dialect: &str) -> Result<SqlRisk, String> {
/// Classify SQL risk using both the parser dialect and the concrete database
/// type so dialect-specific write forms cannot be mistaken for read queries.
pub fn classify_sql_risk_for_database(sql: &str, database_type: DatabaseType) -> Result<SqlRisk, String> {
+ if database_type == DatabaseType::Salesforce {
+ // SOQL is not SQL: sqlparser either misreads it or fails, and the
+ // keyword fallback would then judge a statement by the words inside its
+ // string literals. The Salesforce classifier knows the only two shapes
+ // the driver accepts.
+ return Ok(salesforce_risk_to_sql_risk(crate::query_execution_sql::classify_salesforce_statement_risk(sql)));
+ }
if let Some(risk) = crate::query_execution_sql::classify_search_engine_query_risk(sql, database_type) {
return Ok(match risk {
crate::query_execution_sql::SearchEngineQueryRisk::ReadOnly => SqlRisk::ReadOnly,
@@ -707,11 +714,28 @@ pub fn classify_sql_risk_for_database(sql: &str, database_type: DatabaseType) ->
classify_sql_risk_with_database(sql, normalized, Some(database_type))
}
+/// Map the Salesforce classifier onto the shared risk tiers. A single-record DML
+/// that names its record is an ordinary write, so "safe write" permission is
+/// enough for it; an unscoped or unrecognized statement takes the high-risk tier
+/// and needs the central dangerous-operation permission.
+fn salesforce_risk_to_sql_risk(risk: crate::query_execution_sql::SalesforceStatementRisk) -> SqlRisk {
+ use crate::query_execution_sql::SalesforceStatementRisk;
+ match risk {
+ SalesforceStatementRisk::Read => SqlRisk::ReadOnly,
+ SalesforceStatementRisk::ScopedWrite => SqlRisk::Write,
+ SalesforceStatementRisk::OpaqueWrite => SqlRisk::Ddl,
+ }
+}
+
/// Return whether MCP must require the central dangerous-operation permission.
/// Parse failures fail closed for writes. Safe-write mode permits plain INSERT
/// and single-table UPDATE/DELETE statements with an effective predicate;
/// broader or opaque mutations require central high-risk permission.
pub fn is_dangerous_sql_for_database(sql: &str, database_type: DatabaseType) -> bool {
+ if database_type == DatabaseType::Salesforce {
+ return crate::query_execution_sql::classify_salesforce_statement_risk(sql)
+ == crate::query_execution_sql::SalesforceStatementRisk::OpaqueWrite;
+ }
if let Some(risk) = crate::query_execution_sql::classify_search_engine_query_risk(sql, database_type) {
return risk == crate::query_execution_sql::SearchEngineQueryRisk::Dangerous;
}
@@ -744,6 +768,12 @@ pub fn mcp_sql_has_forbidden_database_switch(sql: &str, database_type: DatabaseT
if crate::query_execution_sql::classify_search_engine_query_risk(sql, database_type).is_some() {
return false;
}
+ if database_type == DatabaseType::Salesforce {
+ // SOQL has no USE, and the Salesforce pool is keyed per connection rather
+ // than per database, so no statement can redirect a later call. Returning
+ // early also keeps the SQL parser off the JSON body of a pseudo-command.
+ return false;
+ }
let database_type_name = format!("{database_type:?}");
let normalized = normalize_dialect(&database_type_name);
let dialect = resolve_dialect(normalized);
@@ -1218,6 +1248,7 @@ impl Visitor for ProofFunctionVisitor<'_> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::query_execution_sql::is_write_sql_for_database;
#[test]
fn mysql_proof_accepts_plain_reads_and_allowlisted_functions() {
@@ -1861,4 +1892,70 @@ mod tests {
assert!(is_dangerous_sql_for_database("DELETE /products", database_type));
}
}
+
+ #[test]
+ fn classifies_salesforce_soql_as_read_even_when_sqlparser_cannot() {
+ let database_type = DatabaseType::Salesforce;
+ for soql in [
+ "SELECT Id, Name FROM Account",
+ // SOQL-only forms: FIELDS(), date literals, relationship subqueries.
+ "SELECT FIELDS(ALL) FROM Account LIMIT 200",
+ "SELECT Id FROM Opportunity WHERE CloseDate = LAST_N_DAYS:7",
+ "SELECT Id, (SELECT Id FROM Contacts) FROM Account",
+ // A literal that names a write verb is still a read.
+ "SELECT Id FROM Case WHERE Subject = 'Delete request'",
+ ] {
+ assert_eq!(classify_sql_risk_for_database(soql, database_type).unwrap(), SqlRisk::ReadOnly, "{soql}");
+ assert!(!is_dangerous_sql_for_database(soql, database_type), "{soql}");
+ assert!(!is_write_sql_for_database(soql, database_type), "{soql}");
+ assert!(!mcp_sql_has_forbidden_database_switch(soql, database_type), "{soql}");
+ }
+ }
+
+ #[test]
+ fn classifies_scoped_salesforce_dml_as_a_safe_write() {
+ let database_type = DatabaseType::Salesforce;
+ let update = "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Opportunity\",\"id\":\"006x\",\"fields\":{\"StageName\":\"Closed Won\"}}";
+ let insert = "DBX SALESFORCE DML\n{\"op\":\"insert\",\"object\":\"Lead\",\"fields\":{\"Company\":\"Acme\"}}";
+ let delete = "DBX SALESFORCE DML\n{\"op\":\"delete\",\"object\":\"Lead\",\"id\":\"00Qx\"}";
+ for dml in [update, insert, delete] {
+ // A single identified record is a scoped write: "safe write" permission
+ // is enough, the central dangerous-operation permission is not.
+ assert_eq!(classify_sql_risk_for_database(dml, database_type).unwrap(), SqlRisk::Write, "{dml}");
+ assert!(!is_dangerous_sql_for_database(dml, database_type), "{dml}");
+ assert!(is_write_sql_for_database(dml, database_type), "{dml}");
+ // The JSON body is never parsed as SQL, so a `USE`-shaped value inside
+ // it cannot trip the database-switch guard.
+ assert!(!mcp_sql_has_forbidden_database_switch(dml, database_type), "{dml}");
+ }
+ assert!(!mcp_sql_has_forbidden_database_switch(
+ "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001x\",\"fields\":{\"Description\":\"USE prod\"}}",
+ database_type
+ ));
+ // The tokenizer fallback treats a `;` inside a JSON value as a statement
+ // boundary, so without the Salesforce branch this write would be refused
+ // as a database switch. SOQL cannot switch databases at all.
+ assert!(!mcp_sql_has_forbidden_database_switch(
+ "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"id\":\"001x\",\"fields\":{\"Description\":\"a; USE prod\"}}",
+ database_type
+ ));
+ }
+
+ #[test]
+ fn classifies_unscoped_salesforce_writes_as_high_risk() {
+ let database_type = DatabaseType::Salesforce;
+ for statement in [
+ // No Id: nothing bounds the write.
+ "DBX SALESFORCE DML\n{\"op\":\"update\",\"object\":\"Account\",\"fields\":{\"Name\":\"x\"}}",
+ // Unknown operation and unknown pseudo-command headers fail closed.
+ "DBX SALESFORCE DML\n{\"op\":\"upsert\",\"object\":\"Account\",\"externalId\":\"E-1\"}",
+ "DBX SALESFORCE BULK\n{}",
+ // Non-SOQL text the driver would reject anyway.
+ "DELETE FROM Account",
+ ] {
+ assert_eq!(classify_sql_risk_for_database(statement, database_type).unwrap(), SqlRisk::Ddl, "{statement}");
+ assert!(is_dangerous_sql_for_database(statement, database_type), "{statement}");
+ assert!(is_write_sql_for_database(statement, database_type), "{statement}");
+ }
+ }
}
diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rs
index 2b25b27323..356087a906 100644
--- a/crates/dbx-types/src/models/connection.rs
+++ b/crates/dbx-types/src/models/connection.rs
@@ -1125,6 +1125,7 @@ impl ConnectionConfig {
let scheme = if self.ssl { "https" } else { "http" };
format!("{scheme}://{host}:{port}")
}
+ DatabaseType::Salesforce => salesforce_instance_url(raw_host, self.ssl, port),
DatabaseType::Dameng => format!("dm://{host}:{port}{db_part}"),
DatabaseType::Kingbase => format!("kingbase://{host}:{port}{db_part}"),
DatabaseType::Highgo => format!("highgo://{host}:{port}{db_part}"),
@@ -1310,6 +1311,7 @@ impl ConnectionConfig {
let scheme = if self.ssl { "https" } else { "http" };
format!("{scheme}://{host}:{port}")
}
+ DatabaseType::Salesforce => salesforce_instance_url(raw_host, self.ssl, port),
DatabaseType::Dameng => {
format!("dm://{}:{}@{host}:{port}{db_part}", username, password)
}
@@ -2604,6 +2606,19 @@ fn bracket_ipv6(host: &str) -> String {
}
}
+/// Salesforce connections store the org instance in `host`: either a full URL
+/// (`https://acme.my.salesforce.com`) or a bare hostname. The access token
+/// lives in the password field and never appears in the URL, so the redacted
+/// and full forms are identical.
+fn salesforce_instance_url(raw_host: &str, ssl: bool, port: u16) -> String {
+ let trimmed = raw_host.trim().trim_end_matches('/');
+ if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
+ return trimmed.to_string();
+ }
+ let scheme = if ssl { "https" } else { "http" };
+ format!("{scheme}://{}:{port}", bracket_ipv6(trimmed))
+}
+
/// Returns `true` when `host` contains two or more comma-separated entries
/// where each entry already embeds its own `:port` suffix.
///
diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rs
index c0d82d9d80..0186a14cf5 100644
--- a/crates/dbx-web/src/main.rs
+++ b/crates/dbx-web/src/main.rs
@@ -463,6 +463,15 @@ async fn serve() {
.route("/connection/mcp/add", post(routes::connection::mcp_add_connection))
.route("/connection/mcp/duplicate", post(routes::connection::mcp_duplicate_connection))
.route("/connection/mcp/remove", post(routes::connection::mcp_remove_connection))
+ .route(
+ "/connection/salesforce-oauth-browser-authorize",
+ post(routes::connection::salesforce_oauth_browser_authorize),
+ )
+ .route("/connection/salesforce-oauth-device-start", post(routes::connection::salesforce_oauth_device_start))
+ .route("/connection/salesforce-oauth-device-poll", post(routes::connection::salesforce_oauth_device_poll))
+ .route("/connection/salesforce-oauth-refresh", post(routes::connection::salesforce_oauth_refresh))
+ .route("/connection/salesforce-oauth-password-login", post(routes::connection::salesforce_oauth_password_login))
+ .route("/salesforce/current-user", get(routes::connection::salesforce_current_user))
.route("/plugins", get(routes::plugins::list_plugins))
.route("/plugins/trusted-keys", get(routes::plugins::list_plugin_trusted_keys))
.route("/plugins/trusted-keys/save", post(routes::plugins::save_plugin_trusted_key))
diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rs
index bea3e93bf1..0bbf57b2e9 100644
--- a/crates/dbx-web/src/routes/connection.rs
+++ b/crates/dbx-web/src/routes/connection.rs
@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::sync::Arc;
-use axum::extract::State;
+use axum::extract::{Query, State};
use axum::http::HeaderMap;
use axum::Json;
use dbx_core::connection::{
@@ -14,6 +14,10 @@ use dbx_core::nacos::config::{
use dbx_core::runtime_config::{
release_runtime_config_on_disconnect, should_retain_runtime_config, TEST_PROBE_ID_PREFIX,
};
+use dbx_core::salesforce_oauth::{
+ device_authorization_request, device_poll, password_grant_token, refresh_access_token, SfDeviceAuthorization,
+ SfDevicePoll, SfOauthParams, SfRefreshedToken, SfTokenSet,
+};
use dbx_core::session_credentials::{PurposeSessionCredentialWriteToken, SessionCredentialWriteToken};
use serde::{Deserialize, Serialize};
@@ -865,6 +869,87 @@ async fn remove_connection_pools_for_connection_ids(state: &WebState, connection
}
}
+// ── Salesforce OAuth ──────────────────────────────────────────────
+//
+// Web mode does not have a system browser opener; the browser flow is refused
+// with a clear message pointing users at the device flow which works fine
+// headless. The device flow endpoints proxy directly into dbx-drivers.
+
+pub async fn salesforce_oauth_browser_authorize(
+ State(_state): State<Arc<WebState>>,
+ Json(_body): Json<SalesforceOauthParamsRequest>,
+) -> Result<Json<SfTokenSet>, AppError> {
+ Err(AppError::from("Browser OAuth is not available in web mode. Use the device code flow instead.".to_string()))
+}
+
+pub async fn salesforce_oauth_device_start(
+ State(_state): State<Arc<WebState>>,
+ Json(body): Json<SalesforceOauthParamsRequest>,
+) -> Result<Json<SfDeviceAuthorization>, AppError> {
+ device_authorization_request(&body.params).await.map(Json).map_err(AppError::from)
+}
+
+pub async fn salesforce_oauth_device_poll(
+ State(_state): State<Arc<WebState>>,
+ Json(body): Json<SalesforceDevicePollRequest>,
+) -> Result<Json<SfDevicePoll>, AppError> {
+ device_poll(&body.params, &body.device_code, body.interval_secs).await.map(Json).map_err(AppError::from)
+}
+
+pub async fn salesforce_oauth_refresh(
+ State(_state): State<Arc<WebState>>,
+ Json(body): Json<SalesforceRefreshRequest>,
+) -> Result<Json<SfRefreshedToken>, AppError> {
+ refresh_access_token(&body.params, &body.refresh_token).await.map(Json).map_err(AppError::from)
+}
+
+pub async fn salesforce_oauth_password_login(
+ State(_state): State<Arc<WebState>>,
+ Json(body): Json<SalesforcePasswordLoginRequest>,
+) -> Result<Json<SfTokenSet>, AppError> {
+ password_grant_token(&body.params, &body.username, &body.password).await.map(Json).map_err(AppError::from)
+}
+
+#[derive(Deserialize)]
+pub struct SalesforceOauthParamsRequest {
+ pub params: SfOauthParams,
+}
+
+#[derive(Deserialize)]
+pub struct SalesforceDevicePollRequest {
+ pub params: SfOauthParams,
+ #[serde(rename = "deviceCode")]
+ pub device_code: String,
+ #[serde(rename = "intervalSecs")]
+ pub interval_secs: u64,
+}
+
+#[derive(Deserialize)]
+pub struct SalesforceRefreshRequest {
+ pub params: SfOauthParams,
+ #[serde(rename = "refreshToken")]
+ pub refresh_token: String,
+}
+
+#[derive(Deserialize)]
+pub struct SalesforcePasswordLoginRequest {
+ pub params: SfOauthParams,
+ pub username: String,
+ pub password: String,
+}
+
+#[derive(Deserialize)]
+pub struct SalesforceCurrentUserQuery {
+ pub connection_id: String,
+}
+
+pub async fn salesforce_current_user(
+ State(state): State<Arc<WebState>>,
+ Query(q): Query<SalesforceCurrentUserQuery>,
+) -> Result<Json<dbx_core::connection::SalesforceCurrentUser>, AppError> {
+ state.app.salesforce_current_user(&q.connection_id).await.map(Json).map_err(AppError::from)
+}
+
#[cfg(test)]
mod tests {
use super::{
diff --git a/crates/dbx-web/src/routes/mcp_policy.rs b/crates/dbx-web/src/routes/mcp_policy.rs
index 7c116e44f2..2e8ca8bf64 100644
--- a/crates/dbx-web/src/routes/mcp_policy.rs
+++ b/crates/dbx-web/src/routes/mcp_policy.rs
@@ -522,6 +522,7 @@ mod tests {
read_only: false,
allow_dangerous_sql: true,
}],
+ allow_salesforce_dml: false,
}],
..Default::default()
}
diff --git a/docs/content/docs/mcp.cn.mdx b/docs/content/docs/mcp.cn.mdx
index 73a341becd..7d32ae3861 100644
--- a/docs/content/docs/mcp.cn.mdx
+++ b/docs/content/docs/mcp.cn.mdx
@@ -109,6 +109,9 @@ DBX MCP 当前提供以下工具(具体可用工具取决于构建功能及权
| `dbx_rollback_transaction` | 回滚当前会话事务 |
| `dbx_close_session` | 关闭会话并释放固定连接资源 |
| `dbx_execute_redis_command` | 执行 Redis 命令 |
+| `dbx_salesforce_current_user` | 显示连接背后的 Salesforce 用户与组织,包括简档是否具有 “Modify All Data” |
+| `dbx_salesforce_prepare_write` | 准备一条 Salesforce 记录写入,返回摘要和一次性确认令牌 |
+| `dbx_salesforce_apply_write` | 使用确认令牌应用已准备的 Salesforce 写入 |
| `dbx_peek_messages` | 读取 Kafka 消息,不提交消费位点 |
| `dbx_send_message` | 向支持的消息队列 Topic 或队列发送消息 |
| `dbx_open_table` | 在运行中的 DBX 桌面端打开表 |
@@ -176,6 +179,31 @@ DBX MCP 当前提供以下工具(具体可用工具取决于构建功能及权
<Callout type="warn">回滚保证依赖 InnoDB 等事务型存储。触发器、存储函数、非事务表及外部副作用可能产生 MySQL 无法回滚的效果。DBX 会在排队完成后重新检查当前连接/数据库范围、工具 allowlist、只读与生产保护以及已确认 SQL。即使写权限被撤销,仍允许原会话执行回滚和关闭以完成清理。</Callout>
+## Salesforce SOQL 与 DML
+
+Salesforce 连接使用 SOQL 而非 SQL,DBX 据此调整了 MCP 的行为:
+
+- `dbx_list_tables` 列出组织中的对象,`dbx_describe_table` 列出对象字段,`dbx_execute_query` 执行 SOQL(例如 `SELECT Id, Name FROM Account LIMIT 10`)。
+- `dbx_list_databases` 会说明一个 Salesforce 组织就是一个作用域,而不会虚构数据库。
+- `dbx_execute_batch` 与 `dbx_open_session` 会被拒绝:SOQL 只读,不存在需要批处理的多语句脚本;每次调用都是无状态 REST 请求,没有可固定的会话,也没有可开启的事务。
+- 写入记录永远不会走查询通道。`dbx_execute_query` 会以 `SALESFORCE_DML_REQUIRES_CONFIRMATION` 拒绝写入尝试,因此下面的确认流程无法被绕过。
+
+### 写入确认
+
+写入分为两次调用,且只有当人看到第一步的摘要后第二步才可能执行:
+
+1. 调用 `dbx_salesforce_prepare_write`,传入 `connection_id`(或 `connection_name`)、`op`(`insert`、`update` 或 `delete`)、`object`(API 名称,如 `Account` 或 `Invoice__c`);`update`/`delete` 需要记录 `id`,`insert`/`update` 需要 `fields`。此时不会向 Salesforce 发送任何请求。
+2. 把返回的摘要展示给用户:操作、对象、记录 Id、每个字段值、连接,以及该变更所归属的身份。
+3. 调用 `dbx_salesforce_apply_write`,传入第 1 步返回的 `confirm_token`。
+
+令牌只能使用一次,签发 5 分钟后过期,并与那一条语句绑定——写入内容变了就必须重新准备。重放、过期或从未签发的令牌会以 `CONFIRM_TOKEN_INVALID` 失败。DBX 在应用阶段会重新检查连接范围、工具白名单、只读与生产保护以及 DML 开关,因此两次调用之间撤销权限会立即生效。
+
+<Callout type="warn">Salesforce 写入不是事务性的。`dbx_salesforce_apply_write` 返回后,组织中的记录已经改变,DBX 无法回滚。每次调用只影响一条记录:`upsert`、批量与 composite 写入会在准备阶段以 `SALESFORCE_DML_INVALID` 拒绝。准备写入需要 **设置 → MCP** 中该连接的 **允许 DML** 开关,它默认关闭,未开启时返回 `SALESFORCE_DML_DISABLED`;执行模式为只读时该开关一律无效。</Callout>
+
+### 写入归属的身份
+
+`dbx_salesforce_current_user` 返回当前连接用户、简档、组织显示名,以及该简档是否具有 **Modify All Data**——这个标志决定字段级安全和记录共享规则是否生效。准备写入前先调用它,也可以用它区分权限失败与记录 Id 错误。`dbx_salesforce_prepare_write` 的摘要中包含同样的身份信息;若查询失败,摘要会写明身份未知并仍然完成准备,把是否应用的决定权留给用户。
+
## 数据库访问
### DBX Desktop 原生 Streamable HTTP
diff --git a/docs/content/docs/mcp.mdx b/docs/content/docs/mcp.mdx
index eebd12ea24..6e326406b1 100644
--- a/docs/content/docs/mcp.mdx
+++ b/docs/content/docs/mcp.mdx
@@ -109,6 +109,9 @@ DBX MCP provides the following tools (availability depends on build features and
| `dbx_rollback_transaction` | Roll back the active session transaction |
| `dbx_close_session` | Close a session and release its pinned connection resources |
| `dbx_execute_redis_command` | Execute a Redis command |
+| `dbx_salesforce_current_user` | Show the Salesforce user and org behind a connection, including whether the profile holds "Modify All Data" |
+| `dbx_salesforce_prepare_write` | Prepare one Salesforce record write and return a summary plus a single-use confirm token |
+| `dbx_salesforce_apply_write` | Apply a prepared Salesforce write using its confirm token |
| `dbx_peek_messages` | Read Kafka messages without committing consumer offsets |
| `dbx_send_message` | Send a message to a supported message queue topic or queue |
| `dbx_open_table` | Open a table in the running DBX desktop app |
@@ -176,6 +179,31 @@ Responses include `transaction_state` (`idle`, `active`, or `unknown`) and, when
<Callout type="warn">Rollback guarantees require transactional storage such as InnoDB. Triggers, stored functions, nontransactional tables, and external side effects can have effects that MySQL cannot roll back. DBX rechecks the current connection/database scope, tool allowlist, read-only and production protections, and confirmed SQL after queue waiting. Rollback and close remain available for cleanup after write permission is revoked.</Callout>
+## Salesforce SOQL and DML
+
+Salesforce connections speak SOQL, not SQL, and DBX shapes the MCP surface around that:
+
+- `dbx_list_tables` lists the org's objects, `dbx_describe_table` lists an object's fields, and `dbx_execute_query` runs SOQL (`SELECT Id, Name FROM Account LIMIT 10`).
+- `dbx_list_databases` explains that one Salesforce org is one scope instead of inventing databases.
+- `dbx_execute_batch` and `dbx_open_session` are refused: SOQL is read-only so there is no multi-statement script to batch, and every call is a stateless REST request — there is no session to pin and no transaction to open.
+- A record write is never a query. `dbx_execute_query` rejects write attempts with `SALESFORCE_DML_REQUIRES_CONFIRMATION` so the confirmation below cannot be bypassed.
+
+### Confirming a write
+
+Writing goes through two calls, and the second one only works if a human saw the first one's summary:
+
+1. `dbx_salesforce_prepare_write` with `connection_id` (or `connection_name`), `op` (`insert`, `update`, or `delete`), `object` (an API name such as `Account` or `Invoice__c`), the record `id` for `update`/`delete`, and `fields` for `insert`/`update`. Nothing is sent to Salesforce.
+2. Show the returned summary to the user: the operation, object, record Id, every field value, the connection, and the identity the change will be attributed to.
+3. `dbx_salesforce_apply_write` with the `confirm_token` from step 1.
+
+The token is single-use, expires 5 minutes after it was issued, and is bound to that exact statement — a changed write needs a new prepare. A replayed, expired, or never-issued token fails with `CONFIRM_TOKEN_INVALID`. DBX re-checks the connection scope, tool allowlist, read-only and production protections, and the DML opt-in at apply time, so revoking permission between the two calls takes effect immediately.
+
+<Callout type="warn">Salesforce writes are not transactional. Once `dbx_salesforce_apply_write` returns, the record has changed in the org and DBX cannot roll it back. Each call touches exactly one record: `upsert`, bulk, and composite writes are rejected at prepare time with `SALESFORCE_DML_INVALID`. Preparing a write needs the per-connection **Allow DML** switch in **Settings → MCP**, which is off by default and returns `SALESFORCE_DML_DISABLED` until a person turns it on; a read-only execution mode ignores the switch entirely.</Callout>
+
+### Who the write is attributed to
+
+`dbx_salesforce_current_user` returns the connected user, their profile, the org display name, and whether that profile holds **Modify All Data** — the flag that decides whether field-level security and record sharing apply at all. Call it before preparing a write, and use it to tell a permission failure apart from a bad record Id. `dbx_salesforce_prepare_write` includes the same identity in its summary; if the lookup fails the summary says the identity is unknown and still prepares the write, leaving the decision with the user.
+
## Database Access
### Native Streamable HTTP for DBX Desktop
diff --git a/docs/salesforce-soql-integration-spec.md b/docs/salesforce-soql-integration-spec.md
new file mode 100644
index 0000000000..bb6b137ca3
--- /dev/null
+++ b/docs/salesforce-soql-integration-spec.md
@@ -0,0 +1,302 @@
+# Salesforce (SOQL) 驱动集成 Spec
+
+> 状态:v1.1 — D1~D6 已决策(见 §13);M0+M1 已交付并经真实 sandbox 验证;M2 OAuth 已实现(PKCE 浏览器流 + Device Flow + refresh 持久化/自动续期),Connected App 暂为 BYO(bundled client id 待注册后填入 salesforce_oauth.rs 默认值)
+> 日期:2026-09-21
+> 范围:为 DBX 新增 Salesforce 连接类型,支持 SOQL 查询、sObject 元数据浏览、行级 DML、SOQL 自动补全,并最终暴露到 MCP。
+
+---
+
+## 1. 目标与非目标
+
+### 目标
+- 用户可以像连接其他 40+ 数据库一样连接 Salesforce org(生产/Sandbox)。
+- 在查询编辑器执行 SOQL,结果以现有 DataGrid 呈现,支持分页。
+- 对象树浏览:sObject → fields(含 label、类型、可编辑性)。
+- 行级 DML:网格内编辑/新增/删除记录(受 capability 与只读会话控制)。
+- SOQL 语法高亮 + 上下文感知自动补全(对象、字段、关系穿越、picklist 值)。
+- MCP bridge 暴露只读查询能力给 AI agent。
+
+### 非目标(明确不做)
+- SQL → SOQL 自动翻译层(语义差异大,见 §10 开放问题 Q1 讨论记录)。
+- Apex 执行、Tooling API(元数据开发类查询)、Metadata API 部署。
+- Bulk API 2.0 大批量导入导出(远期,对齐 `dataTransfer` capability 时再议)。
+- Report / Dashboard / Analytics API。
+
+---
+
+## 2. 认证设计
+
+### 2.1 支持的登录方式(按优先级)
+
+| # | 方式 | 模式 | 说明 |
+|---|------|------|------|
+| 1 | OAuth Authorization Code + PKCE | 桌面 | 主路径。复用 `crates/dbx-drivers/src/mongo_oidc.rs` 的模式:本地 `TcpListener` 监听回调 → 系统浏览器授权 → code 换 token。Connected App 需配置 `refresh_token` scope 以获取长期令牌 |
+| 2 | OAuth Device Flow | 桌面 + **web** | `grant_type=urn:ietf:params:oauth:grant-type:device_code`。UI 显示 user code,用户在任意设备浏览器输入。**这是 web/Docker 模式下唯一的浏览器授权方式** |
+| 3 | 粘贴 Access Token + instance_url | 桌面 + web | 调试/CI/兜底。Session ID 可直接作 Bearer token。无 refresh 能力,过期后需重新粘贴 |
+| 4 | Username-Password OAuth | 桌面 + web | ⚠️ Salesforce 已弃用(新 Connected App 无法启用)。仅作为 BYO Connected App 的兼容项,UI 上明确标注 deprecated;密码需拼接 security token |
+| — | JWT Bearer / Client Credentials | 不做 | 面向无人值守自动化,非交互式用户场景 |
+
+### 2.2 Connected App 策略(**已决策 D1**)
+- **采用方案 A**:DBX 官方内置一个 Connected App(bundle client_id,PKCE 公共客户端无 secret),用户零配置;另留 BYO 高级选项 + token 粘贴兜底。DBeaver、Data Loader 均为内置模式。
+- 落地事项:注册开发者 org、创建 Connected App(redirect URI 含 `http://localhost:*/callback` 与 Device Flow)、client_id 以配置常量内置;撰写「org admin 审批 Connected App」引导文档。
+- 风险:需维护该 app、遵守 Salesforce ToS/品牌规范;部分 org 限制未审批 Connected App(用户卡在授权页,提示文档引导 admin 审批)。
+
+### 2.3 登录端点
+- 三选:`login.salesforce.com`(生产)/ `test.salesforce.com`(Sandbox)/ 自定义 My Domain。
+- `instance_url` 一律以 token 响应为准,后续所有 API 调用打 instance_url,不依赖登录域名。
+
+### 2.4 Token 存储与续期
+- access_token + refresh_token 持久化到现有 SQLite `connection_secrets` 表(`FileSecretStore`,key 形如 `plugin_connection.salesforce_refresh_token`)。
+- ⚠️ **安全注意**:现有 secret 存储为**明文 SQLite**(与所有既有驱动的密码同级)。Salesforce refresh_token 是长期有效凭据,泄露即可完全访问 org。本 spec 接受与现状一致的风险等级,但建议在文档中标注;若未来引入 SQLCipher/keychain 迁移,Salesforce token 应首批受益。
+- 续期逻辑在驱动内实现(无现成通用 token-refresh 框架):access_token 失效(401)→ 用 refresh_token 换新 → 仍失败则标记连接需重新授权。
+- 参考现状:mongo_oidc 的 refresh_token **不持久化**(进程内存活),Salesforce 不能照搬——用户预期是「连一次一直能用」。
+- web 模式:沿用 `owner_scope` 会话隔离机制。
+
+### 2.5 web 模式 OAuth 结论(已由代码调查确认)
+- mongo_oidc 的 localhost 回调在 web 模式**不可用**(监听在服务器、回调打到用户机器;浏览器 opener 是 Tauri-only API,web 端有硬 guard)。
+- 本期方案:**web 模式仅支持 Device Flow + token 粘贴**;桌面模式支持全部方式。
+- 远期可选:dbx-web 增加服务端回调路由(`/oauth/salesforce/callback`),需处理多用户会话与 redirect URI 注册,暂不做。
+
+---
+
+## 3. 当前用户与权限探测(MVP 内含)
+
+连接建立后立即执行:
+1. `GET /services/oauth2/userinfo` → user_id、name、email、organization_id(不消耗 SOQL 配额)。
+2. SOQL:
+ ```sql
+ SELECT Id, Username, Profile.Name, Profile.PermissionsModifyAllData,
+ Profile.PermissionsViewAllData
+ FROM User WHERE Id = '<userId>'
+ ```
+ `PermissionsModifyAllData = true` 即事实管理员(比匹配 Profile.Name 可靠)。
+
+用途:
+- 连接状态栏显示身份徽章(用户名 @ org,admin 加标记)。
+- 非 admin 用户执行 DML 前展示额外警示。
+- MCP 侧暴露 `current_user` 上下文。
+
+粒度说明:PermissionSet 可授予细分权限,二值判断只是粗判,仅作 UI 提示用途,**不作为安全边界**(真正的访问控制在 Salesforce 服务端)。
+
+---
+
+## 4. 驱动架构与文件清单
+
+架构模式与所有既有驱动一致(枚举分发,无统一 trait):
+
+| 文件 | 动作 | 内容 |
+|------|------|------|
+| `plugins/connection-types/salesforce.yaml` | 新建 | 连接类型定义(见 §5) |
+| `crates/dbx-drivers/src/db/salesforce_driver.rs` | 新建 | HTTP client(reqwest)、OAuth 流程、SOQL 执行、describe 元数据、DML 命令解释 |
+| `crates/dbx-drivers/src/db/mod.rs` | 修改 | 注册模块 |
+| `crates/dbx-core/src/connection/mod.rs` | 修改 | `PoolKind::Salesforce(SfClient)` 变体 |
+| `crates/dbx-core/src/connection/driver_runtime.rs` | 修改 | 连接创建路由 |
+| `crates/dbx-core/src/query/mod.rs` | 修改 | 查询分发 match 臂(SOQL 执行 + DML 伪命令解释) |
+| `crates/dbx-core/src/schema/mod.rs` | 修改 | 元数据浏览分发(listTables → sObjects,listColumns → fields) |
+| `crates/dbx-drivers/src/salesforce_oauth.rs` | 新建 | PKCE / Device Flow / token 刷新(参考 mongo_oidc.rs 结构) |
+| `apps/desktop/public/icons/database/salesforce.svg` + `DatabaseIcon.vue` | 新建/修改 | 图标(注意 Salesforce 品牌使用规范) |
+| `apps/desktop/src/components/connection/ConnectionDialog.vue` | 修改 | 连接表单分支(认证方式选择、OAuth 按钮、token 状态) |
+| `apps/desktop/src/i18n/locales/*.ts` | 修改 | en / zh-CN / es 翻译 |
+| `scripts/sync-connection-types.mjs` | 运行 | 生成前端类型 |
+
+参考模板:**Elasticsearch 驱动**(HTTP REST、native + bridge、动态元数据映射)。
+
+### 4.1 API 版本策略
+- Pin 一个固定版本(如 `v62.0`)作为默认;高级配置允许覆盖。
+- Salesforce API 每版本保留 ≥3 年,pin 策略风险可控;每年随大版本升级一次。
+
+---
+
+## 5. 连接配置 Schema(salesforce.yaml 草案)
+
+```yaml
+runtimeMode: native # HTTP REST,同 Elasticsearch
+mcpMode: bridge # SOQL 非标准 SQL
+supportLevel: browse # MVP:查询 + 元数据浏览;DML 落地后升 operate(或自定义 capability 覆盖)
+behaviorTraits:
+ schemaAware: false
+ singleDatabase: true # 一个 org = 一个"数据库"
+```
+
+连接表单字段:
+- 认证方式(枚举:oauth_browser / oauth_device / access_token / user_pass)
+- environment(枚举:production / sandbox / custom_my_domain → 自定义登录 URL)
+- client_id / client_secret(BYO 模式;内置模式隐藏)
+- access_token + instance_url(token 粘贴模式)
+- username / password(+security token)(deprecated 模式,带警示)
+- api_version(高级,默认 pin 值)
+
+capabilities 覆盖(MVP):
+`queryExecution ✅ / metadataBrowse ✅ / objectBrowser ✅ / schemaSearch ✅`,
+其余(objectSource、diagram、tableDataEdit、tableImport、dataTransfer、sqlFileExecution、databaseCreate、sqlExplain、userAdmin、driverManagement、fieldLineage)全 ❌;`tableDataEdit` 在 Phase 2 打开。
+
+---
+
+## 6. 元数据与 Schema 映射
+
+| Salesforce | DBX 抽象 | API |
+|---|---|---|
+| org | database(singleDatabase) | — |
+| sObject | table | `GET /sobjects/`(支持 ETag/If-Modified-Since) |
+| field | column(label + apiName + type + updateable/nillable) | `GET /sobjects/{type}/describe` |
+| relationship | 外键提示(补全用,不建 ER) | describe 的 childRelationships |
+
+### 6.1 缓存策略(关键,配额敏感)
+- 大 org 有数百 sObject,全量 describe 可达数十 MB,且 Salesforce 按 org 限每日 API 调用。
+- **惰性加载**:对象树只拉 `/sobjects/`(轻量列表);describe 仅在展开某对象/补全需要时触发。
+- **磁盘缓存**:describe 结果按 `(instance_url, api_version, sobject)` 键缓存到本地;`/sobjects/` 用条件请求(ETag)做增量刷新。
+- 缓存对前端补全(§9)同样供数。
+
+---
+
+## 7. 查询执行(SOQL → QueryResult)
+
+- `GET /services/data/{ver}/query?q=<SOQL>` → JSON → `QueryResult { columns, column_types, rows, has_more, session_id }`。
+- 列类型用 field type(string/int/double/date/datetime/boolean/reference/picklist/…)填充 `column_types`。
+- **分页**:首批 ≤2000 行;`nextRecordsUrl` 映射到 `has_more=true` + `session_id`(存 QueryLocator),复用现有游标分页机制。UI 提供「加载更多」而非默认全量拉取(配额保护)。
+- **compound fields**(Name/Address):默认展平为子字段列;查询里直接 select compound 字段时按返回 JSON 展平。
+ - 已实现:`parse_describe_columns` 直接过滤 SOQL 无法投影的 describe 字段——compound `address`/`location`(子字段 `BillingStreet` 等本身就在 describe 里,展平即「只保留子字段」)与 `accessible=false`(无 FLS 读权限,SOQL 报 INVALID_FIELD)。这两类字段只要出现在 SELECT 列表里就会让**整条查询**失败,因此不能进网格投影,也不进补全列表。
+- **数据网格 SQL 构建**(右键对象 →「查看数据」):走 `build_table_data_select_sql` 的 Salesforce 专用分支 `build_salesforce_table_select_sql`,不能复用 ANSI 形状。SOQL 三处差异:无 `SELECT *`、无定界标识符(`FROM "Account"` 报 MALFORMED_QUERY,双引号在 SOQL 里是字符串字面量)、无尾分号。投影优先用 describe 字段名逐个列出(任意页大小都合法);拿不到字段列表时退回 `FIELDS(ALL)`,并把 LIMIT 压到 ≤200(Salesforce 对 `FIELDS(*)` 的硬性上限)。`OFFSET` 上限 2000,超出直接透传给 org 报错而不静默改页。
+ - 前端配套:`requiresEagerTableMetadataForDataOpen()` 把 salesforce 与 mysql/postgres 一并列入「必须先拿到列再建 SQL」,否则列列表为空只能走 200 行上限的 `FIELDS(ALL)` 兜底。`quoteTableIdentifier` 对 salesforce 原样返回,与 Rust 侧 `quote_table_identifier` 对齐(网格排序/筛选也走它)。
+- **表数据 CSV 导出**:`export_table_data_csv_core` 对 Salesforce 显式拒绝(不写文件)。该路径用 `LIMIT <page_size> OFFSET <n>` 翻页、以「短页」为终止条件,两个前提在 SOQL 下都不成立(单批 ≤2000 行、`OFFSET` ≤2000),首页永远看起来是短页,结果是**静默截断**的 CSV。正确实现要跟随 QueryLocator(`fetch_more`)翻页,与网格「加载更多」一致;该入口目前没有 UI 调用方,故先拒绝并提示改用「执行 SOQL → 导出结果集」。
+- **reference 字段**:显示 Id;用户在补全引导下自行写 relationship 查询取 Name。
+- **queryAll**(回收站):编辑器工具栏开关,切 `/queryAll` 端点。Phase 2+。
+- **错误映射**:API errorCode → 用户可读信息(MALFORMED_QUERY=语法错误+原文、INVALID_FIELD=字段不存在/无 FLS 权限、INSUFFICIENT_ACCESS、REQUEST_LIMIT_EXCEEDED=当日 API 配额耗尽提示)。governor limit 错误必须明确归因到 Salesforce 侧,避免用户误判为 DBX bug。
+
+---
+
+## 8. DML 设计(**已决策 D2/D6:网格行级编辑 + JSON 伪命令通道**)
+
+### 8.1 背景(代码调查结论)
+- 现有 DataGrid 保存链路是「后端生成 SQL 语句文本 + 回滚语句 → 前端 executeBatch 执行」,**契约是 SQL 文本**,SOQL 无 DML,不能直接复用。
+- **DynamoDB 先例**:非 SQL 驱动的 tableDataEdit 走两条路——DocumentBrowser(JSON 文档编辑)+ 通过查询通道发送伪命令文本(`"DBX DYNAMODB PUT ITEM"` 等),由驱动在 execute_query 里解释执行。
+- Neo4j/TDengine 先例:`prepare_data_grid_save` 有专用 builder,生成方言语句。
+
+### 8.2 采用方案:网格行级编辑 + JSON 伪命令通道(模式 A)
+- 前端复用 `useDataGridEditor`(dirtyRows/newRows/deletedRows 采集、保存编排、错误展示全部现成)。
+- 后端为 Salesforce 写专用 save builder:不生成 SQL,生成**结构化伪命令**(建议 JSON 载荷优于 DynamoDB 式纯文本,如 `DBX SALESFORCE DML {"op":"update","type":"Account","id":"001...","fields":{...}}`),经现有查询通道下发,驱动解释为 REST 调用:
+ - update → `PATCH /sobjects/{type}/{id}`
+ - insert → `POST /sobjects/{type}`(返回新 Id 回填网格)
+ - delete → `DELETE /sobjects/{type}/{id}`
+- **行必须有 Id**:无 Id 列的查询结果禁用编辑(网格已有 keyless 处理经验,直接套用 guard 思路)。
+- **可编辑性由 describe 驱动**:field 的 `updateable=false`(formula/rollup/auto-number)→ 该列网格只读;`nillable/defaultedOnCreate` 参与新增行校验。
+- **错误按行映射**:逐条执行(或 Composite API 批量),validation rule / FLS 失败映射为「第 N 行失败 + Salesforce 错误原文」,成功行不回滚(REST 无事务;如需原子性,Phase 3 评估 Composite Tree/Graph API)。
+- 回滚语句(rollbackStatements)对 Salesforce 无意义 → 返回空 + 前端保存前弹确认(展示将执行的 REST 操作清单预览)。
+
+### 8.3 配套/后续形态
+- **单记录 JSON 编辑器**(模式 C):复用 DocumentBrowser 交互,作为网格编辑的补充(长文本、多字段记录更顺手)。Phase 3。
+- **SQL 风格 DML 翻译**(模式 B):仅受限子集(`WHERE Id = / IN` 直译),Phase 3+,非必须。
+- **External ID upsert**:`PUT /sobjects/{type}/{extIdField}/{value}`,Phase 3。
+- **Bulk API 2.0**:对齐 dataTransfer 时再议,非本 spec 范围。
+
+### 8.4 安全约束
+- 一切写操作受 ReadOnlySessionControl 约束。
+- 非 admin 用户(§3)DML 前额外警示。
+- MCP 侧 DML 暴露见开放决策 D3。
+
+---
+
+## 9. 自动补全与语法高亮
+
+### 9.1 复用面(代码调查结论)
+- 编辑器为 CodeMirror(`QueryEditor.vue` + `@codemirror/lang-sql`),补全引擎 `sqlCompletion.ts` 纯前端,消费后端 `listTables/listColumns` 元数据 → **对象/字段补全的管道全部现成**,只要 §6 的元数据 provider 就位即自动生效。
+- 方言三层,需各加一处:
+ 1. `codemirrorSqlDialect.ts`:新增 `SQLDialect.define()` 注册 SOQL(keywords:FROM/WHERE/ORDER BY/LIMIT/OFFSET/GROUP BY/TYPEOF/INCLUDES/EXCLUDES/FIELDS/NULLS FIRST…;无 JOIN、无 `;` 多语句)。
+ 2. `semantic/dialect.ts`:SOQL 适配器(语句分割、引号语义——SOQL 标识符不引用,字符串单引号)。
+ 3. `plugins/dialects/soql.yaml`:Rust 侧类型目录(Id/Currency/Phone/Email/Picklist/DateTime…),供 dbx-sql 类型映射。
+
+### 9.2 SOQL 特有补全(新工作,按价值排序)
+1. **字段级上下文补全**:确定 FROM 对象后,SELECT/WHERE/ORDER BY/GROUP BY 位置补全字段;**关系逐级穿越**(`Account.` → Owner/Parent 关系字段 → `Account.Owner.` → User 字段)。需要在 completion source 里加「当前光标上下文扫描」(轻量 scanner:找最近 FROM 对象 + 点号前缀,不需完整 parser)。
+2. **picklist 值补全**:`WHERE StageName = '` 后补全 describe 的 `picklistValues`。现有补全引擎没有值级数据源,需要扩展元数据管道(listColumns 返回 picklist values,或新增 API)。**独特卖点,优先做**。
+3. **展开全部字段**:SOQL 无 `SELECT *`,提供快捷动作在 `SELECT ` 后生成全字段列表(过滤无 FLS 权限字段)。
+4. **日期字面量/函数**:TODAY、YESTERDAY、LAST_N_DAYS:n、THIS_FISCAL_YEAR、聚合函数。
+5. 补全列表显示 `Label (ApiName)` 双列,插入 ApiName。
+6. 轻量静态提示(非阻断):`SELECT *` 提示、GROUP BY 一致性。
+
+数据源:全部来自 §6 的 describe 缓存。
+
+---
+
+## 10. MCP 暴露(**已决策 D3:只读默认暴露;DML 连接级开关 + 人工确认,默认关**)
+
+### 10.1 已实现(M5)
+
+清单里的 `mcpMode: bridge` 是**声明性字段**:全仓无运行时消费者(`grep mcp_mode` 只命中 `crates/dbx-types/src/database_manifest.rs`),Salesforce 走 `runtimeMode: native` 进程内路径(`PoolKind::Salesforce`),因此 Local 与 Web 两种 MCP 后端都能直接用同一批工具,不需要 bridge 进程。
+
+只读面(默认暴露,无需额外授权):
+
+| 工具 | Salesforce 行为 |
+|---|---|
+| `dbx_list_tables` | 列出 org 对象(describe global 缓存) |
+| `dbx_describe_table` | 列出对象字段 |
+| `dbx_execute_query` | 执行 SOQL;`dbx-sql` 的 Salesforce 分类器把 SOQL 判为 `Read` |
+| `dbx_list_databases` | 不返回数据库,而是说明「一个 org 就是一个作用域」并指向 `dbx_list_tables` + SOQL 示例 |
+| `dbx_execute_batch` | 拒绝(`DBX_BATCH_UNSUPPORTED`):SOQL 只读,无多语句脚本可批 |
+| `dbx_open_session` | 拒绝(`SESSION_UNSUPPORTED`):每次调用都是无状态 REST,无会话可固定、无事务 |
+| `dbx_salesforce_current_user` | 新增:连接用户 / 简档 / org 显示名 / 是否具备 “Modify All Data” |
+
+写入面(**通道 B:两步确认**,新增三个工具中的后两个):
+
+1. `dbx_salesforce_prepare_write { op, object, id?, fields? }` — 只构造并校验 `DBX SALESFORCE DML` 伪命令,**不发送任何请求**。返回人类可读摘要(操作 / 对象 / 记录 Id / 逐字段值 / 连接 / 身份)+ 一次性 `confirm_token`。
+2. `dbx_salesforce_apply_write { confirm_token }` — 只执行令牌对应的那一条语句;令牌单次有效、TTL 300 秒、与语句绑定,进程内最多 64 条待确认(超出淘汰最旧)。
+
+服务端强制点(agent 无法绕过):
+
+- `dbx_execute_query` 对 Salesforce 连接显式拒绝写入伪命令(`SALESFORCE_DML_REQUIRES_CONFIRMATION`)。没有这一条,可写策略下的 agent 能直接把伪命令当「查询」发出去,同时绕过连接级开关和两步确认——而 Salesforce 无法回滚。
+- 连接级开关 `allowSalesforceDml`(`McpConnectionRule`,`#[serde(default)]`,默认 `false`;老策略反序列化后自然为关)。未开启 → `SALESFORCE_DML_DISABLED`。
+- `read_only` 是硬上限:`connection_allows_salesforce_dml` 要求 `allow_salesforce_dml && !read_only`,`effective_mcp_policy_with_legacy_allow_writes(…, Some(false))` 会连同 `allow_dangerous_sql` 一起清掉该开关;前端 `normalizeMcpGlobalPolicy` 与 `onMcpConnectionExecutionModeChange` 同样在切到只读时撤销它。
+- prepare 与 apply **各自**跑一遍完整 `validate_sql_policy`(全局/连接/数据库只读、高风险分级、`targets_production_database`),所以两次调用之间撤销权限立即生效。
+- prepare 时以驱动的 `parse_salesforce_statement` 为权威校验,保证不会为 org 必然拒绝的语句发令牌;`upsert`/bulk/composite 一律 `SALESFORCE_DML_INVALID`(一次只碰一条记录)。
+- 身份查询是 best-effort:失败只在摘要里写「身份未知」,仍然完成 prepare,把是否 apply 的决定权留给人。
+
+风险分级(`crates/dbx-sql/src/query_execution_sql.rs`,fail-closed):SOQL → `Read`;带 Id 的单记录 DML → `ScopedWrite`(映射 `SqlRisk::Write`,只需 safe_write);无 Id / 无法判定 → `OpaqueWrite`(映射 `SqlRisk::Ddl`,需 allow_dangerous_sql)。
+
+前端开关位置:**设置 → MCP → 连接范围**,仅对 `db_type === "salesforce"` 的连接行渲染(`McpResourceScopePicker.vue`),文案 `settings.mcpConnectionPolicyAllowSalesforceDml`;有效执行模式为只读时点击只提示不保存。工具白名单里三个新工具可独立勾选,因此可以只给 agent 读能力(`current_user` + SOQL)而不给写通道。
+
+历史与活动标签:`mcp_sql_activity_kind` / `mcp_sql_operation` 增加了 Salesforce 分支(`Read` → `query`/`SELECT`;写入 → `data_change`/对应 DML 动词)。通用路径按 SQL 风险档推断标签,而 Salesforce 的无范围写入 fail-closed 落在 DDL 档,会把一次记录写入误标成 `schema_change`;`mcp_sql_operation` 也只会取到伪命令首词 `DBX`。同理 `mcp_sql_has_forbidden_database_switch` 对 Salesforce 直接返回 `false`:SOQL 没有 `USE`、pool 按连接而非库分键,而通用 tokenizer 回退会把 JSON 字段值里的 `;` 当成语句边界,从而把 `{"Description":"a; USE prod"}` 这样的合法写入误判为切库。
+
+### 10.2 未做(有意留待后续)
+
+- 每次 apply 前弹出**桌面端**确认对话框(当前确认发生在 agent ↔ 人之间,DBX 只做服务端强制 + 摘要)。
+- 对象级 createable/updateable/deletable 预检(现在靠 org 自身逐行报错)。
+- External-ID upsert、Composite/Graph 原子多记录写入。
+
+---
+
+## 11. 分阶段里程碑
+
+| 阶段 | 内容 | 验收 |
+|---|---|---|
+| ✅ **M0 骨架** | salesforce.yaml + sync 脚本 + PoolKind/分发接线 + 图标 + 表单(token 粘贴模式)| manifest 三测试通过(`cargo test -p dbx-core --test database_capabilities` + 两个 `driver-manifest.test.ts`),能用粘贴 token 连上 dev org |
+| ✅ **M1 查询闭环** | execute_query(SOQL→QueryResult)+ 分页 + 错误映射 + listTables/listColumns(describe 缓存)+ userinfo/admin 探测 | 对象树可浏览,SOQL 查询出结果,配额友好 |
+| ✅ **M2 OAuth** | PKCE 浏览器流(桌面)+ Device Flow(web)+ token 持久化与刷新 | 桌面一键授权,重启不丢登录 |
+| ✅ **M3 编辑体验** | SOQL 方言高亮 + 补全(对象/字段/关系/picklist)+ 展开全部字段 | 补全基于 describe 缓存,无重复 API 消耗 |
+| ✅ **M4 DML** | 网格行级编辑(§8.2)+ tableDataEdit capability 打开 + 只读/警示联动 + 状态栏身份徽章 | 编辑-保存-逐行错误反馈闭环 |
+| ✅ **M5 MCP** | 只读工具 Salesforce 化(§10.1)+ `dbx_salesforce_current_user` + SOQL 风险分级 + 拒绝 batch/session + 两步确认 DML 通道(连接级开关默认关) | agent 可通过 MCP 查询 org;写入必须 prepare→人工确认→apply,且无法从 `dbx_execute_query` 绕过 |
+
+依赖关系:M1 是核心;M2/M3 可并行;M4 依赖 M1 的 describe 元数据;M5 依赖 M1。
+**最短可演示路径:M0+M1(token 粘贴 + 查询 + 浏览)。**
+
+---
+
+## 12. 测试策略
+
+- **手工/集成**:注册 Free Developer Edition org(developer.salesforce.com/signup)作为固定测试环境;seed 若干 Account/Contact/自定义对象。
+- **Rust 单测**:HTTP 层 mock(照 Elasticsearch 驱动现有测试方式);OAuth 流程用 mock token endpoint;SOQL→QueryResult 映射用录制的真实响应 fixture。
+- **前端**:补全 scanner 单测(vitest);DataGrid 编辑链路沿用现有测试模式。
+- **MCP**:`cargo test -p dbx-mcp --lib salesforce` 覆盖两步确认通道(令牌单次有效/过期/上限、连接级开关、只读与生产规则、伪命令不能从 `dbx_execute_query` 偷渡、batch/session 拒绝、身份摘要);前端 `mcpPolicySelection.spec.ts` 用正则从 `crates/dbx-mcp/src/server.rs` 抓取已注册工具名,断言工具目录与后端严格同步——新增工具若忘记加进 `MCP_TOOL_OPTIONS`,该测试会失败。
+- **manifest 一致性**:CLAUDE.md 规定的三个测试进 CI 必跑。
+- CI 不连真实 org(无 secret 依赖),真实 org 验证走手工 checklist。
+
+---
+
+## 13. 决策记录(2026-09-21 全部确认)
+
+| # | 问题 | 决策 |
+|---|---|---|
+| **D1** | Connected App 分发 | ✅ 官方内置为主 + BYO 高级选项 + token 粘贴兜底 |
+| **D2** | DML 机制 | ✅ 网格行级编辑(JSON 伪命令通道)为主,单记录 JSON 编辑器 Phase 3 补充(§8.2) |
+| **D3** | MCP DML 暴露 | ✅ 只读工具默认暴露;DML 连接级开关 + 人工确认,默认关(实现为两步 `prepare_write`/`apply_write` 令牌通道,见 §10.1) |
+| D4 | refresh_token 明文落盘 | ✅ 接受(与现状一致),文档标注;未来 secret 加密时首批迁移 |
+| D5 | queryAll(回收站) | ✅ Phase 2,不进 MVP |
+| D6 | 伪命令载荷格式 | ✅ JSON(可校验、可扩展) |
diff --git a/packages/mcp-server/README.md b/packages/mcp-server/README.md
index 37ddefaa55..9526d01c44 100644
--- a/packages/mcp-server/README.md
+++ b/packages/mcp-server/README.md
@@ -157,6 +157,9 @@ Ask the MCP client to:
| `dbx_open_session` | Open a stateful SQL query session pinned to one backend connection |
| `dbx_close_session` | Close a session and release its pinned connection resources |
| `dbx_execute_redis_command` | Execute a Redis command |
+| `dbx_salesforce_current_user` | Show the Salesforce user and org behind a connection, including the "Modify All Data" flag |
+| `dbx_salesforce_prepare_write` | Prepare one Salesforce record write and return a summary plus a single-use confirm token |
+| `dbx_salesforce_apply_write` | Apply a prepared Salesforce write using its confirm token |
| `dbx_peek_messages` | Read Kafka messages without committing consumer offsets |
| `dbx_send_message` | Send a message to a supported message queue topic |
| `dbx_open_table` | Open a table in the running DBX desktop application |
@@ -170,6 +173,8 @@ When connection scoping is enabled, mutating connection tools and desktop UI too
`dbx_list_databases` returns only database names allowed by the selected connection's MCP database scope. `dbx_send_message` is available when message-queue support is included in the server build.
+Salesforce connections take SOQL through `dbx_execute_query` and list objects through `dbx_list_tables`. `dbx_execute_batch` and `dbx_open_session` are refused: SOQL is read-only, and every call is a stateless REST request with no session to pin. A record write is a two-step confirmed operation — `dbx_salesforce_prepare_write` returns a summary plus a single-use `confirm_token` that expires after 5 minutes, a person approves that summary, and `dbx_salesforce_apply_write` sends exactly the prepared statement. Preparing needs the per-connection **Allow DML** switch in DBX Settings → MCP, which is off by default, and Salesforce cannot roll an applied write back.
+
## Execution Modes
### Local native mode
@@ -537,6 +542,9 @@ MCP 配置:
| `dbx_open_session` | 为 SQL 连接打开固定后端连接的有状态查询会话 |
| `dbx_close_session` | 关闭会话并释放固定连接资源 |
| `dbx_execute_redis_command` | 执行 Redis 命令 |
+| `dbx_salesforce_current_user` | 显示连接背后的 Salesforce 用户与组织,包括 “Modify All Data” 标志 |
+| `dbx_salesforce_prepare_write` | 准备一条 Salesforce 记录写入,返回摘要和一次性确认令牌 |
+| `dbx_salesforce_apply_write` | 使用确认令牌应用已准备的 Salesforce 写入 |
| `dbx_peek_messages` | 读取 Kafka 消息,不提交消费位点 |
| `dbx_send_message` | 向支持的消息队列 Topic 发送消息 |
| `dbx_open_table` | 在 DBX 桌面端打开表 |
@@ -548,6 +556,8 @@ MCP 配置:
`dbx_list_databases` 只返回该连接 MCP 数据库范围内允许访问的名称。`dbx_send_message` 仅在 Server 构建时包含消息队列支持时可用。
+Salesforce 连接通过 `dbx_execute_query` 执行 SOQL,通过 `dbx_list_tables` 列出对象。`dbx_execute_batch` 与 `dbx_open_session` 会被拒绝:SOQL 只读,且每次调用都是无状态 REST 请求,没有可固定的会话。写入记录是两步确认操作——`dbx_salesforce_prepare_write` 返回摘要和一次性 `confirm_token`(5 分钟后过期),由人确认该摘要后,`dbx_salesforce_apply_write` 才会发送那条已准备好的语句。准备写入需要在 DBX 设置 → MCP 中为该连接开启 **允许 DML**(默认关闭),且 Salesforce 无法回滚已应用的写入。
+
### 本地数据目录
- macOS:`~/Library/Application Support/com.dbx.app/dbx.db`
diff --git a/plugins/connection-types/profiles/catalog.yaml b/plugins/connection-types/profiles/catalog.yaml
index 5e5c64b13e..c9b1769c1b 100644
--- a/plugins/connection-types/profiles/catalog.yaml
+++ b/plugins/connection-types/profiles/catalog.yaml
@@ -736,6 +736,13 @@ profiles:
port: 8428
user: ""
category: timeseries
+ - id: salesforce
+ dbType: salesforce
+ label: Salesforce
+ icon: salesforce
+ port: 443
+ user: ""
+ category: analytics
- id: custom_mysql
dbType: mysql
label: Custom
diff --git a/plugins/connection-types/salesforce.yaml b/plugins/connection-types/salesforce.yaml
new file mode 100644
index 0000000000..a182908466
--- /dev/null
+++ b/plugins/connection-types/salesforce.yaml
@@ -0,0 +1,32 @@
+schemaVersion: 1
+order: 800
+dbType: salesforce
+rustVariant: Salesforce
+label: Salesforce
+dialect: SOQL
+runtimeMode: native
+mcpMode: bridge
+singleConnectionPool: true
+metadataConnectionScoped: false
+skipTcpProbe: true
+defaultPort: 443
+traits:
+ singleDatabase: true
+supportLevel: operate
+capabilities:
+ queryExecution: true
+ metadataBrowse: true
+ objectBrowser: true
+ objectSource: false
+ schemaSearch: true
+ diagram: false
+ tableDataEdit: true
+ tableStructureEdit: false
+ tableImport: false
+ dataTransfer: false
+ sqlFileExecution: false
+ databaseCreate: false
+ fieldLineage: false
+ sqlExplain: false
+ userAdmin: false
+ driverManagement: false
diff --git a/plugins/dialects/soql.yaml b/plugins/dialects/soql.yaml
new file mode 100644
index 0000000000..d0631ff227
--- /dev/null
+++ b/plugins/dialects/soql.yaml
@@ -0,0 +1,85 @@
+# Salesforce SOQL dialect — query-only via REST API, no DDL support.
+# Metadata is fetched through the Salesforce describe API, not SQL queries.
+dialect:
+ name: "SOQL"
+ display_name: "Salesforce SOQL"
+ versions:
+ - version: "62"
+ status: "RECOMMENDED"
+
+types:
+ - name: "string"
+ category: "STRING"
+ has_length: true
+ aliases: ["textarea", "email", "phone", "url", "encryptedstring", "combobox"]
+ - name: "id"
+ category: "STRING"
+ - name: "boolean"
+ category: "BOOLEAN"
+ - name: "int"
+ category: "INTEGER"
+ - name: "long"
+ category: "INTEGER"
+ aliases: ["BIGINT"]
+ - name: "double"
+ category: "FLOAT"
+ has_precision: true
+ - name: "currency"
+ category: "DECIMAL"
+ has_precision: true
+ - name: "percent"
+ category: "DECIMAL"
+ has_precision: true
+ - name: "date"
+ category: "DATE"
+ - name: "datetime"
+ category: "DATETIME"
+ aliases: ["TIMESTAMP"]
+ - name: "time"
+ category: "TIME"
+ - name: "picklist"
+ category: "ENUM"
+ semantic_fidelity_base: 0.9
+ - name: "multipicklist"
+ category: "ENUM"
+ semantic_fidelity_base: 0.8
+ - name: "reference"
+ category: "STRING"
+ - name: "address"
+ category: "JSON"
+ semantic_fidelity_base: 0.7
+ - name: "location"
+ category: "SPATIAL"
+ semantic_fidelity_base: 0.6
+ - name: "base64"
+ category: "BINARY"
+ semantic_fidelity_base: 0.5
+ - name: "anyType"
+ category: "STRING"
+ semantic_fidelity_base: 0.5
+
+# SOQL is query-only from DBX — DML goes through the REST API, not SQL DDL.
+# All DDL capabilities are disabled.
+ddl_capabilities:
+ add_column: false
+ drop_column: false
+ create_index: false
+ drop_index: false
+ create_table: false
+ drop_table: false
+
+structural_capabilities:
+ max_columns_per_table: 500
+ max_query_size_bytes: 20000
+ supports_json_type: true
+
+# SOQL identifiers are case-insensitive and not quoted.
+# The schema requires a quote_char so we use the conventional '"', but
+# case_sensitive is false to reflect that SOQL ignores identifier casing.
+identifier_rules:
+ quote_char: '"'
+ case_sensitive: false
+ max_length: 40
+
+# No metadata_queries — the Salesforce driver uses REST describe calls,
+# not SQL information_schema queries.
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index b93248c24e..355f58aa59 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -1444,6 +1444,17 @@ async fn test_connection_with_info_inner(
.await
.map(|_| "Connection successful".to_string())
}
+ DatabaseType::Salesforce => {
+ let client = db::salesforce_driver::SfClient::from_config(
+ &url,
+ Some(&config.password),
+ config.external_config.as_ref(),
+ connect_timeout,
+ )?;
+ db::salesforce_driver::SfClient::test_connection(&client, connect_timeout)
+ .await
+ .map(|_| "Connection successful".to_string())
+ }
DatabaseType::Easysearch => {
let mut client = db::easysearch_driver::EasysearchClient::from_config(
&url,
@@ -1922,6 +1933,16 @@ pub async fn connect_db(
db::elasticsearch_driver::test_connection(&mut client, connect_timeout).await?;
PoolKind::Elasticsearch(client)
}
+ DatabaseType::Salesforce => {
+ let client = db::salesforce_driver::SfClient::from_config(
+ &url,
+ Some(&db_config.password),
+ db_config.external_config.as_ref(),
+ connect_timeout,
+ )?;
+ db::salesforce_driver::SfClient::test_connection(&client, connect_timeout).await?;
+ PoolKind::Salesforce(client)
+ }
DatabaseType::Easysearch => {
let mut client = db::easysearch_driver::EasysearchClient::from_config(
&url,
diff --git a/src-tauri/src/commands/mcp_bridge.rs b/src-tauri/src/commands/mcp_bridge.rs
index b7de3655c2..05615a240b 100644
--- a/src-tauri/src/commands/mcp_bridge.rs
+++ b/src-tauri/src/commands/mcp_bridge.rs
@@ -484,6 +484,7 @@ mod tests {
McpDatabasePolicy { database_name: "aa".to_string(), read_only: false, allow_dangerous_sql: true },
McpDatabasePolicy { database_name: "aaa".to_string(), read_only: true, allow_dangerous_sql: false },
],
+ allow_salesforce_dml: false,
}],
..Default::default()
};
@@ -520,6 +521,7 @@ mod tests {
read_only: false,
allow_dangerous_sql: true,
}],
+ allow_salesforce_dml: false,
}],
..Default::default()
})
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index aa9ec5cef9..9243a6e520 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -49,6 +49,7 @@ pub mod query_cancel;
pub mod query_result_export;
pub mod redis_cmd;
pub mod redis_pubsub_server;
+pub mod salesforce_oauth;
pub mod saved_sql;
pub mod schema;
pub mod schema_cache;
diff --git a/src-tauri/src/commands/salesforce_oauth.rs b/src-tauri/src/commands/salesforce_oauth.rs
new file mode 100644
index 0000000000..c17d251c35
--- /dev/null
+++ b/src-tauri/src/commands/salesforce_oauth.rs
@@ -0,0 +1,62 @@
+use std::sync::Arc;
+use tauri::State;
+
+use dbx_core::connection::{AppState, SalesforceCurrentUser};
+use dbx_core::salesforce_oauth::{
+ authorize_with_browser, device_authorization_request, device_poll, password_grant_token, refresh_access_token,
+ SfDeviceAuthorization, SfDevicePoll, SfOauthParams, SfRefreshedToken, SfTokenSet,
+};
+
+#[tauri::command]
+pub async fn salesforce_oauth_browser_authorize(
+ state: State<'_, Arc<AppState>>,
+ params: SfOauthParams,
+) -> Result<SfTokenSet, String> {
+ let opener = state.salesforce_browser_opener().ok_or_else(|| {
+ "Browser OAuth is only available in the desktop app. Use the device code flow instead.".to_string()
+ })?;
+ authorize_with_browser(&params, &opener).await
+}
+
+#[tauri::command]
+pub async fn salesforce_oauth_device_start(params: SfOauthParams) -> Result<SfDeviceAuthorization, String> {
+ device_authorization_request(&params).await
+}
+
+#[tauri::command]
+pub async fn salesforce_oauth_device_poll(
+ params: SfOauthParams,
+ device_code: String,
+ interval_secs: u64,
+) -> Result<SfDevicePoll, String> {
+ device_poll(&params, &device_code, interval_secs).await
+}
+
+#[tauri::command]
+pub async fn salesforce_oauth_refresh(
+ params: SfOauthParams,
+ refresh_token: String,
+) -> Result<SfRefreshedToken, String> {
+ refresh_access_token(&params, &refresh_token).await
+}
+
+/// Username-password (ROPC) login for orgs that permit it. Returns no refresh
+/// token; the saved credentials let the driver re-login when the session dies.
+#[tauri::command]
+pub async fn salesforce_oauth_password_login(
+ params: SfOauthParams,
+ username: String,
+ password: String,
+) -> Result<SfTokenSet, String> {
+ password_grant_token(&params, &username, &password).await
+}
+
+/// Cached connected-user identity for a Salesforce connection. Read-only
+/// metadata call used by the identity badge and admin-detection UI.
+#[tauri::command]
+pub async fn salesforce_current_user(
+ state: State<'_, Arc<AppState>>,
+ connection_id: String,
+) -> Result<SalesforceCurrentUser, String> {
+ state.salesforce_current_user(&connection_id).await
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 81a571c062..1caedaf3c1 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1676,6 +1676,13 @@ pub fn run() {
.open_url(url, None::<&str>)
.map_err(|err| format!("Failed to open the system browser: {err}"))
}));
+ let sf_app_handle = app.handle().clone();
+ state.set_salesforce_browser_opener(Arc::new(move |url| {
+ sf_app_handle
+ .opener()
+ .open_url(url, None::<&str>)
+ .map_err(|err| format!("Failed to open the system browser: {err}"))
+ }));
let state = Arc::new(state);
app.manage(state.clone());
commands::plugins::install_plugin_event_bridge(app.handle(), state.clone());
@@ -1894,6 +1901,12 @@ pub fn run() {
commands::connection::test_connection,
commands::connection::test_connection_with_info,
commands::connection::test_ssh_tunnel,
+ commands::salesforce_oauth::salesforce_oauth_browser_authorize,
+ commands::salesforce_oauth::salesforce_oauth_device_start,
+ commands::salesforce_oauth::salesforce_oauth_device_poll,
+ commands::salesforce_oauth::salesforce_oauth_refresh,
+ commands::salesforce_oauth::salesforce_oauth_password_login,
+ commands::salesforce_oauth::salesforce_current_user,
commands::connection::connect_db,
commands::connection::connection_final_proxy_port,
commands::connection::disconnect_db,