diff --git a/extensions/ggsqlOdbc-copies.vitest.ts b/extensions/ggsqlOdbc-copies.vitest.ts new file mode 100644 index 00000000000..9160c1f9fdd --- /dev/null +++ b/extensions/ggsqlOdbc-copies.vitest.ts @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (C) 2026 Posit Software, PBC. All rights reserved. + * Licensed under the Elastic License 2.0. See LICENSE.txt for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as fs from 'fs'; +import * as path from 'path'; + +/** + * `ggsqlOdbc.ts` exists once per data connection driver that writes a ggsql ODBC line for Workbench + * managed credentials, because each extension compiles under its own tsconfig and cannot import from + * another. The copies have to stay in step: a fix to the line checks in one and not the other would + * let one driver write a line that connects with altered settings. The tests in the Snowflake + * extension's `ggsqlOdbc.vitest.ts` cover both copies. + */ +const COPIES = [ + 'positron-data-driver-snowflake/src/ggsqlOdbc.ts', + 'positron-data-driver-databricks/src/ggsqlOdbc.ts', +] as const; + +// `__dirname` is this file's own directory, so the paths hold wherever Vitest is started from. +function read(relativePath: string): string { + return fs.readFileSync(path.join(__dirname, relativePath), 'utf8'); +} + +describe('ggsqlOdbc copies', () => { + it('keeps the Databricks copy identical to the Snowflake copy', () => { + const [snowflake, databricks] = COPIES; + expect(read(databricks)).toBe(read(snowflake)); + }); +}); diff --git a/extensions/positron-data-driver-databricks/src/databricksDriver.ts b/extensions/positron-data-driver-databricks/src/databricksDriver.ts index 4bb0d81fb57..b01d891c980 100644 --- a/extensions/positron-data-driver-databricks/src/databricksDriver.ts +++ b/extensions/positron-data-driver-databricks/src/databricksDriver.ts @@ -25,6 +25,7 @@ import * as vscode from 'vscode'; import { DatabricksConnection } from './databricksConnection.js'; import { DatabricksAuthType, DatabricksConnectionOptions } from './databricksClient.js'; import { DatabricksDataExplorerRpcHandler } from './databricksDataExplorerRpcHandler.js'; +import { DATABRICKS_ODBC_DRIVER_PATHS, ggsqlOdbcConnectLine, resolveOdbcDriver } from './ggsqlOdbc.js'; import { signInToDatabricks } from './databricksSignIn.js'; import { getManagedCredential, isWorkbenchManaged, resolveManagedCredential } from './workbenchCredentials.js'; @@ -114,6 +115,140 @@ export function parseDatabricksHttpPath(input: string): string { return s.replace(/^\/sql\/warehouses\//, '/sql/1.0/warehouses/'); } +/** A host ggsql can put in `Host=`: a bare hostname, with no user, port, or path. */ +const BARE_HOSTNAME = /^[A-Za-z0-9.-]+$/; + +/** An HTTP path ggsql can put in `HTTPPath=`: an API path with no query. */ +const BARE_HTTP_PATH = /^\/[A-Za-z0-9/_.-]+$/; + +/** + * The HTTP path for a ggsql line, or undefined when there is none or ggsql cannot take it. A query + * is dropped: the Databricks UI shows warehouse URLs with `?o=`, which the ODBC driver + * does not need (the host names the workspace), and ggsql cuts the line at the first `?`. + * + * @param params The mechanism's parameter values. + */ +function ggsqlHttpPath(params: positron.DataConnectionParameterValues): string | undefined { + const httpPath = isNonEmptyString(params.httpPath) ? parseDatabricksHttpPath(params.httpPath).split('?')[0] : ''; + return BARE_HTTP_PATH.test(httpPath) ? httpPath : undefined; +} + +/** + * The ggsql connection code for the Workbench-managed credential. The line goes through ggsql's ODBC + * reader and carries no token: ggsql adds the Workbench token at connect time when `Host=` names + * the workspace Workbench issued it for. So the line stays the same when Workbench rotates the token, + * and the token never shows in the console. + * + * @param locator The workspace host or URL the Workbench credential was issued for. + * @param params The mechanism's parameter values, for the HTTP path and the session settings. + * @param driver The ODBC `Driver=` value (see {@link resolveOdbcDriver}). + */ +export function databricksWorkbenchGgsqlCode( + locator: string, + params: positron.DataConnectionParameterValues, + driver: string +): positron.ConnectionCodeVariant[] { + const host = parseDatabricksHost(locator); + const httpPath = ggsqlHttpPath(params); + if (!BARE_HOSTNAME.test(host) || !httpPath) { + return []; + } + const common = commonFields(params); + const code = ggsqlOdbcConnectLine([ + ['Driver', driver], + ['Host', host], + ['Port', '443'], + ['HTTPPath', httpPath], + ['SSL', '1'], + ['ThriftTransport', '2'], + ['Catalog', common.catalog], + ['Schema', common.schema], + ]); + return code ? [{ id: 'ggsql', label: 'ggsql', code }] : []; +} + +/** + * The first ggsql version that adds the Workbench token to a Databricks ODBC line (posit-dev/ggsql#625). + * ggsql 0.5.2, the latest release when this was written, adds it only for Snowflake. + * The ggsql maintainers expect posit-dev/ggsql#625 to ship in 0.6.0. + * TODO: confirm this matches the ggsql release that ships posit-dev/ggsql#625. + */ +const GGSQL_DATABRICKS_TOKEN_VERSION: readonly [number, number, number] = [0, 6, 0]; + +/** + * Whether a ggsql of the given version adds the Workbench token to a Databricks line. A ggsql that + * does not would get a line that cannot sign in. A version that cannot be read is treated as too old. + * + * With no ggsql runtime (no version), the answer depends on the ggsql extension. With no extension, + * the answer is yes: offering ggsql then leads to Positron's dialog that tells the user to install + * it. With the extension, its runtime is not registered yet (the extension activates after startup, + * and discovery takes time), and its version is not known, so the answer is no until it registers. + * + * @param version The `languageVersion` of the preferred ggsql runtime, or undefined when there is none. + * @param ggsqlExtensionInstalled Whether an enabled extension contributes a ggsql language runtime. + */ +export function ggsqlAddsDatabricksToken(version: string | undefined, ggsqlExtensionInstalled: boolean): boolean { + if (version === undefined) { + return !ggsqlExtensionInstalled; + } + const match = /^(?\d+)\.(?\d+)\.(?\d+)/.exec(version.trim()); + if (!match?.groups) { + return false; + } + const parts = [match.groups.major, match.groups.minor, match.groups.patch].map(Number); + for (let i = 0; i < parts.length; i++) { + if (parts[i] !== GGSQL_DATABRICKS_TOKEN_VERSION[i]) { + return parts[i] > GGSQL_DATABRICKS_TOKEN_VERSION[i]; + } + } + return true; +} + +/** Whether an enabled extension contributes a language runtime for ggsql. */ +function ggsqlExtensionInstalled(): boolean { + return vscode.extensions.all.some(extension => { + const runtimes: unknown = extension.packageJSON?.contributes?.languageRuntimes; + return Array.isArray(runtimes) && runtimes.some(runtime => runtime?.languageId === 'ggsql'); + }); +} + +/** Whether the ggsql that Connect With would run adds the Workbench token to a Databricks line. */ +async function preferredGgsqlAddsDatabricksToken(): Promise { + try { + const runtime = await positron.runtime.getPreferredRuntime('ggsql'); + return ggsqlAddsDatabricksToken(runtime?.languageVersion, ggsqlExtensionInstalled()); + } catch { + return false; + } +} + +/** + * A stand-in for the workspace host when checking whether a connection's settings make a ggsql line. + * The real host comes from the Workbench credential, which is read only when code is generated. + */ +const GGSQL_CHECK_HOST = 'workspace.cloud.databricks.com'; + +/** + * The languages one connection can generate code for, for Connect With. R has no inline form for a + * service principal's credentials, and ggsql works only with the Workbench credential and settings + * that make a line (the same check {@link databricksWorkbenchGgsqlCode} makes). + * + * @param mechanismId The connection's mechanism. + * @param params The connection's parameter values. + */ +export function databricksConnectionLanguageIds(mechanismId: string, params: positron.DataConnectionParameterValues): string[] { + switch (mechanismId) { + case WORKBENCH_MECHANISM_ID: + return databricksWorkbenchGgsqlCode(GGSQL_CHECK_HOST, params, 'Databricks').length > 0 + ? ['python', 'r', 'ggsql'] + : ['python', 'r']; + case OAUTH_M2M_MECHANISM_ID: + return ['python']; + default: + return ['python', 'r']; + } +} + /** * Escapes a value for embedding in a double-quoted Python or R string literal. Both languages treat * backslash as an escape character in double-quoted strings, so values containing backslashes or @@ -474,6 +609,9 @@ export function createDatabricksDriver( ): positron.DataConnectionDriver { // Load the SVG icon once at registration time. const iconPath = path.join(context.extensionPath, 'media', 'logo', 'databricks.svg'); + // The driver is built synchronously during activation and needs its icon before it registers. + // This is one small file bundled with the extension, read once. + // eslint-disable-next-line local/code-no-sync-fs const iconSvg = readFileSync(iconPath, 'utf-8'); // Workbench Managed Credentials: the credential Posit Workbench provisions for this session. Its @@ -563,7 +701,9 @@ export function createDatabricksDriver( name: 'Databricks', description: vscode.l10n.t('Connect to a Databricks workspace'), iconSvg, - supportedLanguageIds: ['python', 'r'], + // ggsql reaches Databricks only through the Workbench credential, so it is offered only when + // Workbench supplies one. That is fixed for the session. + supportedLanguageIds: workbenchMechanism ? ['python', 'r', 'ggsql'] : ['python', 'r'], mechanisms, async connect(mechanismId: string, params: positron.DataConnectionParameterValues): Promise { validateRequired(mechanismId, params); @@ -576,7 +716,18 @@ export function createDatabricksDriver( await connection.connect(); return connection; }, + async getSupportedLanguageIds(mechanismId: string, params: positron.DataConnectionParameterValues): Promise { + const languageIds = databricksConnectionLanguageIds(mechanismId, params); + if (languageIds.includes('ggsql') && !(await preferredGgsqlAddsDatabricksToken())) { + return languageIds.filter(languageId => languageId !== 'ggsql'); + } + return languageIds; + }, async generateConnectionCode(mechanismId: string, languageId: string, params: positron.DataConnectionParameterValues): Promise { + // Every mechanism other than the Workbench credential has no ggsql line. + if (languageId === 'ggsql' && mechanismId !== WORKBENCH_MECHANISM_ID) { + return []; + } if (mechanismId === WORKBENCH_MECHANISM_ID) { // The workspace host has no form field; it is the one Workbench's credential was issued // for. With no credential to read, there is no code to generate. @@ -586,6 +737,13 @@ export function createDatabricksDriver( } catch { return []; } + if (languageId === 'ggsql') { + // An older ggsql would get a line it cannot sign in with. + if (!(await preferredGgsqlAddsDatabricksToken())) { + return []; + } + return databricksWorkbenchGgsqlCode(host, params, await resolveOdbcDriver(DATABRICKS_ODBC_DRIVER_PATHS, 'Databricks')); + } return generateConnectionCode(mechanismId, languageId, { ...params, host }); } return generateConnectionCode(mechanismId, languageId, params); diff --git a/extensions/positron-data-driver-databricks/src/ggsqlOdbc.ts b/extensions/positron-data-driver-databricks/src/ggsqlOdbc.ts new file mode 100644 index 00000000000..14baafaf002 --- /dev/null +++ b/extensions/positron-data-driver-databricks/src/ggsqlOdbc.ts @@ -0,0 +1,85 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (C) 2026 Posit Software, PBC. All rights reserved. + * Licensed under the Elastic License 2.0. See LICENSE.txt for license information. + *--------------------------------------------------------------------------------------------*/ + +// Builds ggsql `-- @connect: odbc://...` lines for connections whose credentials ggsql adds at +// connect time (Posit Workbench managed credentials). The line names the ODBC driver and where to +// connect, never a credential. It has no `vscode` import so Vitest can test it directly. + +import { promises as fs } from 'fs'; + +/** + * Where the Snowflake ODBC driver library is installed on Linux: the Posit Pro Drivers first, then + * Snowflake's own installer. The same paths R's `odbc::snowflake()` looks for. + */ +export const SNOWFLAKE_ODBC_DRIVER_PATHS: readonly string[] = [ + '/opt/rstudio-drivers/snowflake/bin/lib/libsnowflakeodbc_sb64.so', + '/usr/lib/snowflake/odbc/lib/libSnowflake.so', +]; + +/** + * Where a Databricks ODBC driver library is installed on Linux: the Posit Pro Drivers first, then the + * Databricks ODBC Driver (its library file name changed between versions), then the older Simba Spark + * driver. + */ +export const DATABRICKS_ODBC_DRIVER_PATHS: readonly string[] = [ + '/opt/rstudio-drivers/spark/bin/lib/libsparkodbc_sb64.so', + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc64.so', + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc_sb64.so', + '/opt/simba/spark/lib/64/libsparkodbc_sb64.so', +]; + +/** + * Characters that would break a ggsql connect line: ODBC's separators and braces, ggsql's own + * query separator (it splits the URI at the first `?`), and line breaks (ggsql reads only the first + * line). + */ +const LINE_BREAKING_CHARACTERS = /[;{}?\r\n]/; + +/** Whether a file exists, without blocking the extension host. */ +async function fileExists(path: string): Promise { + try { + await fs.access(path); + return true; + } catch { + return false; + } +} + +/** + * The value for an ODBC `Driver=` key: the first of `paths` that exists, or `fallbackName` (a driver + * registered in odbcinst.ini) when none does. A library path works whether or not the driver is + * registered. + * + * @param paths Library paths to try, in order. + * @param fallbackName The registered driver name to use when no path exists. + * @param exists Whether a path exists; the file system by default. + */ +export async function resolveOdbcDriver(paths: readonly string[], fallbackName: string, exists: (path: string) => Promise = fileExists): Promise { + for (const path of paths) { + if (await exists(path)) { + return path; + } + } + return fallbackName; +} + +/** + * A ggsql `-- @connect: odbc://...` line from ODBC attributes, in the given order. Values are + * trimmed, and attributes with no value left are left out: ggsql trims the line it reports back, and + * Positron reuses a ggsql session only when that report matches this line exactly. Returns undefined + * when any value contains a character that would break the line, rather than a line that connects + * with altered settings. + * + * @param attributes ODBC `[key, value]` pairs. + */ +export function ggsqlOdbcConnectLine(attributes: ReadonlyArray): string | undefined { + const present = attributes + .map(([key, value]) => [key, value?.trim()] as const) + .filter((entry): entry is readonly [string, string] => !!entry[1]); + if (present.some(([, value]) => LINE_BREAKING_CHARACTERS.test(value))) { + return undefined; + } + return `-- @connect: odbc://${present.map(([key, value]) => `${key}=${value}`).join(';')}`; +} diff --git a/extensions/positron-data-driver-databricks/src/test/databricksDriver.test.ts b/extensions/positron-data-driver-databricks/src/test/databricksDriver.test.ts index 6ae71374eda..cd4684d59a3 100644 --- a/extensions/positron-data-driver-databricks/src/test/databricksDriver.test.ts +++ b/extensions/positron-data-driver-databricks/src/test/databricksDriver.test.ts @@ -19,7 +19,7 @@ import { DBSQLClient } from '@databricks/sql'; import { createCatalogNode, createSchemaNode } from '../databricksNodes.js'; import { formatFileSize } from '../fileSize.js'; import { databricksDisplayType, parseDescribeRows } from '../databricksSql.js'; -import { generateConnectionCode, parseDatabricksHost, parseDatabricksHttpPath, validateRequired } from '../databricksDriver.js'; +import { databricksConnectionLanguageIds, databricksWorkbenchGgsqlCode, ggsqlAddsDatabricksToken, generateConnectionCode, parseDatabricksHost, parseDatabricksHttpPath, validateRequired } from '../databricksDriver.js'; // Default config for tests -- not used to connect, just to construct. const TEST_CONFIG: DatabricksConnectionConfig = { @@ -1019,6 +1019,82 @@ suite('Databricks Connection Code', () => { }); }); +suite('Databricks ggsql Connection Code', () => { + const odbcDriver = '/opt/rstudio-drivers/spark/bin/lib/libsparkodbc_sb64.so'; + + test('the Workbench line names the Workbench host and carries no token', () => { + assert.deepStrictEqual( + databricksWorkbenchGgsqlCode('https://example.cloud.databricks.com', { httpPath: '/sql/warehouses/abc123', catalog: 'main' }, odbcDriver), + [{ id: 'ggsql', label: 'ggsql', code: `-- @connect: odbc://Driver=${odbcDriver};Host=example.cloud.databricks.com;Port=443;HTTPPath=/sql/1.0/warehouses/abc123;SSL=1;ThriftTransport=2;Catalog=main` }]); + }); + + // The Databricks UI shows warehouse URLs with `?o=`. The ODBC driver does not need + // it (the host names the workspace), and ggsql would cut the line at the `?`. + test('a pasted warehouse URL with a workspace query gives a line without the query', () => { + const [variant] = databricksWorkbenchGgsqlCode('example.cloud.databricks.com', { httpPath: 'https://example.cloud.databricks.com/sql/warehouses/abc?o=123' }, odbcDriver); + assert.strictEqual(variant.code, `-- @connect: odbc://Driver=${odbcDriver};Host=example.cloud.databricks.com;Port=443;HTTPPath=/sql/1.0/warehouses/abc;SSL=1;ThriftTransport=2`); + }); + + test('a host that is not a bare hostname gives no line', () => { + assert.deepStrictEqual(databricksWorkbenchGgsqlCode('token@example.cloud.databricks.com', { httpPath: '/sql/1.0/warehouses/abc' }, odbcDriver), []); + }); + + test('a missing HTTP path gives no line', () => { + assert.deepStrictEqual(databricksWorkbenchGgsqlCode('example.cloud.databricks.com', {}, odbcDriver), []); + }); + + test('ggsql is offered only for a ggsql that adds the Workbench token for Databricks', () => { + assert.deepStrictEqual({ + // No ggsql at all: offering it leads to Positron's ggsql Not Installed dialog. + notInstalled: ggsqlAddsDatabricksToken(undefined, false), + // The extension is installed but its runtime has not registered yet: the version is unknown. + notRegisteredYet: ggsqlAddsDatabricksToken(undefined, true), + released: ggsqlAddsDatabricksToken('0.5.2', true), + older: ggsqlAddsDatabricksToken('0.4.9', true), + nextPatch: ggsqlAddsDatabricksToken('0.5.3', true), + first: ggsqlAddsDatabricksToken('0.6.0', true), + laterPatch: ggsqlAddsDatabricksToken('0.6.1', true), + major: ggsqlAddsDatabricksToken('1.0.0', true), + withSuffix: ggsqlAddsDatabricksToken('0.6.0-dev', true), + unreadable: ggsqlAddsDatabricksToken('unknown', true), + }, { + notInstalled: true, + notRegisteredYet: false, + released: false, + older: false, + nextPatch: false, + first: true, + laterPatch: true, + major: true, + withSuffix: true, + unreadable: false, + }); + }); + + test('Connect With offers only the languages each connection can generate code for', () => { + const warehouse = { httpPath: '/sql/1.0/warehouses/abc' }; + assert.deepStrictEqual({ + workbench: databricksConnectionLanguageIds('workbench-oauth', warehouse), + // A pasted warehouse URL with `?o=` still gets a line, without the query. + workbenchPathWithQuery: databricksConnectionLanguageIds('workbench-oauth', { httpPath: 'https://h/sql/warehouses/abc?o=123' }), + workbenchNoPath: databricksConnectionLanguageIds('workbench-oauth', {}), + // A catalog that would break the line gets no line either. + workbenchBadCatalog: databricksConnectionLanguageIds('workbench-oauth', { ...warehouse, catalog: 'a;b' }), + pat: databricksConnectionLanguageIds('pat', warehouse), + u2m: databricksConnectionLanguageIds('oauth-u2m', warehouse), + m2m: databricksConnectionLanguageIds('oauth-m2m', warehouse), + }, { + workbench: ['python', 'r', 'ggsql'], + workbenchPathWithQuery: ['python', 'r', 'ggsql'], + workbenchNoPath: ['python', 'r'], + workbenchBadCatalog: ['python', 'r'], + pat: ['python', 'r'], + u2m: ['python', 'r'], + m2m: ['python'], + }); + }); +}); + suite('Databricks Lazy SDK Loading', () => { // The SDK is reached through a dynamic import() inside the default factory rather than a // top-level import, so that opening the Data Connections pane does not pay to load it. That diff --git a/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.ts b/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.ts new file mode 100644 index 00000000000..14baafaf002 --- /dev/null +++ b/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.ts @@ -0,0 +1,85 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (C) 2026 Posit Software, PBC. All rights reserved. + * Licensed under the Elastic License 2.0. See LICENSE.txt for license information. + *--------------------------------------------------------------------------------------------*/ + +// Builds ggsql `-- @connect: odbc://...` lines for connections whose credentials ggsql adds at +// connect time (Posit Workbench managed credentials). The line names the ODBC driver and where to +// connect, never a credential. It has no `vscode` import so Vitest can test it directly. + +import { promises as fs } from 'fs'; + +/** + * Where the Snowflake ODBC driver library is installed on Linux: the Posit Pro Drivers first, then + * Snowflake's own installer. The same paths R's `odbc::snowflake()` looks for. + */ +export const SNOWFLAKE_ODBC_DRIVER_PATHS: readonly string[] = [ + '/opt/rstudio-drivers/snowflake/bin/lib/libsnowflakeodbc_sb64.so', + '/usr/lib/snowflake/odbc/lib/libSnowflake.so', +]; + +/** + * Where a Databricks ODBC driver library is installed on Linux: the Posit Pro Drivers first, then the + * Databricks ODBC Driver (its library file name changed between versions), then the older Simba Spark + * driver. + */ +export const DATABRICKS_ODBC_DRIVER_PATHS: readonly string[] = [ + '/opt/rstudio-drivers/spark/bin/lib/libsparkodbc_sb64.so', + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc64.so', + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc_sb64.so', + '/opt/simba/spark/lib/64/libsparkodbc_sb64.so', +]; + +/** + * Characters that would break a ggsql connect line: ODBC's separators and braces, ggsql's own + * query separator (it splits the URI at the first `?`), and line breaks (ggsql reads only the first + * line). + */ +const LINE_BREAKING_CHARACTERS = /[;{}?\r\n]/; + +/** Whether a file exists, without blocking the extension host. */ +async function fileExists(path: string): Promise { + try { + await fs.access(path); + return true; + } catch { + return false; + } +} + +/** + * The value for an ODBC `Driver=` key: the first of `paths` that exists, or `fallbackName` (a driver + * registered in odbcinst.ini) when none does. A library path works whether or not the driver is + * registered. + * + * @param paths Library paths to try, in order. + * @param fallbackName The registered driver name to use when no path exists. + * @param exists Whether a path exists; the file system by default. + */ +export async function resolveOdbcDriver(paths: readonly string[], fallbackName: string, exists: (path: string) => Promise = fileExists): Promise { + for (const path of paths) { + if (await exists(path)) { + return path; + } + } + return fallbackName; +} + +/** + * A ggsql `-- @connect: odbc://...` line from ODBC attributes, in the given order. Values are + * trimmed, and attributes with no value left are left out: ggsql trims the line it reports back, and + * Positron reuses a ggsql session only when that report matches this line exactly. Returns undefined + * when any value contains a character that would break the line, rather than a line that connects + * with altered settings. + * + * @param attributes ODBC `[key, value]` pairs. + */ +export function ggsqlOdbcConnectLine(attributes: ReadonlyArray): string | undefined { + const present = attributes + .map(([key, value]) => [key, value?.trim()] as const) + .filter((entry): entry is readonly [string, string] => !!entry[1]); + if (present.some(([, value]) => LINE_BREAKING_CHARACTERS.test(value))) { + return undefined; + } + return `-- @connect: odbc://${present.map(([key, value]) => `${key}=${value}`).join(';')}`; +} diff --git a/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.vitest.ts b/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.vitest.ts new file mode 100644 index 00000000000..0b708b941e4 --- /dev/null +++ b/extensions/positron-data-driver-snowflake/src/ggsqlOdbc.vitest.ts @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (C) 2026 Posit Software, PBC. All rights reserved. + * Licensed under the Elastic License 2.0. See LICENSE.txt for license information. + *--------------------------------------------------------------------------------------------*/ + +/// + +import { DATABRICKS_ODBC_DRIVER_PATHS, ggsqlOdbcConnectLine, resolveOdbcDriver, SNOWFLAKE_ODBC_DRIVER_PATHS } from './ggsqlOdbc'; + +describe('resolveOdbcDriver', () => { + // Databricks' own driver replaced the Simba Spark one. Its library file name changed between + // versions, so a machine with either one installed must still get a path. + it('finds the current Databricks ODBC Driver as well as the Simba Spark one', async () => { + const found = async (installed: string) => + resolveOdbcDriver(DATABRICKS_ODBC_DRIVER_PATHS, 'Databricks', async p => p === installed); + expect([ + await found('/opt/databricks/databricksodbc/lib/64/libdatabricksodbc64.so'), + await found('/opt/databricks/databricksodbc/lib/64/libdatabricksodbc_sb64.so'), + await found('/opt/simba/spark/lib/64/libsparkodbc_sb64.so'), + ]).toEqual([ + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc64.so', + '/opt/databricks/databricksodbc/lib/64/libdatabricksodbc_sb64.so', + '/opt/simba/spark/lib/64/libsparkodbc_sb64.so', + ]); + }); + + it('prefers the first library path that exists', async () => { + const exists = async (p: string) => p === SNOWFLAKE_ODBC_DRIVER_PATHS[1]; + expect(await resolveOdbcDriver(SNOWFLAKE_ODBC_DRIVER_PATHS, 'Snowflake', exists)).toBe(SNOWFLAKE_ODBC_DRIVER_PATHS[1]); + }); + + it('prefers the Pro Drivers path when both libraries exist', async () => { + expect(await resolveOdbcDriver(SNOWFLAKE_ODBC_DRIVER_PATHS, 'Snowflake', async () => true)).toBe(SNOWFLAKE_ODBC_DRIVER_PATHS[0]); + }); + + it('falls back to the name when no path exists', async () => { + expect(await resolveOdbcDriver(SNOWFLAKE_ODBC_DRIVER_PATHS, 'Snowflake', async () => false)).toBe('Snowflake'); + }); +}); + +describe('ggsqlOdbcConnectLine', () => { + it('joins attributes in order and skips empty ones', () => { + expect(ggsqlOdbcConnectLine([['Driver', 'Snowflake'], ['Server', 'a.snowflakecomputing.com'], ['Warehouse', undefined], ['Role', ''], ['Database', 'DB 1']])) + .toBe('-- @connect: odbc://Driver=Snowflake;Server=a.snowflakecomputing.com;Database=DB 1'); + }); + + it('trims values and leaves out ones that are only whitespace', () => { + expect(ggsqlOdbcConnectLine([['Driver', 'Snowflake'], ['Warehouse', ' '], ['Role', ' ANALYST ']])) + .toBe('-- @connect: odbc://Driver=Snowflake;Role=ANALYST'); + }); + + it('rejects values that would break the line', () => { + for (const bad of ['a;b', 'a{b', 'a}b', 'a?reader=odbc', 'a\nb', 'a\rb']) { + expect(ggsqlOdbcConnectLine([['Driver', 'Snowflake'], ['Warehouse', bad]]), JSON.stringify(bad)).toBeUndefined(); + } + }); +}); diff --git a/extensions/positron-data-driver-snowflake/src/snowflakeDriver.ts b/extensions/positron-data-driver-snowflake/src/snowflakeDriver.ts index 89f5dc190da..6453bcb61a0 100644 --- a/extensions/positron-data-driver-snowflake/src/snowflakeDriver.ts +++ b/extensions/positron-data-driver-snowflake/src/snowflakeDriver.ts @@ -28,7 +28,8 @@ import { SnowflakeConnection } from './snowflakeConnection.js'; import { SnowflakeConnectionOptions } from './snowflakeClient.js'; import { displayPath, SnowflakeConnectionsFileEntry, readConnectionsFile } from './snowflakeConnectionsFile.js'; import { SnowflakeDataExplorerRpcHandler } from './snowflakeDataExplorerRpcHandler.js'; -import { isWorkbenchManaged, resolveManagedCredential } from './workbenchCredentials.js'; +import { ggsqlOdbcConnectLine, resolveOdbcDriver, SNOWFLAKE_ODBC_DRIVER_PATHS } from './ggsqlOdbc.js'; +import { getManagedCredential, isWorkbenchManaged, ManagedCredential, resolveManagedCredential } from './workbenchCredentials.js'; /** The id of the mechanism that uses the credentials Posit Workbench provisions for the session. */ const WORKBENCH_MECHANISM_ID = 'workbench-oauth'; @@ -337,6 +338,145 @@ function workbenchConnectionName(): string { return process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME?.trim() || 'workbench'; } +/** + * The connections.toml entry ggsql reads the Workbench token from. ggsql always reads this entry, so + * the connector's `SNOWFLAKE_DEFAULT_CONNECTION_NAME` does not change it. + */ +const GGSQL_WORKBENCH_ENTRY = 'workbench'; + +/** The session settings a ggsql line carries. */ +const GGSQL_SESSION_SETTINGS = ['warehouse', 'database', 'schema', 'role'] as const; + +/** + * Whether a mechanism's connection uses the Workbench-managed credential, and so gets a ggsql line: + * the Workbench mechanism, and the `workbench` entry of connections.toml (which carries the same + * credential) while Workbench manages this session's credentials. + * + * @param mechanismId The connection's mechanism. + * @param params The mechanism's parameter values. + * @param workbenchManaged Whether Workbench supplies the Snowflake credential in this session. + */ +export function isWorkbenchGgsqlTarget( + mechanismId: string, + params: positron.DataConnectionParameterValues, + workbenchManaged: boolean +): boolean { + if (mechanismId === WORKBENCH_MECHANISM_ID) { + return true; + } + return mechanismId === CONNECTIONS_FILE_MECHANISM_ID && workbenchManaged && params.connectionName === GGSQL_WORKBENCH_ENTRY; +} + +/** + * A stand-in for the Workbench account when checking whether a connection's settings make a ggsql + * line. The real account comes from the Workbench credential, which is read only when code is + * generated. + */ +const GGSQL_CHECK_CREDENTIAL = { locator: 'account' }; + +/** + * The languages one connection can generate code for, for Connect With. A connections.toml entry has + * Python code only, and ggsql works only with the Workbench credential and settings that make a line + * (the same check {@link snowflakeWorkbenchGgsqlCode} makes). + * + * @param mechanismId The connection's mechanism. + * @param params The mechanism's parameter values. + * @param workbenchManaged Whether Workbench supplies the Snowflake credential in this session. + * @param fileConnections The named connections now in connections.toml. + */ +export function snowflakeConnectionLanguageIds( + mechanismId: string, + params: positron.DataConnectionParameterValues, + workbenchManaged: boolean, + fileConnections: Record +): string[] { + const languageIds = mechanismId === CONNECTIONS_FILE_MECHANISM_ID ? ['python'] : ['python', 'r']; + if (isWorkbenchGgsqlTarget(mechanismId, params, workbenchManaged) + && snowflakeWorkbenchGgsqlCode(GGSQL_CHECK_CREDENTIAL, workbenchGgsqlSessionParams(mechanismId, params, fileConnections), 'Snowflake').length > 0) { + languageIds.push('ggsql'); + } + return languageIds; +} + +/** + * The session settings for a Workbench ggsql line. A connections.toml entry carries only its name in + * the parameters, so its warehouse, database, schema, and role come from the entry itself. + * + * @param mechanismId The connection's mechanism. + * @param params The mechanism's parameter values. + * @param fileConnections The named connections now in connections.toml. + */ +export function workbenchGgsqlSessionParams( + mechanismId: string, + params: positron.DataConnectionParameterValues, + fileConnections: Record +): positron.DataConnectionParameterValues { + if (mechanismId !== CONNECTIONS_FILE_MECHANISM_ID) { + return params; + } + const entry = typeof params.connectionName === 'string' ? fileConnections[params.connectionName] : undefined; + const settings: positron.DataConnectionParameterValues = {}; + for (const key of GGSQL_SESSION_SETTINGS) { + const value = entry?.[key]; + if (typeof value === 'string') { + settings[key] = value; + } + } + return settings; +} + +/** An account ggsql can put in `Server=`: a bare account identifier, not a URL or a hostname. */ +const BARE_ACCOUNT = /^[A-Za-z0-9_.-]+$/; + +/** + * The hostname of the Workbench account for a ggsql line, or undefined when the account is not a + * bare identifier. ggsql adds the token only when `Server=` is the account as Workbench wrote it + * plus the Snowflake domain, so an account in another form (a URL, or a full hostname) has no line + * that both gets the token and names a real server. Underscores become hyphens: Snowflake serves + * the account at both hostnames, ggsql accepts both, and a hostname with an underscore can fail + * TLS host checks. + * + * @param account The account as Workbench wrote it. + */ +function ggsqlAccountServer(account: string): string | undefined { + const bare = account.trim(); + if (!BARE_ACCOUNT.test(bare) || bare.toLowerCase().includes('.snowflakecomputing.')) { + return undefined; + } + return `${bare.replace(/_/g, '-')}.snowflakecomputing.com`; +} + +/** + * The ggsql connection code for the Workbench-managed credential. The line goes through ggsql's ODBC + * reader and carries no token: ggsql adds the Workbench token at connect time when `Server=` names + * the Workbench account. So the line stays the same when Workbench rotates the token, and the token + * never shows in the console. + * + * @param credential The account (as Workbench wrote it) and the host Workbench names, if any. + * @param params The mechanism's parameter values, for the optional session settings. + * @param driver The ODBC `Driver=` value (see {@link resolveOdbcDriver}). + */ +export function snowflakeWorkbenchGgsqlCode( + credential: Pick, + params: positron.DataConnectionParameterValues, + driver: string +): positron.ConnectionCodeVariant[] { + const common = commonFields(params); + const server = credential.host?.trim() || ggsqlAccountServer(credential.locator); + if (!server) { + return []; + } + const code = ggsqlOdbcConnectLine([ + ['Driver', driver], + ['Server', server], + ['Warehouse', common.warehouse], + ['Database', common.database], + ['Schema', common.schema], + ['Role', common.role], + ]); + return code ? [{ id: 'ggsql', label: 'ggsql', code }] : []; +} + /** * Generates connection code for the Workbench-managed mechanism. Neither snippet embeds a credential: * snowflake-connector-python reads the Workbench-provisioned connections.toml via `connection_name`, @@ -645,6 +785,9 @@ export function createSnowflakeDriver( ): SnowflakeDriver { // Load the SVG icon once at registration time. const iconPath = path.join(context.extensionPath, 'media', 'logo', 'snowflake.svg'); + // The driver is built synchronously during activation and needs its icon before it registers. + // This is one small file bundled with the extension, read once. + // eslint-disable-next-line local/code-no-sync-fs const iconSvg = readFileSync(iconPath, 'utf-8'); // Workbench Managed Credentials: the token Posit Workbench provisions for this session. Nothing to @@ -814,7 +957,9 @@ export function createSnowflakeDriver( name: 'Snowflake', description: vscode.l10n.t('Connect to a Snowflake account'), iconSvg, - supportedLanguageIds: ['python', 'r'], + // ggsql reaches Snowflake only through the Workbench credential, so it is offered only when + // Workbench supplies one. That is fixed for the session. + supportedLanguageIds: isWorkbenchManaged(SNOWFLAKE_MANAGED_ENV_VAR) ? ['python', 'r', 'ggsql'] : ['python', 'r'], mechanisms: buildMechanisms(fileConnections), onDidChange: onDidChange.event, setFileConnections(connections: Record) { @@ -834,7 +979,24 @@ export function createSnowflakeDriver( await connection.connect(); return connection; }, + async getSupportedLanguageIds(mechanismId: string, params: positron.DataConnectionParameterValues): Promise { + return snowflakeConnectionLanguageIds(mechanismId, params, isWorkbenchManaged(SNOWFLAKE_MANAGED_ENV_VAR), fileConnections); + }, async generateConnectionCode(mechanismId: string, languageId: string, params: positron.DataConnectionParameterValues): Promise { + if (languageId === 'ggsql') { + // Every mechanism other than the Workbench credential has no ggsql line. + if (!isWorkbenchGgsqlTarget(mechanismId, params, isWorkbenchManaged(SNOWFLAKE_MANAGED_ENV_VAR))) { + return []; + } + let credential: ManagedCredential; + try { + credential = await getManagedCredential(SNOWFLAKE_AUTH_PROVIDER_ID, 'Snowflake'); + } catch { + return []; + } + const sessionParams = workbenchGgsqlSessionParams(mechanismId, params, fileConnections); + return snowflakeWorkbenchGgsqlCode(credential, sessionParams, await resolveOdbcDriver(SNOWFLAKE_ODBC_DRIVER_PATHS, 'Snowflake')); + } if (mechanismId === WORKBENCH_MECHANISM_ID) { return generateWorkbenchCode(languageId, params); } diff --git a/extensions/positron-data-driver-snowflake/src/test/snowflakeDriver.test.ts b/extensions/positron-data-driver-snowflake/src/test/snowflakeDriver.test.ts index 8e0ce67c817..44020fe7166 100644 --- a/extensions/positron-data-driver-snowflake/src/test/snowflakeDriver.test.ts +++ b/extensions/positron-data-driver-snowflake/src/test/snowflakeDriver.test.ts @@ -13,7 +13,7 @@ import * as vscode from 'vscode'; import { dataExplorerQueryClient, SnowflakeConnection, SnowflakeConnectionConfig } from '../snowflakeConnection.js'; import { defaultConnectionFactory, isStatementError, SnowflakeConnectionFactory, SnowflakeClient, SnowflakeConnectionOptions, SnowflakeQueryOptions } from '../snowflakeClient.js'; import { createDatabaseNode, createSchemaNode, parseSemanticViewDescription, stageFilePath } from '../snowflakeNodes.js'; -import { connectionOptionsFromToml, connectionsFileOptions, parseSnowflakeAccount } from '../snowflakeDriver.js'; +import { connectionOptionsFromToml, connectionsFileOptions, isWorkbenchGgsqlTarget, parseSnowflakeAccount, snowflakeConnectionLanguageIds, snowflakeWorkbenchGgsqlCode, workbenchGgsqlSessionParams } from '../snowflakeDriver.js'; import { isWorkbenchManaged } from '../workbenchCredentials.js'; // Default config for tests -- not used to connect, just to construct. @@ -1402,6 +1402,118 @@ suite('Snowflake Account Parsing', () => { }); }); +suite('Snowflake ggsql Connection Code', () => { + const driver = '/opt/rstudio-drivers/snowflake/bin/lib/libsnowflakeodbc_sb64.so'; + + test('the Workbench line names the account server and carries no token', () => { + assert.deepStrictEqual( + snowflakeWorkbenchGgsqlCode({ locator: ' myorg-acct ' }, { warehouse: 'WH', role: 'ANALYST' }, driver), + [{ id: 'ggsql', label: 'ggsql', code: `-- @connect: odbc://Driver=${driver};Server=myorg-acct.snowflakecomputing.com;Warehouse=WH;Role=ANALYST` }]); + }); + + test('the Workbench line connects through the host Workbench names', () => { + const [variant] = snowflakeWorkbenchGgsqlCode({ locator: 'a', host: 'a.internal.snowflakecomputing.com' }, {}, driver); + assert.strictEqual(variant.code, `-- @connect: odbc://Driver=${driver};Server=a.internal.snowflakecomputing.com`); + }); + + // ggsql adds the token only when Server= is the account as Workbench wrote it plus the Snowflake + // domain. An account in another form would give a line that names no real server. + test('an account that is not a bare identifier gives no line', () => { + const lines = ['https://myorg-acct.snowflakecomputing.com', 'myorg-acct.snowflakecomputing.com', 'myorg/acct', ''] + .map(locator => snowflakeWorkbenchGgsqlCode({ locator }, {}, driver)); + assert.deepStrictEqual(lines, [[], [], [], []]); + }); + + // Snowflake serves an account with an underscore at the hostname with a hyphen too, and only + // that hostname passes TLS host checks everywhere. ggsql gives the token to both. + test('the Workbench line names an underscore account by its hyphen hostname', () => { + const [variant] = snowflakeWorkbenchGgsqlCode({ locator: 'myorg-my_acct' }, {}, driver); + assert.strictEqual(variant.code, `-- @connect: odbc://Driver=${driver};Server=myorg-my-acct.snowflakecomputing.com`); + }); + + test('a value that would break the line gives no line', () => { + assert.deepStrictEqual(snowflakeWorkbenchGgsqlCode({ locator: 'a' }, { warehouse: 'x;Token=y' }, driver), []); + }); + + test('only the Workbench mechanism and the Workbench entry of connections.toml get a line', () => { + // ggsql reads the token from the `workbench` entry, whatever the connector's default + // connection is. So the connector default must not move the line to another entry. + const previous = process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME; + process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME = 'dev'; + const target = (mechanismId: string, connectionName: string | undefined, managed: boolean) => + isWorkbenchGgsqlTarget(mechanismId, { connectionName }, managed); + const result = { + workbenchMechanism: target('workbench-oauth', undefined, true), + workbenchEntry: target('connections-file', 'workbench', true), + workbenchEntryOffWorkbench: target('connections-file', 'workbench', false), + otherEntry: target('connections-file', 'dev', true), + pat: target('pat', undefined, true), + keypair: target('keypair', undefined, true), + externalBrowser: target('externalbrowser', undefined, true), + }; + if (previous === undefined) { + delete process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME; + } else { + process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME = previous; + } + assert.deepStrictEqual(result, { + workbenchMechanism: true, + workbenchEntry: true, + workbenchEntryOffWorkbench: false, + otherEntry: false, + pat: false, + keypair: false, + externalBrowser: false, + }); + }); + + test('Connect With offers only the languages each connection can generate code for', () => { + const fileConnections = { workbench: { account: 'a', warehouse: 'WH' } }; + const languages = (mechanismId: string, connectionName: string | undefined, managed: boolean, params: positron.DataConnectionParameterValues = {}, files: typeof fileConnections = fileConnections) => + snowflakeConnectionLanguageIds(mechanismId, { ...params, ...(connectionName ? { connectionName } : {}) }, managed, files); + assert.deepStrictEqual({ + // A setting that would break the line gets no line, so no menu item: for the mechanism's + // own parameters, and for an entry's settings in connections.toml. + workbenchMechanismBadRole: languages('workbench-oauth', undefined, true, { role: 'x;Token=y' }), + workbenchEntryBadWarehouse: languages('connections-file', 'workbench', true, {}, { workbench: { account: 'a', warehouse: 'a;b' } }), + workbenchMechanism: languages('workbench-oauth', undefined, true), + workbenchMechanismOffWorkbench: languages('workbench-oauth', undefined, false), + workbenchEntry: languages('connections-file', 'workbench', true), + otherEntry: languages('connections-file', 'dev', true), + workbenchEntryOffWorkbench: languages('connections-file', 'workbench', false), + pat: languages('pat', undefined, true), + keypairOffWorkbench: languages('keypair', undefined, false), + }, { + workbenchMechanismBadRole: ['python', 'r'], + workbenchEntryBadWarehouse: ['python'], + workbenchMechanism: ['python', 'r', 'ggsql'], + // Matches generateConnectionCode. Off Workbench the driver does not declare ggsql, so + // Positron leaves it out anyway. + workbenchMechanismOffWorkbench: ['python', 'r', 'ggsql'], + workbenchEntry: ['python', 'ggsql'], + otherEntry: ['python'], + workbenchEntryOffWorkbench: ['python'], + pat: ['python', 'r'], + keypairOffWorkbench: ['python', 'r'], + }); + }); + + test('the Workbench entry takes its session settings from connections.toml', () => { + const fileConnections = { + workbench: { account: 'a', token: 'secret', authenticator: 'oauth', warehouse: 'WH', database: 'DB', schema: 'S', role: 'R', port: 443 }, + }; + assert.deepStrictEqual({ + entry: workbenchGgsqlSessionParams('connections-file', { connectionName: 'workbench' }, fileConnections), + missingEntry: workbenchGgsqlSessionParams('connections-file', { connectionName: 'gone' }, fileConnections), + mechanism: workbenchGgsqlSessionParams('workbench-oauth', { warehouse: 'W2' }, fileConnections), + }, { + entry: { warehouse: 'WH', database: 'DB', schema: 'S', role: 'R' }, + missingEntry: {}, + mechanism: { warehouse: 'W2' }, + }); + }); +}); + suite('Workbench Managed Credentials Detection', () => { // The helper is shared verbatim with the Databricks driver (a vitest guard keeps the copies // identical), so these cases cover both. diff --git a/src/positron-dts/positron.d.ts b/src/positron-dts/positron.d.ts index b125ab57ff4..1bf11a7dbdd 100644 --- a/src/positron-dts/positron.d.ts +++ b/src/positron-dts/positron.d.ts @@ -2588,6 +2588,22 @@ declare module 'positron' { */ generateConnectionCode?(mechanismId: string, languageId: string, parameters: DataConnectionParameterValues): Thenable; + /** + * The languages one connection can generate code for, when that is fewer than the driver's + * `supportedLanguageIds` (for example, a language that works with only one of the driver's + * mechanisms). Positron offers Connect With only for these languages. Languages that are not + * in `supportedLanguageIds` are ignored. When not implemented, every one of the driver's + * `supportedLanguageIds` is offered. + * + * Positron calls this each time the user opens a connection's menu, so it must be fast. It + * gets the saved parameter values without the secret ones. + * + * @param mechanismId The id of the mechanism the connection uses. One of this driver's + * `mechanisms`. + * @param parameters The connection's parameter values, without the secret ones. + */ + getSupportedLanguageIds?(mechanismId: string, parameters: DataConnectionParameterValues): Thenable; + /** * Produces a display-safe, redacted form of a stored secret parameter value, shown in the * configuration dialog when editing an existing connection (for example, masking the password diff --git a/src/vs/workbench/api/browser/positron/mainThreadDataConnections.ts b/src/vs/workbench/api/browser/positron/mainThreadDataConnections.ts index 0a2d4d3d04c..66b8fe06adc 100644 --- a/src/vs/workbench/api/browser/positron/mainThreadDataConnections.ts +++ b/src/vs/workbench/api/browser/positron/mainThreadDataConnections.ts @@ -3,6 +3,7 @@ * Licensed under the Elastic License 2.0. See LICENSE.txt for license information. *--------------------------------------------------------------------------------------------*/ +import { raceTimeout } from '../../../../base/common/async.js'; import { CancellationToken } from '../../../../base/common/cancellation.js'; import { DisposableStore } from '../../../../base/common/lifecycle.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; @@ -17,6 +18,12 @@ import { IDataConnectionDriverMetadataDTO, IDataConnectionDriverSummaryDTO, IDat import { isRuntimeDataConnectionDriverId } from '../../../services/positronConnections/common/runtimeDataConnections.js'; import { ExtHostDataConnectionsShape, ExtHostPositronContext, MainPositronContext, MainThreadDataConnectionsShape } from '../../common/positron/extHost.positron.protocol.js'; +/** + * How long a connection menu waits for a driver to name the languages one connection supports before + * it offers every language the driver declares. + */ +const SUPPORTED_LANGUAGES_TIMEOUT_MS = 500; + /** * Narrows a wire-format IDataConnectionParameterDTO to the service-level * IDataConnectionParameter discriminated union, picking up only the fields each variant carries. @@ -96,6 +103,7 @@ function dtoToServiceMetadata(dto: IDataConnectionDriverMetadataDTO): IDataConne mechanisms: dto.mechanisms.map(dtoToServiceMechanism), supportedLanguageIds: dto.supportedLanguageIds, validatesParameters: dto.validatesParameters, + narrowsLanguageIds: dto.narrowsLanguageIds, }; } @@ -395,6 +403,12 @@ export class MainThreadDataConnections implements MainThreadDataConnectionsShape * wrapping calls back through the RPC proxy to the extension host. */ class MainThreadDataConnectionDriverAdapter implements IDataConnectionDriver { + /** + * The driver's last answer to getSupportedLanguageIds for each connection (keyed by mechanism and + * parameter values), used when the driver is slow or fails. + */ + private readonly _lastSupportedLanguageIds = new Map(); + /** * Constructor. * @param id The unique driver identifier. @@ -433,6 +447,33 @@ class MainThreadDataConnectionDriverAdapter implements IDataConnectionDriver { return variants.map(variant => ({ id: variant.id, label: variant.label, code: variant.code })); } + /** + * Asks the ext host to run driver.getSupportedLanguageIds() via RPC. Resolves to every supported + * language, without the round trip, when the driver does not narrow them. When the driver fails + * or takes longer than {@link SUPPORTED_LANGUAGES_TIMEOUT_MS}, resolves to the driver's last + * answer for the same connection, or to every supported language when there is none: a + * connection menu waits for this, and offering a language that then reports no code is better + * than no menu. An answer that arrives after the timeout is still kept for next time. + * @param mechanismId The id of the mechanism the connection uses. + * @param params The connection's parameter values, without the secret ones. + */ + async getSupportedLanguageIds(mechanismId: string, params: DataConnectionParameterValues): Promise { + if (this.metadata.narrowsLanguageIds !== true) { + return [...this.metadata.supportedLanguageIds]; + } + const key = JSON.stringify([mechanismId, params]); + const fallback = () => [...(this._lastSupportedLanguageIds.get(key) ?? this.metadata.supportedLanguageIds)]; + try { + const request = this._proxy.$getSupportedLanguageIds(this.id, mechanismId, params).then(languageIds => { + this._lastSupportedLanguageIds.set(key, languageIds); + return languageIds; + }); + return (await raceTimeout(request, SUPPORTED_LANGUAGES_TIMEOUT_MS)) ?? fallback(); + } catch { + return fallback(); + } + } + /** * Asks the ext host to run driver.redactParameterValue() via RPC, returning a display-safe form of * the stored secret value. Resolves to undefined when the driver does not implement redaction. diff --git a/src/vs/workbench/api/common/positron/extHost.positron.protocol.ts b/src/vs/workbench/api/common/positron/extHost.positron.protocol.ts index 5cca8dcf615..5419a640271 100644 --- a/src/vs/workbench/api/common/positron/extHost.positron.protocol.ts +++ b/src/vs/workbench/api/common/positron/extHost.positron.protocol.ts @@ -422,6 +422,7 @@ export interface ExtHostDataConnectionsShape { $onDidChangeSessionConnectionCode(sessionId: string, code: string | undefined): void; $driverConnect(driverId: string, mechanismId: string, params: DataConnectionParameterValuesDTO): Promise; $generateConnectionCode(driverId: string, mechanismId: string, languageId: string, params: DataConnectionParameterValuesDTO): Promise; + $getSupportedLanguageIds(driverId: string, mechanismId: string, params: DataConnectionParameterValuesDTO): Promise; $redactParameterValue(driverId: string, mechanismId: string, parameterId: string, value: string): Promise; $validateParameters(driverId: string, mechanismId: string, params: DataConnectionParameterValuesDTO): Promise; $discoverConnections(driverId: string): Promise; diff --git a/src/vs/workbench/api/common/positron/extHostDataConnections.ts b/src/vs/workbench/api/common/positron/extHostDataConnections.ts index e65a7ef8fbb..899a20b805f 100644 --- a/src/vs/workbench/api/common/positron/extHostDataConnections.ts +++ b/src/vs/workbench/api/common/positron/extHostDataConnections.ts @@ -395,6 +395,27 @@ export class ExtHostDataConnections implements extHostProtocol.ExtHostDataConnec return variants.map(variant => ({ id: variant.id, label: variant.label, code: variant.code })); } + /** + * Calls the extension's driver.getSupportedLanguageIds() for the languages one connection can + * generate code for. Keeps only the driver's supported languages, in the driver's order. Returns + * every supported language when the driver does not narrow them, and none when it is gone. + * @param driverId The unique identifier of the driver. + * @param mechanismId The id of the mechanism the connection uses. + * @param params The connection's parameter values, without the secret ones. + */ + async $getSupportedLanguageIds(driverId: string, mechanismId: string, params: Record): Promise { + const driver = this._drivers.get(driverId); + if (!driver) { + return []; + } + if (!driver.getSupportedLanguageIds) { + return [...driver.supportedLanguageIds]; + } + + const languageIds = new Set(await driver.getSupportedLanguageIds(mechanismId, params)); + return driver.supportedLanguageIds.filter(languageId => languageIds.has(languageId)); + } + /** * Calls the extension's driver.redactParameterValue() to produce a display-safe form of a stored * secret value. The cleartext value stays in the ext host; only the redacted result is returned to @@ -622,6 +643,7 @@ export class ExtHostDataConnections implements extHostProtocol.ExtHostDataConnec })), supportedLanguageIds: driver.supportedLanguageIds, validatesParameters: typeof driver.validateParameters === 'function', + narrowsLanguageIds: typeof driver.getSupportedLanguageIds === 'function', }; } diff --git a/src/vs/workbench/api/test/browser/positron/mainThreadDataConnections.vitest.ts b/src/vs/workbench/api/test/browser/positron/mainThreadDataConnections.vitest.ts index c854b327ac8..6e1a85ed5bf 100644 --- a/src/vs/workbench/api/test/browser/positron/mainThreadDataConnections.vitest.ts +++ b/src/vs/workbench/api/test/browser/positron/mainThreadDataConnections.vitest.ts @@ -57,6 +57,9 @@ describe('MainThreadDataConnections', () => { // The ext host end of $validateParameters, so a test can see whether the round trip was made. const $validateParameters = vi.fn(async () => ({ normalizedValues: { databasePath: '/ws/db.duckdb' } })); + // The ext host end of $getSupportedLanguageIds, so a test can see whether the round trip was made. + const $getSupportedLanguageIds = vi.fn(async () => ['python']); + // The ext host end of the session connection code notification. const $onDidChangeSessionConnectionCode = vi.fn<(sessionId: string, code: string | undefined) => void>(); @@ -127,6 +130,7 @@ describe('MainThreadDataConnections', () => { $discoverConnections, $onDidChangeDataConnections, $validateParameters, + $getSupportedLanguageIds, $onDidChangeSessionConnectionCode, }) as T) as IExtHostContext['getProxy'], }); @@ -191,6 +195,63 @@ describe('MainThreadDataConnections', () => { }); }); + it('asks the ext host for a connection\'s languages only for a driver that narrows them', async () => { + mainThread.$registerDataConnectionDriver('duckdb', metadataDto); + mainThread.$registerDataConnectionDriver('narrowing', { ...metadataDto, id: 'narrowing', narrowsLanguageIds: true }); + const [plain, narrowing] = registeredDrivers; + + const results = [ + await plain.getSupportedLanguageIds('file', { databasePath: 'db.duckdb' }), + await narrowing.getSupportedLanguageIds('file', { databasePath: 'db.duckdb' }), + ]; + + expect({ results, calls: $getSupportedLanguageIds.mock.calls }).toEqual({ + results: [['python', 'r'], ['python']], + calls: [['narrowing', 'file', { databasePath: 'db.duckdb' }]], + }); + }); + + it('falls back to every supported language when the driver fails to narrow them', async () => { + $getSupportedLanguageIds.mockRejectedValueOnce(new Error('driver threw')); + mainThread.$registerDataConnectionDriver('narrowing', { ...metadataDto, id: 'narrowing', narrowsLanguageIds: true }); + const [narrowing] = registeredDrivers; + + expect(await narrowing.getSupportedLanguageIds('file', {})).toEqual(['python', 'r']); + }); + + it('stops waiting for a driver that does not answer, and offers every supported language', async () => { + vi.useFakeTimers(); + try { + $getSupportedLanguageIds.mockReturnValueOnce(new Promise(() => { })); + mainThread.$registerDataConnectionDriver('narrowing', { ...metadataDto, id: 'narrowing', narrowsLanguageIds: true }); + const [narrowing] = registeredDrivers; + + const languageIds = narrowing.getSupportedLanguageIds('file', {}); + await vi.advanceTimersByTimeAsync(1000); + + expect(await languageIds).toEqual(['python', 'r']); + } finally { + vi.useRealTimers(); + } + }); + + it('uses the connection\'s last answer when the driver is slow, not every supported language', async () => { + vi.useFakeTimers(); + try { + mainThread.$registerDataConnectionDriver('narrowing', { ...metadataDto, id: 'narrowing', narrowsLanguageIds: true }); + const [narrowing] = registeredDrivers; + const first = await narrowing.getSupportedLanguageIds('file', { databasePath: 'a' }); + + $getSupportedLanguageIds.mockReturnValueOnce(new Promise(() => { })); + const languageIds = narrowing.getSupportedLanguageIds('file', { databasePath: 'a' }); + await vi.advanceTimersByTimeAsync(1000); + + expect({ first, slow: await languageIds }).toEqual({ first: ['python'], slow: ['python'] }); + } finally { + vi.useRealTimers(); + } + }); + it('round-trips driver mechanisms back to the wire shape in driver summaries', async () => { mainThread.$registerDataConnectionDriver('duckdb', metadataDto); diff --git a/src/vs/workbench/api/test/common/positron/extHostDataConnections.vitest.ts b/src/vs/workbench/api/test/common/positron/extHostDataConnections.vitest.ts index 8ed1256ef61..70cecfc3392 100644 --- a/src/vs/workbench/api/test/common/positron/extHostDataConnections.vitest.ts +++ b/src/vs/workbench/api/test/common/positron/extHostDataConnections.vitest.ts @@ -388,6 +388,54 @@ describe('ExtHostDataConnections parameter validation', () => { }); }); +describe('ExtHostDataConnections per-connection languages', () => { + // Registers a driver that supports Python, R, and ggsql, built from the given members. + function registerDriver(members: Partial) { + const $registerDataConnectionDriver = vi.fn(); + const extHost = createExtHost({ $registerDataConnectionDriver }); + extHost.registerDriver({ + id: 'test-driver', + name: 'Test', + description: 'A test driver', + iconSvg: '', + mechanisms: [], + supportedLanguageIds: ['python', 'r', 'ggsql'], + connect: async () => stubInterface({}), + ...members, + }); + return { extHost, narrows: $registerDataConnectionDriver.mock.calls[0][1].narrowsLanguageIds }; + } + + it('asks the driver, and keeps only languages the driver supports, in the driver\'s order', async () => { + const getSupportedLanguageIds = vi.fn(async () => ['ggsql', 'sql', 'python']); + const { extHost, narrows } = registerDriver({ getSupportedLanguageIds }); + + expect({ + narrows, + languageIds: await extHost.$getSupportedLanguageIds('test-driver', 'pat', { account: 'a' }), + calls: getSupportedLanguageIds.mock.calls, + }).toEqual({ + narrows: true, + languageIds: ['python', 'ggsql'], + calls: [['pat', { account: 'a' }]], + }); + }); + + it('gives every supported language for a driver that does not narrow them, and none for a driver that is gone', async () => { + const { extHost, narrows } = registerDriver({}); + + expect({ + narrows, + plain: await extHost.$getSupportedLanguageIds('test-driver', 'pat', {}), + gone: await extHost.$getSupportedLanguageIds('no-such-driver', 'pat', {}), + }).toEqual({ + narrows: false, + plain: ['python', 'r', 'ggsql'], + gone: [], + }); + }); +}); + describe('ExtHostDataConnections unregistering a driver', () => { it('leaves the driver\'s connections open for the main thread to close', async () => { const removeDriver = vi.fn(); diff --git a/src/vs/workbench/contrib/positronDataConnections/browser/components/dataConnectionEntryRow.tsx b/src/vs/workbench/contrib/positronDataConnections/browser/components/dataConnectionEntryRow.tsx index 52a0ac9425a..384cd349292 100644 --- a/src/vs/workbench/contrib/positronDataConnections/browser/components/dataConnectionEntryRow.tsx +++ b/src/vs/workbench/contrib/positronDataConnections/browser/components/dataConnectionEntryRow.tsx @@ -52,6 +52,13 @@ interface DataConnectionEntryRowProps { onMenuOpening: () => IDisposable; } +/** + * Counts the menu requests of every row, so a request that a newer one replaced while it waited for + * its driver shows no menu. Shared by the rows because one menu shows at a time: a menu for a row the + * user has left must not open over the menu of the row they went to. + */ +let latestMenuRequest = 0; + /** * DataConnectionEntryRow component. Renders a root-level entry: the saved profile plus, when * connected, a live-status indicator. Twistie click (handled by PositronTree) opens the connection; @@ -218,10 +225,13 @@ export const DataConnectionEntryRow = ({ entry, hoverManager, onDisconnect, onMe * than at the row's edge; opening from the button has no pointer position to honor and lines * up with the button instead. */ - const showActionsMenu = (anchorElement: HTMLElement, anchorPoint?: AnchorPoint) => { + const showActionsMenu = async (anchorElement: HTMLElement, anchorPoint?: AnchorPoint) => { // Either entry point may be under the actions button's hover, whether a menu or an error follows. hoverManager.hideHover(); + // This request replaces any request that still waits for its driver, on this row or another. + const menuRequest = ++latestMenuRequest; + // A runtime row offers only Refresh and, while it is live, Disconnect, which closes the // connection in its session. Once disconnected the row is gone, so there is nothing else. if (isRuntime) { @@ -327,11 +337,21 @@ export const DataConnectionEntryRow = ({ entry, hoverManager, onDisconnect, onMe }); }; - // Find out what languages the are supported. - const pythonSupported = driver.metadata.supportedLanguageIds.includes('python'); - const rSupported = driver.metadata.supportedLanguageIds.includes('r'); - const sqlSupported = driver.metadata.supportedLanguageIds.includes('sql'); - const ggsqlSupported = driver.metadata.supportedLanguageIds.includes('ggsql'); + // Find out which languages this connection supports. A driver can support a language for only + // some of its connections, and a language this connection can't generate code for would be a + // dead end. The secret-free parameter values are enough for the driver to tell. + const languageIds = await driver.getSupportedLanguageIds(mechanismId, profile.parameterValues); + // While the driver answered, the user can ask for a menu again, on this row or another, or the + // row can re-render without this anchor. Either way, this menu is out of date. + if (menuRequest !== latestMenuRequest || !anchorElement.isConnected) { + return; + } + // The connection can also open or close during the wait, so read it as it is now. + const instance = positronDataConnectionsService.getInstanceForProfile(profile.id); + const pythonSupported = languageIds.includes('python'); + const rSupported = languageIds.includes('r'); + const sqlSupported = languageIds.includes('sql'); + const ggsqlSupported = languageIds.includes('ggsql'); // Build the menu entries. Refresh leads, separated from the profile actions below it -- // Edit Connection is always present, so the separator always has something under it. @@ -394,7 +414,7 @@ export const DataConnectionEntryRow = ({ entry, hoverManager, onDisconnect, onMe // Finally, add a separator and the options that change what the pane holds: disconnect (only // while there is a live connection to close), then save or remove. entries.push(new CustomContextMenuSeparator()); - if (entry.instance) { + if (instance) { entries.push(new CustomContextMenuItem({ icon: 'positron-disconnect-connection', label: localize('positron.dataConnections.disconnect', "Disconnect"), @@ -459,7 +479,7 @@ export const DataConnectionEntryRow = ({ entry, hoverManager, onDisconnect, onMe const onActionsClick = () => { // Guard: if the ref isn't set, we have no anchor for the menu, so do nothing. if (actionsButtonRef.current) { - showActionsMenu(actionsButtonRef.current); + void showActionsMenu(actionsButtonRef.current); } }; @@ -473,7 +493,7 @@ export const DataConnectionEntryRow = ({ entry, hoverManager, onDisconnect, onMe } e.preventDefault(); e.stopPropagation(); - showActionsMenu(rowRef.current, { clientX: e.clientX, clientY: e.clientY }); + void showActionsMenu(rowRef.current, { clientX: e.clientX, clientY: e.clientY }); }; // The connected indicator's label, used as both its tooltip and its accessible name. diff --git a/src/vs/workbench/contrib/positronDataConnections/browser/positronDataConnectionsCommands.ts b/src/vs/workbench/contrib/positronDataConnections/browser/positronDataConnectionsCommands.ts index 4df8f95b8e6..8c90bd98a18 100644 --- a/src/vs/workbench/contrib/positronDataConnections/browser/positronDataConnectionsCommands.ts +++ b/src/vs/workbench/contrib/positronDataConnections/browser/positronDataConnectionsCommands.ts @@ -202,22 +202,24 @@ function extractConnectionVariableName(code: string): string | undefined { * @param profile The data connection profile. * @param mechanismId The id of the mechanism the profile was configured with. * @param driver The registered driver for the profile. + * @param supportedLanguageIds The languages this connection can generate code for. * @param logService The log service. * @param requestedLanguageId The only language to generate code for. Omitted, every language the - * driver supports is generated -- one round trip to the driver each, which is why the catalog + * connection supports is generated -- one round trip to the driver each, which is why the catalog * (getConnections) asks for none of them. */ async function getLanguagePayloads( profile: IDataConnectionProfile, mechanismId: string, driver: IDataConnectionDriver, + supportedLanguageIds: readonly string[], logService: ILogService, requestedLanguageId?: string, ): Promise> { const languages: Record = {}; const languageIds = requestedLanguageId === undefined - ? driver.metadata.supportedLanguageIds - : driver.metadata.supportedLanguageIds.includes(requestedLanguageId) ? [requestedLanguageId] : []; + ? supportedLanguageIds + : supportedLanguageIds.includes(requestedLanguageId) ? [requestedLanguageId] : []; await Promise.all(languageIds.map(async languageId => { // The profile's own parameterValues never contains a value the mechanism declares secret -- a @@ -282,12 +284,13 @@ export async function getDataConnections(accessor: ServicesAccessor): Promise({ mechanisms: [{ id: 'test-mechanism', label: 'Test Mechanism', description: '', parameters: [] }], supportedLanguageIds: [], }, + getSupportedLanguageIds: async () => [], }); describe('DataConnectionEntryRow', () => { + // The driver the row finds. Most tests use the language-free driver above; a test that needs the + // Connect With group swaps in its own, and each test starts from the default again. + let rowDriver: IDataConnectionDriver = driver; + beforeEach(() => { + rowDriver = driver; + }); + // Saving a discovered profile hands back the id of the ordinary profile it became, which the row // then looks up. Declared here so the tests can assert against the calls. const saveDiscoveredProfile = vi.fn((_id: string) => savedDiscoveredProfile.id); @@ -113,12 +121,17 @@ describe('DataConnectionEntryRow', () => { const countOpenDataExplorers = vi.fn((_profileId: string) => 0); const notifyError = vi.fn(); const getProfile = vi.fn((id: string) => id === savedDiscoveredProfile.id ? savedDiscoveredProfile : undefined); + // The live connection the service reports for a profile. rightClickRow sets it to the instance + // it renders the row with; a test can change it while the menu waits. + let liveInstance: IDataConnectionInstance | undefined; + const getInstanceForProfile = vi.fn((_profileId: string) => liveInstance); const ctx = createTestContainer() .withReactServices() .stub(IPositronDataConnectionsService, { - driverManager: stubInterface({ getDriver: () => driver }), + driverManager: stubInterface({ getDriver: () => rowDriver }), getProfile, + getInstanceForProfile, saveDiscoveredProfile, hideDiscoveredProfile, countOpenDataExplorers, @@ -142,6 +155,7 @@ describe('DataConnectionEntryRow', () => { const instance = connected ? stubInterface({ id: 'instance-1', profileId: rowProfile.id }) : undefined; + liveInstance = instance; const onDisconnectRow = vi.fn(); rtl.render( @@ -409,6 +423,118 @@ describe('DataConnectionEntryRow', () => { expect(onDisconnectRow).toHaveBeenCalledOnce(); }); + // A driver can support a language for some of its connections only. The menu offers just the + // languages this connection can generate code for, so no item leads to a dead end. + it('offers Connect With only for the languages this connection supports', async () => { + const getSupportedLanguageIds = vi.fn(async () => ['python']); + rowDriver = stubInterface({ + id: 'test-driver', + metadata: { ...driver.metadata, supportedLanguageIds: ['python', 'r', 'ggsql'] }, + getSupportedLanguageIds, + }); + + const { labels } = await rightClickRow({ connected: false, rowProfile: { ...profile, parameterValues: { account: 'a' } } }); + + expect({ labels, calls: getSupportedLanguageIds.mock.calls }).toEqual({ + labels: ['Refresh', '---', 'Edit Connection', '---', 'Python', '---', 'Remove'], + calls: [['test-mechanism', { account: 'a' }]], + }); + }); + + // The menu waits for the driver's answer. A second click while it waits replaces the first, so + // the user gets one menu, not one per click. + it('opens one menu when the row is clicked again while the languages load', async () => { + const answers: ((languageIds: string[]) => void)[] = []; + rowDriver = stubInterface({ + id: 'test-driver', + metadata: { ...driver.metadata, supportedLanguageIds: ['python'] }, + getSupportedLanguageIds: () => new Promise(resolve => answers.push(resolve)), + }); + rtl.render( + + ); + const user = userEvent.setup(); + const target = screen.getByText(profile.connectionName, { exact: false }); + + await user.pointer({ keys: '[MouseRight]', target }); + await user.pointer({ keys: '[MouseRight]', target }); + await act(async () => answers.forEach(answer => answer(['python']))); + + expect(showCustomContextMenu).toHaveBeenCalledOnce(); + }); + + // The connection can close while the menu waits for the driver. The menu then reflects the + // connection as it is when it opens, not as it was when the user clicked. + it('offers no Disconnect for a connection that closed while the languages loaded', async () => { + const answers: ((languageIds: string[]) => void)[] = []; + rowDriver = stubInterface({ + id: 'test-driver', + metadata: { ...driver.metadata }, + getSupportedLanguageIds: () => new Promise(resolve => answers.push(resolve)), + }); + liveInstance = stubInterface({ id: 'instance-1', profileId: profile.id }); + rtl.render( + + ); + const user = userEvent.setup(); + + await user.pointer({ keys: '[MouseRight]', target: screen.getByText(profile.connectionName, { exact: false }) }); + liveInstance = undefined; + await act(async () => answers.forEach(answer => answer([]))); + + const entries = showCustomContextMenu.mock.calls.at(-1)?.[0].entries; + const labels = entries.map((entry: unknown) => + entry instanceof CustomContextMenuSeparator ? '---' : (entry as CustomContextMenuItem).options.label); + expect(labels).toEqual(['Refresh', '---', 'Edit Connection', '---', 'Remove']); + }); + + // The same holds across rows: a menu for a row the user has left must not open over the menu of + // the row they went to. + it('opens one menu when another row is clicked while the languages load', async () => { + const answers: ((languageIds: string[]) => void)[] = []; + rowDriver = stubInterface({ + id: 'test-driver', + metadata: { ...driver.metadata, supportedLanguageIds: ['python'] }, + getSupportedLanguageIds: () => new Promise(resolve => answers.push(resolve)), + }); + const otherProfile = { ...profile, id: 'other-profile', connectionName: 'Other Connection' }; + rtl.render( + <> + {[profile, otherProfile].map(rowProfile => ( + + ))} + + ); + const user = userEvent.setup(); + const otherRow = screen.getByText(otherProfile.connectionName, { exact: false }); + + await user.pointer({ keys: '[MouseRight]', target: screen.getByText(profile.connectionName, { exact: false }) }); + await user.pointer({ keys: '[MouseRight]', target: otherRow }); + await act(async () => answers.forEach(answer => answer(['python']))); + + expect(vi.mocked(showCustomContextMenu).mock.calls.map(([options]) => otherRow.contains(options.anchorElement) || options.anchorElement.contains(otherRow))) + .toEqual([true]); + }); + // Disconnect shares the bottom group with Remove but not its styling: giving up a connection // leaves the saved profile intact, so nothing about it is unrecoverable. it('marks Remove destructive but not Disconnect', async () => { diff --git a/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsCommands.vitest.ts b/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsCommands.vitest.ts index 400a7ff6320..dd95050feb1 100644 --- a/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsCommands.vitest.ts +++ b/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsCommands.vitest.ts @@ -62,19 +62,22 @@ function createCatalogStubs( } function createDriver(overrides: Partial = {}): IDataConnectionDriver { + const metadata = overrides.metadata ?? { + id: 'test-driver', + name: 'Test Driver', + description: '', + iconSvg: '', + supportedLanguageIds: ['python', 'r'], + mechanisms: [{ id: 'test-mechanism', label: 'Test Mechanism', description: '', parameters: [] }], + }; return stubInterface({ id: 'test-driver', - metadata: { - id: 'test-driver', - name: 'Test Driver', - description: '', - iconSvg: '', - supportedLanguageIds: ['python', 'r'], - mechanisms: [{ id: 'test-mechanism', label: 'Test Mechanism', description: '', parameters: [] }], - }, // No code by default; tests that care about the languages payload override this. generateConnectionCode: vi.fn(async () => []), + // Every declared language by default, as a driver that does not narrow them answers. + getSupportedLanguageIds: vi.fn(async () => [...metadata.supportedLanguageIds]), ...overrides, + metadata, }); } @@ -260,6 +263,20 @@ describe('getDataConnections', () => { 'name=My Connection | driver=test-driver | mechanism=test-mechanism | languages= | parameters=host=localhost'); }); + // A driver can support a language for only some of its connections. A language the summary + // lists is one the caller will ask for code in, so it lists what this connection supports. + it('lists the languages the connection supports, not all the driver declares', async () => { + const getSupportedLanguageIds = vi.fn(async () => ['python']); + const dataConnectionsService = createDataConnectionsService({ driver: createDriver({ getSupportedLanguageIds }) }); + + const [result] = await run(dataConnectionsService); + + expect({ summary: result.summary, calls: getSupportedLanguageIds.mock.calls }).toEqual({ + summary: 'name=My Connection | driver=test-driver | mechanism=test-mechanism | languages=python | parameters=host=localhost', + calls: [['test-mechanism', { host: 'localhost' }]], + }); + }); + // The summary line's own delimiters are ordinary characters in a connection string, so a value // containing one is quoted rather than silently splitting the line into extra parameters. it('quotes a parameter value containing a summary delimiter', async () => { @@ -481,6 +498,22 @@ describe('getDataConnectionCode', () => { }); }); + // A language the driver declares but this connection cannot generate is not supported either: + // naming it in the reply would invite a retry that fails the same way. + it('reports no code for a language the connection does not support, naming those it does', async () => { + const { generateConnectionCode } = createCodeDriver(); + const driver = createDriver({ generateConnectionCode, getSupportedLanguageIds: async () => ['python'] }); + const dataConnectionsService = createDataConnectionsService({ driver }); + + expect({ + result: await run(dataConnectionsService, { profileId: 'conn-1', languageId: 'r' }), + generated: generateConnectionCode.mock.calls.length, + }).toEqual({ + result: { available: false, reason: 'no-code', supportedLanguageIds: ['python'] }, + generated: 0, + }); + }); + // A driver that throws is reported the same way as one that returns nothing: the caller gets a // reason, not a rejected promise. it('reports no code when the driver fails to generate any', async () => { diff --git a/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsInspectActions.vitest.ts b/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsInspectActions.vitest.ts index 03bd8e18ef8..5488fcadf15 100644 --- a/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsInspectActions.vitest.ts +++ b/src/vs/workbench/contrib/positronDataConnections/test/browser/positronDataConnectionsInspectActions.vitest.ts @@ -53,6 +53,7 @@ function createDriver(): IDataConnectionDriver { mechanisms: [{ id: 'test-mechanism', label: 'Test Mechanism', description: '', parameters: [] }], }, generateConnectionCode: vi.fn(async () => [{ id: 'dbi', label: 'DBI', code: 'con <- connect()\n' }]), + getSupportedLanguageIds: vi.fn(async () => ['r']), }); } diff --git a/src/vs/workbench/services/positronConnections/browser/runtimeDataConnectionDriver.ts b/src/vs/workbench/services/positronConnections/browser/runtimeDataConnectionDriver.ts index 450a5ee9edd..3ac45c42871 100644 --- a/src/vs/workbench/services/positronConnections/browser/runtimeDataConnectionDriver.ts +++ b/src/vs/workbench/services/positronConnections/browser/runtimeDataConnectionDriver.ts @@ -157,6 +157,10 @@ export class RuntimeDataConnectionDriver extends Disposable implements IDataConn return []; } + async getSupportedLanguageIds(_mechanismId: string, _params: DataConnectionParameterValues): Promise { + return []; + } + async redactParameterValue(_mechanismId: string, _parameterId: string, _value: string): Promise { return undefined; } diff --git a/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDTOs.ts b/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDTOs.ts index c9cc5f6d2fd..9c97d7bba2f 100644 --- a/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDTOs.ts +++ b/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDTOs.ts @@ -55,6 +55,10 @@ export interface IDataConnectionDriverMetadataDTO { // Whether the driver implements validateParameters. When it doesn't, the main thread skips the // round trip to the extension host. validatesParameters?: boolean; + + // Whether the driver implements getSupportedLanguageIds. When it doesn't, the main thread skips + // the round trip to the extension host and offers every supported language. + narrowsLanguageIds?: boolean; } /** diff --git a/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDriver.ts b/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDriver.ts index 2b86bf1261a..b9916ff2136 100644 --- a/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDriver.ts +++ b/src/vs/workbench/services/positronDataConnections/common/interfaces/dataConnectionDriver.ts @@ -217,6 +217,9 @@ export interface IDataConnectionDriverMetadata { // Whether the driver implements validateParameters. validatesParameters?: boolean; + + // Whether the driver implements getSupportedLanguageIds. + narrowsLanguageIds?: boolean; } /** @@ -269,6 +272,15 @@ export interface IDataConnectionDriver { */ generateConnectionCode(mechanismId: string, languageId: string, params: DataConnectionParameterValues): Promise; + /** + * The languages one connection can generate code for: the driver's supported languages, or + * fewer when the driver narrows them for this connection. Never rejects; when the driver fails + * to answer, resolves to every supported language. + * @param mechanismId The id of the mechanism the connection uses. + * @param params The connection's parameter values, without the secret ones. + */ + getSupportedLanguageIds(mechanismId: string, params: DataConnectionParameterValues): Promise; + /** * Produces a display-safe, redacted form of a stored parameter value (e.g. masking the password * embedded in a connection string) for display in the configuration dialog and in the