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 30f095ef..73ed5104 100644 --- a/lib/DBSQLOperation.ts +++ b/lib/DBSQLOperation.ts @@ -306,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 metadata.schema ?? 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 bbeed622..d48ecc51 100644 --- a/lib/contracts/IOperation.ts +++ b/lib/contracts/IOperation.ts @@ -90,12 +90,17 @@ export default interface IOperation { hasMoreRows(): Promise; /** - * Fetch schema + * 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 10f2d03e..6fbe8040 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; @@ -97,6 +98,8 @@ export default class ThriftOperationBackend implements IOperationBackend { private metadata?: TGetResultSetMetadataResp; + private normalizedMetadata?: TGetResultSetMetadataResp; + private metadataPromise?: Promise; private state: TOperationState = TOperationState.INITIALIZED_STATE; @@ -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); @@ -292,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; @@ -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`. @@ -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; })(); @@ -367,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) { @@ -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, @@ -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 { + await this.thriftResultMetadataResponse(); + return definedOrError(this.normalizedMetadata); + } + // eslint-disable-next-line class-methods-use-this private adaptResultMetadata(response: TGetResultSetMetadataResp): ResultMetadata { return { diff --git a/lib/thrift-backend/resultSchema.ts b/lib/thrift-backend/resultSchema.ts new file mode 100644 index 00000000..1141cd9a --- /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..7f2ba82c --- /dev/null +++ b/tests/e2e/ddl_schema.test.ts @@ -0,0 +1,67 @@ +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); + 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 { + 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 e37b5059..f6121a10 100644 --- a/tests/unit/DBSQLOperation.test.ts +++ b/tests/unit/DBSQLOperation.test.ts @@ -25,10 +25,11 @@ 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'; -import { Type } from 'apache-arrow'; +import { RecordBatchReader, Type } from 'apache-arrow'; function operationHandleStub(overrides: Partial): TOperationHandle { return { @@ -952,6 +953,54 @@ describe('DBSQLOperation', () => { expect(driver.getResultSetMetadata.called).to.be.false; }); + 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, + }); + + 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(); 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..b2428b10 --- /dev/null +++ b/tests/unit/thrift-backend/resultSchema.test.ts @@ -0,0 +1,63 @@ +import { expect } from 'chai'; +import { + TColumnDesc, + TGetResultSetMetadataResp, + TStatusCode, + TTableSchema, + TTypeDesc, + 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); + }); + + 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); + } + }); +});