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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- Kernel backend: `port` is passed to the kernel as is, so a custom port works over HTTPS as on Thrift. IPv6 hosts need brackets, an invalid port or host fails with a `ParameterError`, and the published `@databricks/databricks-sql-kernel-*` native packages must be bumped to a release that includes databricks/databricks-sql-kernel#505, since older packages ignore `port`.
- Release completed Thrift CloudFetch body-reader listeners so idle connections do not retain downloaded result buffers.
- **Behavior change:** Thrift `getSchema()` and `getResultMetadata().schema` return `{ columns: [] }` for statements without output columns when Arrow metadata has no fields. Check `columns.length` before indexing. `getMetadata()` and responses without Arrow metadata (including `arrowEnabled: false` and older protocols) retain the `Result STRING` placeholder. (#651)
- Fix `fetchAll()` and `fetchChunk()` hanging on column-based results with an empty or missing schema. (#651)

## 3.1.0

Expand Down
3 changes: 1 addition & 2 deletions lib/DBSQLOperation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,7 @@ export default class DBSQLOperation implements IOperation {

this.context.getLogger().log(LogLevel.debug, `Fetching schema for operation with id: ${this.id}`);
if (this.backend instanceof ThriftOperationBackend) {
const metadata = await this.backend.thriftResultMetadataResponse();
return metadata.schema ?? null;
return (await this.backend.getSchema()) ?? null;
}
const metadata = await this.getResultMetadata();
return metadata.schema ?? null;
Expand Down
9 changes: 8 additions & 1 deletion lib/contracts/IOperation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,19 @@ export default interface IOperation {
hasMoreRows(): Promise<boolean>;

/**
* Fetch schema
* Fetch schema; returns null when hasResultSet is false or no schema is available.
* Statements without output columns return { columns: [] } on kernel.
* Behavior change: Thrift also returns { columns: [] } when Arrow metadata
* has no fields, replacing its `Result STRING` placeholder. Check columns.length
* before accessing columns[0]. Without Arrow metadata (arrowEnabled: false or
* older protocols), Thrift retains the placeholder.
* The deprecated getMetadata() retains the Thrift wire schema unchanged.
*/
getSchema(options?: GetSchemaOptions): Promise<TTableSchema | null>;

/**
* Fetch result-set metadata in the backend-neutral `ResultMetadata` shape.
* Its schema follows the same column normalization as getSchema().
* Prefer this over the Thrift-shaped surface for new code.
*/
getResultMetadata(): Promise<ResultMetadata>;
Expand Down
3 changes: 3 additions & 0 deletions lib/result/JsonResultHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export default class JsonResultHandler implements IResultsProvider<Array<any>> {
}

public async hasMore() {
if (this.schema.length === 0) {
return false;
}
return this.source.hasMore();
}

Expand Down
47 changes: 32 additions & 15 deletions lib/thrift-backend/ThriftOperationBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { definedOrError } from '../utils';
import HiveDriverError from '../errors/HiveDriverError';
import isObjectNotFound from './metadataErrors';
import { synthesizeThriftResultSetMetadata } from './wireSynthesis';
import getResultSchema from './resultSchema';

interface ThriftOperationBackendOptions {
handle: TOperationHandle;
Expand Down Expand Up @@ -97,6 +98,8 @@ export default class ThriftOperationBackend implements IOperationBackend {

private metadata?: TGetResultSetMetadataResp;

private normalizedMetadata?: TGetResultSetMetadataResp;

private metadataPromise?: Promise<TGetResultSetMetadataResp>;

private state: TOperationState = TOperationState.INITIALIZED_STATE;
Expand All @@ -118,7 +121,7 @@ export default class ThriftOperationBackend implements IOperationBackend {
this.functionCatalog = functionCatalog;
this.emptyResultOnNotFound = emptyResultOnNotFound;
this.rowMode = rowMode;
this.metadata = directResults?.resultSetMetadata;
this.setResultMetadata(directResults?.resultSetMetadata);

const useOnlyPrefetchedResults = Boolean(directResults?.closeOperation);

Expand Down Expand Up @@ -292,15 +295,19 @@ export default class ThriftOperationBackend implements IOperationBackend {
}

public async getResultMetadata(): Promise<ResultMetadata> {
return this.adaptResultMetadata(await this.thriftResultMetadataResponse());
return this.adaptResultMetadata(await this.resultMetadataResponse());
}

public async getSchema(): Promise<TTableSchema | undefined> {
return (await this.resultMetadataResponse()).schema;
}

public getCachedResultMetadata(): ResultMetadata | undefined {
if (!this.metadata) {
if (!this.normalizedMetadata) {
return undefined;
}
try {
return this.adaptResultMetadata(this.metadata);
return this.adaptResultMetadata(this.normalizedMetadata);
} catch {
// Missing or unsupported resultFormat; the fetch path reports that error.
return undefined;
Expand All @@ -310,10 +317,8 @@ export default class ThriftOperationBackend implements IOperationBackend {
/**
* Thrift-specific accessor for the raw `TGetResultSetMetadataResp`.
*
* Used internally by `getResultHandler` (dispatches on Thrift `resultFormat`
* and passes the full Thrift response to the JSON / Arrow / CloudFetch
* result handlers). Also called by the public `DBSQLOperation.getMetadata()`
* facade (zero-loss fast path).
* Called by the public `DBSQLOperation.getMetadata()` facade to preserve
* the wire response. Internal consumers use the normalized copy.
*
* Not declared on `IOperationBackend` — non-Thrift backends do not implement
* it. The facade reaches it via `instanceof ThriftOperationBackend`.
Expand All @@ -333,7 +338,7 @@ export default class ThriftOperationBackend implements IOperationBackend {
operationHandle: this.operationHandle,
});
Status.assert(metadata.status);
this.metadata = metadata;
this.setResultMetadata(metadata);
return metadata;
})();

Expand Down Expand Up @@ -367,7 +372,7 @@ export default class ThriftOperationBackend implements IOperationBackend {
}

public async getResultHandler(): Promise<ResultSlicer<any>> {
const metadata = await this.thriftResultMetadataResponse();
const metadata = await this.resultMetadataResponse();
const resultFormat = definedOrError(metadata.resultFormat);

if (!this.resultHandler) {
Expand Down Expand Up @@ -433,11 +438,13 @@ export default class ThriftOperationBackend implements IOperationBackend {
message: response.errorMessage ?? response.displayMessage ?? response.status.errorMessage,
})}`,
);
this.metadata = synthesizeThriftResultSetMetadata({
schema: this.emptyResultOnNotFound,
resultFormat: ResultFormat.ColumnBased,
isStagingOperation: false,
});
this.setResultMetadata(
synthesizeThriftResultSetMetadata({
schema: this.emptyResultOnNotFound,
resultFormat: ResultFormat.ColumnBased,
isStagingOperation: false,
}),
);
this.resultHandler = new ResultSlicer(this.context, {
fetchNext: async () => [],
hasMore: async () => false,
Expand Down Expand Up @@ -479,6 +486,16 @@ export default class ThriftOperationBackend implements IOperationBackend {
};
}

private setResultMetadata(metadata?: TGetResultSetMetadataResp): void {
this.metadata = metadata;
this.normalizedMetadata = metadata ? { ...metadata, schema: getResultSchema(metadata) } : undefined;
}

private async resultMetadataResponse(): Promise<TGetResultSetMetadataResp> {
await this.thriftResultMetadataResponse();
return definedOrError(this.normalizedMetadata);
}

// eslint-disable-next-line class-methods-use-this
private adaptResultMetadata(response: TGetResultSetMetadataResp): ResultMetadata {
return {
Expand Down
38 changes: 38 additions & 0 deletions lib/thrift-backend/resultSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { RecordBatchReader } from 'apache-arrow';
import { TGetResultSetMetadataResp, TSparkRowSetType, TTableSchema, TTypeId } from '../../thrift/TCLIService_types';

function isPlaceholderSchema(schema?: TTableSchema): boolean {
if (schema?.columns?.length !== 1) {
return false;
}
const [column] = schema.columns;
return column?.columnName === 'Result' && column.typeDesc?.types?.[0]?.primitiveEntry?.type === TTypeId.STRING_TYPE;
}

function hasNoArrowFields(arrowSchema: Buffer): boolean {
try {
const reader = RecordBatchReader.from(arrowSchema);
reader.open();
return reader.schema?.fields.length === 0;
} catch {
return false;
}
}

/**
* Column schema of an Arrow Thrift result. For statements without output (e.g. DDL)
* the server's `TTableSchema` is a placeholder `Result STRING` column, while the
* Arrow schema in the same response has no fields; report no columns, as the
* kernel backend does. Without Arrow metadata the placeholder can't be told apart
* from a real `Result` column and is returned as is.
*/
export default function getResultSchema(metadata: TGetResultSetMetadataResp): TTableSchema | undefined {
const { schema, arrowSchema, resultFormat } = metadata;
if (resultFormat !== TSparkRowSetType.ARROW_BASED_SET && resultFormat !== TSparkRowSetType.URL_BASED_SET) {
return schema;
}
if (arrowSchema && isPlaceholderSchema(schema) && hasNoArrowFields(arrowSchema)) {
return { columns: [] };
}
return schema;
}
89 changes: 89 additions & 0 deletions tests/e2e/ddl_schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { expect } from 'chai';
import { DBSQLClient } from '../../lib';
import DBSQLOperation from '../../lib/DBSQLOperation';
import { ConnectionOptions } from '../../lib/contracts/IDBSQLClient';
import { InternalConnectionOptions } from '../../lib/contracts/InternalConnectionOptions';
import { TTypeId } from '../../thrift/TCLIService_types';

import config from './utils/config';

// From #309: DDL and an empty SELECT both return no rows; only the schema tells them apart.
describe('schema of statements without output', () => {
for (const { name, useKernel, arrowEnabled, maxRows } of [
{ name: 'Thrift with direct results', useKernel: false, arrowEnabled: true, maxRows: undefined },
{ name: 'Thrift without direct results', useKernel: false, arrowEnabled: true, maxRows: null },
{ name: 'Thrift without Arrow', useKernel: false, arrowEnabled: false, maxRows: undefined },
{ name: 'kernel', useKernel: true, arrowEnabled: true, maxRows: undefined },
] as const) {
it(`reports the expected schema with ${name}`, async () => {
const client = new DBSQLClient();
client.getConfig().arrowEnabled = arrowEnabled;
await client.connect({
host: config.host,
path: config.path,
token: config.token,
useKernel,
} as ConnectionOptions & InternalConnectionOptions);
const session = await client.openSession({ initialCatalog: config.catalog, initialSchema: config.schema });
const table = `dbsql_nodejs_sdk_e2e_ddl_schema_${name.toLowerCase().replace(/ /g, '_')}_${config.tableSuffix}`;
const ddlColumns = arrowEnabled ? [] : ['Result'];

const columnsOf = async (statement: string) => {
const operation = await session.executeStatement(statement, { maxRows });
try {
const checkMetadata = async () => {
const schema = await operation.getSchema();
expect((await operation.getResultMetadata()).schema).to.deep.equal(schema);
if (!useKernel) {
const wireSchema = (await (operation as DBSQLOperation).getMetadata()).schema;
expect(
wireSchema?.columns.map((column) => ({
name: column.columnName,
type: column.typeDesc.types[0]?.primitiveEntry?.type,
})),
).to.deep.equal([{ name: 'Result', type: TTypeId.STRING_TYPE }]);
}
return schema;
};

const schema = await checkMetadata();
expect(await operation.fetchAll()).to.deep.equal([]);
expect(await checkMetadata()).to.deep.equal(schema);
return schema?.columns.map((column) => column.columnName);
} finally {
await operation.close();
}
};

let cleanupError: unknown;
try {
await columnsOf(`DROP TABLE IF EXISTS ${table}`);
expect(await columnsOf(`SELECT 'sample' AS Result WHERE 1 = 0`)).to.deep.equal(['Result']);
expect(await columnsOf(`CREATE TABLE ${table} (col1 INT)`)).to.deep.equal(ddlColumns);
expect(await columnsOf(`DROP TABLE ${table}`)).to.deep.equal(ddlColumns);
} finally {
try {
try {
const cleanup = await session.executeStatement(`DROP TABLE IF EXISTS ${table}`);
try {
await cleanup.finished();
} finally {
await cleanup.close();
}
} finally {
try {
await session.close();
} finally {
await client.close();
}
}
} catch (error) {
cleanupError = error;
}
}
if (cleanupError !== undefined) {
throw cleanupError;
}
});
}
});
Loading
Loading