From 3e136463c588bedb27f6d35ad2c7a34fa72969a8 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 04:34:57 +0000 Subject: [PATCH 1/2] 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 ec3f810e391a60aa339236bf05397fd31c510f39 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 26 Nov 2026 05:02:04 +0000 Subject: [PATCH 2/2] 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 | 4 ++ 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, 146 insertions(+), 63 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fbcb477..17c1ebe0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## Unreleased + +- 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 - Upgrade to [kernel 1.5.0](https://github.com/databricks/databricks-sql-kernel/releases/tag/v1.5.0): fix CloudFetch pagination, ordering and cancellation, paged inline Arrow results with CloudFetch disabled, and affected-row counts. 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); + } + }); });