From 248758c8bc9571b5220fc9067717bc532f3284ef Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 04:34:57 +0000 Subject: [PATCH 1/6] Report no columns for Thrift statements without output For DDL the Thrift server sends a placeholder `Result STRING` column, which can't be told apart from `SELECT 'x' AS Result WHERE 1 = 0`. The Arrow schema in the same response has no fields, so getSchema() and getResultMetadata() now report no columns, matching the kernel backend. getMetadata() still returns the wire response. Without Arrow results the wire is identical and the placeholder is kept. Fixes #309 Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- lib/DBSQLOperation.ts | 3 +- lib/contracts/IOperation.ts | 3 +- lib/thrift-backend/ThriftOperationBackend.ts | 3 +- lib/thrift-backend/resultSchema.ts | 35 +++++++++++++++ tests/e2e/ddl_schema.test.ts | 45 +++++++++++++++++++ tests/unit/DBSQLOperation.test.ts | 35 +++++++++++++++ .../unit/thrift-backend/resultSchema.test.ts | 41 +++++++++++++++++ 7 files changed, 162 insertions(+), 3 deletions(-) create mode 100644 lib/thrift-backend/resultSchema.ts create mode 100644 tests/e2e/ddl_schema.test.ts create mode 100644 tests/unit/thrift-backend/resultSchema.test.ts diff --git a/lib/DBSQLOperation.ts b/lib/DBSQLOperation.ts index 30f095ef..a0bd854a 100644 --- a/lib/DBSQLOperation.ts +++ b/lib/DBSQLOperation.ts @@ -19,6 +19,7 @@ import IClientContext from './contracts/IClientContext'; import IOperationBackend, { IOperationBackendWaitOptions } from './contracts/IOperationBackend'; import { ResultFormat, ResultMetadata } from './contracts/ResultMetadata'; import ThriftOperationBackend from './thrift-backend/ThriftOperationBackend'; +import getResultSchema from './thrift-backend/resultSchema'; import { synthesizeThriftStatus, synthesizeThriftResultSetMetadata } from './thrift-backend/wireSynthesis'; import { mapOperationTypeToTelemetryType } from './telemetry/telemetryTypeMappers'; import ExceptionClassifier from './telemetry/ExceptionClassifier'; @@ -308,7 +309,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 getResultSchema(metadata) ?? null; } const metadata = await this.getResultMetadata(); return metadata.schema ?? null; diff --git a/lib/contracts/IOperation.ts b/lib/contracts/IOperation.ts index bbeed622..dc238ad4 100644 --- a/lib/contracts/IOperation.ts +++ b/lib/contracts/IOperation.ts @@ -90,7 +90,8 @@ export default interface IOperation { hasMoreRows(): Promise; /** - * Fetch schema + * Fetch schema. Statements without output, such as DDL, return a schema with + * no columns (on Thrift, only when Arrow results are enabled, the default). */ getSchema(options?: GetSchemaOptions): Promise; diff --git a/lib/thrift-backend/ThriftOperationBackend.ts b/lib/thrift-backend/ThriftOperationBackend.ts index 10f2d03e..b28a26a6 100644 --- a/lib/thrift-backend/ThriftOperationBackend.ts +++ b/lib/thrift-backend/ThriftOperationBackend.ts @@ -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; @@ -482,7 +483,7 @@ export default class ThriftOperationBackend implements IOperationBackend { // eslint-disable-next-line class-methods-use-this private adaptResultMetadata(response: TGetResultSetMetadataResp): ResultMetadata { return { - schema: response.schema, + schema: getResultSchema(response), resultFormat: thriftRowSetTypeToResultFormat(definedOrError(response.resultFormat)), lz4Compressed: response.lz4Compressed, arrowSchema: response.arrowSchema, diff --git a/lib/thrift-backend/resultSchema.ts b/lib/thrift-backend/resultSchema.ts new file mode 100644 index 00000000..72fde0ff --- /dev/null +++ b/lib/thrift-backend/resultSchema.ts @@ -0,0 +1,35 @@ +import { RecordBatchReader } from 'apache-arrow'; +import { TGetResultSetMetadataResp, 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 a 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 } = metadata; + if (arrowSchema && isPlaceholderSchema(schema) && hasNoArrowFields(arrowSchema)) { + return { columns: [] }; + } + return schema; +} diff --git a/tests/e2e/ddl_schema.test.ts b/tests/e2e/ddl_schema.test.ts new file mode 100644 index 00000000..bd9c1451 --- /dev/null +++ b/tests/e2e/ddl_schema.test.ts @@ -0,0 +1,45 @@ +import { expect } from 'chai'; +import { DBSQLClient } from '../../lib'; +import { ConnectionOptions } from '../../lib/contracts/IDBSQLClient'; +import { InternalConnectionOptions } from '../../lib/contracts/InternalConnectionOptions'; + +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] of [ + ['Thrift', false], + ['kernel', true], + ] as const) { + it(`reports no columns for DDL with ${name}`, async () => { + const client = new DBSQLClient(); + 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()}_${config.tableSuffix}`; + + const columnsOf = async (statement: string) => { + const operation = await session.executeStatement(statement); + expect(await operation.fetchAll()).to.deep.equal([]); + const schema = await operation.getSchema(); + await operation.close(); + return schema?.columns.map((column) => column.columnName); + }; + + try { + 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([]); + expect(await columnsOf(`DROP TABLE ${table}`)).to.deep.equal([]); + } finally { + const cleanup = await session.executeStatement(`DROP TABLE IF EXISTS ${table}`); + await cleanup.close(); + await session.close(); + await client.close(); + } + }); + } +}); diff --git a/tests/unit/DBSQLOperation.test.ts b/tests/unit/DBSQLOperation.test.ts index e37b5059..9a20fd00 100644 --- a/tests/unit/DBSQLOperation.test.ts +++ b/tests/unit/DBSQLOperation.test.ts @@ -25,6 +25,7 @@ import ArrowResultConverter from '../../lib/result/ArrowResultConverter'; import ArrowResultHandler from '../../lib/result/ArrowResultHandler'; import CloudFetchResultHandler from '../../lib/result/CloudFetchResultHandler'; import ResultSlicer from '../../lib/result/ResultSlicer'; +import { hiveSchemaToArrowSchema } from '../../lib/result/utils'; import ClientContextStub from './.stubs/ClientContextStub'; import { createOperationForTest } from './.stubs/createOperationForTest'; @@ -952,6 +953,40 @@ describe('DBSQLOperation', () => { expect(driver.getResultSetMetadata.called).to.be.false; }); + it('should report no columns for statements without output', async () => { + const context = new ClientContextStub(); + context.driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; + + // DDL on Thrift: placeholder `Result` column, Arrow schema with no fields. + const placeholder = { + columns: [ + { + columnName: 'Result', + position: 1, + typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, + }, + ], + }; + const directResults: TSparkDirectResults = { + resultSetMetadata: { + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + resultFormat: TSparkRowSetType.ARROW_BASED_SET, + schema: placeholder, + arrowSchema: hiveSchemaToArrowSchema({ columns: [] }), + }, + }; + const operation = createOperationForTest({ + handle: operationHandleStub({ hasResultSet: true }), + context, + directResults, + }); + + expect(await operation.getSchema()).to.deep.equal({ columns: [] }); + expect((await operation.getResultMetadata()).schema).to.deep.equal({ columns: [] }); + // The deprecated wire accessor stays verbatim. + expect((await operation.getMetadata()).schema).to.equal(placeholder); + }); + it('should throw an error in case of a status error', async () => { const context = new ClientContextStub(); context.driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; diff --git a/tests/unit/thrift-backend/resultSchema.test.ts b/tests/unit/thrift-backend/resultSchema.test.ts new file mode 100644 index 00000000..9b9e4d90 --- /dev/null +++ b/tests/unit/thrift-backend/resultSchema.test.ts @@ -0,0 +1,41 @@ +import { expect } from 'chai'; +import { TGetResultSetMetadataResp, TStatusCode, TTableSchema, TTypeId } from '../../../thrift/TCLIService_types'; +import getResultSchema from '../../../lib/thrift-backend/resultSchema'; +import { hiveSchemaToArrowSchema } from '../../../lib/result/utils'; + +function stringColumn(columnName: string, position: number) { + return { columnName, position, typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] } }; +} + +// What the server sends for DDL: a placeholder column alongside an Arrow schema with no fields. +const placeholder: TTableSchema = { columns: [stringColumn('Result', 1)] }; + +function metadata(schema: TTableSchema, arrowSchema?: Buffer): TGetResultSetMetadataResp { + return { status: { statusCode: TStatusCode.SUCCESS_STATUS }, schema, arrowSchema }; +} + +describe('getResultSchema', () => { + it('reports no columns when the Arrow schema has no fields', () => { + expect(getResultSchema(metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })))).to.deep.equal({ + columns: [], + }); + }); + + it('keeps a real `Result` column', () => { + const md = metadata(placeholder, hiveSchemaToArrowSchema(placeholder)); + expect(getResultSchema(md)).to.equal(placeholder); + }); + + it('keeps the placeholder without an Arrow schema', () => { + expect(getResultSchema(metadata(placeholder))).to.equal(placeholder); + }); + + it('keeps the placeholder when the Arrow schema cannot be decoded', () => { + expect(getResultSchema(metadata(placeholder, Buffer.from('not arrow')))).to.equal(placeholder); + }); + + it('returns other schemas unchanged', () => { + const schema: TTableSchema = { columns: [stringColumn('Result', 1), stringColumn('other', 2)] }; + expect(getResultSchema(metadata(schema, hiveSchemaToArrowSchema({ columns: [] })))).to.equal(schema); + }); +}); From 6561ad17422fa76ea5bbba1cc3c58fbdbbed617c Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 05:02:04 +0000 Subject: [PATCH 2/6] Normalize the Thrift schema once and use it for result handling Decode the Arrow schema once per operation and hand the normalized metadata to the result handlers, so DDL results skip FetchResults. getSchema() goes through an optional IOperationBackend.getSchema() instead of an instanceof check and still works without resultFormat. Tolerate Thrift schemas missing required fields, close operations and the session even when e2e assertions fail, and add a changelog entry. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- CHANGELOG.md | 1 + lib/DBSQLOperation.ts | 6 +- lib/contracts/IOperation.ts | 8 ++- lib/contracts/IOperationBackend.ts | 5 +- lib/thrift-backend/ThriftOperationBackend.ts | 48 ++++++++----- lib/thrift-backend/resultSchema.ts | 4 +- tests/e2e/ddl_schema.test.ts | 38 +++++++--- tests/unit/DBSQLOperation.test.ts | 72 +++++++++++-------- .../unit/thrift-backend/resultSchema.test.ts | 24 ++++++- 9 files changed, 143 insertions(+), 63 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3451fe0..7079d07b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - 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. +- Thrift `getSchema()` and `getResultMetadata().schema` now report no columns for DDL when Arrow metadata has no fields. `getMetadata()` and responses without Arrow metadata (including `arrowEnabled: false` and older protocols) retain the `Result STRING` placeholder. (#651) ## 3.1.0 diff --git a/lib/DBSQLOperation.ts b/lib/DBSQLOperation.ts index a0bd854a..73ed5104 100644 --- a/lib/DBSQLOperation.ts +++ b/lib/DBSQLOperation.ts @@ -19,7 +19,6 @@ import IClientContext from './contracts/IClientContext'; import IOperationBackend, { IOperationBackendWaitOptions } from './contracts/IOperationBackend'; import { ResultFormat, ResultMetadata } from './contracts/ResultMetadata'; import ThriftOperationBackend from './thrift-backend/ThriftOperationBackend'; -import getResultSchema from './thrift-backend/resultSchema'; import { synthesizeThriftStatus, synthesizeThriftResultSetMetadata } from './thrift-backend/wireSynthesis'; import { mapOperationTypeToTelemetryType } from './telemetry/telemetryTypeMappers'; import ExceptionClassifier from './telemetry/ExceptionClassifier'; @@ -307,9 +306,8 @@ export default class DBSQLOperation implements IOperation { await this.waitUntilReadyThroughBackend(options); 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 getResultSchema(metadata) ?? null; + if (this.backend.getSchema) { + return (await this.backend.getSchema()) ?? null; } const metadata = await this.getResultMetadata(); return metadata.schema ?? null; diff --git a/lib/contracts/IOperation.ts b/lib/contracts/IOperation.ts index dc238ad4..d48ecc51 100644 --- a/lib/contracts/IOperation.ts +++ b/lib/contracts/IOperation.ts @@ -90,13 +90,17 @@ export default interface IOperation { hasMoreRows(): Promise; /** - * Fetch schema. Statements without output, such as DDL, return a schema with - * no columns (on Thrift, only when Arrow results are enabled, the default). + * Fetch schema; returns null when hasResultSet is false or no schema is available. + * DDL returns { columns: [] } on kernel and on Thrift when Arrow metadata has + * no fields. Thrift retains its `Result STRING` placeholder without Arrow + * metadata (arrowEnabled: false or older protocols). + * The deprecated getMetadata() retains the Thrift wire schema unchanged. */ getSchema(options?: GetSchemaOptions): Promise; /** * 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; diff --git a/lib/contracts/IOperationBackend.ts b/lib/contracts/IOperationBackend.ts index 109de87e..f124c293 100644 --- a/lib/contracts/IOperationBackend.ts +++ b/lib/contracts/IOperationBackend.ts @@ -1,5 +1,5 @@ import Status from '../dto/Status'; -import { TOperationType } from '../../thrift/TCLIService_types'; +import { TOperationType, TTableSchema } from '../../thrift/TCLIService_types'; import { OperationStatus } from './OperationStatus'; import { ResultMetadata } from './ResultMetadata'; @@ -106,6 +106,9 @@ export default interface IOperationBackend { /** Fetch result-set metadata (schema, format, lz4 flag, arrow schema, staging flag). */ getResultMetadata(): Promise; + /** Column schema without requiring result-format metadata; defaults to getResultMetadata().schema. */ + getSchema?(): Promise; + /** * Result-set metadata if it is already on hand (direct results or an earlier * fetch), else `undefined`. MUST NOT issue an RPC or throw — statement diff --git a/lib/thrift-backend/ThriftOperationBackend.ts b/lib/thrift-backend/ThriftOperationBackend.ts index b28a26a6..6fbe8040 100644 --- a/lib/thrift-backend/ThriftOperationBackend.ts +++ b/lib/thrift-backend/ThriftOperationBackend.ts @@ -98,6 +98,8 @@ export default class ThriftOperationBackend implements IOperationBackend { private metadata?: TGetResultSetMetadataResp; + private normalizedMetadata?: TGetResultSetMetadataResp; + private metadataPromise?: Promise; private state: TOperationState = TOperationState.INITIALIZED_STATE; @@ -119,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); @@ -293,15 +295,19 @@ export default class ThriftOperationBackend implements IOperationBackend { } public async getResultMetadata(): Promise { - return this.adaptResultMetadata(await this.thriftResultMetadataResponse()); + return this.adaptResultMetadata(await this.resultMetadataResponse()); + } + + public async getSchema(): Promise { + 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; @@ -311,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`. @@ -334,7 +338,7 @@ export default class ThriftOperationBackend implements IOperationBackend { operationHandle: this.operationHandle, }); Status.assert(metadata.status); - this.metadata = metadata; + this.setResultMetadata(metadata); return metadata; })(); @@ -368,7 +372,7 @@ export default class ThriftOperationBackend implements IOperationBackend { } public async getResultHandler(): Promise> { - const metadata = await this.thriftResultMetadataResponse(); + const metadata = await this.resultMetadataResponse(); const resultFormat = definedOrError(metadata.resultFormat); if (!this.resultHandler) { @@ -434,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, @@ -480,10 +486,20 @@ 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 { + await this.thriftResultMetadataResponse(); + return definedOrError(this.normalizedMetadata); + } + // eslint-disable-next-line class-methods-use-this private adaptResultMetadata(response: TGetResultSetMetadataResp): ResultMetadata { return { - schema: getResultSchema(response), + schema: response.schema, resultFormat: thriftRowSetTypeToResultFormat(definedOrError(response.resultFormat)), lz4Compressed: response.lz4Compressed, arrowSchema: response.arrowSchema, diff --git a/lib/thrift-backend/resultSchema.ts b/lib/thrift-backend/resultSchema.ts index 72fde0ff..1141cd9a 100644 --- a/lib/thrift-backend/resultSchema.ts +++ b/lib/thrift-backend/resultSchema.ts @@ -2,11 +2,11 @@ import { RecordBatchReader } from 'apache-arrow'; import { TGetResultSetMetadataResp, TTableSchema, TTypeId } from '../../thrift/TCLIService_types'; function isPlaceholderSchema(schema?: TTableSchema): boolean { - if (schema?.columns.length !== 1) { + if (schema?.columns?.length !== 1) { return false; } const [column] = schema.columns; - return column.columnName === 'Result' && column.typeDesc.types[0]?.primitiveEntry?.type === TTypeId.STRING_TYPE; + return column?.columnName === 'Result' && column.typeDesc?.types?.[0]?.primitiveEntry?.type === TTypeId.STRING_TYPE; } function hasNoArrowFields(arrowSchema: Buffer): boolean { diff --git a/tests/e2e/ddl_schema.test.ts b/tests/e2e/ddl_schema.test.ts index bd9c1451..7f2ba82c 100644 --- a/tests/e2e/ddl_schema.test.ts +++ b/tests/e2e/ddl_schema.test.ts @@ -24,21 +24,43 @@ describe('schema of statements without output', () => { const columnsOf = async (statement: string) => { const operation = await session.executeStatement(statement); - expect(await operation.fetchAll()).to.deep.equal([]); - const schema = await operation.getSchema(); - await operation.close(); - return schema?.columns.map((column) => column.columnName); + try { + expect(await operation.fetchAll()).to.deep.equal([]); + const schema = await operation.getSchema(); + 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([]); expect(await columnsOf(`DROP TABLE ${table}`)).to.deep.equal([]); } finally { - const cleanup = await session.executeStatement(`DROP TABLE IF EXISTS ${table}`); - await cleanup.close(); - await session.close(); - await client.close(); + 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; } }); } diff --git a/tests/unit/DBSQLOperation.test.ts b/tests/unit/DBSQLOperation.test.ts index 9a20fd00..f6121a10 100644 --- a/tests/unit/DBSQLOperation.test.ts +++ b/tests/unit/DBSQLOperation.test.ts @@ -29,7 +29,7 @@ import { hiveSchemaToArrowSchema } from '../../lib/result/utils'; import ClientContextStub from './.stubs/ClientContextStub'; import { createOperationForTest } from './.stubs/createOperationForTest'; -import { Type } from 'apache-arrow'; +import { RecordBatchReader, Type } from 'apache-arrow'; function operationHandleStub(overrides: Partial): TOperationHandle { return { @@ -953,39 +953,53 @@ describe('DBSQLOperation', () => { expect(driver.getResultSetMetadata.called).to.be.false; }); - it('should report no columns for statements without output', async () => { - const context = new ClientContextStub(); - context.driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; - - // DDL on Thrift: placeholder `Result` column, Arrow schema with no fields. - const placeholder = { - columns: [ - { - columnName: 'Result', - position: 1, - typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, - }, - ], - }; - const directResults: TSparkDirectResults = { - resultSetMetadata: { + for (const prefetched of [true, false]) { + it(`normalizes DDL schemas once with ${prefetched ? 'prefetched' : 'fetched'} metadata`, async () => { + const context = new ClientContextStub(); + const driver = sinon.spy(context.driver); + driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; + + // DDL on Thrift: placeholder `Result` column, Arrow schema with no fields. + const placeholder = { + columns: [ + { + columnName: 'Result', + position: 1, + typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, + }, + ], + }; + const metadata = { status: { statusCode: TStatusCode.SUCCESS_STATUS }, resultFormat: TSparkRowSetType.ARROW_BASED_SET, schema: placeholder, arrowSchema: hiveSchemaToArrowSchema({ columns: [] }), - }, - }; - const operation = createOperationForTest({ - handle: operationHandleStub({ hasResultSet: true }), - context, - directResults, - }); + }; + driver.getResultSetMetadataResp = metadata; + const decode = sinon.spy(RecordBatchReader, 'from'); + try { + const operation = createOperationForTest({ + handle: operationHandleStub({ hasResultSet: true }), + context, + directResults: prefetched ? { resultSetMetadata: metadata } : undefined, + }); - expect(await operation.getSchema()).to.deep.equal({ columns: [] }); - expect((await operation.getResultMetadata()).schema).to.deep.equal({ columns: [] }); - // The deprecated wire accessor stays verbatim. - expect((await operation.getMetadata()).schema).to.equal(placeholder); - }); + const schema = await operation.getSchema(); + expect(schema).to.deep.equal({ columns: [] }); + expect(await operation.getSchema()).to.equal(schema); + expect((await operation.getResultMetadata()).schema).to.equal(schema); + // The deprecated wire accessor stays verbatim. + expect(await operation.getMetadata()).to.equal(metadata); + expect(metadata.schema).to.equal(placeholder); + expect(await operation.fetchAll()).to.deep.equal([]); + expect(driver.fetchResults.called).to.be.false; + expect(driver.getResultSetMetadata.callCount).to.equal(prefetched ? 0 : 1); + expect(decode.callCount).to.equal(1); + } finally { + decode.restore(); + } + }); + } it('should throw an error in case of a status error', async () => { const context = new ClientContextStub(); diff --git a/tests/unit/thrift-backend/resultSchema.test.ts b/tests/unit/thrift-backend/resultSchema.test.ts index 9b9e4d90..b2428b10 100644 --- a/tests/unit/thrift-backend/resultSchema.test.ts +++ b/tests/unit/thrift-backend/resultSchema.test.ts @@ -1,5 +1,12 @@ import { expect } from 'chai'; -import { TGetResultSetMetadataResp, TStatusCode, TTableSchema, TTypeId } from '../../../thrift/TCLIService_types'; +import { + TColumnDesc, + TGetResultSetMetadataResp, + TStatusCode, + TTableSchema, + TTypeDesc, + TTypeId, +} from '../../../thrift/TCLIService_types'; import getResultSchema from '../../../lib/thrift-backend/resultSchema'; import { hiveSchemaToArrowSchema } from '../../../lib/result/utils'; @@ -38,4 +45,19 @@ describe('getResultSchema', () => { const schema: TTableSchema = { columns: [stringColumn('Result', 1), stringColumn('other', 2)] }; expect(getResultSchema(metadata(schema, hiveSchemaToArrowSchema({ columns: [] })))).to.equal(schema); }); + + it('preserves schemas with missing required Thrift fields', () => { + const columnWithoutType = new TColumnDesc(); + columnWithoutType.columnName = 'Result'; + const schemas: TTableSchema[] = [ + new TTableSchema(), + { columns: [columnWithoutType] }, + { columns: [{ ...stringColumn('Result', 1), typeDesc: new TTypeDesc() }] }, + ]; + const arrowSchema = hiveSchemaToArrowSchema({ columns: [] }); + + for (const schema of schemas) { + expect(getResultSchema(metadata(schema, arrowSchema))).to.equal(schema); + } + }); }); From 2b0cdbbb987e4b22c191befef3aa018f845f3dba Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 05:00:38 +0000 Subject: [PATCH 3/6] Guard DDL schema normalization by result format Signed-off-by: Vu Anh Phung --- lib/result/JsonResultHandler.ts | 3 ++ lib/thrift-backend/resultSchema.ts | 9 +++-- tests/unit/DBSQLOperation.test.ts | 38 +++++++++++++++++++ tests/unit/result/JsonResultHandler.test.ts | 18 +++++++++ .../unit/thrift-backend/resultSchema.test.ts | 26 ++++++++++--- 5 files changed, 86 insertions(+), 8 deletions(-) diff --git a/lib/result/JsonResultHandler.ts b/lib/result/JsonResultHandler.ts index 87f6b07d..eb96923a 100644 --- a/lib/result/JsonResultHandler.ts +++ b/lib/result/JsonResultHandler.ts @@ -29,6 +29,9 @@ export default class JsonResultHandler implements IResultsProvider> { } public async hasMore() { + if (this.schema.length === 0) { + return false; + } return this.source.hasMore(); } diff --git a/lib/thrift-backend/resultSchema.ts b/lib/thrift-backend/resultSchema.ts index 1141cd9a..06b8a793 100644 --- a/lib/thrift-backend/resultSchema.ts +++ b/lib/thrift-backend/resultSchema.ts @@ -1,5 +1,5 @@ import { RecordBatchReader } from 'apache-arrow'; -import { TGetResultSetMetadataResp, TTableSchema, TTypeId } from '../../thrift/TCLIService_types'; +import { TGetResultSetMetadataResp, TSparkRowSetType, TTableSchema, TTypeId } from '../../thrift/TCLIService_types'; function isPlaceholderSchema(schema?: TTableSchema): boolean { if (schema?.columns?.length !== 1) { @@ -20,14 +20,17 @@ function hasNoArrowFields(arrowSchema: Buffer): boolean { } /** - * Column schema of a Thrift result. For statements without output (e.g. DDL) + * 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 } = metadata; + 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: [] }; } diff --git a/tests/unit/DBSQLOperation.test.ts b/tests/unit/DBSQLOperation.test.ts index f6121a10..0809f76c 100644 --- a/tests/unit/DBSQLOperation.test.ts +++ b/tests/unit/DBSQLOperation.test.ts @@ -999,6 +999,44 @@ describe('DBSQLOperation', () => { decode.restore(); } }); + + for (const method of ['fetchAll', 'fetchChunk'] as const) { + it(`finishes column-based ${method} with empty Arrow metadata (${ + prefetched ? 'prefetched' : 'fetched' + })`, async () => { + const context = new ClientContextStub(); + const driver = sinon.spy(context.driver); + driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; + const schema = { + columns: [ + { + columnName: 'Result', + position: 1, + typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, + }, + ], + }; + const metadata = { + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + resultFormat: TSparkRowSetType.COLUMN_BASED_SET, + schema, + arrowSchema: hiveSchemaToArrowSchema({ columns: [] }), + }; + driver.getResultSetMetadataResp = metadata; + driver.fetchResultsResp.results!.columns = []; + const operation = createOperationForTest({ + handle: operationHandleStub({ hasResultSet: true }), + context, + directResults: prefetched ? { resultSetMetadata: metadata } : undefined, + }); + + // Fail before fetching if normalization would cause an infinite loop. + expect(await operation.getSchema()).to.equal(schema); + expect(await operation[method]()).to.deep.equal([]); + expect(await operation.hasMoreRows()).to.be.false; + expect(driver.fetchResults.callCount).to.equal(1); + }); + } } it('should throw an error in case of a status error', async () => { diff --git a/tests/unit/result/JsonResultHandler.test.ts b/tests/unit/result/JsonResultHandler.test.ts index 45ea1f34..a64cc621 100644 --- a/tests/unit/result/JsonResultHandler.test.ts +++ b/tests/unit/result/JsonResultHandler.test.ts @@ -31,6 +31,24 @@ const getColumnSchema = (columnName: string, type: TTypeId | undefined, position }; describe('JsonResultHandler', () => { + it('reports no more rows without consuming the source when the schema is empty or missing', async () => { + for (const schema of [undefined, { columns: [] }]) { + const rowSetProvider = new ResultsProviderStub( + [{ startRowOffset: new Int64(0), rows: [], columns: [] }], + undefined, + ); + const result = new JsonResultHandler(new ClientContextStub(), rowSetProvider, { + schema, + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + }); + + expect(await rowSetProvider.hasMore()).to.be.true; + expect(await result.hasMore()).to.be.false; + expect(await result.fetchNext({ limit: 10000 })).to.deep.equal([]); + expect(await rowSetProvider.hasMore()).to.be.true; + } + }); + it('should not buffer any data', async () => { const schema: TTableSchema = { columns: [getColumnSchema('table.id', TTypeId.STRING_TYPE, 1)], diff --git a/tests/unit/thrift-backend/resultSchema.test.ts b/tests/unit/thrift-backend/resultSchema.test.ts index b2428b10..04f368f4 100644 --- a/tests/unit/thrift-backend/resultSchema.test.ts +++ b/tests/unit/thrift-backend/resultSchema.test.ts @@ -2,6 +2,7 @@ import { expect } from 'chai'; import { TColumnDesc, TGetResultSetMetadataResp, + TSparkRowSetType, TStatusCode, TTableSchema, TTypeDesc, @@ -18,15 +19,30 @@ function stringColumn(columnName: string, position: number) { const placeholder: TTableSchema = { columns: [stringColumn('Result', 1)] }; function metadata(schema: TTableSchema, arrowSchema?: Buffer): TGetResultSetMetadataResp { - return { status: { statusCode: TStatusCode.SUCCESS_STATUS }, schema, arrowSchema }; + return { + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + resultFormat: TSparkRowSetType.ARROW_BASED_SET, + schema, + arrowSchema, + }; } describe('getResultSchema', () => { - it('reports no columns when the Arrow schema has no fields', () => { - expect(getResultSchema(metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })))).to.deep.equal({ - columns: [], + for (const resultFormat of [TSparkRowSetType.ARROW_BASED_SET, TSparkRowSetType.URL_BASED_SET]) { + it(`reports no columns for ${TSparkRowSetType[resultFormat]} when the Arrow schema has no fields`, () => { + const md = metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })); + md.resultFormat = resultFormat; + expect(getResultSchema(md)).to.deep.equal({ columns: [] }); }); - }); + } + + for (const resultFormat of [TSparkRowSetType.COLUMN_BASED_SET, undefined]) { + it(`keeps the placeholder with result format ${resultFormat} despite an empty Arrow schema`, () => { + const md = metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })); + md.resultFormat = resultFormat; + expect(getResultSchema(md)).to.equal(placeholder); + }); + } it('keeps a real `Result` column', () => { const md = metadata(placeholder, hiveSchemaToArrowSchema(placeholder)); From 1133cd5523a973f6ad83647185921c6e93dd4e55 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 06:30:11 +0000 Subject: [PATCH 4/6] Cover fetched metadata and Arrow-disabled DDL schemas Signed-off-by: Vu Anh Phung --- tests/e2e/ddl_schema.test.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/e2e/ddl_schema.test.ts b/tests/e2e/ddl_schema.test.ts index 7f2ba82c..457829b5 100644 --- a/tests/e2e/ddl_schema.test.ts +++ b/tests/e2e/ddl_schema.test.ts @@ -7,12 +7,15 @@ 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] of [ - ['Thrift', false], - ['kernel', true], + 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 no columns for DDL with ${name}`, async () => { + 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, @@ -20,13 +23,15 @@ describe('schema of statements without output', () => { 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()}_${config.tableSuffix}`; + 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); + const operation = await session.executeStatement(statement, { maxRows }); try { expect(await operation.fetchAll()).to.deep.equal([]); const schema = await operation.getSchema(); + expect((await operation.getResultMetadata()).schema).to.deep.equal(schema); return schema?.columns.map((column) => column.columnName); } finally { await operation.close(); @@ -37,8 +42,8 @@ describe('schema of statements without output', () => { 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([]); - expect(await columnsOf(`DROP TABLE ${table}`)).to.deep.equal([]); + 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 { From acba40008b2ee67e9bb701b7f18aed39317a1ff4 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 17:43:08 +0000 Subject: [PATCH 5/6] Keep DDL schema normalization within the Thrift backend Signed-off-by: Vu Anh Phung --- lib/DBSQLOperation.ts | 2 +- lib/contracts/IOperationBackend.ts | 5 +---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/DBSQLOperation.ts b/lib/DBSQLOperation.ts index 73ed5104..1006b7a0 100644 --- a/lib/DBSQLOperation.ts +++ b/lib/DBSQLOperation.ts @@ -306,7 +306,7 @@ export default class DBSQLOperation implements IOperation { await this.waitUntilReadyThroughBackend(options); this.context.getLogger().log(LogLevel.debug, `Fetching schema for operation with id: ${this.id}`); - if (this.backend.getSchema) { + if (this.backend instanceof ThriftOperationBackend) { return (await this.backend.getSchema()) ?? null; } const metadata = await this.getResultMetadata(); diff --git a/lib/contracts/IOperationBackend.ts b/lib/contracts/IOperationBackend.ts index f124c293..109de87e 100644 --- a/lib/contracts/IOperationBackend.ts +++ b/lib/contracts/IOperationBackend.ts @@ -1,5 +1,5 @@ import Status from '../dto/Status'; -import { TOperationType, TTableSchema } from '../../thrift/TCLIService_types'; +import { TOperationType } from '../../thrift/TCLIService_types'; import { OperationStatus } from './OperationStatus'; import { ResultMetadata } from './ResultMetadata'; @@ -106,9 +106,6 @@ export default interface IOperationBackend { /** Fetch result-set metadata (schema, format, lz4 flag, arrow schema, staging flag). */ getResultMetadata(): Promise; - /** Column schema without requiring result-format metadata; defaults to getResultMetadata().schema. */ - getSchema?(): Promise; - /** * Result-set metadata if it is already on hand (direct results or an earlier * fetch), else `undefined`. MUST NOT issue an RPC or throw — statement From 2b3a3cbcf01a562dc882aa36166d5441e115a033 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 18:10:09 +0000 Subject: [PATCH 6/6] Cover schema edge cases and clarify no-output behavior Signed-off-by: Vu Anh Phung --- CHANGELOG.md | 3 +- lib/contracts/IOperation.ts | 8 +- tests/e2e/ddl_schema.test.ts | 21 ++- tests/unit/DBSQLOperation.test.ts | 138 ++++++++++++------ .../unit/thrift-backend/resultSchema.test.ts | 31 +++- 5 files changed, 144 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7079d07b..1b630444 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +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. -- Thrift `getSchema()` and `getResultMetadata().schema` now report no columns for DDL when Arrow metadata has no fields. `getMetadata()` and responses without Arrow metadata (including `arrowEnabled: false` and older protocols) retain the `Result STRING` placeholder. (#651) +- **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 diff --git a/lib/contracts/IOperation.ts b/lib/contracts/IOperation.ts index d48ecc51..4ef8390d 100644 --- a/lib/contracts/IOperation.ts +++ b/lib/contracts/IOperation.ts @@ -91,9 +91,11 @@ export default interface IOperation { /** * Fetch schema; returns null when hasResultSet is false or no schema is available. - * DDL returns { columns: [] } on kernel and on Thrift when Arrow metadata has - * no fields. Thrift retains its `Result STRING` placeholder without Arrow - * metadata (arrowEnabled: false or older protocols). + * 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; diff --git a/tests/e2e/ddl_schema.test.ts b/tests/e2e/ddl_schema.test.ts index 457829b5..a655f635 100644 --- a/tests/e2e/ddl_schema.test.ts +++ b/tests/e2e/ddl_schema.test.ts @@ -1,7 +1,9 @@ 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'; @@ -29,9 +31,24 @@ describe('schema of statements without output', () => { 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([]); - const schema = await operation.getSchema(); - expect((await operation.getResultMetadata()).schema).to.deep.equal(schema); + expect(await checkMetadata()).to.deep.equal(schema); return schema?.columns.map((column) => column.columnName); } finally { await operation.close(); diff --git a/tests/unit/DBSQLOperation.test.ts b/tests/unit/DBSQLOperation.test.ts index 0809f76c..36ce2bbe 100644 --- a/tests/unit/DBSQLOperation.test.ts +++ b/tests/unit/DBSQLOperation.test.ts @@ -25,6 +25,7 @@ import ArrowResultConverter from '../../lib/result/ArrowResultConverter'; import ArrowResultHandler from '../../lib/result/ArrowResultHandler'; import CloudFetchResultHandler from '../../lib/result/CloudFetchResultHandler'; import ResultSlicer from '../../lib/result/ResultSlicer'; +import RowSetProvider from '../../lib/result/RowSetProvider'; import { hiveSchemaToArrowSchema } from '../../lib/result/utils'; import ClientContextStub from './.stubs/ClientContextStub'; @@ -954,51 +955,62 @@ describe('DBSQLOperation', () => { }); for (const prefetched of [true, false]) { - it(`normalizes DDL schemas once with ${prefetched ? 'prefetched' : 'fetched'} metadata`, async () => { - const context = new ClientContextStub(); - const driver = sinon.spy(context.driver); - driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; - - // DDL on Thrift: placeholder `Result` column, Arrow schema with no fields. - const placeholder = { - columns: [ - { - columnName: 'Result', - position: 1, - typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, - }, - ], - }; - const metadata = { - status: { statusCode: TStatusCode.SUCCESS_STATUS }, - resultFormat: TSparkRowSetType.ARROW_BASED_SET, - schema: placeholder, - arrowSchema: hiveSchemaToArrowSchema({ columns: [] }), - }; - driver.getResultSetMetadataResp = metadata; - const decode = sinon.spy(RecordBatchReader, 'from'); - try { - const operation = createOperationForTest({ - handle: operationHandleStub({ hasResultSet: true }), - context, - directResults: prefetched ? { resultSetMetadata: metadata } : undefined, - }); + for (const resultFormat of [TSparkRowSetType.ARROW_BASED_SET, TSparkRowSetType.URL_BASED_SET]) { + it(`normalizes empty output schemas once for ${TSparkRowSetType[resultFormat]} with ${ + prefetched ? 'prefetched' : 'fetched' + } metadata`, async () => { + const context = new ClientContextStub(); + const driver = sinon.spy(context.driver); + driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; - const schema = await operation.getSchema(); - expect(schema).to.deep.equal({ columns: [] }); - expect(await operation.getSchema()).to.equal(schema); - expect((await operation.getResultMetadata()).schema).to.equal(schema); - // The deprecated wire accessor stays verbatim. - expect(await operation.getMetadata()).to.equal(metadata); - expect(metadata.schema).to.equal(placeholder); - expect(await operation.fetchAll()).to.deep.equal([]); - expect(driver.fetchResults.called).to.be.false; - expect(driver.getResultSetMetadata.callCount).to.equal(prefetched ? 0 : 1); - expect(decode.callCount).to.equal(1); - } finally { - decode.restore(); - } - }); + // DDL on Thrift: placeholder `Result` column, Arrow schema with no fields. + const placeholder = { + columns: [ + { + columnName: 'Result', + position: 1, + typeDesc: { types: [{ primitiveEntry: { type: TTypeId.STRING_TYPE } }] }, + }, + ], + }; + const metadata = { + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + resultFormat, + schema: placeholder, + arrowSchema: hiveSchemaToArrowSchema({ columns: [] }), + }; + driver.getResultSetMetadataResp = metadata; + const decode = sinon.spy(RecordBatchReader, 'from'); + try { + const operation = createOperationForTest({ + handle: operationHandleStub({ hasResultSet: true }), + context, + directResults: prefetched ? { resultSetMetadata: metadata } : undefined, + }); + + const schema = await operation.getSchema(); + expect(schema).to.deep.equal({ columns: [] }); + expect(await operation.getSchema()).to.equal(schema); + expect((await operation.getResultMetadata()).schema).to.equal(schema); + // The deprecated wire accessor stays verbatim. + expect(await operation.getMetadata()).to.equal(metadata); + expect(metadata.schema).to.equal(placeholder); + const handler = await operation.getResultHandler(); + expect(handler).to.be.instanceOf(ResultSlicer); + const converter = (handler as ResultSlicer)['source']; + expect(converter).to.be.instanceOf(ArrowResultConverter); + expect((converter as ArrowResultConverter)['source']).to.be.instanceOf( + resultFormat === TSparkRowSetType.URL_BASED_SET ? CloudFetchResultHandler : ArrowResultHandler, + ); + expect(await operation.fetchAll()).to.deep.equal([]); + expect(driver.fetchResults.called).to.be.false; + expect(driver.getResultSetMetadata.callCount).to.equal(prefetched ? 0 : 1); + expect(decode.callCount).to.equal(1); + } finally { + decode.restore(); + } + }); + } for (const method of ['fetchAll', 'fetchChunk'] as const) { it(`finishes column-based ${method} with empty Arrow metadata (${ @@ -1030,7 +1042,6 @@ describe('DBSQLOperation', () => { directResults: prefetched ? { resultSetMetadata: metadata } : undefined, }); - // Fail before fetching if normalization would cause an infinite loop. expect(await operation.getSchema()).to.equal(schema); expect(await operation[method]()).to.deep.equal([]); expect(await operation.hasMoreRows()).to.be.false; @@ -1347,6 +1358,43 @@ describe('DBSQLOperation', () => { }); }); + describe('fetching column-based results without columns', () => { + for (const prefetched of [true, false]) { + for (const schema of [undefined, { columns: [] }]) { + for (const method of ['fetchAll', 'fetchChunk'] as const) { + it(`finishes ${method} with ${schema ? 'an empty' : 'a missing'} schema and ${ + prefetched ? 'prefetched' : 'fetched' + } metadata`, async () => { + const context = new ClientContextStub(); + const driver = sinon.spy(context.driver); + driver.getOperationStatusResp.operationState = TOperationState.FINISHED_STATE; + const metadata = { + status: { statusCode: TStatusCode.SUCCESS_STATUS }, + resultFormat: TSparkRowSetType.COLUMN_BASED_SET, + schema, + }; + driver.getResultSetMetadataResp = metadata; + const operation = createOperationForTest({ + handle: operationHandleStub({ hasResultSet: true }), + context, + directResults: prefetched ? { resultSetMetadata: metadata } : undefined, + }); + // Reject source polling so the old infinite loop fails deterministically. + const sourceHasMore = sinon + .stub(operation._data as RowSetProvider, 'hasMore') + .rejects(new Error('An empty-schema result handler must not poll the source')); + + expect(await operation[method]()).to.deep.equal([]); + expect(await operation.hasMoreRows()).to.be.false; + expect(sourceHasMore.called).to.be.false; + expect(driver.fetchResults.called).to.be.false; + expect(driver.getResultSetMetadata.callCount).to.equal(prefetched ? 0 : 1); + }); + } + } + } + }); + describe('hasMoreRows', () => { it('should return initial value prior to first fetch', async () => { const context = new ClientContextStub(); diff --git a/tests/unit/thrift-backend/resultSchema.test.ts b/tests/unit/thrift-backend/resultSchema.test.ts index 04f368f4..32ec21cf 100644 --- a/tests/unit/thrift-backend/resultSchema.test.ts +++ b/tests/unit/thrift-backend/resultSchema.test.ts @@ -18,6 +18,14 @@ function stringColumn(columnName: string, position: number) { // What the server sends for DDL: a placeholder column alongside an Arrow schema with no fields. const placeholder: TTableSchema = { columns: [stringColumn('Result', 1)] }; +// Empty Arrow IPC Schema message encoded directly as a FlatBuffer, without EOS. +const schemaWithoutEos = Buffer.from( + '/////zAAAAAQAAAAAAAKAAwACgAJAAQACgAAABAAAAAAAQQACAAIAAAABAAIAAAABAAAAAAAAAA=', + 'base64', +); +const eos = Buffer.from([0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0]); +const emptyArrowSchema = Buffer.concat([schemaWithoutEos, eos]); + function metadata(schema: TTableSchema, arrowSchema?: Buffer): TGetResultSetMetadataResp { return { status: { statusCode: TStatusCode.SUCCESS_STATUS }, @@ -30,7 +38,7 @@ function metadata(schema: TTableSchema, arrowSchema?: Buffer): TGetResultSetMeta describe('getResultSchema', () => { for (const resultFormat of [TSparkRowSetType.ARROW_BASED_SET, TSparkRowSetType.URL_BASED_SET]) { it(`reports no columns for ${TSparkRowSetType[resultFormat]} when the Arrow schema has no fields`, () => { - const md = metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })); + const md = metadata(placeholder, emptyArrowSchema); md.resultFormat = resultFormat; expect(getResultSchema(md)).to.deep.equal({ columns: [] }); }); @@ -38,7 +46,7 @@ describe('getResultSchema', () => { for (const resultFormat of [TSparkRowSetType.COLUMN_BASED_SET, undefined]) { it(`keeps the placeholder with result format ${resultFormat} despite an empty Arrow schema`, () => { - const md = metadata(placeholder, hiveSchemaToArrowSchema({ columns: [] })); + const md = metadata(placeholder, emptyArrowSchema); md.resultFormat = resultFormat; expect(getResultSchema(md)).to.equal(placeholder); }); @@ -57,9 +65,22 @@ describe('getResultSchema', () => { expect(getResultSchema(metadata(placeholder, Buffer.from('not arrow')))).to.equal(placeholder); }); + for (const { name, arrowSchema } of [ + { name: 'an empty buffer', arrowSchema: Buffer.alloc(0) }, + { name: 'an EOS-only buffer', arrowSchema: eos }, + ]) { + it(`keeps the placeholder with ${name}`, () => { + expect(getResultSchema(metadata(placeholder, arrowSchema))).to.equal(placeholder); + }); + } + + it('reports no columns when the schema message has no EOS marker', () => { + expect(getResultSchema(metadata(placeholder, schemaWithoutEos))).to.deep.equal({ columns: [] }); + }); + it('returns other schemas unchanged', () => { const schema: TTableSchema = { columns: [stringColumn('Result', 1), stringColumn('other', 2)] }; - expect(getResultSchema(metadata(schema, hiveSchemaToArrowSchema({ columns: [] })))).to.equal(schema); + expect(getResultSchema(metadata(schema, emptyArrowSchema))).to.equal(schema); }); it('preserves schemas with missing required Thrift fields', () => { @@ -70,10 +91,8 @@ describe('getResultSchema', () => { { columns: [columnWithoutType] }, { columns: [{ ...stringColumn('Result', 1), typeDesc: new TTypeDesc() }] }, ]; - const arrowSchema = hiveSchemaToArrowSchema({ columns: [] }); - for (const schema of schemas) { - expect(getResultSchema(metadata(schema, arrowSchema))).to.equal(schema); + expect(getResultSchema(metadata(schema, emptyArrowSchema))).to.equal(schema); } }); });