Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions extensions/ggsqlOdbc-copies.vitest.ts
Original file line number Diff line number Diff line change
@@ -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));
});
});
160 changes: 159 additions & 1 deletion extensions/positron-data-driver-databricks/src/databricksDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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=<workspace id>`, 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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think undefined here covers two cases: ggsql isn't installed, or the ggsql extension is installed but hasn't registered its runtime yet.

In the second case, someone with ggsql 0.5.2 who opens Connect With right after startup gets offered ggsql, and the line can't sign in. We could avoid this by waiting for discovery, but extensions have no API for that.

Could we use the ggsql extension being installed as the signal? Something like:

export function ggsqlAddsDatabricksToken(version: string | undefined, ggsqlExtensionInstalled: boolean): boolean {
	if (version === undefined) {
		return !ggsqlExtensionInstalled;
	}
	...
}

with ggsqlExtensionInstalled being the result of vscode.extensions.getExtension('ggsql.ggsql') !== undefined. During discovery it hides ggsql until the next menu open, and a truly missing ggsql still gets the Not Installed dialog.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thank you! I made this change in b926fa2. When the ggsql extension is installed but its runtime is not registered yet, the driver does not offer ggsql. Connect With asks the driver again each time it opens, so ggsql shows when the runtime registers. When no ggsql extension is installed, the driver still offers ggsql, so Connect shows the dialog that tells the user to install it.

I didn't use the extension version as the ggsql version since it is possible for the extension to run a ggsql kernel from ggsql.kernelPath, a Jupyter kernelspec, the PATH, etc (so the runtime version can be different from the extension version).

return !ggsqlExtensionInstalled;
}
const match = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\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<boolean> {
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<positron.DataConnection> {
validateRequired(mechanismId, params);
Expand All @@ -576,7 +716,18 @@ export function createDatabricksDriver(
await connection.connect();
return connection;
},
async getSupportedLanguageIds(mechanismId: string, params: positron.DataConnectionParameterValues): Promise<string[]> {
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<positron.ConnectionCodeVariant[]> {
// 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.
Expand All @@ -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);
Expand Down
85 changes: 85 additions & 0 deletions extensions/positron-data-driver-databricks/src/ggsqlOdbc.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
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<boolean> = fileExists): Promise<string> {
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<readonly [string, string | undefined]>): 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(';')}`;
}
Loading
Loading