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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
5 changes: 2 additions & 3 deletions lib/DBSQLOperation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion lib/contracts/IOperation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,17 @@ export default interface IOperation {
hasMoreRows(): Promise<boolean>;

/**
* 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<TTableSchema | null>;

/**
* Fetch result-set metadata in the backend-neutral `ResultMetadata` shape.
* Its schema follows the same column normalization as getSchema().
* Prefer this over the Thrift-shaped surface for new code.
*/
getResultMetadata(): Promise<ResultMetadata>;
Expand Down
5 changes: 4 additions & 1 deletion lib/contracts/IOperationBackend.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -106,6 +106,9 @@ export default interface IOperationBackend {
/** Fetch result-set metadata (schema, format, lz4 flag, arrow schema, staging flag). */
getResultMetadata(): Promise<ResultMetadata>;

/** Column schema without requiring result-format metadata; defaults to getResultMetadata().schema. */
getSchema?(): Promise<TTableSchema | undefined>;

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

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

private metadata?: TGetResultSetMetadataResp;

private normalizedMetadata?: TGetResultSetMetadataResp;

private metadataPromise?: Promise<TGetResultSetMetadataResp>;

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

const useOnlyPrefetchedResults = Boolean(directResults?.closeOperation);

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

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

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

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

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

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

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

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

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

// eslint-disable-next-line class-methods-use-this
private adaptResultMetadata(response: TGetResultSetMetadataResp): ResultMetadata {
return {
Expand Down
35 changes: 35 additions & 0 deletions lib/thrift-backend/resultSchema.ts
Original file line number Diff line number Diff line change
@@ -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;
}
67 changes: 67 additions & 0 deletions tests/e2e/ddl_schema.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
}
});
51 changes: 50 additions & 1 deletion tests/unit/DBSQLOperation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>): TOperationHandle {
return {
Expand Down Expand Up @@ -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;
Expand Down
Loading