feat(salesforce): add Salesforce SOQL data source

This commit is contained in:
邹超 authored and GitHub committed 2026-09-24 18:25:23 +08:00
1 parent bf3e356540
commit f87b5d1568
125 files changed
+9999 -117

No files matched your search

@@ -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);
@@ -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);
});
});
});
+23 -1
View File
@@ -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`");
+6
View File
@@ -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");
+34
View File
@@ -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 });
}
+32
View File
@@ -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 });
}
@@ -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";
@@ -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"],
@@ -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
@@ -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,
@@ -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"]);
@@ -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";
@@ -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 {
@@ -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" },
@@ -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"]],
@@ -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" },
@@ -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 {
@@ -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 },
@@ -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 {
@@ -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;
@@ -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" },
@@ -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]);
@@ -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);
});
});
+541
View File
@@ -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_.]*$/;
}
+18 -2
View File
@@ -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";
}
@@ -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));
@@ -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);
@@ -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;
}
@@ -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,
@@ -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);